{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# PID line following\n\nTape is drawn on the floor: an oval and a course with sharp bends. Your pod carries\na line sensor, five reflectance cells under its nose. Each cell reads how much of its\nspot is tape (0 to 1, with noise); together they say where the line is across the pod,\n`offset_m`, positive when the line is to the left.\n\nThe controller turns the pod towards the line: the turn rate is a function of the\noffset. You will start with P, see what it does wrong, and add D and I."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "# Get the Plato Pod client from the server (once per session) and its one dependency.\nimport os\nimport subprocess\nimport sys\nimport urllib.request\n\nSERVER = \"https://arena.platopod.com\"\nos.makedirs(\"platopod\", exist_ok=True)\nfor f in (\"__init__.py\", \"arena.py\", \"pod.py\"):\n    urllib.request.urlretrieve(f\"{SERVER}/sdk/platopod/{f}\", f\"platopod/{f}\")\nsubprocess.run([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"websockets>=12\"], check=True)\nprint(\"ready\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Join the room\n\nChoose a name: the same name gets the same pod back next time. The room's code is\n**GFYFYJ** (Control engineering: PID line following). Run the next cell, then open the link it prints to watch your pod."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "from platopod import Arena\n\nROOM_CODE = \"GFYFYJ\"\nMY_NAME = \"your name here\"          # letters, digits and spaces\n\narena, pod = Arena.join_room(ROOM_CODE, MY_NAME)\nprint(\"You are pod\", pod.robot_id, \"at\", pod.pose)\nprint(\"Watch it:\", f\"{arena.url}/view3d.html#key={arena.key}\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## The sensor and the course\n\nFit the line sensor, and read the course from the arena: the mission in force holds\nthe tape's points."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import math\nimport time\n\npod.fit(\"line_follower\")\npod.listen(\"line\")\nlines = {line[\"name\"]: line for line in arena.mission()[\"lines\"]}\noval = lines[\"Oval\"][\"points\"]\nprint(len(oval), \"points on the oval;\", pod.wait_reading(\"line\", 3.0))"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Onto the line\n\nThe pod drives itself to a place on the oval of its own (so that several pods can\nshare the course) and turns to face along the tape, by feedback on its pose: the same\nidea as the square notebook. Then your controller takes over."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def wrap(angle):\n    return (angle + math.pi) % (2 * math.pi) - math.pi\n\ndef go_to(x, y, speed=0.15, timeout=60.0):\n    \"\"\"Drive to a point: steer towards it, slow down near it.\"\"\"\n    end = time.monotonic() + timeout\n    while time.monotonic() < end:\n        p = pod.pose\n        distance = math.dist((p.x, p.y), (x, y))\n        if distance < 0.01:\n            break\n        error = wrap(math.atan2(y - p.y, x - p.x) - p.theta)\n        ahead = min(speed, 1.5 * distance) * max(0.0, math.cos(error))\n        pod.drive(ahead, max(-2.0, min(2.0, 3.0 * error)))\n        time.sleep(0.1)\n    pod.stop()\n\ndef turn_to(heading, tolerance=0.03):\n    while abs(error := wrap(heading - pod.pose.theta)) > tolerance:\n        pod.drive(0.0, max(-1.5, min(1.5, 3.0 * error)))\n        time.sleep(0.1)\n    pod.stop()\n\ni = (7 * pod.robot_id) % (len(oval) - 2)          # a place of your own on the oval\n(ax, ay), (bx, by) = oval[i], oval[i + 1]\ngo_to(ax, ay)\nturn_to(math.atan2(by - ay, bx - ax))\ntime.sleep(0.5)\nr = pod.wait_reading(\"line\", 2.0)\nprint(\"on the line:\", r.data[\"on_line\"], \"offset\", r.data[\"offset_m\"])"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## The controller\n\nOne step every sensor reading (10 a second): error `e` is the offset; the turn rate\nis `kp*e + ki*\u222be dt + kd*de/dt`, clipped to what the pod can do. Three practical touches\nevery real controller needs:\n\n- the derivative is smoothed: the offset jumps as the tape crosses from cell to cell,\n  and a raw difference of a jumpy signal is mostly noise;\n- the integral is capped (anti-windup), or it keeps growing while the pod is off the line;\n- if the line is lost, the pod creeps forward turning towards the side it was last seen on.\n\nEvery run starts from the same place on the line, so runs compare fairly."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def follow_line(kp, ki=0.0, kd=0.0, speed=0.05, seconds=30.0, smooth=0.3, cap=0.5):\n    go_to(ax, ay)                                       # the same start every run\n    turn_to(math.atan2(by - ay, bx - ax))\n    log = []                                            # (time, error, turn or None if lost)\n    integral, last_e, slope, last_t = 0.0, 0.0, 0.0, None\n    t0 = time.monotonic()\n    while time.monotonic() - t0 < seconds:\n        r = pod.wait_reading(\"line\", 1.0)\n        if r is None:\n            continue\n        now = time.monotonic()\n        e = r.data[\"offset_m\"]\n        if e is None:                                   # lost: creep towards where it was\n            pod.drive(0.02, 1.0 if last_e > 0 else -1.0)\n            log.append((now - t0, last_e, None))\n            last_t = None\n            continue\n        dt = now - last_t if last_t is not None else 0.1\n        if ki:\n            integral = max(-cap / ki, min(cap / ki, integral + e * dt))\n        slope = (1 - smooth) * slope + smooth * ((e - last_e) / dt if last_t else 0.0)\n        turn = max(-2.0, min(2.0, kp * e + ki * integral + kd * slope))\n        pod.drive(speed, turn)\n        log.append((now - t0, e, turn))\n        last_e, last_t = e, now\n    pod.stop()\n    return log\n\ndef show(log, title):\n    on = [abs(e) for _, e, turn in log if turn is not None]\n    lost = sum(1 for _, _, turn in log if turn is None)\n    if not on:\n        print(f\"{title}: never on the line\")\n        return\n    print(f\"{title}: mean |error| {1000 * sum(on) / len(on):.1f} mm, \"\n          f\"worst {1000 * max(on):.1f} mm, lost {lost} of {len(log)} steps\")\n    try:\n        import matplotlib.pyplot as plt\n        t = [s[0] for s in log]\n        plt.figure(figsize=(9, 3))\n        plt.plot(t, [1000 * s[1] for s in log], label=\"error (mm)\")\n        plt.plot(t, [s[2] if s[2] is not None else float(\"nan\") for s in log],\n                 label=\"turn (rad/s)\")\n        plt.axhline(0, color=\"grey\", lw=0.5)\n        plt.xlabel(\"s\")\n        plt.title(title)\n        plt.legend()\n        plt.show()\n    except ImportError:\n        pass"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1. P only\n\nAt 5 cm/s. Try kp = 20, 40, 80: a small gain follows lazily, a large one snakes.\nWhy does the error not settle at zero on the curves?"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "show(follow_line(kp=40), \"P, kp=40, 5 cm/s\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2. Faster\n\nThe same controller at 8 cm/s. The reading is a tenth of a second old when it arrives,\nand the command takes a moment to come back: the pod acts on where it *was*. The faster\nit goes, the further it has gone by then. On our server this delay, not the gains, is\nwhat limits the speed."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "show(follow_line(kp=40, speed=0.08), \"P, kp=40, 8 cm/s\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3. D: the textbook cure for snaking\n\nThe derivative reacts to how fast the error changes, which damps oscillation. Here it\nmostly does not help: the offset jumps in steps as the tape crosses from cell to cell,\nand it is late. A derivative of a late, jumpy signal is mostly noise. Try kd between 0.1\nand 1, and the smoothing (`smooth`, 0 to 1)."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "show(follow_line(kp=40, kd=0.5), \"PD, kp=40 kd=0.5\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 4. I: the steady error on the curves\n\nOn a curve the pod must turn steadily, and P alone needs a steady error to do it.\nThe integral builds up that turn so the error can return to zero. Run it here, then\nagain with `speed=0.08`: with this much delay the integral overshoots and the pod can\nlose the line. When is an integral worth its overshoot?"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "show(follow_line(kp=40, ki=10), \"PI, kp=40 ki=10\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 5. Your turn\n\n1. Tune for the fastest lap that does not lose the line. What limits the speed?\n2. Model the delay: if a reading is 0.15 s old, where is the pod now? Predict the offset\n   forward with the pod's speed and turn rate, and control on the prediction.\n3. Move to the course with the sharp bends (`lines[\"Bends\"]`): does your tuning still work?\n   What would help at a square corner?\n4. Use the five raw cells (`r.data[\"values\"]`) instead of `offset_m`: can you do better\n   than their weighted centre?"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "arena.close()"
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 }
}
