{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2e253605",
   "metadata": {},
   "source": [
    "# Beginner example of creating a system-level simulation\n",
    "\n",
    "An introductory example of setting up a time-domain simulation of a serial chain system along with a gravity `KModel` and starting up the GUI for introspection.\n",
    "\n",
    "This notebook builds upon the time domain simulation showcased in the [time domain notebook](../example_time_domain/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": "f2653775",
   "metadata": {},
   "source": [
    "<img src=../resources/nb_images/system_level.png width=400 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 in the earlier notebooks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "68fd102c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[WebUI] Web server is running on port 35765\n",
      "You may be able to connect in your browser at:\n",
      "\t\u001b[1mhttp://newton:35765\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.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": "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. Then, we need to update the `Integrator` by calling `sim.sp.setState`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "112e755e",
   "metadata": {},
   "outputs": [],
   "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",
    "# Update the Integrator with these values\n",
    "sim.sp.ensureHealthy()\n",
    "sim.sp.hardReset()\n",
    "sim.sp.setState(sim.sp.assembleState())"
   ]
  },
  {
   "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 our state propagator here. See [timed events](timed_events_sec) for more information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "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",
    "h = np.timedelta64(100, \"ms\")\n",
    "t = kd.TimedEvent(\"hop_size\", h, fn, False)\n",
    "t.period = h\n",
    "\n",
    "# register the timed event\n",
    "sim.sp.registerTimedEvent(t)\n",
    "del t"
   ]
  },
  {
   "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": 5,
   "id": "f71278a6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dash app started at http://newton:35379\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",
    "                \"Energy\",\n",
    "                sim.sp.getVars().time,\n",
    "                [\n",
    "                    (\n",
    "                        \"Energy\",\n",
    "                        lambda: np.array(\n",
    "                            [\n",
    "                                kd.Algorithms.evalKineticEnergy(sim.mb)\n",
    "                                + kd.Algorithms.evalGravitationalPotentialEnergy(sim.mb)\n",
    "                            ]\n",
    "                        ),\n",
    "                        1,\n",
    "                    )\n",
    "                ],\n",
    "            ),\n",
    "        ],\n",
    "        0.1,\n",
    "        title=\"Time domain plots\",\n",
    "    )\n",
    "\n",
    "# Set the gravitational values for each body so the potential energy starts\n",
    "# off with the correct value\n",
    "sim.sp.getRegisteredModel(\"grav_model\").preDeriv(0.0, np.zeros(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dc7f01d",
   "metadata": {},
   "source": [
    "## Run the simulation\n",
    "Now, let's run the simulation. `advanceTo` will advance to the desired time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "de32a7c2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t = 0.1s; x = [ 0.489652  0.988675 -0.204372 -0.229692]\n",
      "t = 0.2s; x = [ 0.460181  0.952734 -0.377441 -0.498453]\n",
      "t = 0.3s; x = [ 0.416185  0.886566 -0.490348 -0.838926]\n",
      "t = 0.4s; x = [ 0.364848  0.781941 -0.521858 -1.268539]\n",
      "t = 0.5s; x = [ 0.314657  0.630259 -0.469367 -1.774113]\n",
      "t = 0.6s; x = [ 0.272677  0.426878 -0.36784  -2.283512]\n",
      "t = 0.7s; x = [ 0.239785  0.17873  -0.306716 -2.635376]\n",
      "t = 0.8s; x = [ 0.206192 -0.088126 -0.396623 -2.630655]\n",
      "t = 0.9s; x = [ 0.154474 -0.333549 -0.661301 -2.218588]\n",
      "t = 1.0s; x = [ 0.071283 -0.52331  -1.004812 -1.551371]\n",
      "t = 1.1s; x = [-0.045137 -0.641644 -1.309339 -0.816614]\n",
      "t = 1.2s; x = [-0.186801 -0.688619 -1.501951 -0.139627]\n",
      "t = 1.3s; x = [-0.340919 -0.673831 -1.557416  0.410907]\n",
      "t = 1.4s; x = [-0.493874 -0.611752 -1.481105  0.803146]\n",
      "t = 1.5s; x = [-0.633409 -0.518669 -1.292885  1.031963]\n",
      "t = 1.6s; x = [-0.749523 -0.410314 -1.01676   1.112455]\n",
      "t = 1.7s; x = [-0.834624 -0.300165 -0.676448  1.073233]\n",
      "t = 1.8s; x = [-0.883399 -0.198533 -0.293633  0.947541]\n",
      "t = 1.9s; x = [-0.892558 -0.112548  0.113058  0.764388]\n",
      "t = 2.0s; x = [-0.860526 -0.046859  0.52756   0.544736]\n",
      "t = 2.1s; x = [-0.787318 -0.004286  0.933722  0.304692]\n",
      "t = 2.2s; x = [-0.674719  0.014023  1.311554  0.063321]\n",
      "t = 2.3s; x = [-0.526819  0.009286  1.634891 -0.150453]\n",
      "t = 2.4s; x = [-0.350583 -0.013858  1.873087 -0.298011]\n",
      "t = 2.5s; x = [-0.155993 -0.046845  1.997997 -0.342173]\n",
      "t = 2.6s; x = [ 0.044693 -0.078219  1.993934 -0.265322]\n",
      "t = 2.7s; x = [ 0.2386   -0.096313  1.864684 -0.08147 ]\n",
      "t = 2.8s; x = [ 0.414184 -0.092294  1.632343  0.168778]\n",
      "t = 2.9s; x = [ 0.562699 -0.06199   1.328865  0.436432]\n",
      "t = 3.0s; x = [ 0.678645 -0.005763  0.985708  0.682068]\n",
      "t = 3.1s; x = [0.759325 0.072953 0.626754 0.884112]\n",
      "t = 3.2s; x = [0.803962 0.169402 0.266699 1.036415]\n",
      "t = 3.3s; x = [ 0.812907  0.278609 -0.085916  1.139319]\n",
      "t = 3.4s; x = [ 0.787263  0.395537 -0.423845  1.189908]\n",
      "t = 3.5s; x = [ 0.728959  0.514448 -0.737114  1.176198]\n",
      "t = 3.6s; x = [ 0.64115   0.627931 -1.010964  1.07713 ]\n",
      "t = 3.7s; x = [ 0.528747  0.726175 -1.225282  0.867281]\n",
      "t = 3.8s; x = [ 0.398912  0.79689  -1.355059  0.523537]\n",
      "t = 3.9s; x = [ 0.261469  0.825932 -1.373152  0.032507]\n",
      "t = 4.0s; x = [ 0.128759  0.798569 -1.257707 -0.602206]\n",
      "t = 4.1s; x = [ 0.01449   0.701679 -1.00672  -1.349841]\n",
      "t = 4.2s; x = [-0.069282  0.527331 -0.658891 -2.132643]\n",
      "t = 4.3s; x = [-0.117406  0.279326 -0.316789 -2.786375]\n",
      "t = 4.4s; x = [-0.138024 -0.017208 -0.133705 -3.061899]\n",
      "t = 4.5s; x = [-0.152291 -0.315756 -0.187531 -2.831406]\n",
      "t = 4.6s; x = [-0.180252 -0.572292 -0.38172  -2.266976]\n",
      "t = 4.7s; x = [-0.228368 -0.766567 -0.570538 -1.620475]\n",
      "t = 4.8s; x = [-0.291409 -0.898453 -0.672599 -1.033372]\n",
      "t = 4.9s; x = [-0.359302 -0.97683  -0.667755 -0.553106]\n",
      "t = 5.0s; x = [-0.421809 -1.012674 -0.56879  -0.180108]\n",
      "t = 5.1s; x = [-0.47082  -1.015689 -0.402845  0.108261]\n",
      "t = 5.2s; x = [-0.501205 -0.9927   -0.201663  0.346334]\n",
      "t = 5.3s; x = [-0.511046 -0.946794  0.002968  0.573004]\n",
      "t = 5.4s; x = [-0.501492 -0.877223  0.181566  0.825393]\n",
      "t = 5.5s; x = [-0.476425 -0.779904  0.309912  1.131326]\n",
      "t = 5.6s; x = [-0.441636 -0.648893  0.375283  1.49797 ]\n",
      "t = 5.7s; x = [-0.403155 -0.479304  0.388169  1.893053]\n",
      "t = 5.8s; x = [-0.364197 -0.272434  0.396376  2.221638]\n",
      "t = 5.9s; x = [-0.321335 -0.042261  0.480143  2.332989]\n",
      "t = 6.0s; x = [-0.263661  0.18304   0.695745  2.116421]\n",
      "t = 6.1s; x = [-0.178721  0.371186  1.013108  1.608334]\n",
      "t = 6.2s; x = [-0.060716  0.499691  1.340507  0.949453]\n",
      "t = 6.3s; x = [0.086815 0.560731 1.591914 0.27943 ]\n",
      "t = 6.4s; x = [ 0.25345   0.558559  1.717755 -0.30191 ]\n",
      "t = 6.5s; x = [ 0.425659  0.505401  1.703054 -0.732752]\n",
      "t = 6.6s; x = [ 0.589625  0.418007  1.555511 -0.98462 ]\n",
      "t = 6.7s; x = [ 0.732998  0.314375  1.295178 -1.060499]\n",
      "t = 6.8s; x = [ 0.845784  0.210807  0.948332 -0.989591]\n",
      "t = 6.9s; x = [ 0.920725  0.119904  0.54286  -0.814656]\n",
      "t = 7.0s; x = [ 0.953247  0.049968  0.103868 -0.576404]\n",
      "t = 7.1s; x = [ 0.941074  0.005713 -0.347899 -0.305214]\n",
      "t = 7.2s; x = [ 0.883865 -0.01074  -0.793617 -0.02409 ]\n",
      "t = 7.3s; x = [ 7.832650e-01  3.950000e-04 -1.211653e+00  2.415740e-01]\n",
      "t = 7.4s; x = [ 0.643388  0.035854 -1.573871  0.455181]\n",
      "t = 7.5s; x = [ 0.471479  0.088117 -1.846512  0.569534]\n",
      "t = 7.6s; x = [ 0.27815   0.144997 -1.997706  0.542011]\n",
      "t = 7.7s; x = [ 0.076619  0.191263 -2.009211  0.358216]\n",
      "t = 7.8s; x = [-0.119148  0.212318 -1.885068  0.045734]\n",
      "t = 7.9s; x = [-0.296737  0.198163 -1.651616 -0.333927]\n",
      "t = 8.0s; x = [-0.447178  0.145735 -1.349436 -0.707861]\n",
      "t = 8.1s; x = [-0.56575   0.058841 -1.020683 -1.015084]\n",
      "t = 8.2s; x = [-0.651484 -0.053919 -0.696453 -1.222377]\n",
      "t = 8.3s; x = [-0.705649 -0.182244 -0.389955 -1.328594]\n",
      "t = 8.4s; x = [-0.730024 -0.316963 -0.099658 -1.354633]\n",
      "t = 8.5s; x = [-0.725899 -0.451336  0.180944 -1.324984]\n",
      "t = 8.6s; x = [-0.694073 -0.580548  0.454078 -1.252161]\n",
      "t = 8.7s; x = [-0.63554  -0.700168  0.713247 -1.131008]\n",
      "t = 8.8s; x = [-0.552401 -0.804483  0.942952 -0.942053]\n",
      "t = 8.9s; x = [-0.448705 -0.885424  1.119879 -0.658718]\n",
      "t = 9.0s; x = [-0.331156 -0.932218  1.214925 -0.255398]\n",
      "t = 9.1s; x = [-0.209477 -0.93192   1.197596  0.284772]\n",
      "t = 9.2s; x = [-0.096158 -0.87067   1.04539   0.96182 ]\n",
      "t = 9.3s; x = [-0.004897 -0.735886  0.759714  1.747259]\n",
      "t = 9.4s; x = [ 0.05291  -0.520343  0.390407  2.554898]\n",
      "t = 9.5s; x = [ 0.074595 -0.230793  0.065922  3.181135]\n",
      "t = 9.6s; x = [ 0.073723  0.09961  -0.034733  3.327521]\n",
      "t = 9.7s; x = [0.076912 0.415674 0.134148 2.917478]\n",
      "t = 9.8s; x = [0.104419 0.673483 0.419843 2.216783]\n",
      "t = 9.9s; x = [0.159466 0.858236 0.666162 1.487126]\n",
      "t = 10.0s; x = [0.233935 0.973953 0.802703 0.846467]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<SpStatusEnum.REACHED_END_TIME: 1>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sim.sp.setIntegrator(ki.IntegratorType.CVODE)\n",
    "sim.sp.advanceTo(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80b28389",
   "metadata": {},
   "source": [
    "## Python script\n",
    "Let's use the simulation we already have to create a Python script. This will dump just the simulation information."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a08ea98b",
   "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": [
    "This call will show the file in the Jupyter notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7734eca9",
   "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:37:40.279282\n",
       "from Karana.Math.Kquantities import ureg\n",
       "import numpy as np\n",
       "import Karana.Integrators as ki\n",
       "import Karana.Models as kmo\n",
       "import Karana.Scene as ks\n",
       "from Karana.KUtils.Sim import Sim\n",
       "import Karana.Models as kmdl\n",
       "import Karana.Math as km\n",
       "import Karana.Dynamics as kd\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",
       "    # ----------------------------------------------------------------------------------------------\n",
       "    # Define integrator options\n",
       "    cvode_opts = ki.CVodeIntegratorOptions()\n",
       "    cvode_opts.rtol = 0.0001\n",
       "    cvode_opts.atol = 1e-08\n",
       "    cvode_opts.max_num_steps = 1000000\n",
       "    cvode_opts.min_step_size = 1e-12\n",
       "    cvode_opts.anderson_damping = 1.0\n",
       "    cvode_opts.anderson_length = 0\n",
       "    cvode_opts.max_nl_iters = 3\n",
       "\n",
       "    # Set up the integrator\n",
       "    sp.setIntegrator(ki.IntegratorType.CVODE, cvode_opts)\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 grav_model KModel\n",
       "    uniform_gravity = kmo.UniformGravity(\"uniform_gravity\")\n",
       "    uniform_gravity.setGravity(\n",
       "        np.array([0.0, 0.0, -9.81]) * ureg.meter / ureg.second**2,\n",
       "        10.0,\n",
       "        kmo.OutputUpdateType.PRE_DERIV,\n",
       "    )\n",
       "\n",
       "    grav_model = kmdl.Gravity(\"grav_model\", sp, uniform_gravity, sp.getSubTree())\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": 8,
     "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 [time domain notebook](../example_time_domain/notebook.ipynb), as well as code to add the `Gravity` `KModel`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6a7e04fb",
   "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": 10,
   "id": "85b280dd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[WebUI] Web server is running on port 42133\n",
      "You may be able to connect in your browser at:\n",
      "\t\u001b[1mhttp://newton:42133\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": 11,
   "id": "dbf76e3d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.cleanup()>"
      ]
     },
     "execution_count": 11,
     "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": {
   "tags": [
    "dynamics",
    "pendulum",
    "beginner",
    "KModels",
    "time domain"
   ]
  },
  "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
}
