{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# A swarm that searches\n\nTen targets are hidden on the floor. You command a swarm of pods; each carries a target\ndetector that reports a target within 15 cm, with its position. Nobody, not even the\nconsole, shows where they are.\n\nYou will search with no plan (random), then with a plan (divide the floor and sweep\nit), keep one shared map of what the swarm has found, and compare."
  },
  {
   "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**UUDPYD** (Artificial intelligence: a swarm that searches). 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 = \"UUDPYD\"\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": "## Your swarm\n\nThe room lets one program drive up to five pods: the one you joined with, and four\nmore you add. They leave the table when your session ends."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import math\nimport random\nimport time\n\nsize = arena.swarm_size()\nswarm = [pod] + [arena.spawn() for _ in range(size - 1)]\nfor p in swarm:\n    p.configure(\"ied_detector\", {\"rate_hz\": 5.0, \"position_noise_m\": 0.01,\n                                 \"default_detection_radius_m\": 0.15})\n    p.listen(\"ied_detector\")\nprint(\"swarm:\", [p.robot_id for p in swarm])"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## The shared map\n\nEvery detection goes into one list. Two reports closer than 10 cm are the same target."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "found = []                               # (x, y) of each target found\n\ndef note(position):\n    x, y = position\n    if all(math.dist((x, y), f) > 0.10 for f in found):\n        found.append((x, y))\n        print(f\"target {len(found)} at ({x:.2f}, {y:.2f})\")\n\ndef listen():\n    \"\"\"Every detection the swarm has heard, into the map.\"\"\"\n    for p in swarm:\n        r = p.reading(\"ied_detector\")\n        if r is not None:\n            for d in r.data[\"detections\"]:\n                note(d[\"position\"])\n\ndef wrap(angle):\n    return (angle + math.pi) % (2 * math.pi) - math.pi\n\ndef steer(p, target, speed=0.15):\n    \"\"\"One step of a pod towards a point; True once it is there.\"\"\"\n    pose = p.pose\n    if math.dist((pose.x, pose.y), target) < 0.04:\n        return True\n    error = wrap(math.atan2(target[1] - pose.y, target[0] - pose.x) - pose.theta)\n    p.drive(speed * max(0.0, math.cos(error)), max(-2.0, min(2.0, 3.0 * error)))\n    return False\n\ndef run(plans, seconds):\n    \"\"\"Drive every pod through its list of points, listening as they go; the time taken.\"\"\"\n    t0 = time.monotonic()\n    while time.monotonic() - t0 < seconds and any(plans.values()):\n        for p in swarm:\n            if plans[p.robot_id] and steer(p, plans[p.robot_id][0]):\n                plans[p.robot_id].pop(0)\n        listen()\n        time.sleep(0.1)\n    for p in swarm:\n        p.stop()\n    return time.monotonic() - t0"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 1. No plan: a random walk\n\nEach pod goes to a random point, then another. 90 seconds."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "found.clear()\nplans = {p.robot_id: [(random.uniform(0.2, 2.8), random.uniform(0.2, 1.8)) for _ in range(20)]\n         for p in swarm}\ntook = run(plans, 90.0)\nprint(f\"random: {len(found)} of 10 in {took:.0f} s\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 2. A plan: divide the floor and sweep it\n\nSplit the floor into one strip per pod. Each pod sweeps its strip in lanes 25 cm apart\n(a little less than twice the detector's reach), up one lane and down the next."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def lanes(x0, x1, y0=0.15, y1=1.85, spacing=0.25):\n    \"\"\"Up and down a strip of the floor, lanes `spacing` apart.\"\"\"\n    path, x, up = [], x0 + spacing / 2, True\n    while x < x1:\n        path += [(x, y0), (x, y1)] if up else [(x, y1), (x, y0)]\n        x, up = x + spacing, not up\n    return path\n\nfound.clear()\nwidth = 2.8 / len(swarm)\nplans = {p.robot_id: lanes(0.1 + k * width, 0.1 + (k + 1) * width)\n         for k, p in enumerate(sorted(swarm, key=lambda p: p.pose.x))}\ntook = run(plans, 240.0)\nprint(f\"sweep: {len(found)} of 10 in {took:.0f} s\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 3. Your turn\n\n1. Which search finds more per minute? Why might random search still win on a small floor?\n2. A pod stops working halfway: how should the others share its strip? (Try emptying\n   `plans[swarm[2].robot_id]` part way through.)\n3. Allocate by auction: each strip goes to the pod that bids the shortest trip to it.\n4. Once a few targets are found, are the rest likely nearby? Use what you have found to\n   choose where to look next (the map is your knowledge base)."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "arena.close()   # the four added pods leave the table"
  }
 ],
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 }
}
