A3. Walltime | Stiff van-der-Pol¶
In [1]:
Copied!
from collections.abc import Callable
from collections.abc import Callable
In [2]:
Copied!
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numba
import numpy as np
import scipy.integrate
import tqdm
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numba
import numpy as np
import scipy.integrate
import tqdm
In [3]:
Copied!
from probdiffeq import ivpsolve, probdiffeq
from probdiffeq.util import benchmark_util
from probdiffeq import ivpsolve, probdiffeq
from probdiffeq.util import benchmark_util
In [4]:
Copied!
# Fail this notebook on NaN detection (to catch those in the CI)
jax.config.update("jax_debug_nans", True)
# Fail this notebook on NaN detection (to catch those in the CI)
jax.config.update("jax_debug_nans", True)
In [5]:
Copied!
def main(start=6.5, stop=10.0, step=0.25, repeats=2) -> None:
"""Run the script."""
# Set up all the configs
jax.config.update("jax_enable_x64", True)
# Simulate once to plot the state
ts, ys = solve_ivp_once()
_fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(ts, ys)
ax.set_ylim((-6, 6))
ax.set_title("Van-der-Pol problem")
ax.set_xlabel("Time")
ax.set_ylabel("State")
plt.tight_layout()
plt.show()
# Read configuration from command line
tolerances = 0.1 ** jnp.arange(start, stop, step=step)
# Compute a reference solution
reference = solver_scipy(method="LSODA", precision_fun=lambda x: x)(
0.1 * tolerances[-1]
)
precision_fun = benchmark_util.rmse_absolute(reference)
# Assemble algorithms
algorithms = {
"TS1(4)": solver_probdiffeq(num_derivatives=4, precision_fun=precision_fun),
"JetTS1(4)": solver_probdiffeq_jet(
num_derivatives=4, precision_fun=precision_fun
),
"TS1(6)": solver_probdiffeq(num_derivatives=6, precision_fun=precision_fun),
"JetTS1(6)": solver_probdiffeq_jet(
num_derivatives=6, precision_fun=precision_fun
),
"SciPy('LSODA')": solver_scipy(method="LSODA", precision_fun=precision_fun),
}
# Compute all work-precision diagrams
_fig, ax = plt.subplots(figsize=(8, 4), dpi=120, constrained_layout=True)
pbar = tqdm.tqdm(algorithms.items())
for label, algo in pbar:
pbar.set_description(label)
param_to_wp = benchmark_util.workprec(algo, num_timing_calls=repeats)
wp = param_to_wp(tolerances)
ax.loglog(wp.precision, wp.work.mean(axis=-1), ".-", label=label)
ax.set_title("Work-precision diagram")
ax.set_xlabel("Precision (relative RMSE)")
ax.set_ylabel("Work (avg. wall time)")
ax.grid(linestyle="dotted", which="both")
ax.legend(loc="center left", frameon=False, bbox_to_anchor=(1, 0.5))
plt.show()
def main(start=6.5, stop=10.0, step=0.25, repeats=2) -> None:
"""Run the script."""
# Set up all the configs
jax.config.update("jax_enable_x64", True)
# Simulate once to plot the state
ts, ys = solve_ivp_once()
_fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(ts, ys)
ax.set_ylim((-6, 6))
ax.set_title("Van-der-Pol problem")
ax.set_xlabel("Time")
ax.set_ylabel("State")
plt.tight_layout()
plt.show()
# Read configuration from command line
tolerances = 0.1 ** jnp.arange(start, stop, step=step)
# Compute a reference solution
reference = solver_scipy(method="LSODA", precision_fun=lambda x: x)(
0.1 * tolerances[-1]
)
precision_fun = benchmark_util.rmse_absolute(reference)
# Assemble algorithms
algorithms = {
"TS1(4)": solver_probdiffeq(num_derivatives=4, precision_fun=precision_fun),
"JetTS1(4)": solver_probdiffeq_jet(
num_derivatives=4, precision_fun=precision_fun
),
"TS1(6)": solver_probdiffeq(num_derivatives=6, precision_fun=precision_fun),
"JetTS1(6)": solver_probdiffeq_jet(
num_derivatives=6, precision_fun=precision_fun
),
"SciPy('LSODA')": solver_scipy(method="LSODA", precision_fun=precision_fun),
}
# Compute all work-precision diagrams
_fig, ax = plt.subplots(figsize=(8, 4), dpi=120, constrained_layout=True)
pbar = tqdm.tqdm(algorithms.items())
for label, algo in pbar:
pbar.set_description(label)
param_to_wp = benchmark_util.workprec(algo, num_timing_calls=repeats)
wp = param_to_wp(tolerances)
ax.loglog(wp.precision, wp.work.mean(axis=-1), ".-", label=label)
ax.set_title("Work-precision diagram")
ax.set_xlabel("Precision (relative RMSE)")
ax.set_ylabel("Work (avg. wall time)")
ax.grid(linestyle="dotted", which="both")
ax.legend(loc="center left", frameon=False, bbox_to_anchor=(1, 0.5))
plt.show()
In [6]:
Copied!
def solve_ivp_once():
"""Compute plotting-values for the IVP."""
@numba.jit(nopython=True)
def vf_scipy(_t, u):
"""Van-der-Pol dynamics as a first-order differential equation."""
return np.asarray([u[1], 1e5 * ((1.0 - u[0] ** 2) * u[1] - u[0])])
u0 = np.concatenate((np.atleast_1d(2.0), np.atleast_1d(0.0)))
time_span = np.asarray((0.0, 6.3))
tol = 1e-12
solution = scipy.integrate.solve_ivp(
vf_scipy, y0=u0, t_span=time_span, atol=1e-3 * tol, rtol=tol, method="LSODA"
)
return solution.t, solution.y.T
def solve_ivp_once():
"""Compute plotting-values for the IVP."""
@numba.jit(nopython=True)
def vf_scipy(_t, u):
"""Van-der-Pol dynamics as a first-order differential equation."""
return np.asarray([u[1], 1e5 * ((1.0 - u[0] ** 2) * u[1] - u[0])])
u0 = np.concatenate((np.atleast_1d(2.0), np.atleast_1d(0.0)))
time_span = np.asarray((0.0, 6.3))
tol = 1e-12
solution = scipy.integrate.solve_ivp(
vf_scipy, y0=u0, t_span=time_span, atol=1e-3 * tol, rtol=tol, method="LSODA"
)
return solution.t, solution.y.T
In [7]:
Copied!
def solver_probdiffeq(*, num_derivatives: int, precision_fun) -> Callable:
"""Construct a solver that wraps ProbDiffEq's solution routines."""
@probdiffeq.ode_order_two
def vf(u, du, *, t): # noqa: ARG001
"""Van-der-Pol dynamics as a second-order differential equation."""
return 1e5 * ((1.0 - u**2) * du - u)
t0, t1 = 0.0, 3.0
u0, du0 = (jnp.asarray(2.0), jnp.asarray(0.0))
t0, t1 = (0.0, 6.3)
@jax.jit
def param_to_solution(tol):
# Build a solver
jetexpand = probdiffeq.jetexpand_ode_padded_scan(num=num_derivatives - 1)
tcoeffs, _ = jetexpand(vf, (u0, du0), t=t0)
ssm = probdiffeq.state_space_model_dense()
iwp = ssm.prior_wiener_integrated(tcoeffs)
ts = ssm.constraint_ode_ts1(vf)
strategy = probdiffeq.strategy_filter()
solver = probdiffeq.solver_dynamic(strategy=strategy, constraint=ts)
error = probdiffeq.error_state_std(constraint=ts)
control = ivpsolve.control_integral()
solve = ivpsolve.solve_adaptive_terminal_values(
solver=solver, error=error, control=control
)
solution = solve(iwp, t0=t0, t1=t1, atol=1e-3 * tol, rtol=tol)
return precision_fun(solution.u.mean[0])
return param_to_solution
def solver_probdiffeq(*, num_derivatives: int, precision_fun) -> Callable:
"""Construct a solver that wraps ProbDiffEq's solution routines."""
@probdiffeq.ode_order_two
def vf(u, du, *, t): # noqa: ARG001
"""Van-der-Pol dynamics as a second-order differential equation."""
return 1e5 * ((1.0 - u**2) * du - u)
t0, t1 = 0.0, 3.0
u0, du0 = (jnp.asarray(2.0), jnp.asarray(0.0))
t0, t1 = (0.0, 6.3)
@jax.jit
def param_to_solution(tol):
# Build a solver
jetexpand = probdiffeq.jetexpand_ode_padded_scan(num=num_derivatives - 1)
tcoeffs, _ = jetexpand(vf, (u0, du0), t=t0)
ssm = probdiffeq.state_space_model_dense()
iwp = ssm.prior_wiener_integrated(tcoeffs)
ts = ssm.constraint_ode_ts1(vf)
strategy = probdiffeq.strategy_filter()
solver = probdiffeq.solver_dynamic(strategy=strategy, constraint=ts)
error = probdiffeq.error_state_std(constraint=ts)
control = ivpsolve.control_integral()
solve = ivpsolve.solve_adaptive_terminal_values(
solver=solver, error=error, control=control
)
solution = solve(iwp, t0=t0, t1=t1, atol=1e-3 * tol, rtol=tol)
return precision_fun(solution.u.mean[0])
return param_to_solution
In [8]:
Copied!
def solver_probdiffeq_jet(*, num_derivatives: int, precision_fun) -> Callable:
"""Construct a solver that wraps ProbDiffEq's solution routines."""
@probdiffeq.ode_order_two
def vf(u, du, *, t): # noqa: ARG001
"""Van-der-Pol dynamics as a second-order differential equation."""
return 1e5 * ((1.0 - u**2) * du - u)
vf = vf.jet_lift(lift_by=num_derivatives - 2)
t0, t1 = 0.0, 3.0
u0, du0 = (jnp.asarray(2.0), jnp.asarray(0.0))
t0, t1 = (0.0, 6.3)
@jax.jit
def param_to_solution(tol):
# Build a solver
ssm = probdiffeq.state_space_model_dense()
iwp = ssm.prior_wiener_integrated(
(u0, du0), diffuse_derivatives=num_derivatives - 1
)
ts = ssm.constraint_ode_ts1(vf)
strategy = probdiffeq.strategy_filter()
solver = probdiffeq.solver_dynamic(strategy=strategy, constraint=ts)
error = probdiffeq.error_state_std(constraint=ts)
control = ivpsolve.control_integral()
solve = ivpsolve.solve_adaptive_terminal_values(
solver=solver, error=error, control=control
)
solution = solve(iwp, t0=t0, t1=t1, atol=1e-3 * tol, rtol=tol)
return precision_fun(solution.u.mean[0])
return param_to_solution
def solver_probdiffeq_jet(*, num_derivatives: int, precision_fun) -> Callable:
"""Construct a solver that wraps ProbDiffEq's solution routines."""
@probdiffeq.ode_order_two
def vf(u, du, *, t): # noqa: ARG001
"""Van-der-Pol dynamics as a second-order differential equation."""
return 1e5 * ((1.0 - u**2) * du - u)
vf = vf.jet_lift(lift_by=num_derivatives - 2)
t0, t1 = 0.0, 3.0
u0, du0 = (jnp.asarray(2.0), jnp.asarray(0.0))
t0, t1 = (0.0, 6.3)
@jax.jit
def param_to_solution(tol):
# Build a solver
ssm = probdiffeq.state_space_model_dense()
iwp = ssm.prior_wiener_integrated(
(u0, du0), diffuse_derivatives=num_derivatives - 1
)
ts = ssm.constraint_ode_ts1(vf)
strategy = probdiffeq.strategy_filter()
solver = probdiffeq.solver_dynamic(strategy=strategy, constraint=ts)
error = probdiffeq.error_state_std(constraint=ts)
control = ivpsolve.control_integral()
solve = ivpsolve.solve_adaptive_terminal_values(
solver=solver, error=error, control=control
)
solution = solve(iwp, t0=t0, t1=t1, atol=1e-3 * tol, rtol=tol)
return precision_fun(solution.u.mean[0])
return param_to_solution
In [9]:
Copied!
def solver_scipy(method: str, precision_fun) -> Callable:
"""Construct a solver that wraps SciPy's solution routines."""
@numba.jit(nopython=True)
def vf_scipy(_t, u):
"""Van-der-Pol dynamics as a first-order differential equation."""
return np.asarray([u[1], 1e5 * ((1.0 - u[0] ** 2) * u[1] - u[0])])
u0 = np.concatenate((np.atleast_1d(2.0), np.atleast_1d(0.0)))
time_span = np.asarray((0.0, 6.3))
def param_to_solution(tol):
solution = scipy.integrate.solve_ivp(
vf_scipy,
y0=u0,
t_span=time_span,
t_eval=time_span,
atol=1e-3 * tol,
rtol=tol,
method=method,
)
return precision_fun(jnp.asarray(solution.y[0, -1]))
return param_to_solution
def solver_scipy(method: str, precision_fun) -> Callable:
"""Construct a solver that wraps SciPy's solution routines."""
@numba.jit(nopython=True)
def vf_scipy(_t, u):
"""Van-der-Pol dynamics as a first-order differential equation."""
return np.asarray([u[1], 1e5 * ((1.0 - u[0] ** 2) * u[1] - u[0])])
u0 = np.concatenate((np.atleast_1d(2.0), np.atleast_1d(0.0)))
time_span = np.asarray((0.0, 6.3))
def param_to_solution(tol):
solution = scipy.integrate.solve_ivp(
vf_scipy,
y0=u0,
t_span=time_span,
t_eval=time_span,
atol=1e-3 * tol,
rtol=tol,
method=method,
)
return precision_fun(jnp.asarray(solution.y[0, -1]))
return param_to_solution
In [10]:
Copied!
main()
main()
0%| | 0/5 [00:00<?, ?it/s]
TS1(4): 0%| | 0/5 [00:00<?, ?it/s]
TS1(4): 20%|██ | 1/5 [00:02<00:09, 2.32s/it]
JetTS1(4): 20%|██ | 1/5 [00:02<00:09, 2.32s/it]
JetTS1(4): 40%|████ | 2/5 [00:04<00:06, 2.16s/it]
TS1(6): 40%|████ | 2/5 [00:04<00:06, 2.16s/it]
TS1(6): 60%|██████ | 3/5 [00:06<00:04, 2.11s/it]
JetTS1(6): 60%|██████ | 3/5 [00:06<00:04, 2.11s/it]
JetTS1(6): 80%|████████ | 4/5 [00:08<00:02, 2.21s/it]
SciPy('LSODA'): 80%|████████ | 4/5 [00:08<00:02, 2.21s/it]
SciPy('LSODA'): 100%|██████████| 5/5 [00:12<00:00, 2.81s/it]
SciPy('LSODA'): 100%|██████████| 5/5 [00:12<00:00, 2.53s/it]