{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8d7cbf78",
   "metadata": {},
   "source": [
    "# Titan quickstart\n",
    "\n",
    "This notebook opens the converted Titan maps from [Titan Data Atlas](https://titan.swapniltamse.com) straight over HTTP, plots the topography and the radar mosaic around a named place, and asks the atlas MCP server about it with plain `requests`.\n",
    "\n",
    "Nothing to download first. You need Python 3.10 or later with `rasterio`, `numpy`, `matplotlib` and `requests`:\n",
    "\n",
    "```\n",
    "pip install rasterio numpy matplotlib requests\n",
    "```\n",
    "\n",
    "Titan Data Atlas is an independent project. Not affiliated with or endorsed by Cornell University, the Hayes Research Group, NASA or JPL. The data keep their own credit and license; see the last cell."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af0881b5",
   "metadata": {},
   "source": [
    "## 1. Pick a place\n",
    "\n",
    "Any of the 304 IAU names works, in part and without accents: `Selk`, `Kraken Mare`, `Ontario Lacus`, `Xanadu`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5b6e6ff",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "\n",
    "import numpy as np\n",
    "import requests\n",
    "import rasterio\n",
    "from rasterio.io import MemoryFile\n",
    "from rasterio.windows import from_bounds\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "SITE = os.environ.get(\"TITAN_SITE\", \"https://titan.swapniltamse.com\")\n",
    "PLACE = \"Selk\"\n",
    "R_KM = 2575.0  # Titan's radius, the sphere every layer here uses"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "904050a7",
   "metadata": {},
   "source": [
    "## 2. Ask the MCP server\n",
    "\n",
    "The server speaks JSON-RPC over HTTP, so one `POST` per call is enough. No key, no account."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e42f756b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def mcp(tool, **arguments):\n",
    "    r = requests.post(\n",
    "        f\"{SITE}/mcp\",\n",
    "        json={\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"tools/call\", \"params\": {\"name\": tool, \"arguments\": arguments}},\n",
    "        headers={\"Accept\": \"application/json, text/event-stream\"},\n",
    "        timeout=30,\n",
    "    )\n",
    "    r.raise_for_status()\n",
    "    result = r.json()[\"result\"]\n",
    "    text = result[\"content\"][0][\"text\"]\n",
    "    if result.get(\"isError\"):\n",
    "        raise ValueError(text)\n",
    "    return json.loads(text)\n",
    "\n",
    "place = mcp(\"find_feature\", name=PLACE)[\"matches\"][0]\n",
    "print(f\"{place['name']} ({place['type']})\")\n",
    "print(f\"Centre: {place['lat']:.2f}, {place['lon']:.2f} (east-positive); {place['lonWest']:.2f} W in the Gazetteer\")\n",
    "print(f\"Size: about {place['diameterKm']} km across\" if place[\"diameterKm\"] else \"Size: not given\")\n",
    "print(\"Covered by:\", \", \".join(p[\"name\"] for p in place[\"coveredBy\"]))\n",
    "print(\"Place page:\", place[\"page\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3aca0841",
   "metadata": {},
   "source": [
    "## 3. Read a window of the topography over HTTP\n",
    "\n",
    "The GeoTIFFs use plain longitude and latitude on Titan's sphere, east-positive. They are small (4 to 8 MB), so the notebook fetches each one once over HTTP and rasterio opens it in memory. The site's host answers every request with the whole file, so reading only part of it through `/vsicurl/` does not work there."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c91703d9",
   "metadata": {},
   "outputs": [],
   "source": [
    "km_per_deg = 2 * np.pi * R_KM / 360\n",
    "half_lat = max(2.5, 1.2 * (place[\"diameterKm\"] or 120) / km_per_deg)\n",
    "half_lon = min(60, half_lat / max(0.2, np.cos(np.radians(place[\"lat\"]))))\n",
    "west, east = place[\"lon\"] - half_lon, place[\"lon\"] + half_lon\n",
    "south, north = max(-90, place[\"lat\"] - half_lat), min(90, place[\"lat\"] + half_lat)\n",
    "\n",
    "_cache = {}\n",
    "\n",
    "def read_window(url, bounds):\n",
    "    if url not in _cache:\n",
    "        r = requests.get(url, timeout=60)\n",
    "        r.raise_for_status()\n",
    "        _cache[url] = r.content\n",
    "    with MemoryFile(_cache[url]) as mem, mem.open() as src:\n",
    "        win = from_bounds(*bounds, transform=src.transform).round_offsets().round_lengths()\n",
    "        data = src.read(1, window=win, boundless=True, fill_value=src.nodata or 0).astype(\"float32\")\n",
    "        if src.nodata is not None:\n",
    "            data[data == src.nodata] = np.nan\n",
    "        b = src.window_bounds(win)\n",
    "    return data, (b[0], b[2], b[1], b[3])\n",
    "\n",
    "topo, extent = read_window(f\"{SITE}/samples/titan-topo.tif\", (west, south, east, north))\n",
    "print(\"Window\", [round(v, 2) for v in extent], \"shape\", topo.shape)\n",
    "print(f\"Height range {np.nanmin(topo):.0f} m to {np.nanmax(topo):.0f} m, relative to the 2,575 km sphere\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c9f0de7",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(8, 5))\n",
    "im = ax.imshow(topo, extent=extent, origin=\"upper\", cmap=\"viridis\", aspect=1 / np.cos(np.radians(place[\"lat\"])))\n",
    "ax.plot(place[\"lon\"], place[\"lat\"], \"o\", mfc=\"none\", mec=\"white\", ms=12, mew=2)\n",
    "ax.set_xlabel(\"Longitude (degrees east)\")\n",
    "ax.set_ylabel(\"Latitude (degrees)\")\n",
    "ax.set_title(f\"Topography around {place['name']} (Corlies et al. 2017)\")\n",
    "fig.colorbar(im, ax=ax, label=\"Height (m)\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69a4c786",
   "metadata": {},
   "source": [
    "## 4. The radar mosaic, where it exists\n",
    "\n",
    "The radar mosaic on the site covers 60 S to 60 N. Values are 8-bit brightness, stretched for viewing; 0 means no radar pass."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc700d5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "if abs(place[\"lat\"]) <= 60:\n",
    "    radar, rext = read_window(f\"{SITE}/samples/titan-radar.tif\", (west, max(south, -60), east, min(north, 60)))\n",
    "    radar[radar == 0] = np.nan\n",
    "    fig, ax = plt.subplots(figsize=(8, 5))\n",
    "    ax.imshow(radar, extent=rext, origin=\"upper\", cmap=\"gray\", aspect=1 / np.cos(np.radians(place[\"lat\"])))\n",
    "    ax.plot(place[\"lon\"], place[\"lat\"], \"o\", mfc=\"none\", mec=\"orange\", ms=12, mew=2)\n",
    "    ax.set_xlabel(\"Longitude (degrees east)\")\n",
    "    ax.set_ylabel(\"Latitude (degrees)\")\n",
    "    ax.set_title(f\"Radar around {place['name']} (Birch and Hayes 2024)\")\n",
    "    plt.show()\n",
    "else:\n",
    "    print(f\"{place['name']} is outside 60 S to 60 N. The polar mosaics cover it; see its place page: {place['page']}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2330adaa",
   "metadata": {},
   "source": [
    "## 5. More questions for the server"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "094230c5",
   "metadata": {},
   "outputs": [],
   "source": [
    "point = mcp(\"products_at_point\", lat=place[\"lat\"], lon=place[\"lon\"])\n",
    "print(\"At this point:\", \", \".join(p[\"id\"] for p in point[\"coveredBy\"]))\n",
    "print(\"Nearest names:\", \", \".join(f\"{f['name']} ({f['distanceKm']} km)\" for f in point[\"nearestFeatures\"][:4]))\n",
    "\n",
    "dunes = mcp(\"find_products\", query=\"dunes\")\n",
    "print(\"Dunes are best seen in:\", [m[\"id\"] for m in dunes[\"matches\"][:3]])\n",
    "for t in dunes.get(\"featureTypes\", []):\n",
    "    print(f\"{t['namedPlaces']} named {t['words']}, for example\", \", \".join(e[\"name\"] for e in t[\"examples\"]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd153e67",
   "metadata": {},
   "source": [
    "## Credits and how to cite\n",
    "\n",
    "- Topography: Corlies, P., & Hayes, A. (2024). Cassini Synthetic Aperture RADAR Derived Digital Topographic Models of Saturn's Moon Titan [Data set]. Cornell University eCommons. https://doi.org/10.7298/m4dv-gv95 (CC0 1.0).\n",
    "- Radar mosaic: Birch, S., & Hayes, A. (2024). Cassini Synthetic Aperture RADAR Swath Mosaic of Saturn's Moon Titan for the Equatorial Region, Quadrants 1 to 4. Cornell University eCommons. https://doi.org/10.7298/s709-7w42, https://doi.org/10.7298/4az4-gk54, https://doi.org/10.7298/vaaf-sy65, https://doi.org/10.7298/fz1q-ya32 (CC0 1.0).\n",
    "- Place names: IAU/USGS Gazetteer of Planetary Nomenclature (public domain).\n",
    "- The converted files and this notebook: Titan Data Atlas, https://titan.swapniltamse.com (notebook code under the MIT license). Every product page there has APA and BibTeX for its data."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
