Skip to content

Laplace 1-D with a PINN

PINN laplace_1d.py

The smallest complete jNO example: a neural network learns the solution of the 1-D Laplace equation between two fixed end values. The boundary values are built into the network's output, so training only has to remove what is left over.

Two stacked panels over x from 0 to 1. Top: the network output u(x) as an orange line on top of the exact line u = x, indistinguishable at every epoch. Bottom: the correction u - x in units of 1e-3 shrinking from a few thousandths to zero as the epoch counter runs from 0 to 5000.

Top: the network on the exact line. Bottom: what is left, \(u-x\), shrinking from a few \(10^{-3}\) to zero over 5000 epochs (spaced logarithmically).

The problem

\[u''(x) = 0,\qquad x\in[0,1],\qquad u(0)=0,\quad u(1)=1,\]

with the exact solution \(u=x\).

The jNO code

The interval is a curve built with the Path DSL:

run = jno.setup(__file__)
d = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.1).domain()
x, _ = d.variable("interior")

The network output is a lift plus a bubble: \(x\) meets both boundary values, and \(x(1-x)\) vanishes at both ends, so whatever the network learns cannot break them. Bound to its coordinate, u.xx is \(u''\), written as on paper:

net = jno.nn(foundax.mlp(in_features=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(optax.exponential_decay(1e-3, 10, 0.5, end_value=1e-5)))

u = (x + x * (1 - x) * net(x)).scalar.bind(x=x)  # hard boundary values: line + bubble * net

The loss is the mean square of the residual:

crux = jno.core([u.xx.mse])  # u'' = 0
crux.solve(5000)

Result

After 5000 epochs the network matches \(u=x\) to rel. \(L^2\approx2.4\times10^{-6}\). The exact solution lies in the trial space, so the error is set by the training alone.

Full script

The whole script, as it runs in the tests
"""1-D Laplace equation, u'' = 0 on [0, 1] with u(0) = 0, u(1) = 1: the smallest PINN."""

import foundax
import jax
import jax.numpy as jnp
import optax

import jno

run = jno.setup(__file__)
d = jno.Path(0.0, 0.0).line_to(1.0, 0.0).curve(size=0.1).domain()
x, _ = d.variable("interior")

net = jno.nn(foundax.mlp(in_features=1, hidden_dims=32, num_layers=3, key=jax.random.PRNGKey(0)))
net.optimizer(optax.adam(optax.exponential_decay(1e-3, 10, 0.5, end_value=1e-5)))

u = (x + x * (1 - x) * net(x)).scalar.bind(x=x)  # hard boundary values: line + bubble * net
crux = jno.core([u.xx.mse])  # u'' = 0
crux.solve(5000)

u_h, u_ex = crux.eval([u, x])  # exact solution u = x
rel_l2 = float(jnp.linalg.norm(u_h - u_ex) / jnp.linalg.norm(u_ex))
print(f"Relative L2 error: {rel_l2:.4e}")
assert rel_l2 < 1e-1, f"relative L2 error too large: {rel_l2:.3e}"