{
 "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": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.optim\n",
    "import torch.optim.lr_scheduler as lr_scheduler\n",
    "from itertools import chain\n",
    "from collections import OrderedDict\n",
    "from pyDOE import lhs\n",
    "import numpy as np\n",
    "import matplotlib as mpl\n",
    "import matplotlib.pyplot as plt\n",
    "import scipy.io\n",
    "from scipy.interpolate import griddata\n",
    "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
    "import matplotlib.gridspec as gridspec\n",
    "import time\n",
    "# set the random seed\n",
    "np.random.seed(1234)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "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": 3,
   "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_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": 4,
   "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_weights_PBC.pt')\n",
    "    def forward(self, x):\n",
    "        out = self.layers(x)\n",
    "        return out"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "class PhysicsInformedNN():\n",
    "    def __init__(self, period, m, X_IC, u_IC, v_IC, X_PDE, layers):\n",
    "        # IC data point\n",
    "        m_vec = np.expand_dims(np.arange(1, m + 1), axis = 0)\n",
    "        self.ms = torch.tensor(2.0 * np.pi/period * m_vec).float().to(device)\n",
    "        layers[0] = int(2 * m + 2)\n",
    "        self.t_IC = torch.tensor(X_IC[:, 0:1]).float().to(device)\n",
    "        self.x_IC = torch.tensor(X_IC[:, 1:2]).float().to(device)\n",
    "        self.u_IC = torch.tensor(u_IC).float().to(device)\n",
    "        self.v_IC = torch.tensor(v_IC).float().to(device) \n",
    "        N_IC = X_IC.shape[0]\n",
    "        self.LW_uIC = torch.nn.ParameterList([torch.nn.Parameter(torch.ones(N_IC, 1).float(), requires_grad=True).to(device)])\n",
    "        self.LW_vIC = torch.nn.ParameterList([torch.nn.Parameter(torch.ones(N_IC, 1).float(), requires_grad=True).to(device)])\n",
    "\n",
    "        \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",
    "        N_PDE = X_PDE.shape[0]\n",
    "        self.LW_uPDE = torch.nn.ParameterList([torch.nn.Parameter(torch.ones(N_PDE, 1).float(), requires_grad=True).to(device)])\n",
    "        self.LW_vPDE = torch.nn.ParameterList([torch.nn.Parameter(torch.ones(N_PDE, 1).float(), requires_grad=True).to(device)])\n",
    "\n",
    "        # equation related parameters\n",
    "       \n",
    "        self.layers = layers\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",
    "        self.optimizer_LW_uIC = torch.optim.Adam(self.LW_uIC.parameters(), lr = 5e-3)\n",
    "        self.optimizer_LW_uPDE = torch.optim.Adam(self.LW_uPDE.parameters(), lr = 5e-3)\n",
    "        self.optimizer_LW_vIC = torch.optim.Adam(self.LW_vIC.parameters(), lr = 5e-3)\n",
    "        self.optimizer_LW_vPDE = torch.optim.Adam(self.LW_vPDE.parameters(), lr = 5e-3)\n",
    "    \n",
    "   \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",
    "        x_trans = torch.matmul(x, self.ms)\n",
    "        NN = self.dnn(torch.cat([t, torch.ones_like(x), torch.cos(x_trans), torch.sin(x_trans)], dim = 1))\n",
    "        u = NN[:, 0][:, None]\n",
    "        v = NN[:, 1][:, None]\n",
    "        unew = t * u\n",
    "        vnew = t * u\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",
    "        # compute IC loss\n",
    "        uIC_pred, vIC_pred = self.NN_eval(self.t_IC, self.x_IC)\n",
    "       \n",
    "        loss_IC = torch.mean(torch.square(self.LW_uIC[0] * (uIC_pred - self.u_IC)))+torch.mean(torch.square(self.LW_vIC[0] * (vIC_pred - self.v_IC)))\n",
    "       \n",
    "        # compute PDE loss\n",
    "        pde1_pred, pde2_pred = self.pde_eval(self.t_PDE, self.x_PDE)\n",
    "        loss_PDE = torch.mean(torch.square(self.LW_uPDE[0] * pde1_pred)) + torch.mean(torch.square(self.LW_vPDE[0] * pde2_pred))     \n",
    "        # compute the total loss, it can be weighted\n",
    "        loss = loss_IC  + 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('IC: %10.4e,  PDE: %10.4e' % (loss_IC.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",
    "            # compute IC loss\n",
    "            uIC_pred, vIC_pred = self.NN_eval(self.t_IC, self.x_IC)\n",
    "       \n",
    "            loss_IC = torch.mean(torch.square(self.LW_uIC[0] * (uIC_pred - self.u_IC)))+torch.mean(torch.square(self.LW_vIC[0] * (vIC_pred - self.v_IC)))\n",
    "       \n",
    "            # compute PDE loss\n",
    "            pde1_pred, pde2_pred = self.pde_eval(self.t_PDE, self.x_PDE)\n",
    "            loss_PDE = torch.mean(torch.square(self.LW_uPDE[0] * pde1_pred)) + torch.mean(torch.square(self.LW_vPDE[0] * pde2_pred))     \n",
    "            # compute the total loss, it can be weighted\n",
    "            loss = loss_IC  + loss_PDE\n",
    "            # Backward and optimize\n",
    "            self.optimizer_Adam.zero_grad()\n",
    "            self.optimizer_LW_uIC.zero_grad()\n",
    "            \n",
    "            self.optimizer_LW_uPDE.zero_grad()\n",
    "            self.optimizer_LW_vIC.zero_grad()\n",
    "            \n",
    "            self.optimizer_LW_vPDE.zero_grad()\n",
    "            loss.backward()\n",
    "            self.optimizer_Adam.step() \n",
    "            self.LW_uIC[0].grad.data = -self.LW_uIC[0].grad.data\n",
    "            \n",
    "            self.LW_uPDE[0].grad.data = -self.LW_uPDE[0].grad.data\n",
    "            self.LW_vIC[0].grad.data = -self.LW_vIC[0].grad.data\n",
    "            \n",
    "            self.LW_vPDE[0].grad.data = -self.LW_vPDE[0].grad.data\n",
    "            self.optimizer_LW_uIC.step()\n",
    "            \n",
    "            self.optimizer_LW_uPDE.step()\n",
    "            self.optimizer_LW_vIC.step()\n",
    "           \n",
    "            self.optimizer_LW_vPDE.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('IC: %10.4e,  PDE: %10.4e' % (loss_IC.item(),  loss_PDE.item()))\n",
    "                print('For uIC,  min uLW: %10.4e, max uLW: %10.4e' %(torch.min(self.LW_uIC[0]).item(), torch.max(self.LW_uIC[0]).item()))\n",
    "                print('For uPDE, min uLW: %10.4e, max uLW: %10.4e' %(torch.min(self.LW_uPDE[0]).item(), torch.max(self.LW_uPDE[0]).item()))\n",
    "                print('For vIC,  min vLW: %10.4e, max vLW: %10.4e' %(torch.min(self.LW_vIC[0]).item(), torch.max(self.LW_vIC[0]).item()))\n",
    "                print('For vPDE, min vLW: %10.4e, max vLW: %10.4e' %(torch.min(self.LW_vPDE[0]).item(), torch.max(self.LW_vPDE[0]).item()))\n",
    "                \n",
    "                start_time = end_time\n",
    "                # change the learning rate\n",
    "                self.scheduler.step()\n",
    "        \n",
    "        print('Starting with L-BFGS')\n",
    "        self.start_time = time.time()\n",
    "        self.optimizer_LBFGS.step(self.loss_func)    \n",
    "\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": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Starting with Adam\n",
      "Iter  1000, Total: 6.6780e+00, Time: 56.80 secs\n",
      "IC: 5.9466e+00,  PDE: 7.3140e-01\n",
      "For IC,  min LW: 3.4162e+00, max LW: 8.0983e+00\n",
      "For PDE, min LW: 2.8604e+00, max LW: 9.7996e+00\n",
      "Iter  2000, Total: 1.6271e+01, Time: 54.08 secs\n",
      "IC: 1.3509e+01,  PDE: 2.7627e+00\n",
      "For IC,  min LW: 5.8080e+00, max LW: 1.5386e+01\n",
      "For PDE, min LW: 5.3894e+00, max LW: 1.8367e+01\n",
      "Iter  3000, Total: 9.7211e+00, Time: 53.81 secs\n",
      "IC: 7.1759e+00,  PDE: 2.5451e+00\n",
      "For IC,  min LW: 6.5168e+00, max LW: 2.1930e+01\n",
      "For PDE, min LW: 7.9304e+00, max LW: 2.5586e+01\n",
      "Iter  4000, Total: 5.6042e+00, Time: 54.75 secs\n",
      "IC: 3.1917e+00,  PDE: 2.4125e+00\n",
      "For IC,  min LW: 6.6070e+00, max LW: 2.8134e+01\n",
      "For PDE, min LW: 8.2516e+00, max LW: 3.2220e+01\n",
      "Iter  5000, Total: 3.1696e+00, Time: 55.69 secs\n",
      "IC: 1.5446e+00,  PDE: 1.6250e+00\n",
      "For IC,  min LW: 6.6381e+00, max LW: 3.4038e+01\n",
      "For PDE, min LW: 8.4590e+00, max LW: 3.9307e+01\n",
      "Iter  6000, Total: 2.6048e+00, Time: 55.18 secs\n",
      "IC: 1.1205e+00,  PDE: 1.4843e+00\n",
      "For IC,  min LW: 6.6839e+00, max LW: 3.7729e+01\n",
      "For PDE, min LW: 8.8934e+00, max LW: 3.9967e+01\n",
      "Iter  7000, Total: 3.0150e+00, Time: 55.30 secs\n",
      "IC: 1.1274e+00,  PDE: 1.8875e+00\n",
      "For IC,  min LW: 6.7570e+00, max LW: 4.4087e+01\n",
      "For PDE, min LW: 1.0388e+01, max LW: 4.2077e+01\n",
      "Iter  8000, Total: 2.4685e+00, Time: 55.20 secs\n",
      "IC: 1.3199e+00,  PDE: 1.1486e+00\n",
      "For IC,  min LW: 6.8478e+00, max LW: 4.9990e+01\n",
      "For PDE, min LW: 1.1528e+01, max LW: 4.7251e+01\n",
      "Iter  9000, Total: 4.0334e+00, Time: 54.24 secs\n",
      "IC: 1.6789e+00,  PDE: 2.3545e+00\n",
      "For IC,  min LW: 6.9941e+00, max LW: 5.5618e+01\n",
      "For PDE, min LW: 1.2102e+01, max LW: 5.2182e+01\n",
      "Iter 10000, Total: 2.8834e+00, Time: 55.67 secs\n",
      "IC: 1.7326e+00,  PDE: 1.1508e+00\n",
      "For IC,  min LW: 7.2526e+00, max LW: 6.0971e+01\n",
      "For PDE, min LW: 1.2421e+01, max LW: 5.6880e+01\n",
      "Iter 11000, Total: 6.7474e+00, Time: 54.77 secs\n",
      "IC: 2.0990e+00,  PDE: 4.6484e+00\n",
      "For IC,  min LW: 7.6723e+00, max LW: 6.5755e+01\n",
      "For PDE, min LW: 1.2855e+01, max LW: 6.0991e+01\n",
      "Iter 12000, Total: 3.5067e+00, Time: 68.92 secs\n",
      "IC: 2.1958e+00,  PDE: 1.3109e+00\n",
      "For IC,  min LW: 8.4130e+00, max LW: 6.9774e+01\n",
      "For PDE, min LW: 1.3332e+01, max LW: 6.3870e+01\n",
      "Iter 13000, Total: 6.4830e+00, Time: 71.37 secs\n",
      "IC: 3.0939e+00,  PDE: 3.3891e+00\n",
      "For IC,  min LW: 9.7647e+00, max LW: 7.5246e+01\n",
      "For PDE, min LW: 1.3840e+01, max LW: 6.8561e+01\n",
      "Iter 14000, Total: 3.9834e+00, Time: 71.48 secs\n",
      "IC: 2.6240e+00,  PDE: 1.3594e+00\n",
      "For IC,  min LW: 1.1711e+01, max LW: 8.0753e+01\n",
      "For PDE, min LW: 1.4905e+01, max LW: 7.4198e+01\n",
      "Iter 15000, Total: 4.5136e+00, Time: 71.44 secs\n",
      "IC: 2.6479e+00,  PDE: 1.8657e+00\n",
      "For IC,  min LW: 1.4485e+01, max LW: 8.6151e+01\n",
      "For PDE, min LW: 1.6241e+01, max LW: 7.8725e+01\n",
      "Iter 16000, Total: 5.9940e+00, Time: 71.43 secs\n",
      "IC: 3.5955e+00,  PDE: 2.3985e+00\n",
      "For IC,  min LW: 1.5797e+01, max LW: 9.1380e+01\n",
      "For PDE, min LW: 1.7826e+01, max LW: 8.3734e+01\n",
      "Iter 17000, Total: 5.3315e+00, Time: 71.44 secs\n",
      "IC: 2.9900e+00,  PDE: 2.3415e+00\n",
      "For IC,  min LW: 1.7523e+01, max LW: 9.6565e+01\n",
      "For PDE, min LW: 1.9462e+01, max LW: 8.8546e+01\n",
      "Iter 18000, Total: 5.9339e+00, Time: 71.41 secs\n",
      "IC: 3.3123e+00,  PDE: 2.6216e+00\n",
      "For IC,  min LW: 1.9662e+01, max LW: 1.0172e+02\n",
      "For PDE, min LW: 2.1338e+01, max LW: 9.3283e+01\n",
      "Iter 19000, Total: 5.8806e+00, Time: 70.98 secs\n",
      "IC: 3.7118e+00,  PDE: 2.1688e+00\n",
      "For IC,  min LW: 2.2055e+01, max LW: 1.0685e+02\n",
      "For PDE, min LW: 2.3167e+01, max LW: 9.8034e+01\n",
      "Iter 20000, Total: 7.3971e+00, Time: 71.22 secs\n",
      "IC: 3.9354e+00,  PDE: 3.4616e+00\n",
      "For IC,  min LW: 2.3284e+01, max LW: 1.1196e+02\n",
      "For PDE, min LW: 2.4422e+01, max LW: 1.0284e+02\n",
      "Iter 21000, Total: 7.3146e+00, Time: 71.44 secs\n",
      "IC: 4.8324e+00,  PDE: 2.4822e+00\n",
      "For IC,  min LW: 2.4967e+01, max LW: 1.1707e+02\n",
      "For PDE, min LW: 2.5710e+01, max LW: 1.0781e+02\n",
      "Iter 22000, Total: 7.7924e+00, Time: 71.87 secs\n",
      "IC: 4.7427e+00,  PDE: 3.0497e+00\n",
      "For IC,  min LW: 2.7127e+01, max LW: 1.2220e+02\n",
      "For PDE, min LW: 2.7018e+01, max LW: 1.1322e+02\n",
      "Iter 23000, Total: 1.0757e+01, Time: 70.70 secs\n",
      "IC: 4.7550e+00,  PDE: 6.0020e+00\n",
      "For IC,  min LW: 2.9570e+01, max LW: 1.2735e+02\n",
      "For PDE, min LW: 2.8517e+01, max LW: 1.1881e+02\n",
      "Iter 24000, Total: 8.5829e+00, Time: 71.01 secs\n",
      "IC: 6.2614e+00,  PDE: 2.3215e+00\n",
      "For IC,  min LW: 3.2035e+01, max LW: 1.3251e+02\n",
      "For PDE, min LW: 2.9721e+01, max LW: 1.2429e+02\n",
      "Iter 25000, Total: 9.5701e+00, Time: 70.20 secs\n",
      "IC: 5.4914e+00,  PDE: 4.0787e+00\n",
      "For IC,  min LW: 3.4426e+01, max LW: 1.3766e+02\n",
      "For PDE, min LW: 3.1779e+01, max LW: 1.2955e+02\n",
      "Iter 26000, Total: 8.7672e+00, Time: 70.94 secs\n",
      "IC: 6.1673e+00,  PDE: 2.5999e+00\n",
      "For IC,  min LW: 3.6962e+01, max LW: 1.4280e+02\n",
      "For PDE, min LW: 3.3873e+01, max LW: 1.3447e+02\n",
      "Iter 27000, Total: 1.0937e+01, Time: 70.76 secs\n",
      "IC: 7.8698e+00,  PDE: 3.0677e+00\n",
      "For IC,  min LW: 3.9295e+01, max LW: 1.4795e+02\n",
      "For PDE, min LW: 3.6595e+01, max LW: 1.3931e+02\n",
      "Iter 28000, Total: 9.7813e+00, Time: 70.66 secs\n",
      "IC: 6.9877e+00,  PDE: 2.7936e+00\n",
      "For IC,  min LW: 4.1668e+01, max LW: 1.5308e+02\n",
      "For PDE, min LW: 3.9387e+01, max LW: 1.4417e+02\n",
      "Iter 29000, Total: 1.0614e+01, Time: 71.40 secs\n",
      "IC: 7.9506e+00,  PDE: 2.6634e+00\n",
      "For IC,  min LW: 4.4074e+01, max LW: 1.5818e+02\n",
      "For PDE, min LW: 4.1244e+01, max LW: 1.4908e+02\n",
      "Iter 30000, Total: 1.2641e+01, Time: 71.46 secs\n",
      "IC: 7.4316e+00,  PDE: 5.2091e+00\n",
      "For IC,  min LW: 4.6488e+01, max LW: 1.6326e+02\n",
      "For PDE, min LW: 4.3858e+01, max LW: 1.5401e+02\n",
      "Iter 31000, Total: 1.2191e+01, Time: 71.81 secs\n",
      "IC: 9.1271e+00,  PDE: 3.0640e+00\n",
      "For IC,  min LW: 4.8774e+01, max LW: 1.6831e+02\n",
      "For PDE, min LW: 4.6624e+01, max LW: 1.5895e+02\n",
      "Iter 32000, Total: 1.2686e+01, Time: 71.54 secs\n",
      "IC: 8.4926e+00,  PDE: 4.1937e+00\n",
      "For IC,  min LW: 5.0977e+01, max LW: 1.7333e+02\n",
      "For PDE, min LW: 4.9279e+01, max LW: 1.6389e+02\n",
      "Iter 33000, Total: 1.5752e+01, Time: 71.41 secs\n",
      "IC: 8.4141e+00,  PDE: 7.3379e+00\n",
      "For IC,  min LW: 5.3273e+01, max LW: 1.7831e+02\n",
      "For PDE, min LW: 5.2006e+01, max LW: 1.6909e+02\n",
      "Iter 34000, Total: 1.3981e+01, Time: 71.79 secs\n",
      "IC: 1.0344e+01,  PDE: 3.6373e+00\n",
      "For IC,  min LW: 5.5478e+01, max LW: 1.8338e+02\n",
      "For PDE, min LW: 5.4617e+01, max LW: 1.7431e+02\n",
      "Iter 35000, Total: 1.4587e+01, Time: 70.95 secs\n",
      "IC: 9.0089e+00,  PDE: 5.5776e+00\n",
      "For IC,  min LW: 5.7887e+01, max LW: 1.8851e+02\n",
      "For PDE, min LW: 5.6979e+01, max LW: 1.7953e+02\n",
      "Iter 36000, Total: 1.3568e+01, Time: 71.15 secs\n",
      "IC: 9.4584e+00,  PDE: 4.1097e+00\n",
      "For IC,  min LW: 6.0096e+01, max LW: 1.9364e+02\n",
      "For PDE, min LW: 5.9305e+01, max LW: 1.8478e+02\n",
      "Iter 37000, Total: 1.3492e+01, Time: 73.57 secs\n",
      "IC: 9.7849e+00,  PDE: 3.7067e+00\n",
      "For IC,  min LW: 6.1579e+01, max LW: 1.9878e+02\n",
      "For PDE, min LW: 6.1539e+01, max LW: 1.9009e+02\n",
      "Iter 38000, Total: 1.7865e+01, Time: 79.56 secs\n",
      "IC: 8.3786e+00,  PDE: 9.4864e+00\n",
      "For IC,  min LW: 6.3571e+01, max LW: 2.0394e+02\n",
      "For PDE, min LW: 6.3348e+01, max LW: 1.9539e+02\n",
      "Iter 39000, Total: 1.3107e+01, Time: 78.31 secs\n",
      "IC: 9.4148e+00,  PDE: 3.6926e+00\n",
      "For IC,  min LW: 6.5254e+01, max LW: 2.0912e+02\n",
      "For PDE, min LW: 6.4700e+01, max LW: 2.0017e+02\n",
      "Iter 40000, Total: 1.3067e+01, Time: 76.07 secs\n",
      "IC: 9.3340e+00,  PDE: 3.7329e+00\n",
      "For IC,  min LW: 6.7271e+01, max LW: 2.1432e+02\n",
      "For PDE, min LW: 6.6078e+01, max LW: 2.0458e+02\n",
      "Iter 41000, Total: 1.3761e+01, Time: 88.53 secs\n",
      "IC: 9.3746e+00,  PDE: 4.3867e+00\n",
      "For IC,  min LW: 6.9106e+01, max LW: 2.1953e+02\n",
      "For PDE, min LW: 6.7369e+01, max LW: 2.0962e+02\n",
      "Iter 42000, Total: 1.6762e+01, Time: 90.43 secs\n",
      "IC: 1.0579e+01,  PDE: 6.1828e+00\n",
      "For IC,  min LW: 7.0959e+01, max LW: 2.2473e+02\n",
      "For PDE, min LW: 6.8951e+01, max LW: 2.1471e+02\n",
      "Iter 43000, Total: 1.9486e+01, Time: 89.88 secs\n",
      "IC: 9.1520e+00,  PDE: 1.0334e+01\n",
      "For IC,  min LW: 7.3000e+01, max LW: 2.2992e+02\n",
      "For PDE, min LW: 7.0424e+01, max LW: 2.1980e+02\n",
      "Iter 44000, Total: 1.5408e+01, Time: 91.58 secs\n",
      "IC: 1.1079e+01,  PDE: 4.3285e+00\n",
      "For IC,  min LW: 7.4693e+01, max LW: 2.3511e+02\n",
      "For PDE, min LW: 7.1754e+01, max LW: 2.2486e+02\n",
      "Iter 45000, Total: 1.6172e+01, Time: 91.44 secs\n",
      "IC: 1.1641e+01,  PDE: 4.5313e+00\n",
      "For IC,  min LW: 7.6593e+01, max LW: 2.4029e+02\n",
      "For PDE, min LW: 7.3189e+01, max LW: 2.2989e+02\n",
      "Iter 46000, Total: 1.5390e+01, Time: 89.55 secs\n",
      "IC: 1.1302e+01,  PDE: 4.0884e+00\n",
      "For IC,  min LW: 7.8825e+01, max LW: 2.4546e+02\n",
      "For PDE, min LW: 7.4619e+01, max LW: 2.3489e+02\n",
      "Iter 47000, Total: 1.5234e+01, Time: 84.59 secs\n",
      "IC: 1.1032e+01,  PDE: 4.2025e+00\n",
      "For IC,  min LW: 8.0700e+01, max LW: 2.5063e+02\n",
      "For PDE, min LW: 7.6135e+01, max LW: 2.3990e+02\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Iter 48000, Total: 1.5601e+01, Time: 90.37 secs\n",
      "IC: 1.1529e+01,  PDE: 4.0721e+00\n",
      "For IC,  min LW: 8.2379e+01, max LW: 2.5580e+02\n",
      "For PDE, min LW: 7.7740e+01, max LW: 2.4520e+02\n",
      "Iter 49000, Total: 1.6614e+01, Time: 90.29 secs\n",
      "IC: 1.1919e+01,  PDE: 4.6952e+00\n",
      "For IC,  min LW: 8.3899e+01, max LW: 2.6096e+02\n",
      "For PDE, min LW: 7.9755e+01, max LW: 2.5050e+02\n",
      "Iter 50000, Total: 1.8202e+01, Time: 90.77 secs\n",
      "IC: 1.3026e+01,  PDE: 5.1766e+00\n",
      "For IC,  min LW: 8.5315e+01, max LW: 2.6612e+02\n",
      "For PDE, min LW: 8.1884e+01, max LW: 2.5575e+02\n",
      "Iter  1000, Total: 9.7815e+00, Time: 189.85 secs\n",
      "IC: 5.6814e+00,  PDE: 4.1001e+00\n",
      "Iter  2000, Total: 6.0795e+00, Time: 187.30 secs\n",
      "IC: 3.4558e+00,  PDE: 2.6237e+00\n",
      "Iter  3000, Total: 2.9756e+00, Time: 191.82 secs\n",
      "IC: 1.0397e+00,  PDE: 1.9359e+00\n",
      "Iter  4000, Total: 1.4678e+00, Time: 166.08 secs\n",
      "IC: 4.9386e-01,  PDE: 9.7389e-01\n",
      "Iter  5000, Total: 7.9553e-01, Time: 141.48 secs\n",
      "IC: 1.1216e-01,  PDE: 6.8337e-01\n"
     ]
    }
   ],
   "source": [
    "layers = [2, 32, 32, 32, 32, 32, 32, 32, 2]\n",
    "N_IC = 96\n",
    "m = 16\n",
    "ptsIC=np.load('ptsIC.npy')\n",
    "ptsBC=np.load('ptsBC.npy')\n",
    "ptsPDE=np.load('random_data.npy')\n",
    "ptsPDE = np.vstack((ptsPDE,ptsBC))\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",
    "model = PhysicsInformedNN(period, m,  ptsIC, uIC, vIC,  ptsPDE, layers)\n",
    "model.train(50000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "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": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = scipy.io.loadmat('/Users/abraham/Desktop/PINN/New_Data/NLS_1D_t2.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": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 211512 characters]",
      "text/plain": [
       "<Figure size 1100x500 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = plt.figure(figsize=(11, 5))\n",
    "ax = fig.add_subplot(1, 1, 1)\n",
    "#\n",
    "ax.plot(ptsPDE[:, 0], ptsPDE[:, 1], \n",
    "    'rd', label = 'PDE Data (%d points)' % (ptsPDE.shape[0]), \n",
    "    markersize = 4,  # marker size doubled\n",
    "    clip_on = False,\n",
    "    alpha=1.0\n",
    ")\n",
    "\n",
    "ax.plot(ptsIC[:, 0], ptsIC[:, 1], \n",
    "    'bd', label = 'IC Data (%d points)' % (ptsIC.shape[0]), \n",
    "    markersize = 4,  # marker size doubled\n",
    "    clip_on = False,\n",
    "    alpha=1.0\n",
    ")\n",
    "\n",
    "\n",
    "ax.plot(ptsBC[:, 0], ptsBC[:, 1], \n",
    "    'gd', label = 'BC Data (%d points)' % (ptsBC.shape[0]), \n",
    "    markersize = 4,  # marker size doubled\n",
    "    clip_on = False,\n",
    "    alpha=1.0\n",
    ")\n",
    "\n",
    "ax.set_xlabel('$t$', size=15)\n",
    "ax.set_ylabel('$x$', size=15)\n",
    "ax.legend(\n",
    "    loc='upper center', \n",
    "    bbox_to_anchor=(0.9, -0.05), \n",
    "    ncol=5, \n",
    "    frameon=False, \n",
    "    prop={'size': 15}\n",
    ")\n",
    "ax.legend()\n",
    "ax.set_title('Points', fontsize = 15) # font size doubled\n",
    "ax.tick_params(labelsize=12)\n",
    "#\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 146304 characters]",
      "text/plain": [
       "<Figure size 1800x600 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "####### Row 1: u(t,x) slices ################## \n",
    "\n",
    "\"\"\" The aesthetic setting has changed. \"\"\"\n",
    "\n",
    "fig = plt.figure(figsize=(18, 6))\n",
    "#\n",
    "ax = plt.subplot(1, 3, 1)\n",
    "ax.plot(x2, u_sol[0,:], 'bo-', linewidth = 2, label = 'Exact')       \n",
    "ax.plot(x, u_pred[:, 0], 'rx--', linewidth = 2, label = 'u')\n",
    "ax.set_xlabel('$x$')\n",
    "ax.set_ylabel('$u(t,x)$')    \n",
    "ax.set_title('$t = %.1f$' %(t[0]), fontsize = 24)\n",
    "\n",
    "\n",
    "plt.locator_params(axis = 'y', nbins = 5)\n",
    "plt.locator_params(axis = 'x', nbins = 5)\n",
    "for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n",
    "             ax.get_xticklabels() + ax.get_yticklabels()):\n",
    "    item.set_fontsize(24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 2)\n",
    "ax.plot(x,u_sol[100,:], 'bo-', linewidth = 2, label = 'Exact')       \n",
    "ax.plot(x, u_pred[:, 100], 'rx--', linewidth = 2, label = 'u')\n",
    "\n",
    "ax.set_xlabel('x')\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_title('$t = %.1f$' %(t[100]), fontsize = 24)\n",
    "ax.legend(\n",
    "    loc='upper center', \n",
    "    bbox_to_anchor=(0.5, -0.15), \n",
    "    ncol=5, \n",
    "    frameon=False, \n",
    "    prop={'size': 24}\n",
    ")\n",
    "plt.locator_params(axis = 'y', nbins = 5)\n",
    "plt.locator_params(axis = 'x', nbins = 5)\n",
    "for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n",
    "             ax.get_xticklabels() + ax.get_yticklabels()):\n",
    "    item.set_fontsize(24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 3)\n",
    "ax.plot(x,u_sol[200,:], 'bo-', linewidth = 2, label = 'Exact')       \n",
    "ax.plot(x, u_pred[:, 200], 'rx--', linewidth = 2, label = 'u')\n",
    "\n",
    "ax.set_xlabel('$x$')\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_title('$t = %.1f$' %(t[200]), fontsize = 24)\n",
    "plt.locator_params(axis = 'y', nbins = 5)\n",
    "plt.locator_params(axis = 'x', nbins = 5)\n",
    "for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n",
    "             ax.get_xticklabels() + ax.get_yticklabels()):\n",
    "    item.set_fontsize(24)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(18, 6))\n",
    "#\n",
    "ax = plt.subplot(1, 3, 1)\n",
    "ax.plot(x2, v_sol[0,:], 'bo-', linewidth = 2, label = 'Exact')       \n",
    "ax.plot(x, v_pred[:, 0], 'rx--', linewidth = 2, label = 'u')\n",
    "ax.set_xlabel('$x$')\n",
    "ax.set_ylabel('$v(t,x)$')    \n",
    "ax.set_title('$t = %.1f$' %(t[0]), fontsize = 24)\n",
    "\n",
    "\n",
    "plt.locator_params(axis = 'y', nbins = 5)\n",
    "plt.locator_params(axis = 'x', nbins = 5)\n",
    "for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n",
    "             ax.get_xticklabels() + ax.get_yticklabels()):\n",
    "    item.set_fontsize(24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 2)\n",
    "ax.plot(x,v_sol[100,:], 'bo-', linewidth = 2, label = 'Exact')       \n",
    "ax.plot(x, v_pred[:, 100], 'rx--', linewidth = 2, label = 'u')\n",
    "\n",
    "ax.set_xlabel('x')\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_title('$t = %.1f$' %(t[100]), fontsize = 24)\n",
    "ax.legend(\n",
    "    loc='upper center', \n",
    "    bbox_to_anchor=(0.5, -0.15), \n",
    "    ncol=5, \n",
    "    frameon=False, \n",
    "    prop={'size': 24}\n",
    ")\n",
    "plt.locator_params(axis = 'y', nbins = 5)\n",
    "plt.locator_params(axis = 'x', nbins = 5)\n",
    "for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n",
    "             ax.get_xticklabels() + ax.get_yticklabels()):\n",
    "    item.set_fontsize(24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 3)\n",
    "ax.plot(x,v_sol[200,:], 'bo-', linewidth = 2, label = 'Exact')       \n",
    "ax.plot(x, v_pred[:, 200], 'rx--', linewidth = 2, label = 'u')\n",
    "\n",
    "ax.set_xlabel('$x$')\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_title('$t = %.1f$' %(t[200]), fontsize = 24)\n",
    "plt.locator_params(axis = 'y', nbins = 5)\n",
    "plt.locator_params(axis = 'x', nbins = 5)\n",
    "for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +\n",
    "             ax.get_xticklabels() + ax.get_yticklabels()):\n",
    "    item.set_fontsize(24)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "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": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "l2: 1.0074898331283981\n",
      "l1: 1.0069332482660347\n",
      "linf: 1.273587758458132\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": null,
   "metadata": {},
   "outputs": [],
   "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": [
    "fig = plt.figure(figsize=(24, 6))\n",
    "\n",
    "ax = plt.subplot(1, 3, 1)\n",
    "h = ax.imshow(u_sol.T, interpolation='nearest', cmap='rainbow', \n",
    "              extent=[tlo, thi, x.min(), x.max()], \n",
    "              origin='lower', aspect='auto')\n",
    "divider = make_axes_locatable(ax)\n",
    "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.10)\n",
    "cbar = fig.colorbar(h, cax=cax)\n",
    "cbar.ax.tick_params(labelsize=24) \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_xlabel('$t$', size=24)\n",
    "ax.set_ylabel('$x$', size=24)\n",
    "\n",
    "ax.set_title('$GS: u_{exact}(t,x)$', fontsize = 24) # font size doubled\n",
    "ax.tick_params(labelsize=24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 2)\n",
    "h = ax.imshow(u_pred, interpolation='nearest', cmap='rainbow', \n",
    "              extent=[tlo, thi, x.min(), x.max()], \n",
    "              origin='lower', aspect='auto')\n",
    "divider = make_axes_locatable(ax)\n",
    "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.10)\n",
    "cbar = fig.colorbar(h, cax=cax)\n",
    "cbar.ax.tick_params(labelsize=24) \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_xlabel('$t$', size=24)\n",
    "\n",
    "\n",
    "ax.set_title('$NLS: u_{pred}(t,x)$', fontsize = 24) # font size doubled\n",
    "ax.tick_params(labelsize=24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 3)\n",
    "h = ax.imshow(np.abs(u_pred-u_sol.T), interpolation='nearest', cmap='rainbow', \n",
    "              extent=[tlo, thi, x.min(), x.max()], \n",
    "              origin='lower', aspect='auto')\n",
    "divider = make_axes_locatable(ax)\n",
    "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.10)\n",
    "cbar = fig.colorbar(h, cax=cax)\n",
    "cbar.ax.tick_params(labelsize=24) \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_xlabel('$t$', size=24)\n",
    "\n",
    "\n",
    "ax.set_title('$NLS(Error): u(t,x)$', fontsize = 24) # font size doubled\n",
    "ax.tick_params(labelsize=24)\n",
    "\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(24, 6))\n",
    "\n",
    "ax = plt.subplot(1, 3, 1)\n",
    "h = ax.imshow(v_sol.T, interpolation='nearest', cmap='rainbow', \n",
    "              extent=[tlo, thi, x.min(), x.max()], \n",
    "              origin='lower', aspect='auto')\n",
    "divider = make_axes_locatable(ax)\n",
    "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.10)\n",
    "cbar = fig.colorbar(h, cax=cax)\n",
    "cbar.ax.tick_params(labelsize=24) \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_xlabel('$t$', size=24)\n",
    "ax.set_ylabel('$x$', size=24)\n",
    "\n",
    "ax.set_title('$NLS: v_{exact}(t,x)$', fontsize = 24) # font size doubled\n",
    "ax.tick_params(labelsize=24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 2)\n",
    "h = ax.imshow(v_pred, interpolation='nearest', cmap='rainbow', \n",
    "              extent=[tlo, thi, x.min(), x.max()], \n",
    "              origin='lower', aspect='auto')\n",
    "divider = make_axes_locatable(ax)\n",
    "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.10)\n",
    "cbar = fig.colorbar(h, cax=cax)\n",
    "cbar.ax.tick_params(labelsize=24) \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_xlabel('$t$', size=24)\n",
    "\n",
    "ax.set_xticks([0 ,0.5 ,1])\n",
    "ax.set_yticks([-1 ,0 ,1])\n",
    "ax.set_title('$NLS: v_{pred}(t,x)$', fontsize = 24) # font size doubled\n",
    "ax.tick_params(labelsize=24)\n",
    "\n",
    "ax = plt.subplot(1, 3, 3)\n",
    "h = ax.imshow(np.abs(v_pred-v_sol.T), interpolation='nearest', cmap='rainbow', \n",
    "              extent=[tlo, thi, x.min(), x.max()], \n",
    "              origin='lower', aspect='auto')\n",
    "divider = make_axes_locatable(ax)\n",
    "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.10)\n",
    "cbar = fig.colorbar(h, cax=cax)\n",
    "cbar.ax.tick_params(labelsize=24) \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "ax.set_xlabel('$t$', size=24)\n",
    "\n",
    "ax.set_xticks([0 ,0.5 ,1])\n",
    "ax.set_yticks([-1 ,0 ,1])\n",
    "ax.set_title('$NLS(Error): v(t,x)$', fontsize = 24) # font size doubled\n",
    "ax.tick_params(labelsize=24)\n",
    "\n",
    "\n",
    "plt.show()"
   ]
  }
 ],
 "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.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
