{
 "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": [
    "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": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Working on mps\n"
     ]
    }
   ],
   "source": [
    "# MPS or CUDA or CPU\n",
    "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_PDE, layers):\n",
    "        # Prepare the periodic layer\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",
    "        # 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_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",
    "       \n",
    "       \n",
    "    \n",
    "        layers[0] = int(2 * m + 2)\n",
    "        self.layers = layers\n",
    "\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",
    "        self.optimizer_LW_uPDE = torch.optim.Adam(self.LW_uPDE.parameters(), lr = 5e-3)\n",
    "        self.optimizer_LW_vPDE = torch.optim.Adam(self.LW_vPDE.parameters(), lr = 5e-3)\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",
    "       \n",
    "        self.iter = 0\n",
    "    # update alpha\n",
    "    \n",
    "    def NN_reset_iter(self):\n",
    "        self.iter = 0\n",
    "    # evaluater neural network\n",
    "    # with transformation to include the initial condition\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",
    "        uNN = NN[:, 0][:, None]\n",
    "        vNN = NN[:, 1][:, None]\n",
    "        u0_torch = u0_ten(x)\n",
    "        v0_torch = v0_ten(x)\n",
    "        unew = u0_torch*torch.exp(-t) + t * uNN\n",
    "        vnew = v0_torch*torch.exp(-t) + t * vNN\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 PDE loss\n",
    "        pde1_pred, pde2_pred = self.pde_eval(self.t_PDE, self.x_PDE)\n",
    "        loss_PDE = torch.mean((self.LW_uPDE[0]*pde1_pred )** 2) + torch.mean((self.LW_vPDE[0]*pde2_pred )** 2)   \n",
    "         \n",
    "        # compute the total loss, it can be weighted\n",
    "        loss = 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",
    "            print('Iter %5d, Total: %10.4e, PDE: %10.4e' % (self.iter, loss.item(), loss_PDE.item()))\n",
    "        return loss\n",
    "    #\n",
    "    def train(self, nIter):\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 PDE loss\n",
    "            pde1_pred, pde2_pred = self.pde_eval(self.t_PDE, self.x_PDE)\n",
    "            loss_PDE = torch.mean((self.LW_uPDE[0]*pde1_pred )** 2) + torch.mean((self.LW_vPDE[0]*pde2_pred )** 2)   \n",
    "         \n",
    "                # compute the total loss, it can be weighted\n",
    "            loss = loss_PDE\n",
    "                # Backward and optimize\n",
    "            \n",
    "            self.optimizer_Adam.zero_grad()\n",
    "            self.optimizer_LW_uPDE.zero_grad()\n",
    "            self.optimizer_LW_vPDE.zero_grad()\n",
    "            \n",
    "            loss.backward()\n",
    "            self.optimizer_Adam.step() \n",
    "            \n",
    "           \n",
    "            \n",
    "            self.LW_uPDE[0].grad.data = -self.LW_uPDE[0].grad.data\n",
    "            \n",
    "           \n",
    "            self.LW_vPDE[0].grad.data = -self.LW_vPDE[0].grad.data\n",
    "            \n",
    "           \n",
    "            self.optimizer_LW_uPDE.step()\n",
    "            \n",
    "        \n",
    "            self.optimizer_LW_vPDE.step()\n",
    "                # output the progress\n",
    "            if (epoch + 1) % 1000 == 0:\n",
    "                print('Iter %5d, Total: %10.4e' % (epoch + 1, loss.item()))\n",
    "                print('PDE: %10.4e' % (loss_PDE.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",
    "                \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",
    "                # change the learning rate\n",
    "                self.scheduler.step()\n",
    "       # self.optimizer_LBFGS.step(self.loss_func) \n",
    "        print('Starting with L-BFGS')\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",
    "\n",
    "\n",
    "## Configurations"
   ]
  },
  {
   "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.4461e+01\n",
      "PDE: 6.4461e+01\n",
      "For uPDE, min uLW: 1.8699e+00, max uLW: 1.0106e+01\n",
      "For vPDE, min vLW: 2.3013e+00, max vLW: 1.0343e+01\n",
      "Iter  2000, Total: 1.8007e+01\n",
      "PDE: 1.8007e+01\n",
      "For uPDE, min uLW: 2.0491e+00, max uLW: 1.6697e+01\n",
      "For vPDE, min vLW: 2.7147e+00, max vLW: 1.5937e+01\n",
      "Iter  3000, Total: 1.8579e+02\n",
      "PDE: 1.8579e+02\n",
      "For uPDE, min uLW: 2.3852e+00, max uLW: 2.1131e+01\n",
      "For vPDE, min vLW: 3.1214e+00, max vLW: 2.1072e+01\n",
      "Iter  4000, Total: 3.0845e+02\n",
      "PDE: 3.0845e+02\n",
      "For uPDE, min uLW: 2.5379e+00, max uLW: 2.9256e+01\n",
      "For vPDE, min vLW: 3.7529e+00, max vLW: 2.9273e+01\n",
      "Iter  5000, Total: 4.3794e+01\n",
      "PDE: 4.3794e+01\n",
      "For uPDE, min uLW: 2.7003e+00, max uLW: 3.3583e+01\n",
      "For vPDE, min vLW: 4.5370e+00, max vLW: 3.4154e+01\n",
      "Iter  6000, Total: 4.5287e+02\n",
      "PDE: 4.5287e+02\n",
      "For uPDE, min uLW: 2.9701e+00, max uLW: 4.0016e+01\n",
      "For vPDE, min vLW: 4.8095e+00, max vLW: 3.9473e+01\n",
      "Iter  7000, Total: 1.2996e+02\n",
      "PDE: 1.2996e+02\n",
      "For uPDE, min uLW: 3.0819e+00, max uLW: 4.4104e+01\n",
      "For vPDE, min vLW: 5.1273e+00, max vLW: 4.5409e+01\n",
      "Iter  8000, Total: 6.3277e+01\n",
      "PDE: 6.3277e+01\n",
      "For uPDE, min uLW: 3.1664e+00, max uLW: 4.6792e+01\n",
      "For vPDE, min vLW: 5.3157e+00, max vLW: 4.6189e+01\n",
      "Iter  9000, Total: 3.5987e+01\n",
      "PDE: 3.5987e+01\n",
      "For uPDE, min uLW: 3.1866e+00, max uLW: 4.7921e+01\n",
      "For vPDE, min vLW: 5.3217e+00, max vLW: 4.6632e+01\n",
      "Iter 10000, Total: 2.5896e+01\n",
      "PDE: 2.5896e+01\n",
      "For uPDE, min uLW: 3.1950e+00, max uLW: 4.8396e+01\n",
      "For vPDE, min vLW: 5.3241e+00, max vLW: 4.7081e+01\n",
      "Iter 11000, Total: 2.1589e+01\n",
      "PDE: 2.1589e+01\n",
      "For uPDE, min uLW: 3.2066e+00, max uLW: 4.8602e+01\n",
      "For vPDE, min vLW: 5.3725e+00, max vLW: 4.7590e+01\n",
      "Iter 12000, Total: 1.1858e+02\n",
      "PDE: 1.1858e+02\n",
      "For uPDE, min uLW: 3.6976e+00, max uLW: 5.5755e+01\n",
      "For vPDE, min vLW: 7.0593e+00, max vLW: 5.5964e+01\n",
      "Iter 13000, Total: 4.6432e+01\n",
      "PDE: 4.6432e+01\n",
      "For uPDE, min uLW: 3.7230e+00, max uLW: 5.6641e+01\n",
      "For vPDE, min vLW: 7.1176e+00, max vLW: 5.6804e+01\n",
      "Iter 14000, Total: 3.0667e+01\n",
      "PDE: 3.0667e+01\n",
      "For uPDE, min uLW: 3.7550e+00, max uLW: 5.6763e+01\n",
      "For vPDE, min vLW: 7.1332e+00, max vLW: 5.7052e+01\n",
      "Iter 15000, Total: 2.3654e+01\n",
      "PDE: 2.3654e+01\n",
      "For uPDE, min uLW: 3.7857e+00, max uLW: 5.6966e+01\n",
      "For vPDE, min vLW: 7.2117e+00, max vLW: 5.7239e+01\n",
      "Iter 16000, Total: 1.9286e+01\n",
      "PDE: 1.9286e+01\n",
      "For uPDE, min uLW: 3.8284e+00, max uLW: 5.7105e+01\n",
      "For vPDE, min vLW: 7.3188e+00, max vLW: 5.7398e+01\n",
      "Iter 17000, Total: 2.0998e+03\n",
      "PDE: 2.0998e+03\n",
      "For uPDE, min uLW: 4.1023e+00, max uLW: 5.8194e+01\n",
      "For vPDE, min vLW: 7.6452e+00, max vLW: 5.8482e+01\n",
      "Iter 18000, Total: 1.7900e+03\n",
      "PDE: 1.7900e+03\n",
      "For uPDE, min uLW: 4.1029e+00, max uLW: 5.9296e+01\n",
      "For vPDE, min vLW: 7.6460e+00, max vLW: 5.9099e+01\n",
      "Iter 19000, Total: 1.5556e+03\n",
      "PDE: 1.5556e+03\n",
      "For uPDE, min uLW: 4.1041e+00, max uLW: 6.1060e+01\n",
      "For vPDE, min vLW: 7.6462e+00, max vLW: 5.9617e+01\n",
      "Iter 20000, Total: 1.3865e+03\n",
      "PDE: 1.3865e+03\n",
      "For uPDE, min uLW: 4.1049e+00, max uLW: 6.3634e+01\n",
      "For vPDE, min vLW: 7.6476e+00, max vLW: 5.9902e+01\n",
      "Iter 21000, Total: 1.4788e+03\n",
      "PDE: 1.4788e+03\n",
      "For uPDE, min uLW: 4.1056e+00, max uLW: 6.7480e+01\n",
      "For vPDE, min vLW: 7.6482e+00, max vLW: 6.3889e+01\n",
      "Iter 22000, Total: 1.4735e+03\n",
      "PDE: 1.4735e+03\n",
      "For uPDE, min uLW: 4.1081e+00, max uLW: 7.2725e+01\n",
      "For vPDE, min vLW: 7.6486e+00, max vLW: 6.9076e+01\n",
      "Iter 23000, Total: 9.7371e+02\n",
      "PDE: 9.7371e+02\n",
      "For uPDE, min uLW: 4.1459e+00, max uLW: 7.9097e+01\n",
      "For vPDE, min vLW: 7.6490e+00, max vLW: 7.3694e+01\n",
      "Iter 24000, Total: 5.8357e+02\n",
      "PDE: 5.8357e+02\n",
      "For uPDE, min uLW: 4.1797e+00, max uLW: 8.5550e+01\n",
      "For vPDE, min vLW: 7.6624e+00, max vLW: 7.6541e+01\n",
      "Iter 25000, Total: 2.6921e+02\n",
      "PDE: 2.6921e+02\n",
      "For uPDE, min uLW: 4.1929e+00, max uLW: 8.9390e+01\n",
      "For vPDE, min vLW: 7.6914e+00, max vLW: 7.7108e+01\n",
      "Iter 26000, Total: 1.5269e+02\n",
      "PDE: 1.5269e+02\n",
      "For uPDE, min uLW: 4.2137e+00, max uLW: 8.9999e+01\n",
      "For vPDE, min vLW: 7.6922e+00, max vLW: 7.7263e+01\n",
      "Iter 27000, Total: 1.1401e+02\n",
      "PDE: 1.1401e+02\n",
      "For uPDE, min uLW: 4.2264e+00, max uLW: 9.0377e+01\n",
      "For vPDE, min vLW: 7.7037e+00, max vLW: 7.7391e+01\n",
      "Iter 28000, Total: 9.1455e+01\n",
      "PDE: 9.1455e+01\n",
      "For uPDE, min uLW: 4.2370e+00, max uLW: 9.0652e+01\n",
      "For vPDE, min vLW: 7.7385e+00, max vLW: 7.7533e+01\n",
      "Iter 29000, Total: 7.7280e+01\n",
      "PDE: 7.7280e+01\n",
      "For uPDE, min uLW: 4.2480e+00, max uLW: 9.0884e+01\n",
      "For vPDE, min vLW: 7.7917e+00, max vLW: 7.7721e+01\n",
      "Iter 30000, Total: 6.4422e+01\n",
      "PDE: 6.4422e+01\n",
      "For uPDE, min uLW: 4.2606e+00, max uLW: 9.1095e+01\n",
      "For vPDE, min vLW: 7.8566e+00, max vLW: 7.7975e+01\n",
      "Iter 31000, Total: 4.6244e+01\n",
      "PDE: 4.6244e+01\n",
      "For uPDE, min uLW: 4.2750e+00, max uLW: 9.1230e+01\n",
      "For vPDE, min vLW: 7.9240e+00, max vLW: 7.8271e+01\n",
      "Iter 32000, Total: 3.5377e+01\n",
      "PDE: 3.5377e+01\n",
      "For uPDE, min uLW: 4.2926e+00, max uLW: 9.1297e+01\n",
      "For vPDE, min vLW: 8.0072e+00, max vLW: 7.8433e+01\n",
      "Iter 33000, Total: 2.5421e+02\n",
      "PDE: 2.5421e+02\n",
      "For uPDE, min uLW: 4.6867e+00, max uLW: 9.4763e+01\n",
      "For vPDE, min vLW: 8.3193e+00, max vLW: 8.1267e+01\n",
      "Iter 34000, Total: 9.6301e+01\n",
      "PDE: 9.6301e+01\n",
      "For uPDE, min uLW: 4.7071e+00, max uLW: 9.6421e+01\n",
      "For vPDE, min vLW: 8.3531e+00, max vLW: 8.1610e+01\n",
      "Iter 35000, Total: 5.7337e+01\n",
      "PDE: 5.7337e+01\n",
      "For uPDE, min uLW: 4.7124e+00, max uLW: 9.6802e+01\n",
      "For vPDE, min vLW: 8.4114e+00, max vLW: 8.1642e+01\n",
      "Iter 36000, Total: 4.2979e+01\n",
      "PDE: 4.2979e+01\n",
      "For uPDE, min uLW: 4.7134e+00, max uLW: 9.6991e+01\n",
      "For vPDE, min vLW: 8.4739e+00, max vLW: 8.1652e+01\n",
      "Iter 37000, Total: 3.3496e+01\n",
      "PDE: 3.3496e+01\n",
      "For uPDE, min uLW: 4.7166e+00, max uLW: 9.7112e+01\n",
      "For vPDE, min vLW: 8.5222e+00, max vLW: 8.1660e+01\n",
      "Iter 38000, Total: 2.6892e+01\n",
      "PDE: 2.6892e+01\n",
      "For uPDE, min uLW: 4.7280e+00, max uLW: 9.7213e+01\n",
      "For vPDE, min vLW: 8.5468e+00, max vLW: 8.1668e+01\n",
      "Iter 39000, Total: 2.1873e+01\n",
      "PDE: 2.1873e+01\n",
      "For uPDE, min uLW: 4.7455e+00, max uLW: 9.7348e+01\n",
      "For vPDE, min vLW: 8.5500e+00, max vLW: 8.1675e+01\n",
      "Iter 40000, Total: 1.7552e+01\n",
      "PDE: 1.7552e+01\n",
      "For uPDE, min uLW: 4.7566e+00, max uLW: 9.7456e+01\n",
      "For vPDE, min vLW: 8.5604e+00, max vLW: 8.1683e+01\n",
      "Iter 41000, Total: 2.1448e+03\n",
      "PDE: 2.1448e+03\n",
      "For uPDE, min uLW: 5.1157e+00, max uLW: 9.8791e+01\n",
      "For vPDE, min vLW: 9.0084e+00, max vLW: 8.3236e+01\n",
      "Iter 42000, Total: 3.5265e+02\n",
      "PDE: 3.5265e+02\n",
      "For uPDE, min uLW: 5.4661e+00, max uLW: 1.0261e+02\n",
      "For vPDE, min vLW: 9.0828e+00, max vLW: 8.5919e+01\n",
      "Iter 43000, Total: 2.1108e+02\n",
      "PDE: 2.1108e+02\n",
      "For uPDE, min uLW: 5.4947e+00, max uLW: 1.0492e+02\n",
      "For vPDE, min vLW: 9.0877e+00, max vLW: 8.6194e+01\n",
      "Iter 44000, Total: 1.2984e+02\n",
      "PDE: 1.2984e+02\n",
      "For uPDE, min uLW: 5.6230e+00, max uLW: 1.0703e+02\n",
      "For vPDE, min vLW: 9.0885e+00, max vLW: 8.6296e+01\n",
      "Iter 45000, Total: 5.2270e+01\n",
      "PDE: 5.2270e+01\n",
      "For uPDE, min uLW: 5.6275e+00, max uLW: 1.0714e+02\n",
      "For vPDE, min vLW: 9.0967e+00, max vLW: 8.6322e+01\n",
      "Iter 46000, Total: 3.4656e+01\n",
      "PDE: 3.4656e+01\n",
      "For uPDE, min uLW: 5.6438e+00, max uLW: 1.0716e+02\n",
      "For vPDE, min vLW: 9.1075e+00, max vLW: 8.6330e+01\n",
      "Iter 47000, Total: 2.5386e+01\n",
      "PDE: 2.5386e+01\n",
      "For uPDE, min uLW: 5.6661e+00, max uLW: 1.0718e+02\n",
      "For vPDE, min vLW: 9.1098e+00, max vLW: 8.6337e+01\n",
      "Iter 48000, Total: 1.9886e+01\n",
      "PDE: 1.9886e+01\n",
      "For uPDE, min uLW: 5.6884e+00, max uLW: 1.0721e+02\n",
      "For vPDE, min vLW: 9.1113e+00, max vLW: 8.6345e+01\n",
      "Iter 49000, Total: 1.6005e+01\n",
      "PDE: 1.6005e+01\n",
      "For uPDE, min uLW: 5.7089e+00, max uLW: 1.0723e+02\n",
      "For vPDE, min vLW: 9.1178e+00, max vLW: 8.6352e+01\n",
      "Iter 50000, Total: 1.2999e+01\n",
      "PDE: 1.2999e+01\n",
      "For uPDE, min uLW: 5.7304e+00, max uLW: 1.0726e+02\n",
      "For vPDE, min vLW: 9.1289e+00, max vLW: 8.6360e+01\n",
      "Starting with L-BFGS\n",
      "Iter  1000, Total: 1.5185e+00, PDE: 1.5185e+00\n",
      "Iter  2000, Total: 3.9476e-01, PDE: 3.9476e-01\n",
      "Iter  3000, Total: 1.5833e-01, PDE: 1.5833e-01\n",
      "Iter  4000, Total: 8.6152e-02, PDE: 8.6152e-02\n",
      "Iter  5000, Total: 4.9889e-02, PDE: 4.9889e-02\n"
     ]
    }
   ],
   "source": [
    "layers = [2, 32, 32, 32, 32, 32, 32, 32, 2]\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((ptsIC,ptsPDE))\n",
    "ptsPDE = np.vstack((ptsBC,ptsPDE))\n",
    "\n",
    "model = PhysicsInformedNN(period,m,ptsPDE,layers)\n",
    "model.train(50000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "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": 9,
   "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": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 125792 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()\n",
    "fig.savefig('NLSu_1D_BL+PBC+IC1+SA.png',format='png')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "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": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "l2: 0.011035388756549325\n",
      "l1: 0.00787827627567864\n",
      "linf: 0.011988007267256653\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": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "l2: 0.021009415204687118\n",
      "l1: 0.01644631681867614\n",
      "linf: 0.030258460391644842\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": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 257252 characters]",
      "text/plain": [
       "<Figure size 2400x600 with 6 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "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",
    "\n",
    "plt.show()\n",
    "fig.savefig('NLS3v_1D_BL+PBC+IC1+SA.png',format='png')"
   ]
  },
  {
   "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
}
