{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "537c85a5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:46:21.754791Z",
     "iopub.status.busy": "2026-10-02T14:46:21.754514Z",
     "iopub.status.idle": "2026-10-02T14:46:21.761655Z",
     "shell.execute_reply": "2026-10-02T14:46:21.760985Z"
    },
    "papermill": {
     "duration": 0.056761,
     "end_time": "2026-10-02T14:46:21.762250+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:21.705489+00:00",
     "status": "completed"
    },
    "tags": [
     "remove-input",
     "remove-output",
     "active-ipynb"
    ]
   },
   "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": "5cdb189c",
   "metadata": {
    "papermill": {
     "duration": 0.001595,
     "end_time": "2026-10-02T14:46:21.765605+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:21.764010+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "# Reloading Case Data into a Model\n",
    "\n",
    "The OpenMDAO API provides a way to load into a model a case from a case recorder file. The method to do this is `Problem.load_case`. Its only argument is a case object from a case recorder file.\n",
    "\n",
    "```{eval-rst}\n",
    "    .. automethod:: openmdao.core.problem.Problem.load_case\n",
    "        :noindex:\n",
    "```\n",
    "\n",
    "The method pulls all input and output variables from a case into the model.\n",
    "\n",
    "Using case recorders, you can record many sources (driver, system, problem, solver). Therefore, cases can have many different types of values. `load_case` works with all of these recordings. \n",
    "\n",
    "It is important to keep in mind that just the variables in the case are updated in the model. The rest of the model variables are left unchanged."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e48da954",
   "metadata": {
    "papermill": {
     "duration": 0.001451,
     "end_time": "2026-10-02T14:46:21.850798+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:21.849347+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Why would you want to load a case?\n",
    "\n",
    "There are several use cases for using `load_case`.\n",
    "\n",
    "- Save points from a Design of Experiments (DOE) run and then go back and run further analysis on them\n",
    "\n",
    "- Give an optimization run an initial guess with values from a previous optimization run. For example, a user would use one optimization method to quickly get a solution that is close, save the case, then using a more accurate, but slower method to find the solution after loading in that case from the first run\n",
    "\n",
    "- Run a sweep of constraint values. This would allow a user to save time by doing runs using initial values from previous runs instead of starting from scratch each time"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd32a05d",
   "metadata": {
    "papermill": {
     "duration": 0.001746,
     "end_time": "2026-10-02T14:46:21.854012+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:21.852266+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "## Simple load case example\n",
    "\n",
    "Here is a simple example of how to call the `load_case` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4a6f14ca",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:46:21.858634Z",
     "iopub.status.busy": "2026-10-02T14:46:21.858406Z",
     "iopub.status.idle": "2026-10-02T14:46:25.073923Z",
     "shell.execute_reply": "2026-10-02T14:46:25.072738Z"
    },
    "papermill": {
     "duration": 3.218722,
     "end_time": "2026-10-02T14:46:25.074488+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:21.855766+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1790952384.763090] [runnervm8df0l:10529:0]        ib_iface.c:1269 UCX  ERROR mana_0: iface 0x556750757110 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",
      "[1790952384.763335] [runnervm8df0l:10529:0]      ucp_worker.c:1412 UCX  ERROR uct_iface_open(ud_verbs/mana_0:1) failed: Input/output error\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[runnervm8df0l:10529] pml_ucx.c:313  Error: Failed to create UCP worker\n"
     ]
    }
   ],
   "source": [
    "import openmdao.api as om\n",
    "from openmdao.test_suite.components.sellar import SellarProblem\n",
    "\n",
    "prob = SellarProblem(name='loading_cases')\n",
    "\n",
    "model = prob.model\n",
    "model.recording_options['record_inputs'] = True\n",
    "model.recording_options['record_outputs'] = True\n",
    "model.recording_options['record_residuals'] = True\n",
    "case_recorder_filename = \"loading_cases.sql\"\n",
    "model.add_recorder(om.SqliteRecorder(case_recorder_filename))\n",
    "\n",
    "prob.setup()\n",
    "\n",
    "prob.run_driver()\n",
    "prob.cleanup()\n",
    "\n",
    "cr = om.CaseReader(prob.get_outputs_dir() / case_recorder_filename)\n",
    "\n",
    "system_cases = cr.list_cases('root', out_stream=None)\n",
    "case = cr.get_case(system_cases[0])\n",
    "\n",
    "# Now load in the case we recorded\n",
    "prob.load_case(case)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d5daae4d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:46:25.078833Z",
     "iopub.status.busy": "2026-10-02T14:46:25.078298Z",
     "iopub.status.idle": "2026-10-02T14:46:25.083992Z",
     "shell.execute_reply": "2026-10-02T14:46:25.083175Z"
    },
    "papermill": {
     "duration": 0.008408,
     "end_time": "2026-10-02T14:46:25.084517+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:25.076109+00:00",
     "status": "completed"
    },
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [],
   "source": [
    "from openmdao.utils.assert_utils import assert_near_equal\n",
    "\n",
    "inputs = case.list_inputs(val=True,out_stream=None)\n",
    "for name, val in inputs:\n",
    "    assert_near_equal(val['val'], model._inputs[name])\n",
    "\n",
    "outputs = case.list_outputs(val=True, out_stream=None)\n",
    "for name, val in outputs:\n",
    "    assert_near_equal(val['val'], model._outputs[name])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c6f9d02",
   "metadata": {
    "papermill": {
     "duration": 0.001215,
     "end_time": "2026-10-02T14:46:25.087044+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:25.085829+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "As was mentioned before, just the variables values in the case get updated in the model. In this example, the case  contains values for the model variables `x`,`z`,`y1`,`y2`,`con1`,`con2`, and `obj`. \n",
    "\n",
    "But if the recorder had only been attached to a subsystem, like this\n",
    "\n",
    "    model.d2.add_recorder(om.SqliteRecorder(case_recorder_filename))\n",
    "\n",
    "only the variables `z`,`y1`, and `y2` would have been recorded and when `load_case` was called with a case from that recording, only those variables in the model would be updated."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "383a5fe0",
   "metadata": {
    "papermill": {
     "duration": 0.001881,
     "end_time": "2026-10-02T14:46:25.090242+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:25.088361+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "Here is a somewhat more realistic use case for `load_case`. In this example, an optimization is run and then the third case is used to load the model and start the optimization again. Notice how in the second optimization run, the optimization requires fewer iterations since it was given an initial guess."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a76f1d4b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:46:25.093858Z",
     "iopub.status.busy": "2026-10-02T14:46:25.093655Z",
     "iopub.status.idle": "2026-10-02T14:46:25.619092Z",
     "shell.execute_reply": "2026-10-02T14:46:25.617806Z"
    },
    "papermill": {
     "duration": 0.528109,
     "end_time": "2026-10-02T14:46:25.619679+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:25.091570+00:00",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "<!DOCTYPE html>\n",
       "<html lang=\"en\">\n",
       "<head>\n",
       "    <style>\n",
       "        h2 {\n",
       "            text-align: center;\n",
       "        }\n",
       "    </style>\n",
       "</head>\n",
       "<body>\n",
       "    <h2></h2>\n",
       "        <table style=\"border: 1px solid #999; border-collapse: collapse;\">\n",
       "        <tr><th style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; background-color: #E9E9E9; text-align: left;\">root</th></tr>\n",
       "       <tr style=\"background-color: ghostwhite;\"><td style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; text-align: left;\">rank0:ScipyOptimize_SLSQP|0|root._solve_nonlinear|0</td></tr>\n",
       "       <tr style=\"background-color: #F3F3F3;\"><td style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; text-align: left;\">rank0:ScipyOptimize_SLSQP|1|root._solve_nonlinear|1</td></tr>\n",
       "       <tr style=\"background-color: ghostwhite;\"><td style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; text-align: left;\">rank0:ScipyOptimize_SLSQP|2|root._solve_nonlinear|2</td></tr>\n",
       "       <tr style=\"background-color: #F3F3F3;\"><td style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; text-align: left;\">rank0:ScipyOptimize_SLSQP|3|root._solve_nonlinear|3</td></tr>\n",
       "       <tr style=\"background-color: ghostwhite;\"><td style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; text-align: left;\">rank0:ScipyOptimize_SLSQP|4|root._solve_nonlinear|4</td></tr>\n",
       "       <tr style=\"background-color: #F3F3F3;\"><td style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; text-align: left;\">rank0:ScipyOptimize_SLSQP|5|root._solve_nonlinear|5</td></tr>\n",
       "       <tr style=\"background-color: ghostwhite;\"><td style=\"border: 1px solid #999; border-collapse: collapse; padding: 5px; text-align: left;\">rank0:ScipyOptimize_SLSQP|6|root._solve_nonlinear|6</td></tr>\n",
       "    </table>\n",
       "</body>\n",
       "</html>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "iterations before: 7 iterations after: 4\n"
     ]
    }
   ],
   "source": [
    "import openmdao.api as om\n",
    "from openmdao.test_suite.components.sellar_feature import SellarMDA\n",
    "\n",
    "prob = SellarProblem(name='loading_cases2', model_class=SellarMDA)\n",
    "prob.setup()\n",
    "\n",
    "prob.model.nonlinear_solver = om.NonlinearBlockGS()\n",
    "prob.model.linear_solver = om.ScipyKrylov()\n",
    "prob.model.cycle.nonlinear_solver = om.NonlinearBlockGS()\n",
    "prob.model.cycle.linear_solver = om.ScipyKrylov()\n",
    "\n",
    "case_recorder_filename = \"loading_cases.sql\"\n",
    "prob.model.add_recorder(om.SqliteRecorder(case_recorder_filename))\n",
    "\n",
    "driver = prob.driver = om.ScipyOptimizeDriver()\n",
    "driver.options['optimizer'] = 'SLSQP'\n",
    "driver.options['tol'] = 1e-9\n",
    "driver.options['disp'] = False\n",
    "driver.recording_options['record_desvars'] = True\n",
    "driver.recording_options['record_objectives'] = True\n",
    "driver.recording_options['record_constraints'] = True\n",
    "\n",
    "prob.run_driver()\n",
    "prob.cleanup()\n",
    "\n",
    "inputs_before = prob.model.list_inputs(val=True, units=True, out_stream=None)\n",
    "outputs_before = prob.model.list_outputs(val=True, units=True, out_stream=None)\n",
    "\n",
    "cr = om.CaseReader(prob.get_outputs_dir() / case_recorder_filename)\n",
    "\n",
    "# get third case\n",
    "system_cases = cr.list_cases('root')  #, out_stream=None)\n",
    "third_case = cr.get_case(system_cases[4])\n",
    "\n",
    "iter_count_before = driver.iter_count\n",
    "\n",
    "# run the model again with a fresh model\n",
    "prob = SellarProblem(name='loading_cases3', model_class=SellarMDA)\n",
    "prob.setup()\n",
    "\n",
    "prob.model.nonlinear_solver = om.NonlinearBlockGS()\n",
    "prob.model.linear_solver = om.ScipyKrylov()\n",
    "prob.model.cycle.nonlinear_solver = om.NonlinearBlockGS()\n",
    "prob.model.cycle.linear_solver = om.ScipyKrylov()\n",
    "\n",
    "driver = prob.driver = om.ScipyOptimizeDriver()\n",
    "driver.options['optimizer'] = 'SLSQP'\n",
    "driver.options['tol'] = 1e-9\n",
    "driver.options['disp'] = False\n",
    "\n",
    "prob.load_case(third_case)\n",
    "prob.run_driver()\n",
    "prob.cleanup()\n",
    "\n",
    "inputs_after = prob.model.list_inputs(val=True, units=True, out_stream=None)\n",
    "outputs_after = prob.model.list_outputs(val=True, units=True, out_stream=None)\n",
    "\n",
    "iter_count_after = driver.iter_count\n",
    "print(f\"iterations before: {iter_count_before} iterations after: {iter_count_after}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bb406988",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-02T14:46:25.624726Z",
     "iopub.status.busy": "2026-10-02T14:46:25.624363Z",
     "iopub.status.idle": "2026-10-02T14:46:25.631717Z",
     "shell.execute_reply": "2026-10-02T14:46:25.630868Z"
    },
    "papermill": {
     "duration": 0.010169,
     "end_time": "2026-10-02T14:46:25.632225+00:00",
     "exception": false,
     "start_time": "2026-10-02T14:46:25.622056+00:00",
     "status": "completed"
    },
    "tags": [
     "remove-input",
     "remove-output"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "np.float64(0.0)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from openmdao.utils.assert_utils import assert_near_equal\n",
    "import numpy as np\n",
    "\n",
    "for before, after in zip(inputs_before, inputs_after):\n",
    "    np.testing.assert_almost_equal(after[1]['val'], before[1]['val'])\n",
    "\n",
    "for before, after in zip(outputs_before, outputs_after):\n",
    "    np.testing.assert_almost_equal(after[1]['val'], before[1]['val'])\n",
    "\n",
    "# Should take one less iteration since we gave it an initial guess in the second run\n",
    "assert_near_equal(iter_count_before, iter_count_after + 3)"
   ]
  }
 ],
 "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"
  },
  "orphan": true,
  "papermill": {
   "default_parameters": {},
   "duration": 5.41764,
   "end_time": "2026-10-02T14:46:26.350079+00:00",
   "environment_variables": {},
   "exception": null,
   "input_path": "/home/runner/work/OpenMDAO/OpenMDAO/openmdao/docs/openmdao_book/features/recording/loading_cases.ipynb",
   "output_path": "/home/runner/work/OpenMDAO/OpenMDAO/openmdao/docs/_executed_book/features/recording/loading_cases.ipynb",
   "parameters": {},
   "start_time": "2026-10-02T14:46:20.932439+00:00",
   "version": "2.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}