{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": "# 6.4210/2 \u2014 ps7 setup\n\nOn a laptop, these Colab-specific cells detect the local runtime and skip themselves. On Colab, run them once per session: the Drive mount, the fetch (a no-op once the code is in your Drive), and `setup()`. See the course README for the optional one-time private-repo setup (Colab secrets `GH_TOKEN` and `PRIVATE_REPO`)." }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "try:\n import google.colab\n IN_COLAB = True\nexcept ImportError:\n IN_COLAB = False\nif not IN_COLAB:\n print(\"Local runtime: skipping the Colab-only cells below.\")\n" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "if IN_COLAB:\n # Mount Google Drive. This is where we will/have clone(d) your course repo to.\n from google.colab import drive\n\n drive.mount(\"/content/drive\")\n" }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "if IN_COLAB:\n # Fetch the course code into Drive and put it on the import path. With\n # the Colab secrets GH_TOKEN and PRIVATE_REPO set (see the course\n # README), this uses your private homework repo; without them, a plain\n # read-only clone of the public handouts repo.\n import pathlib\n import subprocess\n import sys\n\n from google.colab import userdata\n\n root = pathlib.Path(\"/content/drive/MyDrive/6.4210/repo\")\n public = \"https://github.com/tlpmit/6.4210-2-fall26-handouts.git\"\n try:\n private = userdata.get(\"PRIVATE_REPO\")\n origin = f\"https://github.com/{private}.git\"\n # The token goes in a credential file outside the repo, so it never\n # ends up in .git/config or in what git prints when a fetch fails.\n creds = pathlib.Path(\"/root/.git-credentials\")\n creds.write_text(\n f\"https://x-access-token:{userdata.get('GH_TOKEN')}@github.com\\n\"\n )\n creds.chmod(0o600)\n subprocess.run(\n [\"git\", \"config\", \"--global\",\n \"credential.helper\", f\"store --file={creds}\"],\n check=True,\n )\n print(f\"Colab secrets found: your repo is {private}\")\n except Exception:\n origin = None\n print(\"no Colab secrets configured: \"\n \"using the public repo, read-only\")\n if root.exists():\n print(f\"course code already in Drive at {root}\")\n else:\n print(f\"cloning {'your private repo' if origin else 'the public repo'}: \"\n f\"{origin or public}\")\n root.parent.mkdir(parents=True, exist_ok=True)\n subprocess.run([\"git\", \"clone\", origin or public, str(root)], check=True)\n if origin:\n subprocess.run(\n [\"git\", \"-C\", str(root), \"remote\", \"add\", \"upstream\", public],\n check=True,\n )\n if str(root) not in sys.path:\n sys.path.insert(0, str(root))\n print(\"done: the course code is on the import path\")\n" }, { "cell_type": "markdown", "metadata": {}, "source": "**On Colab, first time only**: stop here, and reopen this notebook from your Drive \u2014 on [drive.google.com](https://drive.google.com) open `My Drive \u2192 6.4210 \u2192 repo \u2192 ps7` and double-click `hybrid_force_position.ipynb`; it opens in Colab. Work in that copy from now on: its edits are saved to Drive and can be committed with git. After opening the Drive copy, start again at the first cell and rerun the mount and fetch cells before continuing." }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": "if IN_COLAB:\n from utils import colab_bootstrap\n colab_bootstrap.setup(\"ps7\")\n import os\n os.chdir(colab_bootstrap.ROOT / \"ps7\")\n" }, { "cell_type": "markdown", "id": "c6b51a64", "metadata": {}, "source": [ "# PS7: Dragging a book with hybrid force-position control\n", "\n", "This notebook goes with \u201cDragging a book with hybrid force-position control\u201d in the PDF. The reading is the [\u201cHybrid Force-Position Control\u201d exercise](https://manipulation.mit.edu/force.html#hybrid_book_push) in Manipulator Control. We complete `compute_ctrl` in `hybrid_force_control.py`, then run the cells in order. After editing the `.py` file, restart the kernel and run again from the top.\n", "\n", "Locally, use the course environment, or install the packages with `python -m pip install numpy drake manipulation`. The same checks also run from a terminal: `python ps7/hybrid_force_demo.py --verify --simulate` from the course root." ] }, { "cell_type": "code", "execution_count": null, "id": "8b344eca", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import sys\n", "HERE = next((p if (p / \"hybrid_force_control.py\").exists() else p / \"ps7\"\n", " for p in [Path.cwd(), *Path.cwd().parents]\n", " if (p / \"hybrid_force_control.py\").exists() or (p / \"ps7/hybrid_force_control.py\").exists()), None)\n", "if HERE is None:\n", " raise FileNotFoundError(\"Open the notebook from the course checkout.\")\n", "sys.path.insert(0, str(HERE))\n", "import numpy as np\n", "from hybrid_force_control import compute_ctrl, build_and_simulate\n" ] }, { "cell_type": "markdown", "id": "a0a87720", "metadata": {}, "source": [ "## Numerical verification\n", "\n", "See \u201cController implementation\u201d in the PDF\u2019s book-dragging problem.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "65942bfe", "metadata": {}, "outputs": [], "source": [ "p_now = np.array([0.1, 0.8, 0.05])\n", "v_now = np.array([0.2, -0.1, 0.0])\n", "u = compute_ctrl(p_now, v_now, x_des=0.65, f_des=2.0)\n", "print(\"[tau_y (N m), f_x (N), f_z (N)] =\", u)\n", "assert np.asarray(u).shape == (3,) and np.isfinite(u).all()\n" ] }, { "cell_type": "markdown", "id": "02bea0f0", "metadata": {}, "source": [ "## Simulating the controller\n", "\n", "See \u201cDragging a book with hybrid force-position control\u201d in the PDF. Set `SHOW_REPLAY=True` to record a Meshcat replay and display it. The simulation runs as soon as the next cell executes.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "c68f59bb", "metadata": {}, "outputs": [], "source": [ "SHOW_REPLAY = False\n", "meshcat = None\n", "if SHOW_REPLAY:\n", " from pydrake.all import StartMeshcat\n", " meshcat = StartMeshcat()\n", "log, plant, plant_context = build_and_simulate(\n", " compute_ctrl, velocity=-0.125, duration=6.5, meshcat=meshcat)\n", "book_pose = plant.GetFreeBodyPose(plant_context, plant.GetBodyByName(\"book\"))\n", "print(\"Final book center (m):\", book_pose.translation())\n", "p = log.data()\n", "tip_z = p[2] - 0.12*np.cos(p[0])\n", "print(\"Minimum finger-tip height (m):\", tip_z.min())\n", "print(\"Book x should end between 0.35 and 0.55 m, and tip z should stay at or above 0.035 m.\")\n", "if meshcat is not None:\n", " from IPython.display import HTML, display\n", " display(HTML(meshcat.StaticHtml()))" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.15" } }, "nbformat": 4, "nbformat_minor": 5 }