{
 "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": [
    "# Details of the N2 Model Visualizations\n",
    "\n",
    "The N2 diagram has a number of sections:\n",
    "\n",
    "- Model hierarchy\n",
    "- Connection matrix\n",
    "- Solver hierarchy\n",
    "- Toolbar\n",
    "- Search bar\n",
    "- Legend\n",
    "- Show/Hide Optimization Variables\n",
    "\n",
    "This page will go into the details of each section.\n",
    "\n",
    "Just like in the [N2 Basics](../n2_basics/n2_basics.ipynb) section of this documentation, we will use the\n",
    "circuit model that is missing a connection as our example code."
   ]
  },
  {
   "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_src77\", 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_src77`\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_src78\", 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_src78`\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_src79\", 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_src79`\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "import openmdao.api as om\n",
    "\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": [
    "Here is the N2 diagram that is generated from this model. There are three parts to the N2 diagram. The model hierarchy is on the left, the connection matrix is displayed in the center, and the solver hierarchy is shown on the right."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "om.n2(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model Hierarchy\n",
    "\n",
    "The model hierarchy is on the left side of the diagram. It is a mix of Systems and variables, both\n",
    "inputs and outputs.\n",
    "\n",
    "The top System, the root of the model, is on the left and the subsystem hierarchy is displayed to its right.\n",
    "\n",
    "The colors indicate the type of item in the hierarchy. To see what the colors represent, an optional legend can be displayed using the <img src=\"../images/show_legend.png\" alt=\"show_legend\" width=\"25\" height=\"25\"> button. Here is the part of the legend that explains the colors of the model hierarchy.\n",
    "\n",
    "![systems_and_variables_legend](../images/systems_and_variables_legend.png)\n",
    "\n",
    "You can click in the model hierarchy to zoom into, and also collapse and expand sections of the hierarchy. Left clicking on a subsystem zooms the hierarchy display to just that subsystem in the hierarchy. Right clicking on a subsystem collapses all of the hierarchy to the right of it.\n",
    "\n",
    "Buttons on the toolbar, which are explained in the [Toolbar](#toolbar) section,\n",
    "also can be used to control what is displayed in the hierarchy.\n",
    "\n",
    "## Connection Matrix\n",
    "\n",
    "The matrix in the middle of the diagram shows what items in the model are connected.\n",
    "\n",
    "The color of an item on a diagonal cell matches the color of the rightmost element in the model hierarchy. The colors\n",
    "for the off-diagonal items, which indicate connections, are always black.\n",
    "\n",
    "The symbol of an item in the connection matrix indicates whether the variable is a scalar, vector, or collapsed variable.\n",
    "\n",
    "![connection_matrix_legend](../images/connection_matrix_legend.png)\n",
    "\n",
    "Boxes, with thin black line borders, outline items in the matrix to show the grouping of the variables of the lowest level Systems.\n",
    "\n",
    "When you hover over a connection in the matrix, arrows are drawn to indicate connections. The behavior is different\n",
    "depending on whether you hover over a diagonal or an off-diagonal cell.\n",
    "\n",
    "When hovering over a diagonal item, the explicit connections to/from that variable are displayed. Salmon colored arrows indicate that element is the target of the connection. A green arrow indicates it is the source.\n",
    "\n",
    "When hovering over an off-diagonal, the behavior differs depending on whether the cell is in the lower or upper\n",
    "triangular part of the diagram.\n",
    "\n",
    "In the lower triangular, the marked cells represent upstream (in the sense of execution order of the\n",
    "components) connections. All the connections involved in that cycle\n",
    "are drawn to indicate which systems and components are involved in the convergence loop. Downstream connection arrows are green and upstream connections are salmon colored.\n",
    "\n",
    "In the upper triangular, the marked cells represent downstream connections. The salmon colored arrow that is drawn shows that connection.\n",
    "\n",
    "Clicking in the matrix on a connection or diagonal, lets you pin connection arrows so that they don't\n",
    "disappear when you hover away from the cell. You can clear these connections arrows by using the\n",
    "`Hide all connection arrow button` <img src=\"../images/hide_conn_arrows.png\" alt=\"hide_conn_arrows\" width=\"25\" height=\"25\"> in the toolbar.\n",
    "\n",
    "## Solver Hierarchy\n",
    "\n",
    "Each System in a model can potentially have a linear and nonlinear solver associated with it. On the right side\n",
    "of the N2 diagram, the hierarchy of the solvers is shown. This time the hierarchy goes from right to left with the root of the model on the right.\n",
    "\n",
    "There are three states of the solver hierarchy display. Use these buttons to switch between them. Hiding the\n",
    "solver hierarchy creates more space for the rest of the N2 display.\n",
    " \n",
    "| Button                                                                                               \t| Title                   \t| Description                                 \t|\n",
    "|------------------------------------------------------------------------------------------------------\t|-------------------------\t|---------------------------------------------\t|\n",
    "| <img src=\"../images/show_nonlinear_solvers.png\" alt=\"show_nonlinear_solvers\" width=\"50\" height=\"50\"> \t| Show linear solvers     \t| Show linear solvers in solver hierarchy     \t|\n",
    "| <img src=\"../images/show_linear_solvers.png\" alt=\"show_linear_solvers\" width=\"50\" height=\"50\">       \t| Show non-linear solvers \t| Show non-linear solvers in solver hierarchy \t|\n",
    "| <img src=\"../images/hide_solvers.png\" alt=\"hide_solvers\" width=\"50\" height=\"50\">                     \t| Hide Solvers            \t| Hide the solver hierarchy                   \t|\n",
    "\n",
    "The colors indicate the type of solver. The colors are shown in the legend. The section of the legend showing\n",
    "the colors of the solver types changes depending on which are displayed in the solver structure.\n",
    "Here is what the section of the legend looks like for both linear and non-linear solvers.\n",
    "\n",
    "| Non-Linear Solver Legend                                                        \t| Linear Solver Legend                                                        \t|\n",
    "|---------------------------------------------------------------------------------\t|-----------------------------------------------------------------------------\t|\n",
    "| <img src=\"../images/nonlinear_solvers_legend.png\" alt=\"show_nonlinear_solvers\"> \t| <img src=\"../images/linear_solvers_legend.png\" alt=\"linear_solvers_legend\"> \t|\n",
    "\n",
    "```{Note}\n",
    "When a System has a Newton non-linear solver and the `solve_subsystems` option is set to True for that solver,\n",
    "the Solver hierarchy box for that System has the text `NL: Newton (sub_solve)`.\n",
    "```\n",
    "\n",
    "As in the model hierarchy, you can also do zooming, collapsing, and expanding in the Solver hierarchy using left and\n",
    "right mouse clicks.\n",
    "\n",
    "## Toolbar\n",
    "\n",
    "The toolbar to the left of the N2 diagram provides many useful capabilities. Explanations for all the buttons\n",
    "is below. Tooltips are also provided for all the buttons as you hover over them.\n",
    "\n",
    "### View Control\n",
    "\n",
    "The model hierarchy display has the notion of a `view`. The `view` is defined by the node in the hierarchy\n",
    "that is visible in the diagram. Initially, it is the root of the model but if you click on a subsystem, then\n",
    "only the part of the hierarchy beginning at that subsystem is shown.\n",
    "\n",
    "You can change the view and zoom into a System by left clicking on it. Other parts of the hierarchy are no longer\n",
    "visible.\n",
    "\n",
    "The diagram keeps track of the view history and then lets you go back and forth through the history similar to undo and\n",
    "redo in apps.\n",
    "\n",
    "| Button                                                                               \t| Title          \t| Description                          \t|\n",
    "|--------------------------------------------------------------------------------------\t|----------------\t|--------------------------------------\t|\n",
    "| <img src=\"../images/home.png\" alt=\"return_to_root\" width=\"50\" height=\"50\"> \t| Return to root \t| View entire model starting from root \t|\n",
    "| <img src=\"../images/back.png\" alt=\"back\" width=\"50\" height=\"50\">                     \t| Back           \t| Move back in view history            \t|\n",
    "| <img src=\"../images/forward.png\" alt=\"forward\" width=\"50\" height=\"50\">               \t| Forward        \t| Move forward in view history         \t|\n",
    "\n",
    "### Collapsing and Expanding the System Hierarchy\n",
    "\n",
    "The next set of buttons lets you control the collapsing and expanding of elements in the System hierarchy. The first four buttons are revealed as a fly-out menu as you hover over this button, <img src=\"../images/control_collapse.png\" alt=\"forward\" width=\"50\" height=\"50\"> .\n",
    "\n",
    "| Button                                                                               | Title                           | Description                                          |\n",
    "|--------------------------------------------------------------------------------------|---------------------------------|------------------------------------------------------|\n",
    "| <img src=\"../images/collapse_view.png\" alt=\"collapse_view\" width=\"50\" height=\"50\">   | Collapse variables in view only | Collapse only the variables in the current view      |\n",
    "| <img src=\"../images/expand_view.png\" alt=\"expand_view\" width=\"50\" height=\"50\">       | Expand variables in view only   | Expand only the variables in the current view        |\n",
    "| <img src=\"../images/collapse_all.png\" alt=\"collapse_all\" width=\"50\" height=\"50\">     | Collapse all variables          | Collapse all the variables in the entire model       |\n",
    "| <img src=\"../images/expand_all.png\" alt=\"expand_all\" width=\"50\" height=\"50\">         | Expand all variables            | Expand all the variables in the entire model         |\n",
    "| <img src=\"../images/collapse_depth.png\" alt=\"collapse_depth\" width=\"50\" height=\"50\"> | Collapse depth                  | Set the number of hierarchy levels shown in the view |\n",
    "\n",
    "### Connections Arrow Visibility\n",
    "\n",
    "The connections visibility is controlled using the buttons that appear when hovering over\n",
    "the <img src=\"../images/connection_visibility.png\" alt=\"connections_visibility\" width=\"50\" height=\"50\"> button.\n",
    "\n",
    "| Button                                                                                           | Title                        | Description                                |\n",
    "|--------------------------------------------------------------------------------------------------|------------------------------|--------------------------------------------|\n",
    "| <img src=\"../images/hide_conn_arrows.png\" alt=\"hide_conn_arrows\" width=\"50\" height=\"50\">         | Hide all connection arrows   | Hide all pinned connection arrows.         |\n",
    "| <img src=\"../images/show_all_conn_arrows.png\" alt=\"show_all_conn_arrows\" width=\"50\" height=\"50\"> | Show all connections in view | Show all connections in view and pin them. |\n",
    "\n",
    "### Remaining Toolbar Buttons\n",
    "\n",
    "The buttons in the remaining part of the toolbar offer a variety of other options:\n",
    "\n",
    "| Button                                                                                   | Title                         | Description                                                       |\n",
    "|------------------------------------------------------------------------------------------|-------------------------------|-------------------------------------------------------------------|\n",
    "| <img src=\"../images/show_legend.png\" alt=\"show_legend\" width=\"50\" height=\"50\">               | Show legend / Hide legend     | Show the legend explaining the colors and icons in the diagram    |\n",
    "| <img src=\"../images/model_opt_button.png\" alt=\"model_opt_button\" width=\"50\" height=\"50\"> | Show opt vars / Hide opt vars | Show the optimization variables in the diagram                    |\n",
    "| <img src=\"../images/font_size.png\" alt=\"font_size\" width=\"50\" height=\"50\">               | Font Size                     | Set the font size for the text in the diagram                     |\n",
    "| <img src=\"../images/collapse_depth.png\" alt=\"collapse_depth\" width=\"50\" height=\"50\">     | Set collapse depth            | Set how many levels are shown in the System hierarchy on the left |\n",
    "| <img src=\"../images/model_height.png\" alt=\"model_height\" width=\"50\" height=\"50\">         | Model Height                  | Set the height of the diagram in pixels                           |\n",
    "| <img src=\"../images/save_svg.png\" alt=\"save_svg\" width=\"50\" height=\"50\">                 | Save SVG                      | Save the current view of the diagram to an SVG file               |\n",
    "| <img src=\"../images/show_node_info.png\" alt=\"show_node_info\" width=\"50\" height=\"50\">     | Show / Hide Node Info         | Toggle info box that is displayed on hover                        |\n",
    "| <img src=\"../images/help.png\" alt=\"help\" width=\"50\" height=\"50\">                         | Help                          | Bring up the help window                                          |\n",
    "\n",
    "\n",
    "## Show Legend\n",
    "\n",
    "If you click on the legend button <img src=\"../images/show_legend.png\" alt=\"show_legend\" width=\"50\" height=\"50\">, you will see the legend appear below the N2 diagram.\n",
    "The Legend window can then be dragged to a location of the user's choice.\n",
    "\n",
    "![legend](../images/legend.png)\n",
    "\n",
    "Here are explanations of the sections in the legend:\n",
    "\n",
    "- The System & Variables section shows the colors for the different items in the model hierarchy.\n",
    "- The N2 Symbols section shows the icons used to indicate the type of connection in the connection matrix. The shape of the icon in the matrix shows whether the connection is between scalars, vectors, or groups. The color of the icon is based on the color associated with the variable of that type as shown in the System & Variables part of the legend.\n",
    "- The Solvers section shows the colors used for the different solvers on the right side of the N2. Either the Linear or Nonlinear solvers are shown depending on the state of the Toggle Solver Names button.\n",
    "\n",
    "\n",
    "## Show/Hide Optimization Variables\n",
    "\n",
    "Selecting this button <img src=\"../images/model_opt_button.png\" alt=\"model_opt_button\" width=\"50\" height=\"50\"> allows you to see your model's design variables, constraints, and objectives which are highlighted in purple. If your optimization variable is an Auto IVC, the Auto IVC cell will be highlighted as well which can be seen below.\n",
    "\n",
    "| Hidden                                                           | Shown                                                        |\n",
    "|------------------------------------------------------------------|--------------------------------------------------------------|\n",
    "| <img src=\"../images/model_opt_not_selected.png\" alt=\"model_opt_not_selected\"> | <img src=\"../images/model_opt_selected.png\" alt=\"model_opt_selected\"> |\n",
    "\n",
    "\n",
    "## Show Node Info\n",
    "\n",
    "The Show Node Info button |show_node_info|, brings up a small window that displays information about the item the\n",
    "cursor is hovering over.\n",
    "Here are some examples of what the user can see when hovering over variables, Systems, connection matrix cells, and\n",
    "Solvers.\n",
    "\n",
    "| Variable                                                                                     | System                                                                       | Connection                                                                 | Solver                                                                       |\n",
    "|----------------------------------------------------------------------------------------------|------------------------------------------------------------------------------|----------------------------------------------------------------------------|------------------------------------------------------------------------------|\n",
    "| <img src=\"../images/variable_node_info.png\" alt=\"variable_node_info\" width=\"200\" height=\"200\"> | <img src=\"../images/system_node_info.png\" alt=\"hide\" width=\"200\" height=\"200\"> | <img src=\"../images/cell_node_info.png\" alt=\"hide\" width=\"200\" height=\"200\"> | <img src=\"../images/solver_node_info.png\" alt=\"hide\" width=\"200\" height=\"200\"> |\n",
    "\n",
    "## Search bar\n",
    "\n",
    "The search bar below the Toolbar lets you search for variables in the model. This can be very useful when working\n",
    "with very large models.\n",
    "\n",
    "When you enter a variable name into the search box and click the search button <img src=\"../images/search.png\" alt=\"search\" width=\"50\" height=\"50\"> or hit the Enter key, the N2\n",
    "diagram will redraw such that it collapses and shows only variables that were searched for.\n",
    "\n",
    "A search could find multiple instances of variables with the same name. For example, in the diagram above,\n",
    "a search for `V_in` would find `R1.V_in`, `R2.V_in`, and `D1.V_in`.\n",
    "\n",
    "To return to a view that is not filtered by the variable search, clear the search box and hit the Enter key or the\n",
    "Search button.\n",
    "\n",
    "## Show external connections\n",
    "\n",
    "When you zoom into a System, it is useful to see external connections into that System from other Systems\n",
    "that are no longer visible as a result of zooming. In that situation, the N2 diagram indicates external connections\n",
    "with dashed line arrows. For example:\n",
    "\n",
    "![external_connection](../images/external_connection.png)\n",
    "\n",
    "The dashed line arrow shows that `R2.V_out` variable is connected to `circuit.n2.V` even though that variable is no longer visible in the diagram."
   ]
  }
 ],
 "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
}
