{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dbbb73cb-a632-4056-bbca-b483b2ad5f9c",
   "metadata": {},
   "source": [
    "# Tutorial 8: Reduced order model (PODNN) for parametric problems"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84508f26-1ba6-4b59-926b-3e340d632a15",
   "metadata": {},
   "source": [
    "The tutorial aims to show how to employ the **PINA** library in order to apply a reduced order modeling technique [1]. Such methodologies have several similarities with machine learning approaches, since the main goal consists of predicting the solution of differential equations (typically parametric PDEs) in a real-time fashion.\n",
    "\n",
    "In particular we are going to use the Proper Orthogonal Decomposition with Neural Network (PODNN) [2], which basically perform a dimensional reduction using the POD approach, approximating the parametric solution manifold (at the reduced space) using a NN. In this example, we use a simple multilayer perceptron, but the plenty of different archiutectures can be plugged as well.\n",
    "\n",
    "#### References\n",
    "1. Rozza G., Stabile G., Ballarin F. (2022). Advanced Reduced Order Methods and Applications in Computational Fluid Dynamics, Society for Industrial and Applied Mathematics. \n",
    "2. Hesthaven, J. S., & Ubbiali, S. (2018). Non-intrusive reduced order modeling of nonlinear problems using neural networks. Journal of Computational Physics, 363, 55-78."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1f8cb1b-c1bc-4495-96e2-ce8e9102fe56",
   "metadata": {},
   "source": [
    "Let's start with the necessary imports.\n",
    "It's important to note the minimum PINA version to run this tutorial is the `0.1`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "00d1027d-13f2-4619-9ff7-a740568f13ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "We are using PINA version 0.1\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import torch\n",
    "import pina\n",
    "\n",
    "from pina.geometry import CartesianDomain\n",
    "\n",
    "from pina.problem import ParametricProblem\n",
    "from pina.model.layers import PODLayer\n",
    "from pina import Condition, LabelTensor, Trainer\n",
    "from pina.model import FeedForward\n",
    "from pina.solvers import SupervisedSolver\n",
    "\n",
    "print(f'We are using PINA version {pina.__version__}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5138afdf-bff6-46bf-b423-a22673190687",
   "metadata": {},
   "source": [
    "We exploit the [Smithers](www.github.com/mathLab/Smithers) library to collect the parametric snapshots. In particular, we use the `NavierStokesDataset` class that contains a set of parametric solutions of the Navier-Stokes equations in a 2D L-shape domain. The parameter is the inflow velocity.\n",
    "The dataset is composed by 500 snapshots of the velocity (along $x$, $y$, and the magnitude) and pressure fields, and the corresponding parameter values.\n",
    "\n",
    "To visually check the snapshots, let's plot also the data points and the reference solution: this is the expected output of the neural network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "2c55d972-09a9-41de-9400-ba051c28cdcb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 0:   0%|          | 0/5 [48:45<?, ?it/s]\n",
      "Epoch 0:   0%|          | 0/5 [46:33<?, ?it/s]\n",
      "Epoch 0:   0%|          | 0/5 [46:17<?, ?it/s]\n",
      "Epoch 0:   0%|          | 0/5 [44:52<?, ?it/s]\n",
      "Epoch 0:   0%|          | 0/5 [43:41<?, ?it/s]\n",
      "Epoch 0:   0%|          | 0/5 [43:01<?, ?it/s]\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 37212 characters]",
      "text/plain": [
       "<Figure size 1400x300 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from smithers.dataset import NavierStokesDataset\n",
    "dataset = NavierStokesDataset()\n",
    "\n",
    "fig, axs = plt.subplots(1, 4, figsize=(14, 3))\n",
    "for ax, p, u in zip(axs, dataset.params[:4], dataset.snapshots['mag(v)'][:4]):\n",
    "    ax.tricontourf(dataset.triang, u, levels=16)\n",
    "    ax.set_title(f'$\\mu$ = {p[0]:.2f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bef4d79d",
   "metadata": {},
   "source": [
    "The *snapshots* - aka the numerical solutions computed for several parameters - and the corresponding parameters are the only data we need to train the model, in order to predict for any new test parameter the solution.\n",
    "To properly validate the accuracy, we initially split the 500 snapshots into the training dataset (90% of the original data) and the testing one (the reamining 10%). It must be said that, to plug the snapshots into **PINA**, we have to cast them to `LabelTensor` objects."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "bd081bcd-192f-4370-a013-9b73050b5383",
   "metadata": {},
   "outputs": [],
   "source": [
    "u = torch.tensor(dataset.snapshots['mag(v)']).float()\n",
    "p = torch.tensor(dataset.params).float()\n",
    "\n",
    "p = LabelTensor(p, labels=['mu'])\n",
    "u = LabelTensor(u, labels=[f's{i}' for i in range(u.shape[1])])\n",
    "\n",
    "ratio_train_test = 0.9\n",
    "n = u.shape\n",
    "n_train = int(u.shape[0] * ratio_train_test)\n",
    "n_test = u - n_train\n",
    "u_train, u_test = u[:n_train], u[n_train:]\n",
    "p_train, p_test = p[:n_train], p[n_train:]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c46410fa-2718-4fc9-977a-583fe2390028",
   "metadata": {},
   "source": [
    "It is now time to define the problem! We inherit from `ParametricProblem` (since the space invariant typically of this methodology), just defining a simple *input-output* condition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "55cef553-7495-401d-9d17-1acff8ec5953",
   "metadata": {},
   "outputs": [],
   "source": [
    "class SnapshotProblem(ParametricProblem):\n",
    "    output_variables = [f's{i}' for i in range(u.shape[1])]\n",
    "    parameter_domain = CartesianDomain({'mu': [0, 100]})\n",
    "\n",
    "    conditions = {\n",
    "        'io': Condition(input_points=p, output_points=u)\n",
    "    }"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b264569-57b3-458d-bb69-8e94fe89017d",
   "metadata": {},
   "source": [
    "Then, we define the model we want to use: basically we have a MLP architecture that takes in input the parameter and return the *modal coefficients*, so the reduced dimension representation (the coordinates in the POD space). Such latent variable is the projected to the original space using the POD modes, which are computed and stored in the `PODLayer` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "c4170514-eb73-488e-8942-0129070e4e13",
   "metadata": {},
   "outputs": [],
   "source": [
    "class PODNN(torch.nn.Module):\n",
    "    \"\"\"\n",
    "    Proper orthogonal decomposition with neural network model.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(self, pod_rank, layers, func):\n",
    "        \"\"\"\n",
    "        \n",
    "        \"\"\"\n",
    "        super().__init__()\n",
    "        \n",
    "        self.pod = PODLayer(pod_rank)\n",
    "        self.nn = FeedForward(\n",
    "            input_dimensions=1,\n",
    "            output_dimensions=pod_rank,\n",
    "            layers=layers,\n",
    "            func=func\n",
    "        )\n",
    "            \n",
    "\n",
    "    def forward(self, x):\n",
    "        \"\"\"\n",
    "        Defines the computation performed at every call.\n",
    "\n",
    "        :param x: The tensor to apply the forward pass.\n",
    "        :type x: torch.Tensor\n",
    "        :return: the output computed by the model.\n",
    "        :rtype: torch.Tensor\n",
    "        \"\"\"\n",
    "        coefficents = self.nn(x)\n",
    "        return self.pod.expand(coefficents)\n",
    "\n",
    "    def fit_pod(self, x):\n",
    "        \"\"\"\n",
    "        Just call the :meth:`pina.model.layers.PODLayer.fit` method of the\n",
    "        :attr:`pina.model.layers.PODLayer` attribute.\n",
    "        \"\"\"\n",
    "        self.pod.fit(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16e1f085-7818-4624-92a1-bf7010dbe528",
   "metadata": {},
   "source": [
    "We highlight that the POD modes are directly computed by means of the singular value decomposition (computed over the input data), and not trained using the back-propagation approach. Only the weights of the MLP are actually trained during the optimization loop."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "e998cad5-e3a7-4a3b-a1a5-400b6ff575a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "poisson_problem = SnapshotProblem()\n",
    "\n",
    "pod_nn = PODNN(pod_rank=20, layers=[10, 10, 10], func=torch.nn.Tanh)\n",
    "pod_nn.fit_pod(u)\n",
    "\n",
    "pinn_stokes = SupervisedSolver(\n",
    "    problem=poisson_problem, \n",
    "    model=pod_nn, \n",
    "    optimizer=torch.optim.Adam,\n",
    "    optimizer_kwargs={'lr': 0.0001})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aab51202-36a7-40d2-b96d-47af8892cd2c",
   "metadata": {},
   "source": [
    "Now that we set the `Problem` and the `Model`, we have just to train the model and use it for predict the test snapshots."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "f1e94f42-cf80-4ca7-bb5e-ad47c1dd2784",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "GPU available: False, used: False\n",
      "TPU available: False, using: 0 TPU cores\n",
      "IPU available: False, using: 0 IPUs\n",
      "HPU available: False, using: 0 HPUs\n",
      "\n",
      "  | Name        | Type    | Params\n",
      "----------------------------------------\n",
      "0 | _loss       | MSELoss | 0     \n",
      "1 | _neural_net | Network | 460   \n",
      "----------------------------------------\n",
      "460       Trainable params\n",
      "0         Non-trainable params\n",
      "460       Total params\n",
      "0.002     Total estimated model params size (MB)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 999: 100%|██████████| 5/5 [00:00<00:00, 286.50it/s, v_num=20, mean_loss=0.902]"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "`Trainer.fit` stopped: `max_epochs=1000` reached.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 999: 100%|██████████| 5/5 [00:00<00:00, 248.36it/s, v_num=20, mean_loss=0.902]\n"
     ]
    }
   ],
   "source": [
    "trainer = Trainer(\n",
    "    solver=pinn_stokes,\n",
    "    max_epochs=1000,\n",
    "    batch_size=100,\n",
    "    log_every_n_steps=5,\n",
    "    accelerator='cpu')\n",
    "trainer.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3234710e",
   "metadata": {},
   "source": [
    "Done! Now the computational expensive part is over, we can load in future the model to infer new parameters (simply loading the checkpoint file automatically created by `Lightning`) or test its performances. We measure the relative error for the training and test datasets, printing the mean one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "26c91385-5cd8-400a-90db-1c9f2afdf110",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Error summary:\n",
      "  Train: 3.865598e-02\n",
      "  Test:  3.593161e-02\n"
     ]
    }
   ],
   "source": [
    "u_test_pred = pinn_stokes(p_test)\n",
    "u_train_pred = pinn_stokes(p_train)\n",
    "\n",
    "relative_error_train = torch.norm(u_train_pred - u_train)/torch.norm(u_train)\n",
    "relative_error_test = torch.norm(u_test_pred - u_test)/torch.norm(u_test)\n",
    "\n",
    "print('Error summary:')\n",
    "print(f'  Train: {relative_error_train.item():e}')\n",
    "print(f'  Test:  {relative_error_test.item():e}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5ba9ab9",
   "metadata": {},
   "source": [
    "We can of course also plot the solutions predicted by the `PODNN` model, comparing them to the original ones. We can note here some differences, especially for low velocities, but improvements can be accomplished thanks to longer training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "ed8bf2ce-9208-4395-9a64-42ac96006bc3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 180772 characters]",
      "text/plain": [
       "<Figure size 1400x900 with 24 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "idx = torch.randint(0, len(u_test_pred), (4,))\n",
    "u_idx = pinn_stokes(p_test[idx])\n",
    "import numpy as np\n",
    "import matplotlib\n",
    "fig, axs = plt.subplots(3, 4, figsize=(14, 9))\n",
    "\n",
    "relative_error = np.abs(u_test[idx] - u_idx.detach())\n",
    "relative_error = np.where(u_test[idx] < 1e-7, 1e-7, relative_error/u_test[idx])\n",
    "                        \n",
    "for i, (idx_, u_, err_) in enumerate(zip(idx, u_idx, relative_error)):\n",
    "    cm = axs[0, i].tricontourf(dataset.triang, u_.detach())\n",
    "    axs[0, i].set_title(f'$\\mu$ = {p_test[idx_].item():.2f}')\n",
    "    plt.colorbar(cm)\n",
    "\n",
    "    cm = axs[1, i].tricontourf(dataset.triang, u_test[idx_].flatten())\n",
    "    plt.colorbar(cm)\n",
    "\n",
    "    cm = axs[2, i].tripcolor(dataset.triang, err_, norm=matplotlib.colors.LogNorm())\n",
    "    plt.colorbar(cm)\n",
    "\n",
    "\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.18 ('gridcal')",
   "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.9.18"
  },
  "vscode": {
   "interpreter": {
    "hash": "812fc65ca8c4f5385369e756893b1e5d443bf42489b0b3ab8df91541fbfe2649"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
