{
 "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": [
    "# BoundsEnforceLS\n",
    "\n",
    "The BoundsEnforceLS only backtracks until variables violate their upper and lower bounds.\n",
    "\n",
    "Here is a simple example where BoundsEnforceLS is used to backtrack during the Newton solver's iteration on\n",
    "a system that contains an implicit component with 3 states that are confined to a small range of values."
   ]
  },
  {
   "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_src20\", get_code(\"openmdao.test_suite.components.implicit_newton_linesearch.ImplCompTwoStatesArrays\"), display=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ":::{Admonition} `ImplCompTwoStatesArrays` class definition \n",
    ":class: dropdown\n",
    "\n",
    "{glue:}`code_src20`\n",
    ":::"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "import openmdao.api as om\n",
    "from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n",
    "\n",
    "top = om.Problem()\n",
    "top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n",
    "\n",
    "top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n",
    "top.model.nonlinear_solver.options['maxiter'] = 10\n",
    "top.model.linear_solver = om.ScipyKrylov()\n",
    "\n",
    "top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS()\n",
    "\n",
    "top.setup()\n",
    "top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n",
    "\n",
    "# Test lower bounds: should go to the lower bound and stall\n",
    "top.set_val('comp.y', 0.)\n",
    "top.set_val('comp.z', 1.6)\n",
    "top.run_model()\n",
    "\n",
    "for ind in range(3):\n",
    "    print(top.get_val('comp.z', indices=ind))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.assert_utils import assert_near_equal\n",
    "\n",
    "for ind in range(3):\n",
    "    assert_near_equal(top.get_val('comp.z', indices=ind), [1.5], 1e-8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## BoundsEnforceLS Options"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input"
    ]
   },
   "outputs": [],
   "source": [
    "om.show_options_table(\"openmdao.solvers.linesearch.backtracking.BoundsEnforceLS\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## BoundsEnforceLS Constructor\n",
    "\n",
    "The call signature for the `BoundsEnforceLS` constructor is:\n",
    "\n",
    "```{eval-rst}\n",
    "    .. automethod:: openmdao.solvers.linesearch.backtracking.BoundsEnforceLS.__init__\n",
    "        :noindex:\n",
    "```\n",
    "\n",
    "## BoundsEnforceLS Option Examples\n",
    "\n",
    "**bound_enforcement**\n",
    "\n",
    "BoundsEnforceLS includes the `bound_enforcement` option in its options dictionary. This option has a dual role:\n",
    "\n",
    "1. Behavior of the non-bounded variables when the bounded ones are capped.\n",
    "2. Direction of the further backtracking.\n",
    "\n",
    "There are three difference bounds enforcement schemes available in this option.\n",
    "\n",
    "With \"scalar\" bounds enforcement, only the variables that violate their bounds are pulled back to feasible values; the\n",
    "remaining values are kept at the Newton-stepped point. This changes the direction of the backtracking vector so that\n",
    "it still moves in the direction of the initial point. This is the default bounds enforcement for `BoundsEnforceLS`.\n",
    "\n",
    "![BT2](images/BT2.jpg)\n",
    "\n",
    "With \"vector\" bounds enforcement, the solution in the output vector is pulled back in unison to a point where none of the\n",
    "variables violate any upper or lower bounds. Further backtracking continues along the Newton gradient direction vector back towards the\n",
    "initial point.\n",
    "\n",
    "![BT1](images/BT1.jpg)\n",
    "\n",
    "With \"wall\" bounds enforcement, only the variables that violate their bounds are pulled back to feasible values; the remaining values are kept at the Newton-stepped point. Further backtracking only occurs in the direction of the non-violating variables, so that it will move along the wall.\n",
    "\n",
    "```{Note}\n",
    "When using BoundsEnforceLS linesearch, the `scalar` and `wall` methods are exactly the same because no further\n",
    "backtracking is performed.\n",
    "```\n",
    "\n",
    "![BT3](images/BT3.jpg)\n",
    "\n",
    "Here are a few examples of this option:\n",
    "\n",
    "- bound_enforcement: vector\n",
    "\n",
    "  The `bound_enforcement` option in the options dictionary is used to specify how the output bounds\n",
    "  are enforced. When this is set to \"vector\", the output vector is rolled back along the computed gradient until\n",
    "  it reaches a point where the earliest bound violation occurred. The backtracking continues along the original\n",
    "  computed gradient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n",
    "\n",
    "top = om.Problem()\n",
    "top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n",
    "\n",
    "top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n",
    "top.model.nonlinear_solver.options['maxiter'] = 10\n",
    "top.model.linear_solver = om.ScipyKrylov()\n",
    "\n",
    "top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='vector')\n",
    "\n",
    "top.setup()\n",
    "top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n",
    "\n",
    "# Test lower bounds: should go to the lower bound and stall\n",
    "top.set_val('comp.y', 0.)\n",
    "top.set_val('comp.z', 1.6)\n",
    "top.run_model()\n",
    "\n",
    "for ind in range(3):\n",
    "    print(top.get_val('comp.z', indices=ind))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "for ind in range(3):\n",
    "    assert_near_equal(top.get_val('comp.z', indices=ind), [1.5], 1e-8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- bound_enforcement: scalar\n",
    "\n",
    "  The `bound_enforcement` option in the options dictionary is used to specify how the output bounds\n",
    "  are enforced. When this is set to \"scaler\", then the only indices in the output vector that are rolled back\n",
    "  are the ones that violate their upper or lower bounds. The backtracking continues along the modified gradient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n",
    "\n",
    "top = om.Problem()\n",
    "top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n",
    "\n",
    "top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n",
    "top.model.nonlinear_solver.options['maxiter'] = 10\n",
    "top.model.linear_solver = om.ScipyKrylov()\n",
    "\n",
    "top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='scalar')\n",
    "\n",
    "top.setup()\n",
    "top.set_val('x', np.array([2., 2, 2]).reshape(3, 1))\n",
    "top.run_model()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test lower bounds: should stop just short of the lower bound\n",
    "top.set_val('comp.y', 0.)\n",
    "top.set_val('comp.z', 1.6)\n",
    "top.run_model()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- bound_enforcement: wall\n",
    "\n",
    "  The `bound_enforcement` option in the options dictionary is used to specify how the output bounds\n",
    "  are enforced. When this is set to \"wall\", then the only indices in the output vector that are rolled back\n",
    "  are the ones that violate their upper or lower bounds. The backtracking continues along a modified gradient\n",
    "  direction that follows the boundary of the violated output bounds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from openmdao.test_suite.components.implicit_newton_linesearch import ImplCompTwoStatesArrays\n",
    "\n",
    "top = om.Problem()\n",
    "top.model.add_subsystem('comp', ImplCompTwoStatesArrays(), promotes_inputs=['x'])\n",
    "\n",
    "top.model.nonlinear_solver = om.NewtonSolver(solve_subsystems=False)\n",
    "top.model.nonlinear_solver.options['maxiter'] = 10\n",
    "top.model.linear_solver = om.ScipyKrylov()\n",
    "\n",
    "top.model.nonlinear_solver.linesearch = om.BoundsEnforceLS(bound_enforcement='wall')\n",
    "\n",
    "top.setup()\n",
    "top.set_val('x', np.array([0.5, 0.5, 0.5]).reshape(3, 1))\n",
    "\n",
    "# Test upper bounds: should go to the upper bound and stall\n",
    "top.set_val('comp.y', 0.)\n",
    "top.set_val('comp.z', 2.4)\n",
    "top.run_model()\n",
    "\n",
    "print(top.get_val('comp.z', indices=0))\n",
    "print(top.get_val('comp.z', indices=1))\n",
    "print(top.get_val('comp.z', indices=2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "assert_near_equal(top.get_val('comp.z', indices=0), [2.6], 1e-8)\n",
    "assert_near_equal(top.get_val('comp.z', indices=1), [2.5], 1e-8)\n",
    "assert_near_equal(top.get_val('comp.z', indices=2), [2.65], 1e-8)"
   ]
  }
 ],
 "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
}
