{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# PINN Solution of the Nonlinear Shroedinger PDE\n",
    "\n",
    "This PyTorch code demonstrates the application of physically-informed neural networks (PINN) in the solution of a well-known Nonlinear Shroedinger PDE with periodic boundary condition\n",
    "\\begin{aligned}\n",
    "  &\\mathbf{u}_t = i * \\mathbf{u}_{xx} + i * |\\mathbf{u}|^2 * \\mathbf{u} \\in [0, T]\\times[-L, L]\\\\\n",
    "  &\\mathbf{u}(0, x) = \\mathbf{u}_0(x), \\quad \\forall x \\in [-L, L] \\\\\n",
    "  &\\mathbf{u}(t, -L) = \\mathbf{u}(t, L), \\quad \\forall t \\in [0, T]\n",
    "\\end{aligned}\n",
    "where $i^2 = -1$, and $[-L, L]$ covers one full period, i.e. $T = 2L$.  If we let $\\mathbf{u} = u + i * v$, then we obtain two PDEs\n",
    "\\begin{aligned}\n",
    "u_t &= -v_{xx} - (u^2 + v^2) * v \\\\\n",
    "v_t &= u_{xx} + (u^2 + v^2) * u\n",
    "\\end{aligned}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Libraries and Dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from itertools import chain\n",
    "from collections import OrderedDict\n",
    "import time\n",
    "import numpy as np\n",
    "import scipy as sp\n",
    "import scipy.io\n",
    "from scipy.interpolate import griddata\n",
    "from pyDOE import lhs\n",
    "import torch\n",
    "import torch.optim\n",
    "import torch.optim.lr_scheduler as lr_scheduler\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt\n",
    "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
    "import matplotlib.gridspec as gridspec\n",
    "np.random.seed(1234)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Working on mps\n"
     ]
    }
   ],
   "source": [
    "if torch.backends.mps.is_available():\n",
    "    device = torch.device('mps')\n",
    "elif torch.cuda.is_available():\n",
    "    device = torch.device('cuda')\n",
    "else:\n",
    "    device = torch.device('cpu')\n",
    "#\n",
    "print(f\"Working on {device}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "L = np.pi\n",
    "xlo = -L\n",
    "xhi = L\n",
    "period = xhi - xlo\n",
    "tlo = 0.0\n",
    "thi = 2.0\n",
    "sqrt2 = torch.tensor(np.sqrt(2)).float().to(device)\n",
    "# taking A = 1 and B = 1\n",
    "u0 = lambda x: 2.0/(2.0 - np.sqrt(2) * np.cos(x)) - 1.0\n",
    "v0 = lambda x: np.zeros_like(x)\n",
    "u0_ten = lambda x: 2.0/(2.0 - sqrt2 * torch.cos(x)) - 1.0\n",
    "v0_ten = lambda x: torch.zeros_like(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Physics-informed Neural Networks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# the deep neural network\n",
    "class DNN(torch.nn.Module):\n",
    "    def __init__(self, layers):\n",
    "        super(DNN, self).__init__()\n",
    "        # parameters\n",
    "        self.depth = len(layers) - 1\n",
    "        # set up layer order dict\n",
    "        self.activation = torch.nn.Tanh\n",
    "        layer_list = list()\n",
    "        for i in range(self.depth - 1): \n",
    "            layer_list.append(\n",
    "                ('layer_%d' % i, torch.nn.Linear(layers[i], layers[i+1]))\n",
    "            )\n",
    "            layer_list.append(('activation_%d' % i, self.activation()))\n",
    "            \n",
    "        layer_list.append(\n",
    "            ('layer_%d' % (self.depth - 1), torch.nn.Linear(layers[-2], layers[-1]))\n",
    "        )\n",
    "        layerDict = OrderedDict(layer_list)\n",
    "        # deploy layers\n",
    "        self.layers = torch.nn.Sequential(layerDict)\n",
    "        self.layers[0].weight = torch.load('initial_weight.pt')\n",
    "    def forward(self, x):\n",
    "        out = self.layers(x)\n",
    "        return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "class PhysicsInformedNN():\n",
    "    def __init__(self, period, X_BC,u_BC, v_BC, X_PDE, layers):\n",
    "       \n",
    "        # BC data point\n",
    "        self.t_BC = torch.tensor(X_BC[:, 0:1]).float().to(device)\n",
    "        self.x_BC = torch.tensor(X_BC[:, 1:2]).float().to(device)\n",
    "        self.u_BC = torch.tensor(u_BC).float().to(device)\n",
    "        self.v_BC = torch.tensor(v_BC).float().to(device)\n",
    "        self.period = torch.tensor(period).float().to(device)\n",
    "        # PDE data, gradients will be computed on these points so requires_grad = True\n",
    "        self.t_PDE = torch.tensor(X_PDE[:, 0:1], requires_grad=True).float().to(device)\n",
    "        self.x_PDE = torch.tensor(X_PDE[:, 1:2], requires_grad=True).float().to(device)\n",
    "        \n",
    "        # deep neural networks\n",
    "        self.dnn = DNN(layers).to(device)    \n",
    "        # prepare the optimizer\n",
    "        self.optimizer_Adam = torch.optim.Adam(self.dnn.parameters(), lr = 1e-3)\n",
    "        # add a learning rate scheduler\n",
    "        self.optimizer_LBFGS = torch.optim.LBFGS(\n",
    "            self.dnn.parameters(), \n",
    "            lr=1.0, \n",
    "            max_iter=10000, \n",
    "            max_eval=5000, \n",
    "            history_size=50,\n",
    "            tolerance_grad=1e-7, \n",
    "            tolerance_change=1.0 * np.finfo(float).eps,\n",
    "            line_search_fn=\"strong_wolfe\"       # can be \"strong_wolfe\"\n",
    "        )      \n",
    "        self.scheduler = lr_scheduler.ExponentialLR(self.optimizer_Adam, gamma=0.99)\n",
    "        self.iter = 0\n",
    "    # evaluater neural network, no transformation\n",
    "    def NN_eval(self, t, x): \n",
    "        NN = self.dnn(torch.cat([t, x], dim = 1)) \n",
    "        u = NN[:, 0][:, None]\n",
    "        v = NN[:, 1][:, None]\n",
    "        u0_torch = u0_ten(x)\n",
    "        v0_torch = v0_ten(x)\n",
    "        unew = u0_torch*torch.exp(-0.1*t) + t * u\n",
    "        vnew = v0_torch*torch.exp(-0.1*t) + t * v\n",
    "        return unew,vnew\n",
    "    # compute the PDE\n",
    "    def pde_eval(self, t, x):\n",
    "        \"\"\" The pytorch autograd version of calculating residual \"\"\"\n",
    "        u, v = self.NN_eval(t, x)\n",
    "        # compute the derivatives for u\n",
    "        u_t    = torch.autograd.grad(u,     t, grad_outputs = torch.ones_like(u), retain_graph = True, create_graph=True)[0]\n",
    "        u_x    = torch.autograd.grad(u,     x, grad_outputs = torch.ones_like(u), retain_graph = True, create_graph=True)[0]\n",
    "        u_xx   = torch.autograd.grad(u_x,   x, grad_outputs = torch.ones_like(u), retain_graph = True, create_graph=True)[0]\n",
    "        v_t    = torch.autograd.grad(v,     t, grad_outputs = torch.ones_like(u), retain_graph = True, create_graph=True)[0]\n",
    "        v_x    = torch.autograd.grad(v,     x, grad_outputs = torch.ones_like(u), retain_graph = True, create_graph=True)[0]\n",
    "        v_xx   = torch.autograd.grad(v_x,   x, grad_outputs = torch.ones_like(u), retain_graph = True, create_graph=True)[0]   \n",
    "        # pre-compute the norm of \\mathbf{u}, so that it can be re-used\n",
    "        U_norm = torch.pow(u, 2.0) + torch.pow(v, 2.0)\n",
    "        Eq1    = u_t + v_xx + U_norm * v\n",
    "        Eq2    = v_t - u_xx - U_norm * u\n",
    "        return Eq1, Eq2\n",
    "    # compute the total loss for the second-order optimizer\n",
    "    def loss_func(self):\n",
    "        # reset the gradient\n",
    "        self.optimizer_LBFGS.zero_grad()\n",
    "\n",
    "        \n",
    "        # compute PBC loss\n",
    "        uBC_pred_left, vBC_pred_left = self.NN_eval(self.t_BC, self.x_BC)\n",
    "        uBC_pred_right, vBC_pred_right = self.NN_eval(self.t_BC, self.x_BC+self.period)\n",
    "        loss_BC = torch.mean(( uBC_pred_left - uBC_pred_right)**2.0) + torch.mean((vBC_pred_left - vBC_pred_right)**2.0)\n",
    "        \n",
    "        # compute PDE loss\n",
    "        pde1_pred, pde2_pred = self.pde_eval(self.t_PDE, self.x_PDE)\n",
    "        loss_PDE = torch.mean(pde1_pred ** 2) + torch.mean(pde2_pred ** 2)   \n",
    " \n",
    "        # compute the total loss, it can be weighted\n",
    "        loss =  loss_BC + loss_PDE\n",
    "        # backward propagation\n",
    "        loss.backward()\n",
    "        # increase the iteration counter\n",
    "        self.iter += 1\n",
    "        # output\n",
    "        # output the progress\n",
    "        if self.iter % 1000 == 0:\n",
    "            end_time = time.time()\n",
    "            print('Iter %5d, Total: %10.4e, Time: %.2f secs' % (self.iter, loss.item(), end_time - self.start_time))\n",
    "            print('PBC: %10.4e, PDE: %10.4e' % (loss_BC.item(), loss_PDE.item()))\n",
    "            self.start_time = end_time\n",
    "        return loss\n",
    "    #\n",
    "    def train(self, nIter):\n",
    "        # start the timer\n",
    "        start_time = time.time()        \n",
    "        # start the training with Adam first\n",
    "        self.dnn.train()\n",
    "        print('Starting with Adam')\n",
    "        for epoch in range(nIter):\n",
    "          \n",
    "            # compute PBC loss\n",
    "            uBC_pred_left, vBC_pred_left = self.NN_eval(self.t_BC, self.x_BC)\n",
    "            uBC_pred_right, vBC_pred_right = self.NN_eval(self.t_BC, self.x_BC+self.period)\n",
    "            loss_BC = torch.mean(( uBC_pred_left - uBC_pred_right)**2.0) + torch.mean((vBC_pred_left - vBC_pred_right)**2.0)\n",
    "        \n",
    "       \n",
    "        # compute PDE loss\n",
    "            pde1_pred, pde2_pred = self.pde_eval(self.t_PDE, self.x_PDE)\n",
    "            loss_PDE = torch.mean(pde1_pred ** 2) + torch.mean(pde2_pred ** 2)   \n",
    "  \n",
    "            # compute the total loss, it can be weighted\n",
    "            loss =  loss_BC + loss_PDE\n",
    "            # Backward and optimize\n",
    "            self.optimizer_Adam.zero_grad()\n",
    "            loss.backward()\n",
    "            self.optimizer_Adam.step() \n",
    "            # output the progress\n",
    "            if (epoch + 1) % 1000 == 0:\n",
    "                end_time = time.time()\n",
    "                print('Iter %5d, Total: %10.4e, Time: %.2f secs' % (epoch + 1, loss.item(), end_time - start_time))\n",
    "                print('PBC: %10.4e, PDE: %10.4e' % ( loss_BC.item(), loss_PDE.item()))\n",
    "                start_time = end_time\n",
    "                # change the learning rate\n",
    "                self.scheduler.step()\n",
    "  \n",
    "        self.start_time = time.time()\n",
    "        self.optimizer_LBFGS.step(self.loss_func)    \n",
    "   \n",
    "    def predict(self, X):\n",
    "        t = torch.tensor(X[:, 0:1], requires_grad=True).float().to(device)\n",
    "        x = torch.tensor(X[:, 1:2], requires_grad=True).float().to(device)\n",
    "        self.dnn.eval()\n",
    "        u, v = self.NN_eval(t, x)\n",
    "        u = u.detach().cpu().numpy()\n",
    "        v = v.detach().cpu().numpy()\n",
    "        return u,v\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Training"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting with Adam\n",
      "Iter  1000, Total: 2.2908e-02, Time: 153.64 secs\n",
      "PBC: 3.6763e-05, PDE: 2.2871e-02\n",
      "Iter  2000, Total: 1.1369e-02, Time: 153.57 secs\n",
      "PBC: 1.2758e-04, PDE: 1.1242e-02\n",
      "Iter  3000, Total: 1.1457e-02, Time: 153.67 secs\n",
      "PBC: 6.6898e-05, PDE: 1.1390e-02\n",
      "Iter  4000, Total: 6.4013e-03, Time: 154.73 secs\n",
      "PBC: 2.1391e-05, PDE: 6.3799e-03\n",
      "Iter  5000, Total: 4.1863e-03, Time: 153.80 secs\n",
      "PBC: 1.3407e-03, PDE: 2.8456e-03\n",
      "Iter  6000, Total: 4.7363e-03, Time: 153.43 secs\n",
      "PBC: 8.3235e-04, PDE: 3.9040e-03\n",
      "Iter  7000, Total: 4.3045e-03, Time: 153.20 secs\n",
      "PBC: 4.1257e-04, PDE: 3.8920e-03\n",
      "Iter  8000, Total: 3.6826e-03, Time: 153.58 secs\n",
      "PBC: 1.4205e-03, PDE: 2.2621e-03\n",
      "Iter  9000, Total: 2.5360e-03, Time: 153.55 secs\n",
      "PBC: 5.5412e-04, PDE: 1.9819e-03\n",
      "Iter 10000, Total: 2.4564e-03, Time: 154.62 secs\n",
      "PBC: 2.3885e-04, PDE: 2.2176e-03\n",
      "Iter 11000, Total: 1.8499e-03, Time: 154.92 secs\n",
      "PBC: 9.1800e-05, PDE: 1.7581e-03\n",
      "Iter 12000, Total: 1.5816e-03, Time: 154.33 secs\n",
      "PBC: 2.1503e-04, PDE: 1.3666e-03\n",
      "Iter 13000, Total: 1.9130e-03, Time: 155.41 secs\n",
      "PBC: 8.0490e-04, PDE: 1.1081e-03\n",
      "Iter 14000, Total: 7.8098e-04, Time: 153.66 secs\n",
      "PBC: 1.2635e-04, PDE: 6.5464e-04\n",
      "Iter 15000, Total: 1.3110e-03, Time: 154.15 secs\n",
      "PBC: 7.7708e-05, PDE: 1.2333e-03\n",
      "Iter 16000, Total: 9.5230e-04, Time: 154.62 secs\n",
      "PBC: 1.6685e-05, PDE: 9.3561e-04\n",
      "Iter 17000, Total: 1.3586e-03, Time: 155.12 secs\n",
      "PBC: 6.9014e-04, PDE: 6.6849e-04\n",
      "Iter 18000, Total: 5.0204e-04, Time: 153.01 secs\n",
      "PBC: 2.6808e-05, PDE: 4.7523e-04\n",
      "Iter 19000, Total: 3.6958e-04, Time: 154.50 secs\n",
      "PBC: 1.3944e-05, PDE: 3.5564e-04\n",
      "Iter 20000, Total: 3.6688e-04, Time: 155.09 secs\n",
      "PBC: 5.0549e-05, PDE: 3.1633e-04\n",
      "Iter 21000, Total: 1.1121e-03, Time: 155.36 secs\n",
      "PBC: 2.7068e-04, PDE: 8.4139e-04\n",
      "Iter 22000, Total: 4.5729e-04, Time: 154.94 secs\n",
      "PBC: 8.9565e-05, PDE: 3.6772e-04\n",
      "Iter 23000, Total: 3.5207e-03, Time: 154.66 secs\n",
      "PBC: 1.8493e-03, PDE: 1.6714e-03\n",
      "Iter 24000, Total: 4.9553e-04, Time: 154.38 secs\n",
      "PBC: 1.7387e-04, PDE: 3.2166e-04\n",
      "Iter 25000, Total: 1.0853e-03, Time: 149.27 secs\n",
      "PBC: 1.7268e-04, PDE: 9.1261e-04\n",
      "Iter 26000, Total: 4.5627e-04, Time: 148.24 secs\n",
      "PBC: 3.0115e-05, PDE: 4.2615e-04\n",
      "Iter 27000, Total: 5.0347e-04, Time: 143.23 secs\n",
      "PBC: 6.0308e-06, PDE: 4.9743e-04\n",
      "Iter 28000, Total: 5.5664e-04, Time: 141.90 secs\n",
      "PBC: 6.5879e-05, PDE: 4.9076e-04\n",
      "Iter 29000, Total: 3.1991e-04, Time: 144.15 secs\n",
      "PBC: 1.5917e-06, PDE: 3.1832e-04\n",
      "Iter 30000, Total: 4.2131e-04, Time: 142.43 secs\n",
      "PBC: 4.2576e-05, PDE: 3.7873e-04\n",
      "Iter 31000, Total: 6.9448e-03, Time: 143.76 secs\n",
      "PBC: 8.1352e-04, PDE: 6.1312e-03\n",
      "Iter 32000, Total: 5.5833e-04, Time: 144.47 secs\n",
      "PBC: 2.0122e-04, PDE: 3.5711e-04\n",
      "Iter 33000, Total: 5.8959e-04, Time: 141.48 secs\n",
      "PBC: 6.3090e-05, PDE: 5.2650e-04\n",
      "Iter 34000, Total: 4.3024e-04, Time: 143.67 secs\n",
      "PBC: 1.6760e-04, PDE: 2.6264e-04\n",
      "Iter 35000, Total: 5.6112e-04, Time: 142.46 secs\n",
      "PBC: 5.1989e-05, PDE: 5.0913e-04\n",
      "Iter 36000, Total: 2.1379e-04, Time: 143.16 secs\n",
      "PBC: 3.3705e-06, PDE: 2.1042e-04\n",
      "Iter 37000, Total: 3.5114e-04, Time: 141.01 secs\n",
      "PBC: 9.5440e-05, PDE: 2.5570e-04\n",
      "Iter 38000, Total: 1.7310e-04, Time: 142.39 secs\n",
      "PBC: 4.0196e-06, PDE: 1.6908e-04\n",
      "Iter 39000, Total: 3.0678e-04, Time: 144.97 secs\n",
      "PBC: 2.0469e-05, PDE: 2.8631e-04\n",
      "Iter 40000, Total: 1.5974e-04, Time: 141.98 secs\n",
      "PBC: 9.5408e-06, PDE: 1.5020e-04\n",
      "Iter 41000, Total: 1.5377e-03, Time: 145.95 secs\n",
      "PBC: 2.1427e-04, PDE: 1.3234e-03\n",
      "Iter 42000, Total: 1.6001e-04, Time: 141.11 secs\n",
      "PBC: 6.2849e-06, PDE: 1.5372e-04\n",
      "Iter 43000, Total: 1.2779e-04, Time: 144.03 secs\n",
      "PBC: 5.5666e-06, PDE: 1.2222e-04\n",
      "Iter 44000, Total: 2.5854e-04, Time: 144.04 secs\n",
      "PBC: 8.2665e-05, PDE: 1.7588e-04\n",
      "Iter 45000, Total: 1.0537e-04, Time: 142.09 secs\n",
      "PBC: 2.7915e-06, PDE: 1.0258e-04\n",
      "Iter 46000, Total: 1.1980e-04, Time: 143.11 secs\n",
      "PBC: 5.0467e-06, PDE: 1.1476e-04\n",
      "Iter 47000, Total: 1.1410e-04, Time: 142.37 secs\n",
      "PBC: 1.1106e-05, PDE: 1.0300e-04\n",
      "Iter 48000, Total: 3.0086e-04, Time: 144.51 secs\n",
      "PBC: 9.2820e-05, PDE: 2.0804e-04\n",
      "Iter 49000, Total: 1.1021e-04, Time: 142.28 secs\n",
      "PBC: 5.7335e-06, PDE: 1.0448e-04\n",
      "Iter 50000, Total: 1.2912e-03, Time: 138.07 secs\n",
      "PBC: 1.2892e-04, PDE: 1.1623e-03\n"
     ]
    }
   ],
   "source": [
    "layers = [2, 32, 32, 32, 32, 32, 32, 32, 2]\n",
    "N_IC = 96\n",
    "ptsIC=np.load('ptsIC.npy')\n",
    "ptsBC=np.load('ptsBC.npy')\n",
    "ptsPDE=np.load('random_data.npy')\n",
    "ptsPDE = np.vstack((ptsPDE,ptsIC))\n",
    "x_IC = np.expand_dims(np.linspace(xlo, xhi, N_IC), axis = 1)\n",
    "uIC = u0(x_IC)\n",
    "vIC = v0(x_IC)\n",
    "uBC = np.load('uBC.npy')\n",
    "vBC = np.load('vBC.npy')\n",
    "model = PhysicsInformedNN(period,  ptsBC, uBC, vBC, ptsPDE, layers)\n",
    "model.train(50000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "# apply PINN to the same grid as the quadrature solution for comparison\n",
    "t = np.linspace(tlo, thi, 201)\n",
    "x = np.linspace(xlo, xhi, 501)\n",
    "T, X = np.meshgrid(t, x)\n",
    "pts_flat = np.hstack((T.flatten()[:, None], X.flatten()[:, None]))\n",
    "u_pred, v_pred = model.predict(pts_flat)           \n",
    "u_pred = griddata(pts_flat, u_pred.flatten(), (T, X), method='cubic')\n",
    "v_pred = griddata(pts_flat, v_pred.flatten(), (T, X), method='cubic')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizations"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = scipy.io.loadmat('Data/NLS.mat')\n",
    "t = data['t'].flatten()[:,None]\n",
    "x2 = data['x'].flatten()[:,None]\n",
    "u_sol = np.real(data['Exact']).T\n",
    "v_sol = np.imag(data['Exact']).T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "def relative_error_l2(pred,exact):\n",
    "    error_l2 = np.sqrt(np.sum(np.power(pred - exact,2)))\n",
    "    relative = error_l2/np.sqrt(np.sum(np.power(exact,2)))\n",
    "    return relative\n",
    "def relative_error_l1(pred,exact):\n",
    "    error_l1 = np.sum(np.abs(pred-exact))\n",
    "    relative = error_l1/np.sum(np.abs(exact))\n",
    "    return relative\n",
    "def relative_error_linf(pred,exact):\n",
    "    error_linf = np.max(np.abs(pred-exact))\n",
    "    relative = error_linf/np.max(np.abs(exact))\n",
    "    return relative"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "l2: 0.050363556889343276\n",
      "l1: 0.03730460577480075\n",
      "linf: 0.05974554304436736\n"
     ]
    }
   ],
   "source": [
    "print(f'l2: {relative_error_l2(u_pred.T,u_sol)}')\n",
    "print(f'l1: {relative_error_l1(u_pred.T,u_sol)}')\n",
    "print(f'linf: {relative_error_linf(u_pred.T,u_sol)}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "l2: 0.12098751241795912\n",
      "l1: 0.09319874591644131\n",
      "linf: 0.22219351595836584\n"
     ]
    }
   ],
   "source": [
    "print(f'l2: {relative_error_l2(-v_pred.T,v_sol)}')\n",
    "print(f'l1: {relative_error_l1(-v_pred.T,v_sol)}')\n",
    "print(f'linf: {relative_error_linf(-v_pred.T,v_sol)}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
