{
 "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": [
    "# Basics of Creating N2 Model Visualizations\n",
    "\n",
    "An OpenMDAO model can have a number of connections, and several different residuals being converged.\n",
    "Trying to keep track of all the connections in your head can be a bit challenging, but OpenMDAO offers\n",
    "some visualization tools to help see what's going on. This page explains the basics of generating an N2 diagram\n",
    "either from the command line or from a script.\n",
    "\n",
    "An N2 diagram, also known as an N-squared diagram, is a diagram in the shape of a matrix, representing functional or\n",
    "physical interfaces between system elements. It is used to systematically identify, define, tabulate, design, and\n",
    "analyze functional and physical interfaces. It applies to system interfaces and hardware and/or software interfaces.\n",
    "For more information, see [N2_chart](https://en.wikipedia.org/wiki/N2_chart).\n",
    "\n",
    "For this page, we will be using this code example. Notice that there is an error in this code because one of the\n",
    "connection lines has been commented out. This was done to show how the N2 diagram can help point out unconnected\n",
    "inputs quickly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.notebook_utils import get_code\n",
    "from myst_nb import glue\n",
    "glue(\"code_src74\", get_code(\"openmdao.test_suite.scripts.circuit_analysis.Resistor\"), display=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{Admonition} `Resistor` class definition \n",
    ":class: dropdown\n",
    "\n",
    "{glue:}`code_src74`\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.notebook_utils import get_code\n",
    "from myst_nb import glue\n",
    "glue(\"code_src75\", get_code(\"openmdao.test_suite.scripts.circuit_analysis.Diode\"), display=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{Admonition} `Diode` class definition \n",
    ":class: dropdown\n",
    "\n",
    "{glue:}`code_src75`\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.notebook_utils import get_code\n",
    "from myst_nb import glue\n",
    "glue(\"code_src76\", get_code(\"openmdao.test_suite.scripts.circuit_analysis.Node\"), display=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{Admonition} `Node` class definition \n",
    ":class: dropdown\n",
    "\n",
    "{glue:}`code_src76`\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "import openmdao.api as om\n",
    "from openmdao.test_suite.scripts.circuit_analysis import Resistor, Diode, Node\n",
    "\n",
    "\n",
    "class Circuit(om.Group):\n",
    "\n",
    "    def setup(self):\n",
    "        self.add_subsystem('n1', Node(n_in=1, n_out=2), promotes_inputs=[('I_in:0', 'I_in')])\n",
    "        self.add_subsystem('n2', Node())  # leaving defaults\n",
    "\n",
    "        self.add_subsystem('R1', Resistor(R=100.), promotes_inputs=[('V_out', 'Vg')])\n",
    "        self.add_subsystem('R2', Resistor(R=10000.))\n",
    "        self.add_subsystem('D1', Diode(), promotes_inputs=[('V_out', 'Vg')])\n",
    "\n",
    "        self.connect('n1.V', ['R1.V_in', 'R2.V_in'])\n",
    "        self.connect('R1.I', 'n1.I_out:0')\n",
    "        self.connect('R2.I', 'n1.I_out:1')\n",
    "\n",
    "        self.connect('n2.V', ['R2.V_out', 'D1.V_in'])\n",
    "        self.connect('R2.I', 'n2.I_in:0')\n",
    "        # self.connect('D1.I', 'n2.I_out:0') # commented out so there is an unconnected input\n",
    "                                             # example for docs for the N2 diagram\n",
    "\n",
    "        self.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n",
    "        self.nonlinear_solver.options['iprint'] = 2\n",
    "        self.nonlinear_solver.options['maxiter'] = 20\n",
    "        self.linear_solver = om.DirectSolver()\n",
    "\n",
    "p = om.Problem()\n",
    "model = p.model\n",
    "\n",
    "model.set_input_defaults('ground.V', 0., units='V')\n",
    "model.set_input_defaults('source.I', 0.1, units='A')\n",
    "model.add_subsystem('circuit', Circuit(),\n",
    "                    promotes_inputs=[('Vg', 'ground.V'), ('I_in', 'source.I')])\n",
    "\n",
    "model.add_design_var('ground.V')\n",
    "model.add_design_var('source.I')\n",
    "model.add_objective('circuit.D1.I')\n",
    "\n",
    "p.setup()\n",
    "p.check_config(checks=['unconnected_inputs'], out_file=None)\n",
    "\n",
    "# set some initial guesses\n",
    "p['circuit.n1.V'] = 10.\n",
    "p['circuit.n2.V'] = 1.\n",
    "\n",
    "p.run_model()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## From the Command Line\n",
    "\n",
    "Generating an N2 diagram for a model from the command line is easy. First, you need either a Python\n",
    "script that runs the model or a case recording file that was created when running the model.\n",
    "\n",
    "```{Note}\n",
    "If using a script and `final_setup` isn't called in the script (either directly or as a\n",
    "result of `run_model` or `run_driver`) then nothing will happen. Also, when using\n",
    "the command line version, even if the script does call `run_model` or `run_driver`,\n",
    "the script will terminate after `final_setup` and will not actually run the model.\n",
    "```\n",
    "\n",
    "The `openmdao n2` command will generate an N2 diagram of the model that is\n",
    "viewable in a browser, for example:\n",
    "\n",
    "```\n",
    "openmdao n2 openmdao/test_suite/scripts/circuit_with_unconnected_input.py\n",
    "```\n",
    "\n",
    "will generate an N2 diagram like the one below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "om.n2(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `openmdao n2` has several options:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```\n",
    "openmdao n2 -h\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "!openmdao n2 -h"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## From a Script\n",
    "\n",
    "You can do the same thing programmatically by calling the `n2` function.\n",
    "\n",
    "```{eval-rst}\n",
    "    .. autofunction:: openmdao.visualization.n2_viewer.n2_viewer.n2\n",
    "       :noindex:\n",
    "```\n",
    "\n",
    "Notice that the data source can be either a `Problem` or case recorder database containing\n",
    "the model or model data. The latter is indicated by a string giving the file path to the case\n",
    "recorder file.\n",
    "\n",
    "Here are some code snippets showing the two cases.\n",
    "\n",
    "### Problem as Data Source\n",
    "\n",
    "```python\n",
    "p.setup()\n",
    "\n",
    "om.n2(p)\n",
    "```\n",
    "\n",
    "Case Recorder as Data Source\n",
    "****************************\n",
    "\n",
    "```python\n",
    "r = om.SqliteRecorder('circuit.sqlite')\n",
    "p.driver.add_recorder(r)\n",
    "\n",
    "p.setup()\n",
    "p.final_setup()\n",
    "r.shutdown()\n",
    "\n",
    "om.n2('circuit.sqlite', outfile='circuit.html')\n",
    "```\n",
    "\n",
    "In the latter case, you could view the N2 diagram at a later time using the command:\n",
    "\n",
    "```\n",
    "openmdao n2 circuit.sqlite\n",
    "```\n",
    "\n",
    "For more details on N2 diagrams, see the [N2 Details](../n2_details/n2_details.ipynb) section."
   ]
  }
 ],
 "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.1"
  },
  "orphan": true
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
