{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "802ca67f",
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output",
     "active-ipynb"
    ]
   },
   "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",
   "id": "f4a68df6",
   "metadata": {},
   "source": [
    "# Visually Checking Partial Derivatives with Matrix Diagrams\n",
    "\n",
    "The function `partial_deriv_plot` lets you see a visual representation of the values returned by `check_partials`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48671407",
   "metadata": {},
   "source": [
    "```{eval-rst}\n",
    "    .. autofunction:: openmdao.visualization.partial_deriv_plot.partial_deriv_plot\n",
    "        :noindex:\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fe1e73d",
   "metadata": {},
   "source": [
    "Here are two examples of its use. Note that in these examples, the `compute_partials` method intentionally computes the incorrect value so that the plots show how this function can be used to detect such errors.\n",
    "\n",
    "With the default value of `binary` equal to `True`, the plots will only show the presence of a non-zero derivative, not the value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7a85c98",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import openmdao.api as om\n",
    "\n",
    "class ArrayComp2D(om.ExplicitComponent):\n",
    "    \"\"\"\n",
    "    A fairly simple array component with an intentional error in compute_partials.\n",
    "    \"\"\"\n",
    "    def setup(self):\n",
    "        self.JJ = np.array([[1.0, 0.0, 0.0, 7.0],\n",
    "                            [0.0, 2.5, 0.0, 0.0],\n",
    "                            [-1.0, 0.0, 8.0, 0.0],\n",
    "                            [0.0, 4.0, 0.0, 6.0]])\n",
    "        # Params\n",
    "        self.add_input('x1', np.ones([4]))\n",
    "        # Unknowns\n",
    "        self.add_output('y1', np.zeros([4]))\n",
    "        self.declare_partials(of='*', wrt='*')\n",
    "\n",
    "    def compute(self, inputs, outputs):\n",
    "        \"\"\"\n",
    "        Execution.\n",
    "        \"\"\"\n",
    "        outputs['y1'] = self.JJ.dot(inputs['x1'])\n",
    "\n",
    "    def compute_partials(self, inputs, partials):\n",
    "        \"\"\"\n",
    "        Analytical derivatives.\n",
    "        \"\"\"\n",
    "        # create some error to force the diff plot to show something\n",
    "        error = np.zeros((4, 4))\n",
    "        err = 1e-7\n",
    "        error[0][3] = err\n",
    "        error[1][2] = - 2.0 * err\n",
    "        partials[('y1', 'x1')] = self.JJ + error\n",
    "\n",
    "prob = om.Problem()\n",
    "model = prob.model\n",
    "model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1'])\n",
    "prob.setup(check=False, mode='fwd')\n",
    "check_partials_data = prob.check_partials(out_stream=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "866df6b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot with defaults\n",
    "om.partial_deriv_plot('y1', 'x1', check_partials_data)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ccc1f33",
   "metadata": {},
   "source": [
    "With the value of `binary` equal to `False`, the plots show the actual value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d975bff5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import openmdao.api as om\n",
    "\n",
    "class ArrayComp2D(om.ExplicitComponent):\n",
    "    \"\"\"\n",
    "    A fairly simple array component with an intentional error in compute_partials.\n",
    "    \"\"\"\n",
    "    def setup(self):\n",
    "        self.JJ = np.array([[1.0, 0.0, 0.0, 7.0],\n",
    "                            [0.0, 2.5, 0.0, 0.0],\n",
    "                            [-1.0, 0.0, 8.0, 0.0],\n",
    "                            [0.0, 4.0, 0.0, 6.0]])\n",
    "        # Params\n",
    "        self.add_input('x1', np.ones([4]))\n",
    "        # Unknowns\n",
    "        self.add_output('y1', np.zeros([4]))\n",
    "        self.declare_partials(of='*', wrt='*')\n",
    "\n",
    "    def compute(self, inputs, outputs):\n",
    "        \"\"\"\n",
    "        Execution.\n",
    "        \"\"\"\n",
    "        outputs['y1'] = self.JJ.dot(inputs['x1'])\n",
    "\n",
    "    def compute_partials(self, inputs, partials):\n",
    "        \"\"\"\n",
    "        Analytical derivatives.\n",
    "        \"\"\"\n",
    "        # create some error to force the diff plot to show something\n",
    "        error = np.zeros((4, 4))\n",
    "        err = 1e-7\n",
    "        error[0][3] = err\n",
    "        error[1][2] = - 2.0 * err\n",
    "        partials[('y1', 'x1')] = self.JJ + error\n",
    "\n",
    "prob = om.Problem()\n",
    "model = prob.model\n",
    "model.add_subsystem('mycomp', ArrayComp2D(), promotes=['x1', 'y1'])\n",
    "prob.setup(check=False, mode='fwd')\n",
    "check_partials_data = prob.check_partials(out_stream=None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc83d108",
   "metadata": {},
   "outputs": [],
   "source": [
    "# plot in non-binary mode\n",
    "om.partial_deriv_plot('y1', 'x1', check_partials_data, binary = False)"
   ]
  }
 ],
 "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": 5
}
