{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d5add21d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:40:21.576410Z",
     "iopub.status.busy": "2026-10-02T14:40:21.576200Z",
     "iopub.status.idle": "2026-10-02T14:40:21.580302Z",
     "shell.execute_reply": "2026-10-02T14:40:21.579808Z"
    },
    "papermill": {
     "duration": 0.006637,
     "end_time": "2026-10-02T14:40:21.580802+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:21.574165+00:00",
     "status": "completed"
    },
    "tags": [
     "remove-input",
     "active-ipynb",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    from openmdao.utils.notebook_utils import notebook_mode  # noqa: F401\n",
    "except ImportError:\n",
    "    !python -m pip install openmdao[notebooks]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30324373",
   "metadata": {
    "papermill": {
     "duration": 0.138573,
     "end_time": "2026-10-02T14:40:21.784334+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:21.645761+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "In the [previous tutorial](../models_implicit_components/models_with_solvers_implicit.ipynb) , we built up a model of an electrical circuit using a combination of [ImplicitComponent](../../features/core_features/working_with_components/implicit_component.ipynb) and [ExplicitComponent](../../features/core_features/working_with_components/explicit_component.ipynb) instances.In that tutorial, all of the implicit relationships in the model came directly from the physics of the model itself.\n",
    "\n",
    "However, you often need to add implicit relationships to models by driving the values of two separate variables to be equal to each other. In this tutorial, we'll show you how to do that using the [BalanceComp](../../features/building_blocks/components/balance_comp.ipynb).\n",
    "\n",
    "# Using BalanceComp to Create Implicit Relationships in Groups\n",
    "\n",
    "The electrical circuit model from the [previous tutorial](../models_implicit_components/models_with_solvers_implicit.ipynb) represents a very basic\n",
    "circuit with a current source of .1 Amps. Here is a reminder of what that circuit looked like:\n",
    "\n",
    "![circuit_diagram](images/circuit_diagram.png)\n",
    "\n",
    "When we solved that circuit, the resulting voltage at *node 1* was 9.9 Volts. Let's say you wanted to power this circuit with a 1.5-Volt battery, instead of using a current source. We can make a small modification to our original model to capture this new setup.\n",
    "\n",
    "Given any value for `source.I`, this model outputs the value for `n1.V` that balances the model. The voltage at the ground is also known via `ground.V`. So the voltage across the current source is\n",
    "\n",
    "$$V_{source} = V1 - V0$$\n",
    "\n",
    "To represent a voltage source with a specific voltage, we can add an additional state variable and residual equation to our model:\n",
    "\n",
    "$${R}_{batt} = V1 - V0 - V_{source}^{*}$$\n",
    "\n",
    "where $V_{source}^{*}$, the desired source voltage, is given by the user as parameter to the model.\n",
    "\n",
    "We could write a new component, inheriting from [ImplicitComponent](../../features/core_features/working_with_components/implicit_component.ipynb), to include this new relationship into the model, but OpenMDAO provides [BalanceComp](../../features/building_blocks/components/balance_comp.ipynb), a general utility component that is designed specifically for this type of situation.\n",
    "\n",
    "What we're going to do is add a [BalanceComp](../../features/building_blocks/components/balance_comp.ipynb) to the top level of the model.\n",
    "The `BalanceComp` will define a residual that will drive the source current to force the delta-V across the battery to be what we want. We'll also add an [ExecComp](../../features/building_blocks/components/exec_comp.ipynb) to compute that delta-V from the ground voltage and the voltage at node 1 and then connect everything up. Lastly, since we added an [ImplicitComponent](../../features/core_features/working_with_components/implicit_component.ipynb) at the top level of the model, we'll also move the [NewtonSolver](../../features/building_blocks/solvers/newton.ipynb) up to the top level of the model, too.\n",
    "\n",
    "```{important}\n",
    "BalanceComp can handle more than just $lhs-rhs=0$. It has a number of inputs that let you tweak that behavior. It can support multiple residuals and array variables as well. Check out the [documentation](../../features/building_blocks/components/balance_comp.ipynb) on it for details.\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8f48e274",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:40:21.874795Z",
     "iopub.status.busy": "2026-10-02T14:40:21.874552Z",
     "iopub.status.idle": "2026-10-02T14:40:23.920016Z",
     "shell.execute_reply": "2026-10-02T14:40:23.919472Z"
    },
    "papermill": {
     "duration": 2.053859,
     "end_time": "2026-10-02T14:40:23.920945+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:21.867086+00:00",
     "status": "completed"
    },
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "application/papermill.record/text/html": "<style>pre { line-height: 125%; }\ntd.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\nspan.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }\ntd.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\nspan.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }\n.output_html .hll { background-color: #ffffcc }\n.output_html { background: #f8f8f8; }\n.output_html .c { color: #3D7B7B; font-style: italic } /* Comment */\n.output_html .err { border: 1px solid #F00 } /* Error */\n.output_html .k { color: #008000; font-weight: bold } /* Keyword */\n.output_html .o { color: #666 } /* Operator */\n.output_html .ch { color: #3D7B7B; font-style: italic } /* Comment.Hashbang */\n.output_html .cm { color: #3D7B7B; font-style: italic } /* Comment.Multiline */\n.output_html .cp { color: #9C6500 } /* Comment.Preproc */\n.output_html .cpf { color: #3D7B7B; font-style: italic } /* Comment.PreprocFile */\n.output_html .c1 { color: #3D7B7B; font-style: italic } /* Comment.Single */\n.output_html .cs { color: #3D7B7B; font-style: italic } /* Comment.Special */\n.output_html .gd { color: #A00000 } /* Generic.Deleted */\n.output_html .ge { font-style: italic } /* Generic.Emph */\n.output_html .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */\n.output_html .gr { color: #E40000 } /* Generic.Error */\n.output_html .gh { color: #000080; font-weight: bold } /* Generic.Heading */\n.output_html .gi { color: #008400 } /* Generic.Inserted */\n.output_html .go { color: #717171 } /* Generic.Output */\n.output_html .gp { color: #000080; font-weight: bold } /* Generic.Prompt */\n.output_html .gs { font-weight: bold } /* Generic.Strong */\n.output_html .gu { color: #800080; font-weight: bold } /* Generic.Subheading */\n.output_html .gt { color: #04D } /* Generic.Traceback */\n.output_html .kc { color: #008000; font-weight: bold } /* Keyword.Constant */\n.output_html .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */\n.output_html .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */\n.output_html .kp { color: #008000 } /* Keyword.Pseudo */\n.output_html .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */\n.output_html .kt { color: #B00040 } /* Keyword.Type */\n.output_html .m { color: #666 } /* Literal.Number */\n.output_html .s { color: #BA2121 } /* Literal.String */\n.output_html .na { color: #687822 } /* Name.Attribute */\n.output_html .nb { color: #008000 } /* Name.Builtin */\n.output_html .nc { color: #00F; font-weight: bold } /* Name.Class */\n.output_html .no { color: #800 } /* Name.Constant */\n.output_html .nd { color: #A2F } /* Name.Decorator */\n.output_html .ni { color: #717171; font-weight: bold } /* Name.Entity */\n.output_html .ne { color: #CB3F38; font-weight: bold } /* Name.Exception */\n.output_html .nf { color: #00F } /* Name.Function */\n.output_html .nl { color: #767600 } /* Name.Label */\n.output_html .nn { color: #00F; font-weight: bold } /* Name.Namespace */\n.output_html .nt { color: #008000; font-weight: bold } /* Name.Tag */\n.output_html .nv { color: #19177C } /* Name.Variable */\n.output_html .ow { color: #A2F; font-weight: bold } /* Operator.Word */\n.output_html .w { color: #BBB } /* Text.Whitespace */\n.output_html .mb { color: #666 } /* Literal.Number.Bin */\n.output_html .mf { color: #666 } /* Literal.Number.Float */\n.output_html .mh { color: #666 } /* Literal.Number.Hex */\n.output_html .mi { color: #666 } /* Literal.Number.Integer */\n.output_html .mo { color: #666 } /* Literal.Number.Oct */\n.output_html .sa { color: #BA2121 } /* Literal.String.Affix */\n.output_html .sb { color: #BA2121 } /* Literal.String.Backtick */\n.output_html .sc { color: #BA2121 } /* Literal.String.Char */\n.output_html .dl { color: #BA2121 } /* Literal.String.Delimiter */\n.output_html .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */\n.output_html .s2 { color: #BA2121 } /* Literal.String.Double */\n.output_html .se { color: #AA5D1F; font-weight: bold } /* Literal.String.Escape */\n.output_html .sh { color: #BA2121 } /* Literal.String.Heredoc */\n.output_html .si { color: #A45A77; font-weight: bold } /* Literal.String.Interpol */\n.output_html .sx { color: #008000 } /* Literal.String.Other */\n.output_html .sr { color: #A45A77 } /* Literal.String.Regex */\n.output_html .s1 { color: #BA2121 } /* Literal.String.Single */\n.output_html .ss { color: #19177C } /* Literal.String.Symbol */\n.output_html .bp { color: #008000 } /* Name.Builtin.Pseudo */\n.output_html .fm { color: #00F } /* Name.Function.Magic */\n.output_html .vc { color: #19177C } /* Name.Variable.Class */\n.output_html .vg { color: #19177C } /* Name.Variable.Global */\n.output_html .vi { color: #19177C } /* Name.Variable.Instance */\n.output_html .vm { color: #19177C } /* Name.Variable.Magic */\n.output_html .il { color: #666 } /* Literal.Number.Integer.Long */</style><div class=\"highlight\"><pre><span></span><span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Circuit</span><span class=\"p\">(</span><span class=\"n\">om</span><span class=\"o\">.</span><span class=\"n\">Group</span><span class=\"p\">):</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">setup</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">add_subsystem</span><span class=\"p\">(</span><span class=\"s1\">&#39;n1&#39;</span><span class=\"p\">,</span> <span class=\"n\">Node</span><span class=\"p\">(</span><span class=\"n\">n_in</span><span class=\"o\">=</span><span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"n\">n_out</span><span class=\"o\">=</span><span class=\"mi\">2</span><span class=\"p\">),</span> <span class=\"n\">promotes_inputs</span><span class=\"o\">=</span><span class=\"p\">[(</span><span class=\"s1\">&#39;I_in:0&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;I_in&#39;</span><span class=\"p\">)])</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">add_subsystem</span><span class=\"p\">(</span><span class=\"s1\">&#39;n2&#39;</span><span class=\"p\">,</span> <span class=\"n\">Node</span><span class=\"p\">())</span>  <span class=\"c1\"># leaving defaults</span>\n\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">add_subsystem</span><span class=\"p\">(</span><span class=\"s1\">&#39;R1&#39;</span><span class=\"p\">,</span> <span class=\"n\">Resistor</span><span class=\"p\">(</span><span class=\"n\">R</span><span class=\"o\">=</span><span class=\"mf\">100.</span><span class=\"p\">),</span> <span class=\"n\">promotes_inputs</span><span class=\"o\">=</span><span class=\"p\">[(</span><span class=\"s1\">&#39;V_out&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Vg&#39;</span><span class=\"p\">)])</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">add_subsystem</span><span class=\"p\">(</span><span class=\"s1\">&#39;R2&#39;</span><span class=\"p\">,</span> <span class=\"n\">Resistor</span><span class=\"p\">(</span><span class=\"n\">R</span><span class=\"o\">=</span><span class=\"mf\">10000.</span><span class=\"p\">))</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">add_subsystem</span><span class=\"p\">(</span><span class=\"s1\">&#39;D1&#39;</span><span class=\"p\">,</span> <span class=\"n\">Diode</span><span class=\"p\">(),</span> <span class=\"n\">promotes_inputs</span><span class=\"o\">=</span><span class=\"p\">[(</span><span class=\"s1\">&#39;V_out&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Vg&#39;</span><span class=\"p\">)])</span>\n\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">connect</span><span class=\"p\">(</span><span class=\"s1\">&#39;n1.V&#39;</span><span class=\"p\">,</span> <span class=\"p\">[</span><span class=\"s1\">&#39;R1.V_in&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;R2.V_in&#39;</span><span class=\"p\">])</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">connect</span><span class=\"p\">(</span><span class=\"s1\">&#39;R1.I&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;n1.I_out:0&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">connect</span><span class=\"p\">(</span><span class=\"s1\">&#39;R2.I&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;n1.I_out:1&#39;</span><span class=\"p\">)</span>\n\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">connect</span><span class=\"p\">(</span><span class=\"s1\">&#39;n2.V&#39;</span><span class=\"p\">,</span> <span class=\"p\">[</span><span class=\"s1\">&#39;R2.V_out&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;D1.V_in&#39;</span><span class=\"p\">])</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">connect</span><span class=\"p\">(</span><span class=\"s1\">&#39;R2.I&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;n2.I_in:0&#39;</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">connect</span><span class=\"p\">(</span><span class=\"s1\">&#39;D1.I&#39;</span><span class=\"p\">,</span> <span class=\"s1\">&#39;n2.I_out:0&#39;</span><span class=\"p\">)</span>\n\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">nonlinear_solver</span> <span class=\"o\">=</span> <span class=\"n\">om</span><span class=\"o\">.</span><span class=\"n\">NewtonSolver</span><span class=\"p\">(</span><span class=\"n\">solve_subsystems</span><span class=\"o\">=</span><span class=\"kc\">False</span><span class=\"p\">)</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">nonlinear_solver</span><span class=\"o\">.</span><span class=\"n\">options</span><span class=\"p\">[</span><span class=\"s1\">&#39;iprint&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"mi\">2</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">nonlinear_solver</span><span class=\"o\">.</span><span class=\"n\">options</span><span class=\"p\">[</span><span class=\"s1\">&#39;maxiter&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"mi\">20</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">linear_solver</span> <span class=\"o\">=</span> <span class=\"n\">om</span><span class=\"o\">.</span><span class=\"n\">DirectSolver</span><span class=\"p\">()</span>\n</pre></div>\n",
      "application/papermill.record/text/latex": "\\begin{Verbatim}[commandchars=\\\\\\{\\}]\n\\PY{k}{class}\\PY{+w}{ }\\PY{n+nc}{Circuit}\\PY{p}{(}\\PY{n}{om}\\PY{o}{.}\\PY{n}{Group}\\PY{p}{)}\\PY{p}{:}\n\n    \\PY{k}{def}\\PY{+w}{ }\\PY{n+nf}{setup}\\PY{p}{(}\\PY{n+nb+bp}{self}\\PY{p}{)}\\PY{p}{:}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{add\\PYZus{}subsystem}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n1}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{n}{Node}\\PY{p}{(}\\PY{n}{n\\PYZus{}in}\\PY{o}{=}\\PY{l+m+mi}{1}\\PY{p}{,} \\PY{n}{n\\PYZus{}out}\\PY{o}{=}\\PY{l+m+mi}{2}\\PY{p}{)}\\PY{p}{,} \\PY{n}{promotes\\PYZus{}inputs}\\PY{o}{=}\\PY{p}{[}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{I\\PYZus{}in:0}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{I\\PYZus{}in}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{)}\\PY{p}{]}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{add\\PYZus{}subsystem}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n2}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{n}{Node}\\PY{p}{(}\\PY{p}{)}\\PY{p}{)}  \\PY{c+c1}{\\PYZsh{} leaving defaults}\n\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{add\\PYZus{}subsystem}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R1}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{n}{Resistor}\\PY{p}{(}\\PY{n}{R}\\PY{o}{=}\\PY{l+m+mf}{100.}\\PY{p}{)}\\PY{p}{,} \\PY{n}{promotes\\PYZus{}inputs}\\PY{o}{=}\\PY{p}{[}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{V\\PYZus{}out}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{Vg}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{)}\\PY{p}{]}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{add\\PYZus{}subsystem}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R2}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{n}{Resistor}\\PY{p}{(}\\PY{n}{R}\\PY{o}{=}\\PY{l+m+mf}{10000.}\\PY{p}{)}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{add\\PYZus{}subsystem}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{D1}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{n}{Diode}\\PY{p}{(}\\PY{p}{)}\\PY{p}{,} \\PY{n}{promotes\\PYZus{}inputs}\\PY{o}{=}\\PY{p}{[}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{V\\PYZus{}out}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{Vg}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{)}\\PY{p}{]}\\PY{p}{)}\n\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{connect}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n1.V}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{p}{[}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R1.V\\PYZus{}in}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R2.V\\PYZus{}in}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{]}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{connect}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R1.I}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n1.I\\PYZus{}out:0}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{connect}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R2.I}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n1.I\\PYZus{}out:1}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{)}\n\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{connect}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n2.V}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{p}{[}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R2.V\\PYZus{}out}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{D1.V\\PYZus{}in}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{]}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{connect}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{R2.I}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n2.I\\PYZus{}in:0}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{connect}\\PY{p}{(}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{D1.I}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{,} \\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{n2.I\\PYZus{}out:0}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{)}\n\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{nonlinear\\PYZus{}solver} \\PY{o}{=} \\PY{n}{om}\\PY{o}{.}\\PY{n}{NewtonSolver}\\PY{p}{(}\\PY{n}{solve\\PYZus{}subsystems}\\PY{o}{=}\\PY{k+kc}{False}\\PY{p}{)}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{nonlinear\\PYZus{}solver}\\PY{o}{.}\\PY{n}{options}\\PY{p}{[}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{iprint}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{]} \\PY{o}{=} \\PY{l+m+mi}{2}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{nonlinear\\PYZus{}solver}\\PY{o}{.}\\PY{n}{options}\\PY{p}{[}\\PY{l+s+s1}{\\PYZsq{}}\\PY{l+s+s1}{maxiter}\\PY{l+s+s1}{\\PYZsq{}}\\PY{p}{]} \\PY{o}{=} \\PY{l+m+mi}{20}\n        \\PY{n+nb+bp}{self}\\PY{o}{.}\\PY{n}{linear\\PYZus{}solver} \\PY{o}{=} \\PY{n}{om}\\PY{o}{.}\\PY{n}{DirectSolver}\\PY{p}{(}\\PY{p}{)}\n\\end{Verbatim}\n",
      "application/papermill.record/text/plain": "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')\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()"
     },
     "metadata": {
      "scrapbook": {
       "mime_prefix": "application/papermill.record/",
       "name": "circuit_src"
      }
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from openmdao.utils.notebook_utils import get_code\n",
    "from myst_nb import glue\n",
    "glue(\"circuit_src\", get_code(\"openmdao.test_suite.scripts.circuit_analysis.Circuit\"), display=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7e134f5a",
   "metadata": {
    "papermill": {
     "duration": 0.113804,
     "end_time": "2026-10-02T14:40:24.076333+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:23.962529+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    ":::{dropdown} `Circuit` class definition \n",
    "\n",
    "{glue:}`circuit_src`\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2079ac0e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:40:24.245979Z",
     "iopub.status.busy": "2026-10-02T14:40:24.245680Z",
     "iopub.status.idle": "2026-10-02T14:40:25.548542Z",
     "shell.execute_reply": "2026-10-02T14:40:25.547799Z"
    },
    "papermill": {
     "duration": 1.357438,
     "end_time": "2026-10-02T14:40:25.549047+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:24.191609+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1790952025.471382] [runnervm8df0l:5830 :0]        ib_iface.c:1269 UCX  ERROR mana_0: iface 0x55ed6e929940 failed to create UD QP TX wr:256 sge:6 inl:64 resp:0 RX wr:4096 sge:1 resp:0 failed: Operation not supported\n",
      "[1790952025.471617] [runnervm8df0l:5830 :0]      ucp_worker.c:1412 UCX  ERROR uct_iface_open(ud_verbs/mana_0:1) failed: Input/output error\n",
      "NL: Newton 0 ; 5.38788524 1\n",
      "NL: Newton 1 ; 0.000156774226 2.90975437e-05\n",
      "NL: Newton 2 ; 4.09995323e-05 7.60957788e-06\n",
      "NL: Newton 3 ; 5.81925105e-06 1.08006217e-06\n",
      "NL: Newton 4 ; 1.73138595e-07 3.21347964e-08\n",
      "NL: Newton 5 ; 1.65860813e-10 3.07840285e-11\n",
      "NL: Newton Converged\n",
      "[1.5]\n",
      "[0.65113362]\n",
      "[0.015]\n",
      "[8.48866377e-05]\n",
      "[8.48868035e-05]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[runnervm8df0l:05830] pml_ucx.c:313  Error: Failed to create UCP worker\n"
     ]
    }
   ],
   "source": [
    "import openmdao.api as om\n",
    "from openmdao.test_suite.scripts.circuit_analysis import Circuit\n",
    "\n",
    "p = om.Problem()\n",
    "model = p.model\n",
    "\n",
    "model.add_subsystem('ground', om.IndepVarComp('V', 0., units='V'))\n",
    "\n",
    "# replacing the fixed current source with a BalanceComp to represent a fixed Voltage source\n",
    "# model.add_subsystem('source', om.IndepVarComp('I', 0.1, units='A'))\n",
    "model.add_subsystem('batt', om.IndepVarComp('V', 1.5, units='V'))\n",
    "bal = model.add_subsystem('batt_balance', om.BalanceComp())\n",
    "bal.add_balance('I', units='A', eq_units='V')\n",
    "\n",
    "model.add_subsystem('circuit', Circuit())\n",
    "model.add_subsystem('batt_deltaV', om.ExecComp('dV = V1 - V2', V1={'units':'V'},\n",
    "                                               V2={'units':'V'}, dV={'units':'V'}))\n",
    "\n",
    "# current into the circuit is now the output state from the batt_balance comp\n",
    "model.connect('batt_balance.I', 'circuit.I_in')\n",
    "model.connect('ground.V', ['circuit.Vg','batt_deltaV.V2'])\n",
    "model.connect('circuit.n1.V', 'batt_deltaV.V1')\n",
    "\n",
    "# set the lhs and rhs for the battery residual\n",
    "model.connect('batt.V', 'batt_balance.rhs:I')\n",
    "model.connect('batt_deltaV.dV', 'batt_balance.lhs:I')\n",
    "\n",
    "p.setup()\n",
    "\n",
    "###################\n",
    "# Solver Setup\n",
    "###################\n",
    "\n",
    "# change the circuit solver to RunOnce because we're\n",
    "# going to converge at the top level of the model with newton instead\n",
    "p.model.circuit.nonlinear_solver = om.NonlinearRunOnce()\n",
    "p.model.circuit.linear_solver = om.LinearRunOnce()\n",
    "\n",
    "# Put Newton at the top so it can also converge the new BalanceComp residual\n",
    "newton = p.model.nonlinear_solver = om.NewtonSolver()\n",
    "p.model.linear_solver = om.DirectSolver()\n",
    "newton.options['iprint'] = 2\n",
    "newton.options['maxiter'] = 20\n",
    "newton.options['solve_subsystems'] = True\n",
    "newton.linesearch = om.ArmijoGoldsteinLS()\n",
    "newton.linesearch.options['maxiter'] = 10\n",
    "newton.linesearch.options['iprint'] = 2\n",
    "\n",
    "# set initial guesses from the current source problem\n",
    "p['circuit.n1.V'] = 9.8\n",
    "p['circuit.n2.V'] = .7\n",
    "\n",
    "p.run_model()\n",
    "\n",
    "print(p['circuit.n1.V'])\n",
    "print(p['circuit.n2.V'])\n",
    "print(p['circuit.R1.I'])\n",
    "print(p['circuit.R2.I'])\n",
    "print(p['circuit.D1.I'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "61b0c44b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:40:25.619468Z",
     "iopub.status.busy": "2026-10-02T14:40:25.619254Z",
     "iopub.status.idle": "2026-10-02T14:40:25.624579Z",
     "shell.execute_reply": "2026-10-02T14:40:25.623970Z"
    },
    "papermill": {
     "duration": 0.026743,
     "end_time": "2026-10-02T14:40:25.625136+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:25.598393+00:00",
     "status": "completed"
    },
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.float64(1.955693697827626e-06)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from openmdao.utils.assert_utils import assert_near_equal\n",
    "\n",
    "assert_near_equal(p['circuit.n1.V'], 1.5, 1e-5)\n",
    "assert_near_equal(p['circuit.n2.V'], 0.65113362, 1e-5)\n",
    "assert_near_equal(p['circuit.R1.I'], 0.015, 1e-5)\n",
    "assert_near_equal(p['circuit.R2.I'], 8.48866375e-05, 1e-5)\n",
    "assert_near_equal(p['circuit.D1.I'], 8.48866375e-05, 1e-5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7708a60c",
   "metadata": {
    "papermill": {
     "duration": 0.061923,
     "end_time": "2026-10-02T14:40:25.692691+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:25.630768+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Understanding How Everything Is Connected in This Model\n",
    "\n",
    "There are a number of connections in this model, and several different residuals being converged. Trying to keep track of all the connections in your head can be a bit challenging, but OpenMDAO offers some visualization tools to help see what's going on.\n",
    "\n",
    "The `openmdao n2` command can be used to view an $N^2$ diagram of the model.  It can be used\n",
    "as follows:\n",
    "```\n",
    "openmdao n2 <your_python_script>\n",
    "```\n",
    "\n",
    "You can do the same thing programmatically by calling the `n2` function in your python script (after setup):\n",
    "```\n",
    "p.setup()\n",
    "\n",
    "om.n2(p)\n",
    "```\n",
    "\n",
    "Here is what the resulting visualization would look like for the above model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ee3fd4f8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:40:25.723348Z",
     "iopub.status.busy": "2026-10-02T14:40:25.723093Z",
     "iopub.status.idle": "2026-10-02T14:40:25.767860Z",
     "shell.execute_reply": "2026-10-02T14:40:25.767216Z"
    },
    "papermill": {
     "duration": 0.066199,
     "end_time": "2026-10-02T14:40:25.768340+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:40:25.702141+00:00",
     "status": "completed"
    },
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "        <iframe\n",
       "            width=\"100%\"\n",
       "            height=\"700\"\n",
       "            src=\"circuit_analysis.html\"\n",
       "            frameborder=\"0\"\n",
       "            allowfullscreen\n",
       "            \n",
       "        ></iframe>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.lib.display.IFrame at 0x7f6bbd644830>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "om.n2(p, outfile=\"circuit_analysis.html\")"
   ]
  }
 ],
 "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.13.14"
  },
  "papermill": {
   "default_parameters": {},
   "duration": 5.595844,
   "end_time": "2026-10-02T14:40:26.509796+00:00",
   "environment_variables": {},
   "exception": null,
   "input_path": "/home/runner/work/OpenMDAO/OpenMDAO/openmdao/docs/openmdao_book/advanced_user_guide/models_implicit_components/implicit_with_balancecomp.ipynb",
   "output_path": "/home/runner/work/OpenMDAO/OpenMDAO/openmdao/docs/_executed_book/advanced_user_guide/models_implicit_components/implicit_with_balancecomp.ipynb",
   "parameters": {},
   "start_time": "2026-10-02T14:40:20.913952+00:00",
   "version": "2.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}