{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Tutorial 1: Physics Informed Neural Networks on PINA"
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "In this tutorial we will show the typical use case of PINA on a toy problem. Specifically, the tutorial aims to introduce the following topics:\n",
    "\n",
    "* Defining a PINA Problem,\n",
    "* Build a `pinn` object,\n",
    "* Sample points in the domain.\n",
    "\n",
    "These are the three main steps needed **before** training a Physics Informed Neural Network (PINN). We will show in detailed each step, and at the end we will solve a very simple problem with PINA."
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "## PINA Problem"
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Initialize the Problem class"
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "The problem definition in the PINA framework is done by building a phython `class`, inherited from one or more problem classes (`SpatialProblem`, `TimeDependentProblem`, `ParametricProblem`), depending on the nature of the problem treated. Let's see an example to better understand:\n",
    "#### Simple Ordinary Differential Equation\n",
    "Consider the following:\n",
    "\n",
    "$$\n",
    "\\begin{equation}\n",
    "\\begin{cases}\n",
    "\\frac{d}{dx}u(x) &=  u(x) \\quad x\\in(0,1)\\\\\n",
    "u(x=0) &= 1 \\\\\n",
    "\\end{cases}\n",
    "\\end{equation}\n",
    "$$\n",
    "\n",
    "with analytical solution $u(x) = e^x$. In this case we have that our ODE depends only on the spatial variable $x\\in(0,1)$ , this means that our problem class is going to be inherited from `SpatialProblem` class:\n",
    "\n",
    "```python\n",
    "from pina.problem import SpatialProblem\n",
    "from pina import Span\n",
    "\n",
    "class SimpleODE(SpatialProblem):\n",
    "    \n",
    "    output_variables = ['u']\n",
    "    spatial_domain = Span({'x': [0, 1]})\n",
    "\n",
    "    # other stuff ...\n",
    "```\n",
    "\n",
    "Notice that we define `output_variables` as a list of symbols, indicating the output variables of our equation (in this case only $u$). The `spatial_domain` variable indicates where the sample points are going to be sampled in the domain, in this case $x\\in(0,1)$."
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "What about if we also have a time depencency in the equation? Well in that case our `class` will inherit from both `SpatialProblem` and `TimeDependentProblem`:\n",
    "```python\n",
    "from pina.problem import SpatialProblem, TimeDependentProblem\n",
    "from pina import Span\n",
    "\n",
    "class TimeSpaceODE(SpatialProblem, TimeDependentProblem):\n",
    "    \n",
    "    output_variables = ['u']\n",
    "    spatial_domain = Span({'x': [0, 1]})\n",
    "    temporal_domain = Span({'x': [0, 1]})\n",
    "\n",
    "    # other stuff ...\n",
    "```\n",
    "where we have included the `temporal_domain` variable indicating the time domain where we want the solution.\n",
    "\n",
    "Summarizing, in PINA we can initialize a problem with a class which is inherited from three base classes: `SpatialProblem`, `TimeDependentProblem`, `ParametricProblem`, depending on the type of problem we are considering. For reference:\n",
    "* `SpatialProblem` $\\rightarrow$ spatial variable(s) presented in the differential equation\n",
    "* `TimeDependentProblem` $\\rightarrow$ time variable(s) presented in the differential equation\n",
    "* `ParametricProblem` $\\rightarrow$ parameter(s) presented in the differential equation\n"
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Write the problem class\n",
    "\n",
    "Once the problem class is initialized we need to write the differential equation in PINA language. For doing this we need to load the pina operators found in `pina.operators` module. Let's again consider the Equation (1) and try to write the PINA model class:"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "source": [
    "from pina.problem import SpatialProblem\n",
    "from pina.operators import grad\n",
    "from pina import Condition, Span\n",
    "\n",
    "import torch\n",
    "\n",
    "\n",
    "class SimpleODE(SpatialProblem):\n",
    "\n",
    "    output_variables = ['u']\n",
    "    spatial_domain = Span({'x': [0, 1]})\n",
    "\n",
    "    # defining the ode equation\n",
    "    def ode_equation(input_, output_):\n",
    "\n",
    "        # computing the derivative\n",
    "        u_x = grad(output_, input_, components=['u'], d=['x'])\n",
    "\n",
    "        # extracting u input variable\n",
    "        u = output_.extract(['u'])\n",
    "\n",
    "        # calculate residual and return it\n",
    "        return u_x - u\n",
    "\n",
    "    # defining initial condition\n",
    "    def initial_condition(input_, output_):\n",
    "        \n",
    "        # setting initial value\n",
    "        value = 1.0\n",
    "\n",
    "        # extracting u input variable\n",
    "        u = output_.extract(['u'])\n",
    "\n",
    "        # calculate residual and return it\n",
    "        return u - value\n",
    "\n",
    "    # Conditions to hold\n",
    "    conditions = {\n",
    "        'x0': Condition(Span({'x': 0.}), initial_condition),\n",
    "        'D': Condition(Span({'x': [0, 1]}), ode_equation),\n",
    "    }\n",
    "\n",
    "    # defining true solution\n",
    "    def truth_solution(self, pts):\n",
    "        return torch.exp(pts.extract(['x']))\n"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "After the defition of the Class we need to write different class methods, where each method is a function returning a residual. This functions are the ones minimized during the PINN optimization, for the different conditions. For example, in the domain $(0,1)$ the ODE equation (`ode_equation`) must be satisfied, so we write it by putting all the ODE equation on the right hand side, such that we return the zero residual. This is done for all the conditions  (`ode_equation`, `initial_condition`). \n",
    "\n",
    "Once we have defined the function we need to tell the network where these methods have to be applied. For doing this we use the class `Condition`. In `Condition` we pass the location points and the function to be minimized on those points (other possibilities are allowed, see the documentation for reference).\n",
    "\n",
    "Finally, it's possible to defing the `truth_solution` function, which can be useful if we want to plot the results and see a comparison of real vs expected solution. Notice that `truth_solution` function is a method of the `PINN` class, but it is not mandatory for the problem definition."
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Build PINN object"
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "The basics requirements for building a PINN model are a problem and a model. We have already covered the problem definition. For the model one can use the default models provided in PINA or use a custom model. We will not go into the details of model definition, Tutorial2 and Tutorial3 treat the topic in detail."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "source": [
    "from pina.model import FeedForward\n",
    "from pina import PINN\n",
    "\n",
    "# initialize the problem\n",
    "problem = SimpleODE()\n",
    "\n",
    "# build the model\n",
    "model = FeedForward(\n",
    "    layers=[10, 10],\n",
    "    func=torch.nn.Tanh,\n",
    "    output_variables=problem.output_variables,\n",
    "    input_variables=problem.input_variables\n",
    ")\n",
    "\n",
    "# create the PINN object\n",
    "pinn = PINN(problem, model)\n"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "Creating the pinn object is fairly simple by using the `PINN` class, different optional inputs can be passed: optimizer, batch size, ... (see [documentation](https://mathlab.github.io/PINA/) for reference)."
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "## Sample points in the domain "
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "Once the `pinn` object is created, we need to generate the points for starting the optimization. For doing this we use the `span_pts` method of the `PINN` class.\n",
    "Let's see some methods to sample in $(0,1 )$."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "source": [
    "# sampling 20 points in (0, 1) with discrite step\n",
    "pinn.span_pts(20, 'grid', locations=['D'])\n",
    "\n",
    "# sampling 20 points in (0, 1) with latin hypercube\n",
    "pinn.span_pts(20, 'latin', locations=['D'])\n",
    "\n",
    "# sampling 20 points in (0, 1) randomly\n",
    "pinn.span_pts(20, 'random', locations=['D'])\n"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "We can also use a dictionary for specific variables:"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "source": [
    "pinn.span_pts({'variables': ['x'], 'mode': 'grid', 'n': 20}, locations=['D'])\n"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "We are going to use equispaced points for sampling. We need to sample in all the conditions domains. In our case we sample in `D` and `x0`."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "source": [
    "# sampling for training\n",
    "pinn.span_pts(1, 'random', locations=['x0'])\n",
    "pinn.span_pts(20, 'grid', locations=['D'])\n"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "### Very simple training and plotting\n",
    "\n",
    "Once we have defined the PINA model, created a network and sampled points in the domain, we have everything that is necessary for training a PINN. Here we show a very short training and some method for plotting the results."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "source": [
    "# simple training \n",
    "final_loss = pinn.train(stop=3000, frequency_print=1000)"
   ],
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "              sum          x0initial_co Dode_equatio \n",
      "[epoch 00000] 1.933187e+00 1.825489e+00 1.076983e-01 \n",
      "              sum          x0initial_co Dode_equatio \n",
      "[epoch 00001] 1.860870e+00 1.766795e+00 9.407549e-02 \n",
      "              sum          x0initial_co Dode_equatio \n",
      "[epoch 01000] 4.974120e-02 1.635524e-02 3.338596e-02 \n",
      "              sum          x0initial_co Dode_equatio \n",
      "[epoch 02000] 1.099083e-03 3.420736e-05 1.064875e-03 \n",
      "[epoch 03000] 4.049759e-04 2.937766e-06 4.020381e-04 \n"
     ]
    }
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "After the training we have saved the final loss in `final_loss`, which we can inspect. By default PINA uses mean square error loss."
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "source": [
    "# inspecting final loss\n",
    "final_loss\n"
   ],
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "0.0004049759008921683"
      ]
     },
     "metadata": {},
     "execution_count": 36
    }
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "By using the `Plotter` class from PINA we can also do some quatitative plots of the loss function. "
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "source": [
    "from pina.plotter import Plotter\n",
    "\n",
    "# plotting the loss\n",
    "plotter = Plotter()\n",
    "plotter.plot_loss(pinn)"
   ],
   "outputs": [
    {
     "output_type": "display_data",
     "data": {
      "image/png": "[encoded data, 12756 characters]",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     }
    }
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "We have a very smooth loss decreasing!"
   ],
   "metadata": {}
  }
 ],
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3.9.0 64-bit"
  },
  "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.0"
  },
  "interpreter": {
   "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}