{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "active-ipynb",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    from openmdao.utils.notebook_utils import notebook_mode\n",
    "except ImportError:\n",
    "    !python -m pip install openmdao[notebooks]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# NearestNeighbor\n",
    "\n",
    "Surrogate model based on the N-Dimensional Interpolation library by Stephen Marone.\n",
    "\n",
    "Here is a simple example where the *NearestNeighbor* surrogate is used to approximate the output of a sinusoidal component."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import openmdao.api as om\n",
    "\n",
    "prob = om.Problem()\n",
    "\n",
    "sin_mm = om.MetaModelUnStructuredComp()\n",
    "sin_mm.add_input('x', 2.1)\n",
    "sin_mm.add_output('f_x', 0., surrogate=om.NearestNeighbor(interpolant_type='linear'))\n",
    "\n",
    "prob.model.add_subsystem('sin_mm', sin_mm)\n",
    "\n",
    "prob.setup()\n",
    "\n",
    "# train the surrogate and check predicted value\n",
    "sin_mm.options['train:x'] = np.linspace(0,10,20)\n",
    "sin_mm.options['train:f_x'] = .5*np.sin(sin_mm.options['train:x'])\n",
    "\n",
    "prob.set_val('sin_mm.x', 2.1)\n",
    "\n",
    "prob.run_model()\n",
    "\n",
    "print(prob.get_val('sin_mm.f_x'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.assert_utils import assert_near_equal\n",
    "assert_near_equal(prob.get_val('sin_mm.f_x'), .5*np.sin(prob.get_val('sin_mm.x')), 2e-3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## NearestNeighbor Options\n",
    "\n",
    "All options can be passed in as arguments or set later by accessing the *options* dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "om.show_options_table(\"openmdao.surrogate_models.nearest_neighbor.NearestNeighbor\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additional interpolant-specific options can be passed in as call arguments.\n",
    "\n",
    "## NearestNeighbor Constructor\n",
    "\n",
    "The call signature for the *NearestNeighbor* constructor is:\n",
    "```{eval-rst}\n",
    "    .. automethod:: openmdao.surrogate_models.nearest_neighbor.NearestNeighbor.__init__\n",
    "        :noindex:\n",
    "```\n",
    "\n",
    "## NearestNeighbor Option Examples\n",
    "\n",
    "**interpolant_type**\n",
    "\n",
    "The NearestNeighbor surrogate allows you to choose from three different interpolant types.\n",
    "\n",
    "| Interpolant | Description |\n",
    "| --- | --- |\n",
    "| linear | Interpolates values by forming a hyperplane between the points closest to the prescribed inputs |\n",
    "| weighted | Computes the weights based on the distance and distance effect. |\n",
    "| rbf | Compactly Supported Radial Basis Function. (Default) |\n",
    "\n",
    "**rbf interpolator arguments**\n",
    "\n",
    "When the \"interpolant_type\" option is set to \"rbf\", there are some additional arguments that can be used to control the radial basis function interpolant.\n",
    "\n",
    "For example, here we use the rbf interpolant for our simple sine model and set the number of neighbors (\"num_neighbors\") to 3."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import openmdao.api as om\n",
    "\n",
    "prob = om.Problem()\n",
    "\n",
    "sin_mm = om.MetaModelUnStructuredComp()\n",
    "sin_mm.add_input('x', 2.1)\n",
    "sin_mm.add_output('f_x', 0., surrogate=om.NearestNeighbor(interpolant_type='rbf', num_neighbors=3))\n",
    "\n",
    "prob.model.add_subsystem('sin_mm', sin_mm)\n",
    "\n",
    "prob.setup()\n",
    "\n",
    "# train the surrogate and check predicted value\n",
    "sin_mm.options['train:x'] = np.linspace(0,10,20)\n",
    "sin_mm.options['train:f_x'] = .5*np.sin(sin_mm.options['train:x'])\n",
    "\n",
    "prob.set_val('sin_mm.x', 2.1)\n",
    "\n",
    "prob.run_model()\n",
    "\n",
    "print(prob.get_val('sin_mm.f_x'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "assert_near_equal(prob.get_val('sin_mm.f_x'), .5*np.sin(prob.get_val('sin_mm.x')), 5e-3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "The following parameters are available to be adjusted:\n",
    "\n",
    "**num_neighbors** (int)\n",
    "    \n",
    "The number of neighbors to use for interpolation.\n",
    "    \n",
    "**rbf_family** (int)\n",
    "    \n",
    "Specifies the order of the radial basis function to be used.\n",
    "  \n",
    " - -2 uses an 11th order\n",
    " - -1 uses a 9th order\n",
    " - any value from 0 to 4 uses an order equal to floor((dimensions-1)/2) + (3\\*comp) +1"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "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.5"
  },
  "orphan": true
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
