Forward-mode AD through the JAX solver#
Goal: Differentiate a scalar of the final 1-D shallow-water state with respect to the Manning n by jax.jvp and check it against finite differences.
Prerequisite: A 1-D mesh
import numpy as np
import matplotlib.pyplot as plt
import jax
jax.config.update("jax_enable_x64", True)
import jax.numpy as jnp
import zoomy_core.model.boundary_conditions as BC
import zoomy_core.model.initial_conditions as IC
from zoomy_core.mesh import LSQMesh
from zoomy_core.model.models import SME
from zoomy_core.model.models.closures import ManningFriction, Newtonian, StressFree
from zoomy_core.numerics import NumericalSystemModel, ReconstructionSpec
from zoomy_core.systemmodel import SystemModel
from zoomy_jax.symsolver.solver import AdMode, SymbolicHyperbolicSolverJax
model = SME(
level=0, dimension=2,
closures=[Newtonian(), ManningFriction(), StressFree()],
boundary_conditions=BC.BoundaryConditions(
[BC.Extrapolation(tag="left"), BC.Extrapolation(tag="right")]),
)
sm = SystemModel.from_model(model)
s, P = sm.fields, sm.parameters
def initial_state(x):
h = 1.0 + 0.2 * np.exp(-(x[0] - 5.0) ** 2)
return {s.h: h, s.q_0: h}
sm.initial_conditions = IC.UserFunction(function=initial_state)
nsm = NumericalSystemModel.from_system_model(sm, reconstruction=ReconstructionSpec(order=1))
mesh = LSQMesh.create_1d(domain=(0.0, 10.0), n_inner_cells=100)
def objective(ad_mode, ad_checkpoints=16):
solver = SymbolicHyperbolicSolverJax(time_end=0.5, dt=1e-2, mood=False,
ad_mode=ad_mode, ad_checkpoints=ad_checkpoints)
Q0, Qaux0 = solver.setup(mesh, nsm)
q = s.slot(s.q_0)
V = solver.mesh.cell_volumes[:Q0.shape[1]]
def final_state(n):
p = {P.n: n}
return solver.run(Q0, solver.initial_aux(Q0, Qaux0, p), parameters=p).Q
def J(n):
return jnp.sum(final_state(n)[q] ** 2 * V)
return jax.jit(J), final_state, solver
J, final_state, solver = objective(AdMode.forward)
n0 = 0.05
Q = np.asarray(final_state(n0))
forward = float(jax.jvp(J, (n0,), (1.0,))[1])
r = 1e-3 * n0
central = float(J(n0 + r) - J(n0 - r)) / (2 * r)
print(f"J = {float(J(n0)):.8f}")
print(f"dJ/dn forward {forward:.8e} central difference {central:.8e}")
J = 10.70960113
dJ/dn forward -1.00101431e+01 central difference -1.00101428e+01
x = mesh.cell_centers[0, :mesh.n_inner_cells]
h0 = [initial_state([xi])[s.h] for xi in x]
fig, ax = plt.subplots(figsize=(6, 2.6))
ax.plot(x, h0, "--", label="t = 0")
ax.plot(x, Q[s.slot(s.h)], label="t = 0.5")
ax.set_xlabel("x")
ax.set_ylabel("h")
ax.legend()
plt.show()
assert abs(forward - central) / abs(forward) < 1e-5