diff --git a/.github/skills/code-review/SKILL.md b/.github/skills/code-review/SKILL.md index 32e0af8..a2c5191 100644 --- a/.github/skills/code-review/SKILL.md +++ b/.github/skills/code-review/SKILL.md @@ -120,6 +120,12 @@ annotations both have to survive. A **new** overridable field should follow the same pattern, not invent a second convention. `max_steps` is also `static=True`; leave it that way. +The `max_steps` **field** has a second sentinel, `"auto"`, resolved in +`__call__` after the `MISSING` check: `len(ts) - 1` for a `diffrax.StepTo` +controller, the scraped `default_max_steps` otherwise. It must stay resolved at +solve time, not at construction, so that `eqx.tree_at` on `stepsize_controller` +picks up the new grid. An explicit integer or `None` must never be rewritten. + ## Shape bookkeeping [interp.py](../../../src/diffraxtra/_src/interp.py) maintains one invariant by diff --git a/AGENTS.md b/AGENTS.md index 33adbd0..d4a8e65 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,8 @@ `DiffEqSolver`, an `equinox.Module` that pre-configures `diffrax.diffeqsolve` behind a callable object, and `VectorizedDenseInterpolation`, which makes the `diffrax.DenseInterpolation` produced by a batched solve evaluable at -arbitrarily-shaped arrays of times. +arbitrarily-shaped arrays of times. A small helper, `fixed_steps`, builds a +`diffrax.StepTo` grid for a fixed number of steps. The design goal is to extend diffrax without diverging from it: follow diffrax's own API conventions, keep dependencies minimal, and keep every object a PyTree @@ -34,7 +35,7 @@ new session needs its group to exist. ## Architecture -The public API is the four names re-exported from +The public API is the five names re-exported from [src/diffraxtra/\_\_init\_\_.py](src/diffraxtra/__init__.py); everything else lives under `src/diffraxtra/_src/` and is private. Each public class is an abstract/`@final` pair of `equinox.Module`s, with `eqx.AbstractVar` fields on @@ -45,6 +46,7 @@ the ABC. | [\_src/diffeq_abc.py](src/diffraxtra/_src/diffeq_abc.py) | `AbstractDiffEqSolver`: the five `AbstractVar` fields, the plum-dispatched `__call__` pair that forwards to `dfx.diffeqsolve`, the `params` signature scrape, and four `from_` overloads | | [\_src/diffeq.py](src/diffraxtra/_src/diffeq.py) | `DiffEqSolver`: the `@final` concrete module, plus the `default_stepsize_controller` / `default_max_steps` / `default_adjoint` re-exports | | [\_src/interp.py](src/diffraxtra/_src/interp.py) | `AbstractVectorizedDenseInterpolation` and `VectorizedDenseInterpolation`: the batch-flattening `__init__`, the doubly-vmapped `evaluate`, the `DenseInterpolation` property forwards, and three `from_` overloads | +| [\_src/steps.py](src/diffraxtra/_src/steps.py) | `fixed_steps`: the `optimization_barrier`-wrapped `StepTo` grid and `(t0, t1, StepTo, max_steps)` | | [conftest.py](conftest.py) | sybil collection and x64 | `__call__` is **two** methods: a `@dispatch`ed positional one on the class, and @@ -106,7 +108,9 @@ is an example run by [sybil](https://sybil.readthedocs.io) from "not passed" (use the field) stays distinguishable from an explicit `None` (unbounded / no event). Never "simplify" either default to `None`. `max_steps` is additionally `static=True`, so each distinct value is a separate - compilation. + compilation. The `max_steps` field defaults to `"auto"`, resolved at solve + time to `len(ts) - 1` for a `diffrax.StepTo` controller and to the scraped + `default_max_steps` otherwise. - **`__call__` is `eqx.filter_jit`-wrapped, twice.** `throw`, `vectorize_interpolation` and `max_steps` are static; a structurally different `solver` / `stepsize_controller` / `adjoint` retraces. Both dispatch overloads @@ -127,7 +131,7 @@ is an example run by [sybil](https://sybil.readthedocs.io) from - **`jax` and `numpy` are imported in `src/` but not declared** in `[project.dependencies]` (which lists `diffrax`, `equinox`, `jaxtyping`, `plum-dispatch`, `typing_extensions`). They arrive transitively. -- **CI runs `--resolution lowest`**, so new code must work on `diffrax>=0.6`, +- **CI runs `--resolution lowest`**, so new code must work on `diffrax>=0.6.2`, not just the newest release. Because that lowers _transitive_ deps too, a dependency that only publishes an old sdist can break the job during install, before a single test runs — hence the transitive lower bounds in @@ -149,8 +153,9 @@ is an example run by [sybil](https://sybil.readthedocs.io) from ## Dependencies -`diffrax>=0.6`, `equinox>=0.11.5`, `jaxtyping>=0.2.35`, `plum-dispatch>=2.5.7`, -`typing_extensions>=4.12.2`; Python >=3.11. Minimum supported versions follow +`diffrax>=0.6.2`, `equinox>=0.11.10`, `jaxtyping>=0.2.35`, +`plum-dispatch>=2.5.7`, `typing_extensions>=4.12.2`; Python >=3.11. Minimum +supported versions follow [SPEC 0](https://scientific-python.org/specs/spec-0000/). ## Further Reading diff --git a/README.md b/README.md index 46b2f2b..dcffe7c 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,24 @@ DiffEqSolver(...solver=Dopri5(...)... For a full enumeration of the ways to construct a `DiffEqSolver` object, see `diffraxtra.DiffEqSolver.from_`. +### `fixed_steps` + +`fixed_steps(t0, dt, n_steps)` returns the `t0`, `t1`, `diffrax.StepTo` +controller and `max_steps` for `n_steps` fixed steps of size `dt`. `t0` and `dt` +can be traced, and a negative `dt` runs backward. A `DiffEqSolver` with a +`StepTo` controller sets `max_steps` to the number of steps on the grid by +itself, so you can drop the fourth value. + +```pycon +>>> from diffraxtra import fixed_steps +>>> t0, t1, stepto, max_steps = fixed_steps(0.0, 0.1, 30) +>>> solver = DiffEqSolver(dfx.Tsit5(), stepsize_controller=stepto) +>>> soln = solver(term, t0, t1, None, 1.0) +>>> soln.ys.round(3) +Array([0.05], dtype=float64) + +``` + ### `VectorizedDenseInterpolation` Vectorized wrapper around a `diffrax.DenseInterpolation` diff --git a/pyproject.toml b/pyproject.toml index b7acc7a..3859518 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,8 +24,8 @@ ] dynamic = ["version"] dependencies = [ - "diffrax>=0.6", - "equinox>=0.11.5", + "diffrax>=0.6.2", + "equinox>=0.11.10", "jaxtyping>=0.2.35", "plum-dispatch>=2.5.7", "typing_extensions>=4.12.2", @@ -143,6 +143,8 @@ filterwarnings = [ "ignore:jax.core.pp_eqn_rules is deprecated:DeprecationWarning", # Equinox 0.11.5 & Jax 0.4.35 "ignore:jax.interpreters.batching.NotMapped is deprecated:DeprecationWarning", + # Equinox 0.11.10 & Jax 0.4.38 + "ignore:jax\\.core\\.\\w+ is deprecated:DeprecationWarning", ] log_cli_level = "INFO" testpaths = ["README.md", "src/", "skills/", "tests/"] @@ -218,7 +220,6 @@ constraint-dependencies = [ "pillow>=10.3.0", # Jax "scipy>=1.14", - "jax>0.4.34", # Misc "opt-einsum>=3.3.0", # Transitive dependencies for --resolution lowest diff --git a/skills/diffraxtra/SKILL.md b/skills/diffraxtra/SKILL.md index 429cc10..076bd67 100644 --- a/skills/diffraxtra/SKILL.md +++ b/skills/diffraxtra/SKILL.md @@ -7,14 +7,15 @@ description: when a batched `diffrax.diffeqsolve` result needs `.evaluate`, when the output of a batched solve has an unexpected shape, when `vectorize_interpolation` or `apply_to_solution` appears, when a per-call `max_steps` or `event` override - is needed, when `max_steps=None` conflicts with a `diffrax.SaveAt`, or when a - `DiffEqSolver` recompiles on every call. + is needed, when `max_steps=None` conflicts with a `diffrax.SaveAt`, when a + `DiffEqSolver` recompiles on every call, or when running a fixed number of + `diffrax.StepTo` steps with `fixed_steps`. --- # Using diffraxtra Effectively `diffraxtra` is two extras for [diffrax](https://docs.kidger.site/diffrax/), and -nothing else: +a small helper: - **`DiffEqSolver`** — an `equinox.Module` holding a `solver`, `stepsize_controller`, `adjoint`, `event` and `max_steps`, callable with the @@ -23,12 +24,14 @@ nothing else: - **`VectorizedDenseInterpolation`** — a wrapper around `diffrax.DenseInterpolation` that evaluates a **batched** solution at an **arbitrarily-shaped** array of times, without you writing the `jax.vmap`. +- **`fixed_steps(t0, dt, n_steps)`** — the `(t0, t1, StepTo, max_steps)` for + `n_steps` fixed steps of size `dt`, with `t0` and `dt` allowed to be traced. -Each comes as an `Abstract*`/`@final` pair of `equinox.Module`s, and each has a -`plum`-dispatched `from_` constructor. That is the whole library. +Each class comes as an `Abstract*`/`@final` pair of `equinox.Module`s, and each +has a `plum`-dispatched `from_` constructor. Checked against diffraxtra 1.5.3, diffrax 0.7.0, equinox 0.13.0, plum-dispatch -2.5.7, jax 0.7.1, Python >=3.11. The supported floor is `diffrax>=0.6`. +2.5.7, jax 0.7.1, Python >=3.11. The supported floor is `diffrax>=0.6.2`. ## Quick start @@ -179,8 +182,13 @@ genuinely three-way — omitting the argument is **not** the same as passing `None`. The parameter defaults to `dataclasses.MISSING`, and only that sentinel means "use the field". +The `max_steps` field defaults to `"auto"`, which is resolved at solve time. +With a `diffrax.StepTo` controller it is `len(ts) - 1`, the exact number of +steps on the grid. With any other controller it is diffrax's default, 4096. An +integer or `None`, on the field or in the call, is used as is. + ```python -assert DiffEqSolver(dfx.Dopri5()).max_steps == 4096 # diffrax's default, scraped +assert DiffEqSolver(dfx.Dopri5()).max_steps == "auto" assert DiffEqSolver(dfx.Dopri5()).event is None solver(term, t0=0.0, t1=3.0, dt0=0.1, y0=1.0, saveat=t1_only) # use the field @@ -219,6 +227,33 @@ solver( That is exactly why the per-call override exists — configure a solver once with a bounded `max_steps`, and drop the bound only for the calls that can take it. +## Fixed steps + +`fixed_steps(t0, dt, n_steps)` builds the grid `t0 + dt * arange(n_steps + 1)` +behind `jax.lax.optimization_barrier` and returns `(t0, t1, StepTo, max_steps)`. +The barrier stops XLA's simplifier from rewriting `t1` and the grid separately +with different roundings, and `StepTo` rejects a `t1` that is one rounding off +`ts[-1]`. `t0` and `dt` can be traced, and a negative `dt` runs backward. With +`DiffEqSolver` the fourth value isn't needed, because `"auto"` reads it off the +`StepTo`. With `RecursiveCheckpointAdjoint` the exact bound matters: it sets how +many checkpoints the backward pass stores. + +```python +from diffraxtra import fixed_steps + + +@jax.jit +def final_y(t0, dt): + t0, t1, stepto, _ = fixed_steps(t0, dt, 100) + fixed = DiffEqSolver(dfx.Heun(), stepsize_controller=stepto) + return fixed(dfx.ODETerm(lambda t, y, args: t), t0, t1, None, 1.0).ys[-1] + + +assert jnp.allclose(final_y(1.0, 0.01), 2.5) # 1 + (2**2 - 1**2) / 2 +assert jnp.allclose(final_y(2.0, -0.01), -0.5) # backward: 1 + (1**2 - 2**2) / 2 +assert jnp.allclose(jax.grad(final_y, argnums=1)(1.0, 0.01), 200.0) # n_steps * t1 +``` + ## What is static, and what retraces `AbstractDiffEqSolver.__call__` is wrapped in `eqx.filter_jit`, so the whole @@ -339,7 +374,8 @@ compile-time constant everywhere it is used. ## Version notes diffraxtra reads `diffrax.diffeqsolve`'s defaults out of its signature at import -time, so `max_steps=4096`, the default `adjoint`, and the default -`stepsize_controller` are diffrax's values, and change when diffrax changes. -`diffrax>=0.6` is the supported floor and is tested in CI; minimum supported -versions follow [SPEC 0](https://scientific-python.org/specs/spec-0000/). +time, so the 4096 that `max_steps="auto"` falls back to, the default `adjoint`, +and the default `stepsize_controller` are diffrax's values, and change when +diffrax changes. `diffrax>=0.6.2` is the supported floor and is tested in CI; +minimum supported versions follow +[SPEC 0](https://scientific-python.org/specs/spec-0000/). diff --git a/src/diffraxtra/__init__.py b/src/diffraxtra/__init__.py index 9e62292..3dc2f53 100644 --- a/src/diffraxtra/__init__.py +++ b/src/diffraxtra/__init__.py @@ -5,6 +5,7 @@ "DiffEqSolver", "AbstractVectorizedDenseInterpolation", "VectorizedDenseInterpolation", + "fixed_steps", ] from ._src import ( @@ -12,6 +13,7 @@ AbstractVectorizedDenseInterpolation, DiffEqSolver, VectorizedDenseInterpolation, + fixed_steps, ) from ._version import ( # noqa: F401 version as __version__, diff --git a/src/diffraxtra/_src/__init__.py b/src/diffraxtra/_src/__init__.py index d4c864e..f715717 100644 --- a/src/diffraxtra/_src/__init__.py +++ b/src/diffraxtra/_src/__init__.py @@ -1,10 +1,13 @@ """Extras for `diffrax`. Private API.""" -__all__ = [ # pylint: disable=R0801 +# pylint: disable=duplicate-code + +__all__ = [ "AbstractDiffEqSolver", "DiffEqSolver", "AbstractVectorizedDenseInterpolation", "VectorizedDenseInterpolation", + "fixed_steps", ] from .diffeq import DiffEqSolver @@ -13,3 +16,4 @@ AbstractVectorizedDenseInterpolation, VectorizedDenseInterpolation, ) +from .steps import fixed_steps diff --git a/src/diffraxtra/_src/diffeq.py b/src/diffraxtra/_src/diffeq.py index 533c8a3..73db1ac 100644 --- a/src/diffraxtra/_src/diffeq.py +++ b/src/diffraxtra/_src/diffeq.py @@ -13,15 +13,14 @@ ] from dataclasses import KW_ONLY -from typing import Any, final +from typing import Any, Literal, final import diffrax as dfx import equinox as eqx -from .diffeq_abc import AbstractDiffEqSolver, params +from .diffeq_abc import AbstractDiffEqSolver, default_max_steps, params default_stepsize_controller = params["stepsize_controller"].default -default_max_steps = params["max_steps"].default default_adjoint = params["adjoint"].default @@ -99,6 +98,47 @@ class DiffEqSolver(AbstractDiffEqSolver): # pylint: disable=R0903,W0223 Array([[0.90483742, 0.81872516], [0.74080871, 0.67031456]], dtype=float64) + With a `diffrax.StepTo` controller, ``max_steps`` defaults to the number of + steps on the grid, ``len(ts) - 1``. Saving every step shows the bound, + because diffrax pads the saved steps out to ``max_steps``. + + >>> grid = jnp.linspace(0, 1, 11) + >>> stepto = DiffEqSolver(dfx.Euler(), stepsize_controller=dfx.StepTo(grid)) + >>> every_step = dfx.SaveAt(steps=True) + >>> stepto(term, t0=0, t1=1, y0=1, saveat=every_step).ys.shape + (10,) + + A ``max_steps`` given to the solver or to the call is used as is. + + >>> stepto(term, t0=0, t1=1, y0=1, saveat=every_step, max_steps=20).ys.shape + (20,) + >>> stepto30 = DiffEqSolver(dfx.Euler(), stepsize_controller=dfx.StepTo(grid), + ... max_steps=30) + >>> stepto30(term, t0=0, t1=1, y0=1, saveat=every_step).ys.shape + (30,) + + Passing ``max_steps="auto"`` to the call asks for the grid's step count + even when the solver holds an integer. + + >>> stepto30(term, t0=0, t1=1, y0=1, saveat=every_step, max_steps="auto").ys.shape + (10,) + + ``max_steps=None`` stays unbounded, so diffrax rejects it when saving + every step. + + >>> stepto(term, t0=0, t1=1, y0=1, saveat=every_step, max_steps=None) + Traceback (most recent call last): + ... + ValueError: `max_steps=None` is incompatible with saving at `steps=... + + Other controllers use diffrax's default. + + >>> solver(term, t0=0, t1=3, dt0=0.1, y0=1, saveat=every_step).ys.shape + (4096,) + + `diffraxtra.fixed_steps` builds a `diffrax.StepTo` grid from ``t0``, + ``dt`` and a number of steps. + """ #: The solver for the differential equation. @@ -121,6 +161,8 @@ class DiffEqSolver(AbstractDiffEqSolver): # pylint: disable=R0903,W0223 event: dfx.Event | None = None #: The maximum number of steps to take before quitting. + #: The default, ``"auto"``, means ``len(ts) - 1`` with a `diffrax.StepTo` + #: controller, and `diffrax.diffeqsolve`'s default otherwise. #: Some `diffrax.SaveAt` options can be incompatible with `max_steps=None`, #: so you can override the `max_steps` argument when calling `DiffEqSolver` - max_steps: int | None = eqx.field(default=default_max_steps, static=True) + max_steps: int | None | Literal["auto"] = eqx.field(default="auto", static=True) diff --git a/src/diffraxtra/_src/diffeq_abc.py b/src/diffraxtra/_src/diffeq_abc.py index ec9426b..f54c44a 100644 --- a/src/diffraxtra/_src/diffeq_abc.py +++ b/src/diffraxtra/_src/diffeq_abc.py @@ -7,13 +7,14 @@ __all__ = [ "AbstractDiffEqSolver", # exported to Public API "params", + "default_max_steps", ] import functools as ft import inspect from collections.abc import Mapping from dataclasses import _MISSING_TYPE, KW_ONLY, MISSING -from typing import Any, TypeAlias +from typing import Any, Literal, TypeAlias import diffrax as dfx import equinox as eqx @@ -34,6 +35,7 @@ default_progress_meter = params["progress_meter"].default default_event = params["event"].default default_throw = params["throw"].default +default_max_steps = params["max_steps"].default class AbstractDiffEqSolver(eqx.Module): @@ -72,9 +74,11 @@ class AbstractDiffEqSolver(eqx.Module): event: eqx.AbstractVar[dfx.Event | None] #: The maximum number of steps to take before quitting. + #: ``"auto"`` means ``len(ts) - 1`` with a `diffrax.StepTo` controller, and + #: `diffrax.diffeqsolve`'s default otherwise. #: Some `diffrax.SaveAt` options can be incompatible with `max_steps=None`, #: so you can override the `max_steps` argument when calling `DiffEqSolver` - max_steps: eqx.AbstractVar[int | None] + max_steps: eqx.AbstractVar[int | None | Literal["auto"]] # ------------------------------------------- @@ -94,7 +98,7 @@ def __call__( # pylint: disable=R0913,R0914,R0917 # Diffrax options saveat: dfx.SaveAt = default_saveat, event: dfx.Event | None | _MISSING_TYPE = MISSING, - max_steps: int | None | _MISSING_TYPE = MISSING, + max_steps: int | None | Literal["auto"] | _MISSING_TYPE = MISSING, throw: bool = default_throw, progress_meter: dfx.AbstractProgressMeter[Any] = default_progress_meter, solver_state: PyTree[ArrayLike] | None = None, @@ -118,6 +122,9 @@ def __call__( # pylint: disable=R0913,R0914,R0917 adjoint: how to differentiate diffeqsolve. event: an event at which to terminate the solve early. max_steps: the maximum number of steps to take before quitting. + Omit it to use the field. ``"auto"`` means ``len(ts) - 1`` + with a `diffrax.StepTo` controller, and diffrax's default + otherwise. throw: whether to raise an exception if the integration fails. progress_meter: a progress meter. solver_state: some initial state for the solver. @@ -130,6 +137,15 @@ def __call__( # pylint: disable=R0913,R0914,R0917 """ # Parse `max_steps`, allowing for it to be overridden. max_steps = self.max_steps if max_steps is MISSING else max_steps + # A `StepTo` grid takes exactly `len(ts) - 1` steps. An exact bound + # matters because `RecursiveCheckpointAdjoint` sizes its checkpoints + # from it. `len(ts)` is a shape, so it is static even under `jit`. + if max_steps == "auto": + max_steps = ( + len(self.stepsize_controller.ts) - 1 + if isinstance(self.stepsize_controller, dfx.StepTo) + else default_max_steps + ) # Parse `event`, allowing for it to be overridden. event = self.event if event is MISSING else event diff --git a/src/diffraxtra/_src/steps.py b/src/diffraxtra/_src/steps.py new file mode 100644 index 0000000..e5d1407 --- /dev/null +++ b/src/diffraxtra/_src/steps.py @@ -0,0 +1,135 @@ +"""Fixed-step grids for `diffrax.StepTo`. + +This module is private. See `diffraxtra` for the public API. + +""" + +__all__ = ["fixed_steps"] # exported to Public API + +import operator + +import diffrax as dfx +import jax +import jax.numpy as jnp +from jaxtyping import Array, ArrayLike, Real + + +# jax < 0.5.3 has no JVP rule for `optimization_barrier`. The barrier is the +# identity, so its tangent passes straight through. +# TODO: call `jax.lax.optimization_barrier` directly once the jax floor is 0.5.3. +@jax.custom_jvp +def _barrier(x: Array) -> Array: + return jax.lax.optimization_barrier(x) # type: ignore[no-untyped-call,no-any-return] + + +@_barrier.defjvp +def _barrier_jvp(primals: tuple[Array], tangents: tuple[Array]) -> tuple[Array, Array]: + return _barrier(*primals), tangents[0] + + +def fixed_steps( + t0: Real[ArrayLike, ""], dt: Real[ArrayLike, ""], n_steps: int, / +) -> tuple[Real[Array, ""], Real[Array, ""], dfx.StepTo, int]: + """Make the grid for ``n_steps`` fixed steps of size ``dt`` from ``t0``. + + The grid is ``t0 + dt * arange(n_steps + 1)``. This returns + ``(t0, t1, stepsize_controller, max_steps)``, ready to pass to + `diffrax.diffeqsolve` with ``dt0=None``. ``t0`` and ``t1`` are the ends of + the grid, the controller is a `diffrax.StepTo` on the grid, and + ``max_steps`` is ``n_steps``. `DiffEqSolver` takes ``max_steps`` from a + `diffrax.StepTo` by itself, so with it you can drop the fourth value. + + The grid is built behind `jax.lax.optimization_barrier`, which stops + XLA's simplifier from rewriting ``t1`` and the grid separately with + different roundings. `diffrax.StepTo` rejects a ``t1`` that is even one + rounding off ``ts[-1]``. + + ``t0`` and ``dt`` can be traced, so this works under `jax.jit`, + `jax.vmap` and `jax.grad`. ``n_steps`` sets the shape of the grid, so it + must be a concrete integer. A negative ``dt`` runs backward in time. + ``t0`` and ``dt`` must be scalars. To run several grids, `jax.vmap` over + them. + + Examples + -------- + >>> import jax + >>> import jax.numpy as jnp + >>> import diffrax as dfx + >>> from diffraxtra import DiffEqSolver, fixed_steps + + >>> t0, t1, stepto, max_steps = fixed_steps(0.0, 0.25, 4) + >>> t0, t1, max_steps + (Array(0., dtype=float64...), Array(1., dtype=float64...), 4) + >>> stepto.ts + Array([0. , 0.25, 0.5 , 0.75, 1. ], dtype=float64...) + + Solve ``dy/dt = t`` with `diffrax.diffeqsolve`. Heun's method is exact on + it, so ``y(t1) = y0 + (t1**2 - t0**2) / 2``. + + >>> term = dfx.ODETerm(lambda t, y, args: t) + >>> soln = dfx.diffeqsolve(term, dfx.Heun(), t0, t1, None, 1.0, + ... stepsize_controller=stepto, max_steps=max_steps) + >>> soln.ys + Array([1.5], dtype=float64) + >>> soln.stats["num_steps"] + Array(4, dtype=...) + + A negative ``dt`` runs backward, here from 1 to 0. + + >>> t0, t1, stepto, _ = fixed_steps(1.0, -0.25, 4) + >>> solver = DiffEqSolver(dfx.Heun(), stepsize_controller=stepto) + >>> soln = solver(term, t0, t1, None, 1.5) + >>> soln.ts, soln.ys + (Array([0.], dtype=float64), Array([1.], dtype=float64)) + + ``t0`` and ``dt`` can be traced. Here ``t1 = t0 + 100 dt``, so the + derivatives of ``y(t1)`` are ``t1 - t0 = 1`` for ``t0`` and + ``100 t1 = 200`` for ``dt``. + + >>> @jax.jit + ... def y1(t0, dt): + ... t0, t1, stepto, _ = fixed_steps(t0, dt, 100) + ... solver = DiffEqSolver(dfx.Heun(), stepsize_controller=stepto) + ... return solver(term, t0, t1, None, 1.0).ys[-1] + >>> y1(1.0, 0.01) + Array(2.5, dtype=float64) + >>> jnp.round(jnp.stack(jax.grad(y1, argnums=(0, 1))(1.0, 0.01)), 8) + Array([ 1., 200.], dtype=float64) + >>> jnp.round(jax.vmap(y1, in_axes=(0, None))(jnp.array([0.0, 1.0]), 0.01), 8) + Array([1.5, 2.5], dtype=float64) + + ``n_steps`` must be at least 1. + + >>> fixed_steps(0.0, 0.1, 0) + Traceback (most recent call last): + ... + ValueError: n_steps must be at least 1, got 0 + + >>> fixed_steps(jnp.array([0.0, 1.0, 2.0]), 0.1, 2) + Traceback (most recent call last): + ... + ValueError: t0 and dt must be scalars, got shapes (3,) and () + >>> fixed_steps(0.0, jnp.array([0.1, 0.2, 0.3]), 2) + Traceback (most recent call last): + ... + ValueError: t0 and dt must be scalars, got shapes () and (3,) + + ``n_steps`` must be an integer. + + >>> fixed_steps(0.0, 0.1, 2.5) + Traceback (most recent call last): + ... + TypeError: 'float' object cannot be interpreted as an integer + + """ + n_steps = operator.index(n_steps) + if n_steps < 1: + msg = f"n_steps must be at least 1, got {n_steps}" + raise ValueError(msg) + if jnp.ndim(t0) or jnp.ndim(dt): + msg = ( + f"t0 and dt must be scalars, got shapes {jnp.shape(t0)} and {jnp.shape(dt)}" + ) + raise ValueError(msg) + grid = _barrier(t0 + dt * jnp.arange(n_steps + 1)) + return grid[0], grid[-1], dfx.StepTo(ts=grid), n_steps diff --git a/uv.lock b/uv.lock index 957b812..34011e6 100644 --- a/uv.lock +++ b/uv.lock @@ -17,7 +17,6 @@ constraints = [ { name = "decorator", specifier = ">=5.1" }, { name = "future", specifier = ">=0.16.0" }, { name = "iniconfig", specifier = ">=0.1.0" }, - { name = "jax", specifier = ">0.4.34" }, { name = "matplotlib", specifier = ">=3.10" }, { name = "nest-asyncio", specifier = ">=0.1.0" }, { name = "opt-einsum", specifier = ">=3.3.0" }, @@ -722,8 +721,8 @@ test = [ [package.metadata] requires-dist = [ - { name = "diffrax", specifier = ">=0.6" }, - { name = "equinox", specifier = ">=0.11.5" }, + { name = "diffrax", specifier = ">=0.6.2" }, + { name = "equinox", specifier = ">=0.11.10" }, { name = "jaxtyping", specifier = ">=0.2.35" }, { name = "plum-dispatch", specifier = ">=2.5.7" }, { name = "typing-extensions", specifier = ">=4.12.2" },