{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "b5c8a1ff",
   "metadata": {},
   "source": [
    "# Notebook 2 · A boundary value problem: PINN vs finite differences\n",
    "\n",
    "*RACM–SciML 2026 · Foundations for Scientific Machine Learning — hands-on notebook.*\n",
    "\n",
    "**How to run:** open [Google Colab](https://colab.research.google.com) → *File → Upload notebook* → choose this file → *Runtime → Run all*. It runs on a CPU in a few minutes; no GPU needed.\n",
    "\n",
    "We solve $-u''(x) = \\pi^2\\sin(\\pi x)$ on $[0,1]$, $u(0)=u(1)=0$. Exact solution: $u=\\sin(\\pi x)$. We compare a PINN with the classical central finite-difference scheme (**Chapters 8, 16, 21**)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5003f0ce",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T04:24:14.494650Z",
     "iopub.status.busy": "2026-11-29T04:24:14.494443Z",
     "iopub.status.idle": "2026-11-29T04:24:15.996396Z",
     "shell.execute_reply": "2026-11-29T04:24:15.994162Z"
    }
   },
   "outputs": [],
   "source": [
    "import torch, numpy as np, matplotlib.pyplot as plt\n",
    "torch.set_default_dtype(torch.float64)   # float64: see Chapter 17, best-practice item 6\n",
    "torch.manual_seed(0); np.random.seed(0)\n",
    "\n",
    "def net(width=32, depth=3):\n",
    "    layers, d = [], 1\n",
    "    for _ in range(depth):\n",
    "        layers += [torch.nn.Linear(d, width), torch.nn.Tanh()]; d = width\n",
    "    layers += [torch.nn.Linear(d, 1)]\n",
    "    return torch.nn.Sequential(*layers)\n",
    "\n",
    "def d(y, x):   # derivative dy/dx by automatic differentiation (Chapter 14)\n",
    "    return torch.autograd.grad(y, x, torch.ones_like(y), create_graph=True)[0]\n",
    "\n",
    "def train(params, loss_fn, adam_steps=3000, lbfgs_steps=300, lr=1e-3, every=1000):\n",
    "    \"\"\"Adam first, then L-BFGS (Chapter 17, best-practice item 5).\"\"\"\n",
    "    opt = torch.optim.Adam(params, lr=lr)\n",
    "    for k in range(adam_steps):\n",
    "        opt.zero_grad(); L = loss_fn(); L.backward(); opt.step()\n",
    "        if k % every == 0: print(f\"Adam {k:5d}  loss = {L.item():.3e}\")\n",
    "    opt = torch.optim.LBFGS(params, max_iter=lbfgs_steps, tolerance_grad=1e-12, tolerance_change=1e-14, line_search_fn=\"strong_wolfe\")\n",
    "    def closure():\n",
    "        opt.zero_grad(); L = loss_fn(); L.backward(); return L\n",
    "    opt.step(closure)\n",
    "    print(f\"after L-BFGS loss = {loss_fn().item():.3e}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "68ee42f0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T04:24:16.000226Z",
     "iopub.status.busy": "2026-11-29T04:24:15.999919Z",
     "iopub.status.idle": "2026-11-29T04:24:23.442559Z",
     "shell.execute_reply": "2026-11-29T04:24:23.441091Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Adam     0  loss = 5.486e+01\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Adam  1000  loss = 3.600e-03\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Adam  2000  loss = 1.144e-03\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "after L-BFGS loss = 6.899e-07\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "x = torch.linspace(0, 1, 50).reshape(-1, 1).requires_grad_(True)\n",
    "f = lambda x: np.pi**2 * torch.sin(np.pi * x)\n",
    "N = net()\n",
    "u = lambda x: x * (1 - x) * N(x)          # hard constraint: u(0) = u(1) = 0\n",
    "def loss():\n",
    "    ux = d(u(x), x); uxx = d(ux, x)\n",
    "    return ((-uxx - f(x))**2).mean()\n",
    "t0 = time.time(); train(list(N.parameters()), loss); t_pinn = time.time() - t0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7a2d8013",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-29T04:24:23.444788Z",
     "iopub.status.busy": "2026-11-29T04:24:23.444389Z",
     "iopub.status.idle": "2026-11-29T04:24:23.487199Z",
     "shell.execute_reply": "2026-11-29T04:24:23.485750Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PINN (50 points, 2209 parameters): max error 2.32e-06, training time 7.4 s\n",
      "FD with   10 unknowns: max error 6.76e-03, time 0.6 ms\n",
      "FD with   50 unknowns: max error 3.16e-04, time 0.3 ms\n",
      "FD with  200 unknowns: max error 2.04e-05, time 1.3 ms\n",
      "FD with 1000 unknowns: max error 8.21e-07, time 31.2 ms\n"
     ]
    }
   ],
   "source": [
    "# finite differences with n interior points: (-u_{i-1} + 2u_i - u_{i+1}) / h^2 = f_i\n",
    "def fd(n):\n",
    "    h = 1/(n+1); xi = np.linspace(h, 1-h, n)\n",
    "    A = (np.diag(2*np.ones(n)) - np.diag(np.ones(n-1), 1) - np.diag(np.ones(n-1), -1)) / h**2\n",
    "    ui = np.linalg.solve(A, np.pi**2*np.sin(np.pi*xi))\n",
    "    return np.abs(ui - np.sin(np.pi*xi)).max()\n",
    "xt = torch.linspace(0, 1, 401).reshape(-1, 1)\n",
    "with torch.no_grad(): ep = (u(xt) - torch.sin(np.pi*xt)).abs().max().item()\n",
    "print(f\"PINN (50 points, {sum(p.numel() for p in N.parameters())} parameters): max error {ep:.2e}, training time {t_pinn:.1f} s\")\n",
    "for n in [10, 50, 200, 1000]:\n",
    "    t0 = time.time(); e = fd(n); print(f\"FD with {n:4d} unknowns: max error {e:.2e}, time {1000*(time.time()-t0):.1f} ms\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8eff541e",
   "metadata": {},
   "source": [
    "**What to notice.** On this smooth problem the trained PINN is accurate. But compare the *cost*: finite differences reach similar accuracy in milliseconds, with a guaranteed $O(h^2)$ rate (halve $h$, the error drops by 4), and no training that can fail. The PINN needed thousands of optimisation steps, and its accuracy depends on the seed and settings. For one forward problem in 1-D the classical method is the better tool — as Chapter 21 explains. PINNs pay off for inverse problems, data assimilation and high dimension (Notebook 3).\n",
    "\n",
    "## Try this\n",
    "1. Replace the right-hand side by $\\pi^2 k^2\\sin(k\\pi x)$ with $k=4$ (exact $\\sin(4\\pi x)$). Does the PINN still learn it? This is *spectral bias* (Chapter 15).\n",
    "2. Add Fourier features: feed $[\\sin(\\pi x), \\cos(\\pi x), \\dots]$ as inputs."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
