{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2e253605",
   "metadata": {},
   "source": [
    "# Time domain\n",
    "\n",
    "This notebook builds upon the serial chain system showcased in the [serial chain notebook](../example_serial_chain/notebook.ipynb). If you are not already familiar with the concepts described in that notebook, please go through it before this one."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6830a700",
   "metadata": {},
   "source": [
    "<img src=../resources/nb_images/two_link_pendulum_flipped.PNG width=800 align=center>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "22ae75ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import Karana.Dynamics as kd\n",
    "import Karana.Dynamics.SOADyn_types as kdt\n",
    "from Karana.KUtils.Sim import SimDS\n",
    "import Karana.Models as kmdl\n",
    "import Karana.Integrators as ki\n",
    "import Karana.KUtils as ku\n",
    "import Karana.Core as kc\n",
    "import atexit\n",
    "import Karana.Math as km\n",
    "from Karana.Math.Kquantities import ureg\n",
    "from pathlib import Path\n",
    "import runpy\n",
    "from tempfile import NamedTemporaryFile"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dfd3d9dc",
   "metadata": {},
   "source": [
    "Create the same serial chain simulation and populate the multibody using a DataStruct (DS) file just as before."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "68fd102c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[WebUI] Web server is running on port 35157\n",
      "You may be able to connect in your browser at:\n",
      "\t\u001b[1mhttp://newton:35157\u001b[0m\n",
      "[WebUI] Karana Viewer is running on port 29534\n",
      "Open this URL to connect:\n",
      "\t\u001b[1mhttp://newton:29534\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"http://newton:29534\">\n",
       "            <b>Click to open Karana Viewer in a new tab</b>\n",
       "        </a>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "sim_ds_path = Path(\"..\") / \"resources\" / \"2_link_pendulum\" / \"2_link_pendulum_no_gravity.h5\"\n",
    "sim = SimDS.fromFile(sim_ds_path).toSim()\n",
    "sim.mb.resetData()\n",
    "sim.mb.getScene().viewAroundFrame(\n",
    "    sim.mb.virtualRoot(), np.array([0.0, 5.0, 0.0]), np.zeros(3), np.array([0.0, 0.0, 1.0])\n",
    ")\n",
    "sim.mb.getScene().update()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54c6482e",
   "metadata": {},
   "source": [
    "# State propagator\n",
    "In order to move the simulation forward in time, we need to solve the equations of motion and numerically integrate the state in time. We need a `StatePropagator` instance to do this. The `Sim` class creates one for us with a default integrator. Here, we will utilize the Python API to change that integrator to RK4."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "632206d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "sim.sp.setIntegrator(ki.IntegratorType.RK4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e83f05af",
   "metadata": {},
   "source": [
    "## Set initial position\n",
    "As before, we'll use the Python API to set the joint values to 0.5 and 1 radians. We will also set the velocity of the second pendulum to 1 rad/s. Then, we need to transfer the state from the bodies to the `Integrator` by calling `sim.sp.setState`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "97a85358-e8e0-475e-b64b-47c9909c4b56",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Set the first body's hinge to 0.5 radians\n",
    "bd1 = sim.mb.getBody(\"bd1\")\n",
    "bd1.parentHinge().subhinge(0).setQ(0.5)\n",
    "\n",
    "# Set the second body's hinge to 1.0 radians\n",
    "bd2 = sim.mb.getBody(\"bd2\")\n",
    "bd2.parentHinge().subhinge(0).setQ(1.0)\n",
    "\n",
    "# Assign a 1 radian/s rate to the second body's hinge\n",
    "bd2.parentHinge().subhinge(0).setU(1.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "398ac53a-87b8-4d8a-b129-8730ee6afc78",
   "metadata": {},
   "source": [
    "Now we will initialize the Integrator state with these values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f706fd1f-2340-4259-8034-a16709c8c758",
   "metadata": {},
   "outputs": [],
   "source": [
    "sim.sp.ensureHealthy()\n",
    "\n",
    "# first call hardReset() to resize the integrator's internal state to\n",
    "# match the coordinates in the multibody model\n",
    "sim.sp.hardReset()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0d0fb35-9fb7-4541-805d-ed5447adc19d",
   "metadata": {},
   "source": [
    "Now use assembleState() to look up the current angle and rate coordinates for the bodies in the multibody model and pack them into a state vector to use to set the integrator's state"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d7dc4f98-5bfc-4faa-98a0-77af4aa087fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "x = sim.sp.assembleState()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22f9244b-7663-4471-a164-1dc660cf9507",
   "metadata": {},
   "source": [
    "Use this state vector to initialize the integrator's state via the state propagator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "112e755e",
   "metadata": {},
   "outputs": [],
   "source": [
    "sim.sp.setState(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f99f7e2",
   "metadata": {},
   "source": [
    "## Register a Timed Event\n",
    "\n",
    "To stop the simulation and print information every 0.1 seconds, we create a timed event and register it with the state propagator. See [timed events](timed_events_sec) for more information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ee0a5819",
   "metadata": {},
   "outputs": [],
   "source": [
    "sp = sim.sp\n",
    "\n",
    "\n",
    "def fn(t):\n",
    "    \"\"\"Print out the time and state.\n",
    "\n",
    "    Parameters\n",
    "    ----------\n",
    "    t : float\n",
    "        The current time.\n",
    "    \"\"\"\n",
    "    print(f\"t = {float(sp.getTime()) / 1e9}s; x = {np.round(sp.getIntegrator().getX(), 6)}\")\n",
    "\n",
    "\n",
    "# the time period at which the above function should be invoked\n",
    "h = np.timedelta64(100, \"ms\")\n",
    "\n",
    "# create the 'show_state' timed event inst\n",
    "te = kd.TimedEvent(\"show_state\", h, fn, False)\n",
    "te.period = h\n",
    "\n",
    "# register the timed event\n",
    "sim.sp.registerTimedEvent(te)\n",
    "del te"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3133f7d",
   "metadata": {},
   "source": [
    "## Add plots\n",
    "Use the `addPlot` helper method on the `sim` to add some plots to the GUI."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "3024ee0a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dash app started at http://newton:41771\n"
     ]
    }
   ],
   "source": [
    "import platform\n",
    "\n",
    "if platform.system() != \"Darwin\":\n",
    "    # In the Jupyter notebook, the live plotting does not work on macOS due to multiprocessing issues.\n",
    "    # This works just fine from a regular Python script if guarded by if __name__ == \"__main__\"\n",
    "    sim.addPlots(\n",
    "        [\n",
    "            ku.SinglePlotData(\n",
    "                \"Pendulum Angles\",\n",
    "                sim.sp.getVars().time,\n",
    "                [\n",
    "                    kc.VarVec(\n",
    "                        \"p1_angle\", bd1.parentHinge().subhinge(0).getVars().Q, \"pendulum 1 angle\"\n",
    "                    ),\n",
    "                    kc.VarVec(\n",
    "                        \"p2_angle\", bd2.parentHinge().subhinge(0).getVars().Q, \"pendulum 2 angle\"\n",
    "                    ),\n",
    "                ],\n",
    "            ),\n",
    "            ku.SinglePlotData(\n",
    "                \"Kinetic Energy\",\n",
    "                sim.sp.getVars().time,\n",
    "                [\n",
    "                    (\n",
    "                        \"Kinetic Energy\",\n",
    "                        lambda: np.array([kd.Algorithms.evalKineticEnergy(sim.mb)]),\n",
    "                        1,\n",
    "                    )\n",
    "                ],\n",
    "            ),\n",
    "        ],\n",
    "        0.1,\n",
    "        title=\"Time domain plots\",\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dc7f01d",
   "metadata": {},
   "source": [
    "## Run the simulation\n",
    "Now, let's run the simulation. `advanceTo` will advance the simulation by the specified time interval, while invoking the registered timed event at its specified period. You can view the evolving state of the system in the gui's 3D graphics as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "de32a7c2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t = 0.1s; x = [0.502012 1.097472 0.040353 0.949576]\n",
      "t = 0.2s; x = [0.508088 1.189946 0.081222 0.900079]\n",
      "t = 0.3s; x = [0.518266 1.277523 0.122369 0.851642]\n",
      "t = 0.4s; x = [0.532565 1.36031  0.163611 0.804272]\n",
      "t = 0.5s; x = [0.550986 1.438411 0.204798 0.757902]\n",
      "t = 0.6s; x = [0.573518 1.511921 0.245789 0.712428]\n",
      "t = 0.7s; x = [0.600133 1.580923 0.286447 0.667733]\n",
      "t = 0.8s; x = [0.630791 1.64549  0.326632 0.623705]\n",
      "t = 0.9s; x = [0.665438 1.705682 0.366199 0.580238]\n",
      "t = 1.0s; x = [0.704006 1.761553 0.405002 0.537243]\n",
      "t = 1.1s; x = [0.746408 1.813144 0.442893 0.494644]\n",
      "t = 1.2s; x = [0.792549 1.860493 0.479729 0.452381]\n",
      "t = 1.3s; x = [0.842315 1.90363  0.515376 0.410408]\n",
      "t = 1.4s; x = [0.89558  1.942583 0.549709 0.368686]\n",
      "t = 1.5s; x = [0.952209 1.977375 0.58262  0.327187]\n",
      "t = 1.6s; x = [1.012054 2.008027 0.614017 0.285887]\n",
      "t = 1.7s; x = [1.074959 2.034558 0.643823 0.244763]\n",
      "t = 1.8s; x = [1.140763 2.056985 0.67198  0.203795]\n",
      "t = 1.9s; x = [1.209299 2.075321 0.698447 0.162961]\n",
      "t = 2.0s; x = [1.280396 2.089581 0.723199 0.122238]\n",
      "t = 2.1s; x = [1.353881 2.099772 0.746221 0.081601]\n",
      "t = 2.2s; x = [1.429582 2.105903 0.767515 0.041022]\n",
      "t = 2.3s; x = [1.507327e+00 2.107977e+00 7.870900e-01 4.730000e-04]\n",
      "t = 2.4s; x = [ 1.586943  2.105997  0.804965 -0.040076]\n",
      "t = 2.5s; x = [ 1.668264  2.099961  0.821169 -0.080653]\n",
      "t = 2.6s; x = [ 1.751123  2.089865  0.835737 -0.121289]\n",
      "t = 2.7s; x = [ 1.835358  2.075701  0.848716 -0.16201 ]\n",
      "t = 2.8s; x = [ 1.920814  2.057459  0.860159 -0.202841]\n",
      "t = 2.9s; x = [ 2.007341  2.035128  0.870133 -0.243805]\n",
      "t = 3.0s; x = [ 2.094795  2.008693  0.878717 -0.284925]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<SpStatusEnum.REACHED_END_TIME: 1>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sim.sp.advanceTo(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e512b9d",
   "metadata": {},
   "source": [
    "Invoke the `advanceBy` method again to advance the simulation further in time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "182c0b88",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t = 3.1s; x = [ 2.183041  1.978137  0.886005 -0.326221]\n",
      "t = 3.2s; x = [ 2.271956  1.943442  0.892106 -0.367715]\n",
      "t = 3.3s; x = [ 2.361427  1.904587  0.897149 -0.409431]\n",
      "t = 3.4s; x = [ 2.451356  1.861547  0.90128  -0.451398]\n",
      "t = 3.5s; x = [ 2.541658  1.814297  0.904664 -0.493654]\n",
      "t = 3.6s; x = [ 2.63227   1.762806  0.907485 -0.536244]\n",
      "t = 3.7s; x = [ 2.723143  1.707035  0.909945 -0.57923 ]\n",
      "t = 3.8s; x = [ 2.814254  1.646944  0.912259 -0.622685]\n",
      "t = 3.9s; x = [ 2.905598  1.58248   0.914655 -0.666699]\n",
      "t = 4.0s; x = [ 2.997195  1.513582  0.917369 -0.711376]\n",
      "t = 4.1s; x = [ 3.08909   1.440179  0.92064  -0.756831]\n",
      "t = 4.2s; x = [ 3.18135   1.362186  0.924703 -0.803179]\n",
      "t = 4.3s; x = [ 3.274064  1.27951   0.929782 -0.850525]\n",
      "t = 4.4s; x = [ 3.367346  1.192046  0.936075 -0.898936]\n",
      "t = 4.5s; x = [ 3.461325  1.099687  0.943741 -0.948409]\n",
      "t = 4.6s; x = [ 3.556144  1.002332  0.95287  -0.998815]\n",
      "t = 4.7s; x = [ 3.651948  0.899903  0.963453 -1.049822]\n",
      "t = 4.8s; x = [ 3.748878  0.792368  0.975333 -1.100802]\n",
      "t = 4.9s; x = [ 3.847046  0.679778  0.988152 -1.15071 ]\n",
      "t = 5.0s; x = [ 3.946519  0.562314  1.001301 -1.197978]\n",
      "t = 5.1s; x = [ 4.047288  0.440341  1.013893 -1.240474]\n",
      "t = 5.2s; x = [ 4.149242  0.314464  1.024809 -1.2756  ]\n",
      "t = 5.3s; x = [ 4.252154  0.185559  1.032846 -1.300618]\n",
      "t = 5.4s; x = [ 4.35568   0.054757  1.036966 -1.313198]\n",
      "t = 5.5s; x = [ 4.459396 -0.076621  1.036584 -1.312038]\n",
      "t = 5.6s; x = [ 4.562848 -0.207194  1.031756 -1.297261]\n",
      "t = 5.7s; x = [ 4.665621 -0.335668  1.023159 -1.270379]\n",
      "t = 5.8s; x = [ 4.76739  -0.460948  1.011879 -1.233833]\n",
      "t = 5.9s; x = [ 4.867947 -0.582204  0.999122 -1.190371]\n",
      "t = 6.0s; x = [ 4.967202 -0.698876  0.985974 -1.142531]\n",
      "t = 6.1s; x = [ 5.065158 -0.810633  0.973276 -1.092351]\n",
      "t = 6.2s; x = [ 5.161891 -0.917318  0.961594 -1.041307]\n",
      "t = 6.3s; x = [ 5.257521 -1.018898  0.951247 -0.990365]\n",
      "t = 6.4s; x = [ 5.352189 -1.115414  0.942364 -0.940099]\n",
      "t = 6.5s; x = [ 5.446043 -1.20695   0.934935 -0.890798]\n",
      "t = 6.6s; x = [ 5.539222 -1.29361   0.928856 -0.842566]\n",
      "t = 6.7s; x = [ 5.631853 -1.375499  0.923961 -0.795392]\n",
      "t = 6.8s; x = [ 5.724046 -1.452721  0.920046 -0.749201]\n",
      "t = 6.9s; x = [ 5.815888 -1.525368  0.916884 -0.703884]\n",
      "t = 7.0s; x = [ 5.907441 -1.593523  0.91424  -0.659324]\n",
      "t = 7.1s; x = [ 5.998745 -1.657255  0.911874 -0.61541 ]\n",
      "t = 7.2s; x = [ 6.089817 -1.716623  0.909551 -0.572039]\n",
      "t = 7.3s; x = [ 6.180649 -1.771678  0.907046 -0.529125]\n",
      "t = 7.4s; x = [ 6.271213 -1.822461  0.904144 -0.486594]\n",
      "t = 7.5s; x = [ 6.361458 -1.869007  0.900648 -0.444389]\n",
      "t = 7.6s; x = [ 6.451316 -1.911348  0.896377 -0.402466]\n",
      "t = 7.7s; x = [ 6.540702 -1.949509  0.891167 -0.360789]\n",
      "t = 7.8s; x = [ 6.629514 -1.983513  0.884877 -0.31933 ]\n",
      "t = 7.9s; x = [ 6.717637 -2.013381  0.87738  -0.278064]\n",
      "t = 8.0s; x = [ 6.804946 -2.039132  0.86857  -0.236972]\n",
      "t = 8.1s; x = [ 6.891304 -2.060781  0.858357 -0.196031]\n",
      "t = 8.2s; x = [ 6.976568 -2.078342  0.846662 -0.15522 ]\n",
      "t = 8.3s; x = [ 7.060585 -2.091828  0.833422 -0.114515]\n",
      "t = 8.4s; x = [ 7.143199 -2.101248  0.818584 -0.073891]\n",
      "t = 8.5s; x = [ 7.224247 -2.106608  0.802104 -0.03332 ]\n",
      "t = 8.6s; x = [ 7.303564e+00 -2.107913e+00  7.839480e-01  7.226000e-03]\n",
      "t = 8.7s; x = [ 7.38098  -2.105163  0.764088  0.047778]\n",
      "t = 8.8s; x = [ 7.456324 -2.098356  0.742506  0.088365]\n",
      "t = 8.9s; x = [ 7.529424 -2.087488  0.719196  0.129015]\n",
      "t = 9.0s; x = [ 7.600106 -2.07255   0.694157  0.169754]\n",
      "t = 9.1s; x = [ 7.668198 -2.053533  0.667406  0.210609]\n",
      "t = 9.2s; x = [ 7.733531 -2.030424  0.638971  0.251601]\n",
      "t = 9.3s; x = [ 7.795938 -2.003207  0.608896  0.292753]\n",
      "t = 9.4s; x = [ 7.855257 -1.971867  0.577241  0.334085]\n",
      "t = 9.5s; x = [ 7.911336 -1.936384  0.544086  0.375619]\n",
      "t = 9.6s; x = [ 7.964028 -1.896736  0.509526  0.41738 ]\n",
      "t = 9.7s; x = [ 8.013198 -1.852899  0.473672  0.459399]\n",
      "t = 9.8s; x = [ 8.058723 -1.804846  0.436651  0.501714]\n",
      "t = 9.9s; x = [ 8.100494 -1.752545  0.398598  0.544375]\n",
      "t = 10.0s; x = [ 8.138413 -1.695957  0.359658  0.587443]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<SpStatusEnum.REACHED_END_TIME: 1>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sim.sp.advanceBy(7.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80b28389",
   "metadata": {},
   "source": [
    "## Python script\n",
    "Let's use the simulation we already have to create a standalone Python script. This will dump the `Multibody` and `StatePropagator` information to a file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "030de17d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[warning] Model auto_time_display (TimeDisplay) does not have a \"toDS\" method, so it cannot be added to the StatePropagatorDS.\n",
      "[warning] Model data_plotter (DataPlotter) does not have a \"toDS\" method, so it cannot be added to the StatePropagatorDS.\n",
      "1 file reformatted\n"
     ]
    }
   ],
   "source": [
    "tf = NamedTemporaryFile(suffix=\".py\")\n",
    "sim.toDS().toFile(tf.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ad920f2",
   "metadata": {},
   "source": [
    "The following will display the generated file within the Jupyter notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "67112d07",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "```python\n",
       "# This is an auto-generated file for the Sim\n",
       "# This file was generated on 2026-06-30 09:56:03.205060\n",
       "import Karana.Math as km\n",
       "from Karana.Math.Kquantities import ureg\n",
       "import Karana.Dynamics as kd\n",
       "import Karana.Scene as ks\n",
       "import Karana.Integrators as ki\n",
       "from Karana.KUtils.Sim import Sim\n",
       "import numpy as np\n",
       "import Karana.Models as kmdl\n",
       "import atexit\n",
       "\n",
       "\n",
       "def populateMultibodyAndStatePropagator(mb: kd.Multibody, sp: kd.StatePropagator):\n",
       "    \"\"\"Populate and configure the provided Multibody and StatePropagator.\n",
       "\n",
       "    Parameters\n",
       "    ----------\n",
       "    mb : kd.Multibody\n",
       "        The Multibody to populate with physical bodies.\n",
       "    sp : kd.StatePropagator\n",
       "        The StatePropagator to populate and configure.\n",
       "    \"\"\"\n",
       "    # This creates, adds, and connects physical bodies via hinges,\n",
       "    # also referred to as joints, to the provided Multibody instance.\n",
       "    # Often, the input `Multibody' instance is empty and contains just a\n",
       "    # virtual root body.\n",
       "    #\n",
       "    # The code below consists of repeated blocks - one per body. Each block\n",
       "    # defines the mass properties for the body, the parent hinge type and\n",
       "    # location on the body and its parent body, and the mesh geometries attached.\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Look up the unique virtual root body for the multibody system that\n",
       "    # will serve as an anchor for the new physical bodies.\n",
       "    vroot = mb.virtualRoot()\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Create 'bd1' body\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Start defining meshes for 'bd1' body\"\n",
       "\n",
       "    # Create one or more meshes attached to the 'bd1' body. Each mesh\n",
       "    # consists of the shape and color/texture definition for its visual appearance.\n",
       "    # The shapes can be parameterized shapes (e.g., spheres, boxes, etc., or be\n",
       "    # defined in external files such as '.glb', '.obj', etc. formats.\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Define the 'bd1_body' mesh parameters for 'bd1' body\n",
       "    # Define the part shape (geometry)\n",
       "    box = ks.BoxGeometry(0.05000000074505806, 0.05000000074505806, 1.0)\n",
       "\n",
       "    # Define the part color/texture material\n",
       "    physical_material_info = ks.PhysicalMaterialInfo()\n",
       "    physical_material_info.color = ks.Color.fromRGBA(\n",
       "        0.6980392336845398, 0.13333334028720856, 0.13333334028720856, 1.0\n",
       "    )\n",
       "    physical_material_info.roughness = 1.0\n",
       "    physical_material = ks.PhysicalMaterial(physical_material_info)\n",
       "    bd1_body = ks.ScenePartSpec(\n",
       "        name=\"bd1_body\",\n",
       "        transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([0.0, 0.0, 0.0]) * ureg.meter,\n",
       "        ),\n",
       "        geometry=box,\n",
       "        material=physical_material,\n",
       "        scale=np.array([1.0, 1.0, 1.0]),\n",
       "        layers=419430400,\n",
       "    )\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Define the 'bd1_pivot' mesh parameters for 'bd1' body\n",
       "    # Define the part shape (geometry)\n",
       "    cylinder = ks.CylinderGeometry(0.10000000149011612, 0.10000000149011612)\n",
       "\n",
       "    # Define the part color/texture material\n",
       "    physical_material_1_info = ks.PhysicalMaterialInfo()\n",
       "    physical_material_1_info.color = ks.Color.fromRGBA(\n",
       "        0.6980392336845398, 0.13333334028720856, 0.13333334028720856, 1.0\n",
       "    )\n",
       "    physical_material_1_info.roughness = 1.0\n",
       "    physical_material_1 = ks.PhysicalMaterial(physical_material_1_info)\n",
       "    bd1_pivot = ks.ScenePartSpec(\n",
       "        name=\"bd1_pivot\",\n",
       "        transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([0.0, 0.0, -0.5]) * ureg.meter,\n",
       "        ),\n",
       "        geometry=cylinder,\n",
       "        material=physical_material_1,\n",
       "        scale=np.array([1.0, 1.0, 1.0]),\n",
       "        layers=419430400,\n",
       "    )\n",
       "\n",
       "    # End defining meshes for 'bd1' body\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "    # Assemble overall parameters needed to define the 'bd1' body\n",
       "    # including mass and kinematics properties.\n",
       "    bd1_params = kd.PhysicalBodyParams(\n",
       "        # 'bd1' mass properties\n",
       "        spI=km.SpatialInertia(\n",
       "            2.0 * ureg.kilogram,\n",
       "            np.array([0.0, 0.0, 0.0]) * ureg.meter,\n",
       "            np.array([[3.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 1.0]])\n",
       "            * ureg.kilogram\n",
       "            * ureg.meter**2,\n",
       "        ),\n",
       "        # Define the location and orientation of the 'bd1' parent hinge\n",
       "        # relative to the 'bd1' body frame\n",
       "        body_to_joint_transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([-0.0, -0.0, 0.5]) * ureg.meter,\n",
       "        ),\n",
       "        # Define the location and orientation of the 'bd1' parent hinge\n",
       "        # relative to the parent body's frame\n",
       "        inb_to_joint_transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([0.0, 0.0, 0.0]) * ureg.meter,\n",
       "        ),\n",
       "        # define the 'bd1' parent hinge type and parameters\n",
       "        hinge_params=kd.PhysicalHingeParams(\n",
       "            hinge_type=kd.HingeType.REVOLUTE,\n",
       "            subhinge_params=[\n",
       "                kd.PinSubhingeParams(\n",
       "                    unit_axis=np.array([0.0, 1.0, 0.0]),\n",
       "                    prescribed=False,\n",
       "                ),\n",
       "            ],\n",
       "        ),\n",
       "        # Add 'bd1' scene parts defined above\n",
       "        scene_part_specs=[bd1_body, bd1_pivot],\n",
       "    )\n",
       "\n",
       "    # Create the 'bd1' body\n",
       "    bd1 = kd.PhysicalBody(\"bd1\", mb)\n",
       "\n",
       "    # Connect the 'bd1' body to its parent via a hinge\n",
       "    kd.PhysicalHinge(vroot, bd1, kd.HingeType.REVOLUTE)\n",
       "\n",
       "    # Set the parameters for the 'bd1' body\n",
       "    bd1.setParams(bd1_params)\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Create 'bd2' body\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Start defining meshes for 'bd2' body\"\n",
       "\n",
       "    # Create one or more meshes attached to the 'bd2' body. Each mesh\n",
       "    # consists of the shape and color/texture definition for its visual appearance.\n",
       "    # The shapes can be parameterized shapes (e.g., spheres, boxes, etc., or be\n",
       "    # defined in external files such as '.glb', '.obj', etc. formats.\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Define the 'bd2_body' mesh parameters for 'bd2' body\n",
       "    # Define the part shape (geometry)\n",
       "    box_1 = ks.BoxGeometry(0.05000000074505806, 0.05000000074505806, 1.0)\n",
       "\n",
       "    # Define the part color/texture material\n",
       "    physical_material_2_info = ks.PhysicalMaterialInfo()\n",
       "    physical_material_2_info.color = ks.Color.fromRGBA(\n",
       "        0.6980392336845398, 0.13333334028720856, 0.13333334028720856, 1.0\n",
       "    )\n",
       "    physical_material_2_info.roughness = 1.0\n",
       "    physical_material_2 = ks.PhysicalMaterial(physical_material_2_info)\n",
       "    bd2_body = ks.ScenePartSpec(\n",
       "        name=\"bd2_body\",\n",
       "        transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([0.0, 0.0, 0.5]) * ureg.meter,\n",
       "        ),\n",
       "        geometry=box_1,\n",
       "        material=physical_material_2,\n",
       "        scale=np.array([1.0, 1.0, 1.0]),\n",
       "        layers=419430400,\n",
       "    )\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Define the 'bd2_end' mesh parameters for 'bd2' body\n",
       "    # Define the part shape (geometry)\n",
       "    cylinder_1 = ks.CylinderGeometry(0.10000000149011612, 0.10000000149011612)\n",
       "\n",
       "    # Define the part color/texture material\n",
       "    physical_material_3_info = ks.PhysicalMaterialInfo()\n",
       "    physical_material_3_info.color = ks.Color.fromRGBA(1.0, 0.843137264251709, 0.0, 1.0)\n",
       "    physical_material_3_info.roughness = 1.0\n",
       "    physical_material_3 = ks.PhysicalMaterial(physical_material_3_info)\n",
       "    bd2_end = ks.ScenePartSpec(\n",
       "        name=\"bd2_end\",\n",
       "        transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([0.0, 0.0, 0.0]) * ureg.meter,\n",
       "        ),\n",
       "        geometry=cylinder_1,\n",
       "        material=physical_material_3,\n",
       "        scale=np.array([2.0, 2.0, 2.0]),\n",
       "        layers=419430400,\n",
       "    )\n",
       "\n",
       "    # End defining meshes for 'bd2' body\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "    # Assemble overall parameters needed to define the 'bd2' body\n",
       "    # including mass and kinematics properties.\n",
       "    bd2_params = kd.PhysicalBodyParams(\n",
       "        # 'bd2' mass properties\n",
       "        spI=km.SpatialInertia(\n",
       "            2.0 * ureg.kilogram,\n",
       "            np.array([0.0, 0.0, 0.0]) * ureg.meter,\n",
       "            np.array([[3.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 1.0]])\n",
       "            * ureg.kilogram\n",
       "            * ureg.meter**2,\n",
       "        ),\n",
       "        # Define the location and orientation of the 'bd2' parent hinge\n",
       "        # relative to the 'bd2' body frame\n",
       "        body_to_joint_transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([-0.0, -0.0, 1.0]) * ureg.meter,\n",
       "        ),\n",
       "        # Define the location and orientation of the 'bd2' parent hinge\n",
       "        # relative to the parent body's frame\n",
       "        inb_to_joint_transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([0.0, 0.0, -0.5]) * ureg.meter,\n",
       "        ),\n",
       "        # define the 'bd2' parent hinge type and parameters\n",
       "        hinge_params=kd.PhysicalHingeParams(\n",
       "            hinge_type=kd.HingeType.REVOLUTE,\n",
       "            subhinge_params=[\n",
       "                kd.PinSubhingeParams(\n",
       "                    unit_axis=np.array([0.0, 1.0, 0.0]),\n",
       "                    prescribed=False,\n",
       "                ),\n",
       "            ],\n",
       "        ),\n",
       "        # Add 'bd2' scene parts defined above\n",
       "        scene_part_specs=[bd2_body, bd2_end],\n",
       "    )\n",
       "\n",
       "    # Create the 'bd2' body\n",
       "    bd2 = kd.PhysicalBody(\"bd2\", mb)\n",
       "\n",
       "    # Connect the 'bd2' body to its parent via a hinge\n",
       "    kd.PhysicalHinge(bd1, bd2, kd.HingeType.REVOLUTE)\n",
       "\n",
       "    # Set the parameters for the 'bd2' body\n",
       "    bd2.setParams(bd2_params)\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Start defining parts attached to the virtual root\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Define the 'obstacle_part' mesh parameters for virtual root\n",
       "    # Define the part shape (geometry)\n",
       "    box_2 = ks.BoxGeometry(0.25, 0.25, 0.25)\n",
       "\n",
       "    # Define the part color/texture material\n",
       "    physical_material_4_info = ks.PhysicalMaterialInfo()\n",
       "    physical_material_4_info.color = ks.Color.fromRGBA(\n",
       "        0.49803921580314636, 1.0, 0.8313725590705872, 1.0\n",
       "    )\n",
       "    physical_material_4_info.roughness = 1.0\n",
       "    physical_material_4 = ks.PhysicalMaterial(physical_material_4_info)\n",
       "    obstacle_part = ks.ScenePartSpec(\n",
       "        name=\"obstacle_part\",\n",
       "        transform=km.HomTran(\n",
       "            km.UnitQuaternion(np.array([0.0, 0.0, 0.0, 1.0])),\n",
       "            np.array([0.0, 0.0, 0.0]) * ureg.meter,\n",
       "        ),\n",
       "        geometry=box_2,\n",
       "        material=physical_material_4,\n",
       "        scale=np.array([1.0, 1.0, 1.0]),\n",
       "        layers=419430400,\n",
       "    )\n",
       "\n",
       "    vroot.addScenePartSpec(obstacle_part)\n",
       "\n",
       "    # End defining parts attached to the virtual root\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Finished physical body additions\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "    # Finalize the multibody for the added bodies\n",
       "    mb.ensureHealthy()\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Populate and configure the StatePropagator. This will involve\n",
       "    # defining the type of solver to use for the multibody equations of\n",
       "    # motion, adding an integrator to use for state propagation,\n",
       "    # addition of KModels for interacting with the multibody dynamics,\n",
       "    # and timed events for execution during time advancement.\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Set the StatePropagator's solver type. 'FORWARD_DYNAMICS' is the\n",
       "    # typical choice for setting up the propagator to solve the\n",
       "    # equations of motion for time domain simulations\n",
       "    sp.setSolverType(kd.MMSolverType.FORWARD_DYNAMICS)\n",
       "\n",
       "    # Set up the integrator\n",
       "    sp.setIntegrator(ki.IntegratorType.RK4)\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Set the StatePropagator options\n",
       "\n",
       "    # Call with True to make an extra dynamics derivative call at the\n",
       "    # end of a simulation step to update the acceleration values.\n",
       "    sp.setUpdateStateDerivativesHopEnd(False)\n",
       "\n",
       "    # Set a limit on the maximum integration time step size.\n",
       "    # A value of 0.0 means there is no maximum limit.\n",
       "    sp.setMaxStepSize(0.0)\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Add KModels. KModels are parameterized models for\n",
       "    # component actuator, sensors, environmental, etc. that interact\n",
       "    # with the dynamics.\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Add the update_proxy_scene KModel\n",
       "    multibody_scene = mb.getScene()\n",
       "    if multibody_scene is not None:\n",
       "        update_proxy_scene = kmdl.UpdateProxyScene(\"update_proxy_scene\", sp, multibody_scene)\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Add the gil_release KModel\n",
       "    gil_release = kmdl.GilRelease(\"gil_release\", sp)\n",
       "\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Add the sync_real_time KModel\n",
       "    sync_real_time = kmdl.SyncRealTime(\"sync_real_time\", sp, 1.0)\n",
       "\n",
       "    # Finalize the StatePropagator for the updated multibody system, the\n",
       "    # KModels and the integrator\n",
       "    sp.hardReset()\n",
       "    sp.ensureHealthy()\n",
       "\n",
       "    # End setting up StatePropagator and KModels\n",
       "    # ----------------------------------------------------------------------------------------------\n",
       "\n",
       "\n",
       "if __name__ == \"__main__\":\n",
       "    # Create a simulation\n",
       "    sim = Sim()\n",
       "\n",
       "    # Populate the Multibody and StatePropagator for the Sim\n",
       "    populateMultibodyAndStatePropagator(sim.mb, sim.sp)\n",
       "\n",
       "    # Code to cleanup upon exit\n",
       "    def cleanup():\n",
       "        global sim\n",
       "        del sim\n",
       "\n",
       "    atexit.register(cleanup)\n",
       "\n",
       "```"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from IPython.display import Markdown\n",
    "from pathlib import Path\n",
    "\n",
    "Markdown(f\"```python\\n{Path(tf.name).read_text()}\\n```\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "073230ce",
   "metadata": {},
   "source": [
    "Above, you'll see the multibody code similar to the [serial chain notebook](../example_serial_chain/notebook.ipynb), as well as code to create the `StatePropagator`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "534e2807",
   "metadata": {},
   "outputs": [],
   "source": [
    "del sim\n",
    "globals().update(runpy.run_path(tf.name, run_name=\"__main__\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b60265b",
   "metadata": {},
   "source": [
    "Let's bring up the GUI again just to show we captured everything"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f2cd6a30",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[WebUI] Web server is running on port 39963\n",
      "You may be able to connect in your browser at:\n",
      "\t\u001b[1mhttp://newton:39963\u001b[0m\n",
      "[WebUI] Karana Viewer is running on port 29534\n",
      "Open this URL to connect:\n",
      "\t\u001b[1mhttp://newton:29534\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "        <a target=\"_blank\" rel=\"noopener noreferrer\" href=\"http://newton:29534\">\n",
       "            <b>Click to open Karana Viewer in a new tab</b>\n",
       "        </a>\n",
       "        "
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Create the GUI\n",
    "sim.setupGui()\n",
    "\n",
    "# Update the camera view\n",
    "sim.mb.resetData()\n",
    "sim.mb.getScene().viewAroundFrame(\n",
    "    sim.mb.virtualRoot(), np.array([0.0, 5.0, 0.0]), np.zeros(3), np.array([0.0, 0.0, 1.0])\n",
    ")\n",
    "\n",
    "# Redraw the scene\n",
    "sim.mb.getScene().update()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "550b3b2e",
   "metadata": {},
   "source": [
    "## Cleanup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "dbf76e3d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.cleanup()>"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def cleanup():\n",
    "    \"\"\"Clean up the simulation.\"\"\"\n",
    "    global bd1, bd2, sim, sp\n",
    "    del bd1, bd2, sim, sp\n",
    "\n",
    "\n",
    "atexit.register(cleanup)"
   ]
  }
 ],
 "metadata": {
  "docs": {
   "draft": true,
   "tags": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
