{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "dbbb73cb-a632-4056-bbca-b483b2ad5f9c",
   "metadata": {},
   "source": [
    "# Tutorial 7: Resolution of an inverse problem"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "84508f26-1ba6-4b59-926b-3e340d632a15",
   "metadata": {},
   "source": [
    "### Introduction to the inverse problem"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cae54664-4572-49df-8b2d-9e7dd1e45ec0",
   "metadata": {},
   "source": [
    "This tutorial shows how to solve an inverse Poisson problem with Physics-Informed Neural Networks. The problem definition is that of a Poisson problem with homogeneous boundary conditions and it reads:\n",
    "\\begin{equation}\n",
    "\\begin{cases}\n",
    "\\Delta u = e^{-2(x-\\mu_1)^2-2(y-\\mu_2)^2} \\text{ in } \\Omega\\, ,\\\\\n",
    "u = 0 \\text{ on }\\partial \\Omega,\\\\\n",
    "u(\\mu_1, \\mu_2) = \\text{ data}\n",
    "\\end{cases}\n",
    "\\end{equation}\n",
    "where $\\Omega$ is a square domain $[-2, 2] \\times [-2, 2]$, and $\\partial \\Omega=\\Gamma_1 \\cup \\Gamma_2 \\cup \\Gamma_3 \\cup \\Gamma_4$ is the union of the boundaries of the domain.\n",
    "\n",
    "This kind of problem, namely the \"inverse problem\", has two main goals:\n",
    "- find the solution $u$ that satisfies the Poisson equation;\n",
    "- find the unknown parameters ($\\mu_1$, $\\mu_2$) that better fit some given data (third equation in the system above).\n",
    "\n",
    "In order to achieve both the goals we will need to define an `InverseProblem` in PINA."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1f8cb1b-c1bc-4495-96e2-ce8e9102fe56",
   "metadata": {},
   "source": [
    "Let's start with useful imports."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "00d1027d-13f2-4619-9ff7-a740568f13ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import torch\n",
    "from pytorch_lightning.callbacks import Callback\n",
    "from pina.problem import SpatialProblem, InverseProblem\n",
    "from pina.operators import laplacian\n",
    "from pina.model import FeedForward\n",
    "from pina.equation import Equation, FixedValue\n",
    "from pina import Condition, Trainer\n",
    "from pina.solvers import PINN\n",
    "from pina.geometry import CartesianDomain"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5138afdf-bff6-46bf-b423-a22673190687",
   "metadata": {},
   "source": [
    "Then, we import the pre-saved data, for ($\\mu_1$, $\\mu_2$)=($0.5$, $0.5$). These two values are the optimal parameters that we want to find through the neural network training. In particular, we import the `input_points`(the spatial coordinates), and the `output_points` (the corresponding $u$ values evaluated at the `input_points`)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2c55d972-09a9-41de-9400-ba051c28cdcb",
   "metadata": {},
   "outputs": [],
   "source": [
    "data_output = torch.load('data/pinn_solution_0.5_0.5').detach()\n",
    "data_input = torch.load('data/pts_0.5_0.5')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6541ffbe-7940-421a-9048-a796ec56f1d6",
   "metadata": {},
   "source": [
    "Moreover, 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": 3,
   "id": "55cef553-7495-401d-9d17-1acff8ec5953",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 152184 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "points = data_input.extract(['x', 'y']).detach().numpy()\n",
    "truth = data_output.detach().numpy()\n",
    "\n",
    "plt.scatter(points[:, 0], points[:, 1], c=truth, s=8)\n",
    "plt.axis('equal')\n",
    "plt.colorbar()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de7c4c83",
   "metadata": {},
   "source": [
    "### Inverse problem definition in PINA"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c46410fa-2718-4fc9-977a-583fe2390028",
   "metadata": {},
   "source": [
    "Then, we initialize the Poisson problem, that is inherited from the `SpatialProblem` and from the `InverseProblem` classes. We here have to define all the variables, and the domain where our unknown parameters ($\\mu_1$, $\\mu_2$) belong. Notice that the laplace equation takes as inputs also the unknown variables, that will be treated as parameters that the neural network optimizes during the training process."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8ec0d95d-72c2-40a4-a310-21c3d6fe17d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "### Define ranges of variables\n",
    "x_min = -2\n",
    "x_max = 2\n",
    "y_min = -2\n",
    "y_max = 2\n",
    "\n",
    "class Poisson(SpatialProblem, InverseProblem):\n",
    "    '''\n",
    "    Problem definition for the Poisson equation.\n",
    "    '''\n",
    "    output_variables = ['u']\n",
    "    spatial_domain = CartesianDomain({'x': [x_min, x_max], 'y': [y_min, y_max]})\n",
    "    # define the ranges for the parameters\n",
    "    unknown_parameter_domain = CartesianDomain({'mu1': [-1, 1], 'mu2': [-1, 1]})\n",
    "\n",
    "    def laplace_equation(input_, output_, params_):\n",
    "        '''\n",
    "        Laplace equation with a force term.\n",
    "        '''\n",
    "        force_term = torch.exp(\n",
    "                - 2*(input_.extract(['x']) - params_['mu1'])**2\n",
    "                - 2*(input_.extract(['y']) - params_['mu2'])**2)\n",
    "        delta_u = laplacian(output_, input_, components=['u'], d=['x', 'y'])\n",
    "\n",
    "        return delta_u - force_term\n",
    "\n",
    "    # define the conditions for the loss (boundary conditions, equation, data)\n",
    "    conditions = {\n",
    "        'gamma1': Condition(location=CartesianDomain({'x': [x_min, x_max],\n",
    "            'y':  y_max}),\n",
    "            equation=FixedValue(0.0, components=['u'])),\n",
    "        'gamma2': Condition(location=CartesianDomain({'x': [x_min, x_max], 'y': y_min\n",
    "            }),\n",
    "            equation=FixedValue(0.0, components=['u'])),\n",
    "        'gamma3': Condition(location=CartesianDomain({'x':  x_max, 'y': [y_min, y_max]\n",
    "            }),\n",
    "            equation=FixedValue(0.0, components=['u'])),\n",
    "        'gamma4': Condition(location=CartesianDomain({'x': x_min, 'y': [y_min, y_max]\n",
    "            }),\n",
    "            equation=FixedValue(0.0, components=['u'])),\n",
    "        'D': Condition(location=CartesianDomain({'x': [x_min, x_max], 'y': [y_min, y_max]\n",
    "            }),\n",
    "        equation=Equation(laplace_equation)),\n",
    "        'data': Condition(input_points=data_input.extract(['x', 'y']), output_points=data_output)\n",
    "    }\n",
    "\n",
    "problem = Poisson()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b264569-57b3-458d-bb69-8e94fe89017d",
   "metadata": {},
   "source": [
    "Then, we define the model of the neural network we want to use. Here we used a model which impose hard constrains on the boundary conditions, as also done in the Wave tutorial!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c4170514-eb73-488e-8942-0129070e4e13",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = FeedForward(\n",
    "    layers=[20, 20, 20],\n",
    "    func=torch.nn.Softplus,\n",
    "    output_dimensions=len(problem.output_variables),\n",
    "    input_dimensions=len(problem.input_variables)\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16e1f085-7818-4624-92a1-bf7010dbe528",
   "metadata": {},
   "source": [
    "After that, we discretize the spatial domain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e3e0ae40-d8c6-4c08-81e8-85adc60a94e6",
   "metadata": {},
   "outputs": [],
   "source": [
    "problem.discretise_domain(20, 'grid', locations=['D'], variables=['x', 'y'])\n",
    "problem.discretise_domain(1000, 'random', locations=['gamma1', 'gamma2',\n",
    "    'gamma3', 'gamma4'], variables=['x', 'y'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b272796a-888c-4795-9d88-3e13121e8f38",
   "metadata": {},
   "source": [
    "Here, we define a simple callback for the trainer. We use this callback to save the parameters predicted by the neural network during the training. The parameters are saved every 100 epochs as `torch` tensors in a specified directory (`tmp_dir` in our case).\n",
    "The goal is to read the saved parameters after training and plot their trend across the epochs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e1409953-eb1b-443b-923d-c7ec3af0dfb0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# temporary directory for saving logs of training\n",
    "tmp_dir = \"tmp_poisson_inverse\"\n",
    "\n",
    "class SaveParameters(Callback):\n",
    "    '''\n",
    "    Callback to save the parameters of the model every 100 epochs.\n",
    "    '''\n",
    "    def on_train_epoch_end(self, trainer, __):\n",
    "        if trainer.current_epoch % 100 == 99:\n",
    "            torch.save(trainer.solver.problem.unknown_parameters, '{}/parameters_epoch{}'.format(tmp_dir, trainer.current_epoch))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fc6e0030-f6ae-40cf-a3b3-d21d6538e7f2",
   "metadata": {},
   "source": [
    "Then, we define the `PINN` object and train the solver using the `Trainer`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "05a0f311-3cca-429b-be2c-1fa899b14e62",
   "metadata": {},
   "outputs": [],
   "source": [
    "### train the problem with PINN\n",
    "max_epochs = 5000\n",
    "pinn = PINN(problem, model, optimizer_kwargs={'lr':0.005})\n",
    "# define the trainer for the solver\n",
    "trainer = Trainer(solver=pinn, accelerator='cpu', max_epochs=max_epochs,\n",
    "        default_root_dir=tmp_dir, callbacks=[SaveParameters()])\n",
    "trainer.train()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aab51202-36a7-40d2-b96d-47af8892cd2c",
   "metadata": {},
   "source": [
    "One can now see how the parameters vary during the training by reading the saved solution and plotting them. The plot shows that the parameters stabilize to their true value before reaching the epoch $1000$!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "dd328887-7c18-4b96-ada4-c9eec630c069",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 13812 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "epochs_saved = range(99, max_epochs, 100)\n",
    "parameters = torch.empty((int(max_epochs/100), 2))\n",
    "for i, epoch in enumerate(epochs_saved):\n",
    "    params_torch = torch.load('{}/parameters_epoch{}'.format(tmp_dir, epoch))\n",
    "    for e, var in enumerate(pinn.problem.unknown_variables):         \n",
    "        parameters[i, e] = params_torch[var].data\n",
    "\n",
    "# Plot parameters\n",
    "plt.close()\n",
    "plt.plot(epochs_saved, parameters[:, 0], label='mu1', marker='o')\n",
    "plt.plot(epochs_saved, parameters[:, 1], label='mu2', marker='s')\n",
    "plt.ylim(-1, 1)\n",
    "plt.grid()\n",
    "plt.legend()\n",
    "plt.xlabel('Epoch')\n",
    "plt.ylabel('Parameter value')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f6a0ba58",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
