{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# PolyCAT Dataset — Quickstart\n", "\n", "This notebook demonstrates how to load and visualize the PolyCAT dataset.\n", "\n", "**Display setup:** 27\" 4K monitor (3840×2160) at 70 cm viewing distance ≈ 78.5 px/deg." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import csv\n", "from collections import defaultdict\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "# Adjust to your project root\n", "PROJECT_ROOT = Path(\"../..\").resolve()\n", "\n", "# Display constants (27\" 4K at 70 cm)\n", "SCREEN_W, SCREEN_H = 3840, 2160\n", "PPD = 78.5 # pixels per degree\n", "\n", "def load_csv(path):\n", " with open(path) as f:\n", " return list(csv.DictReader(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Load Metadata" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "participants = load_csv(PROJECT_ROOT / \"data/metadata/participants.csv\")\n", "trials = load_csv(PROJECT_ROOT / \"data/metadata/trials.csv\")\n", "quality = load_csv(PROJECT_ROOT / \"data/metadata/quality_metrics.csv\")\n", "\n", "print(f\"Participants: {len(participants)}\")\n", "print(f\"Trials: {len(trials)}\")\n", "print(f\"\\nQuality metrics columns: {list(quality[0].keys())}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Quality Overview" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "pids = [q[\"participant_id\"] for q in quality]\n", "tracking_ratios = [float(q[\"tracking_ratio_mean\"]) for q in quality]\n", "fix_per_trial = [float(q[\"fixations_per_trial_mean\"]) for q in quality]\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(12, 4))\n", "\n", "axes[0].bar(range(len(pids)), tracking_ratios, color=\"steelblue\")\n", "axes[0].set_xticks(range(len(pids)))\n", "axes[0].set_xticklabels(pids, rotation=45, ha=\"right\", fontsize=7)\n", "axes[0].set_ylabel(\"Fixation tracking ratio\")\n", "axes[0].set_title(\"Per-eye fixation tracking ratio by participant\")\n", "axes[0].axhline(y=0.6, color=\"red\", linestyle=\"--\", alpha=0.5, label=\"Exclusion threshold\")\n", "axes[0].legend(fontsize=8)\n", "\n", "axes[1].bar(range(len(pids)), fix_per_trial, color=\"darkorange\")\n", "axes[1].set_xticks(range(len(pids)))\n", "axes[1].set_xticklabels(pids, rotation=45, ha=\"right\", fontsize=7)\n", "axes[1].set_ylabel(\"Mean fixations per trial (both eyes)\")\n", "axes[1].set_title(\"Fixation count by participant\")\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Load Fixations" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fixations = load_csv(PROJECT_ROOT / \"data/fixations/fixations_all.csv\")\n", "print(f\"Total fixations: {len(fixations):,}\")\n", "\n", "# Quick summary\n", "durations = [float(f[\"duration_ms\"]) for f in fixations]\n", "print(f\"Duration: mean={np.mean(durations):.0f} ms, median={np.median(durations):.0f} ms\")\n", "print(f\"Columns: {list(fixations[0].keys())}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Fixation Duration Distribution" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(8, 4))\n", "ax.hist(durations, bins=np.arange(0, 2000, 25), color=\"steelblue\", edgecolor=\"white\")\n", "ax.set_xlabel(\"Fixation duration (ms)\")\n", "ax.set_ylabel(\"Count\")\n", "ax.set_title(\"Fixation Duration Distribution\")\n", "ax.axvline(np.median(durations), color=\"red\", linestyle=\"--\",\n", " label=f\"Median: {np.median(durations):.0f} ms\")\n", "ax.legend()\n", "ax.set_xlim(0, 1500)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Spatial Distribution of Fixations\n", "\n", "Fixation positions on the 3840×2160 px display (27\" 4K at 70 cm ≈ 78.5 px/deg)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Right eye fixations only\n", "r_fix = [(float(f[\"x_px\"]), float(f[\"y_px\"])) for f in fixations if f[\"eye\"] == \"R\"]\n", "xs = np.array([p[0] for p in r_fix])\n", "ys = np.array([p[1] for p in r_fix])\n", "\n", "fig, axes = plt.subplots(1, 2, figsize=(14, 5))\n", "\n", "# Heatmap in pixels\n", "h, xedges, yedges = np.histogram2d(xs, ys, bins=[96, 54],\n", " range=[[0, SCREEN_W], [0, SCREEN_H]])\n", "axes[0].imshow(h.T, extent=[0, SCREEN_W, SCREEN_H, 0],\n", " aspect=\"equal\", cmap=\"hot\", interpolation=\"gaussian\")\n", "axes[0].set_xlabel(\"X (pixels)\")\n", "axes[0].set_ylabel(\"Y (pixels)\")\n", "axes[0].set_title(f\"Fixation density — all participants (N={len(r_fix):,})\")\n", "\n", "# Heatmap in degrees\n", "xs_deg = (xs - SCREEN_W / 2) / PPD\n", "ys_deg = (ys - SCREEN_H / 2) / PPD\n", "h2, _, _ = np.histogram2d(xs_deg, ys_deg, bins=[96, 54],\n", " range=[[-SCREEN_W/2/PPD, SCREEN_W/2/PPD],\n", " [-SCREEN_H/2/PPD, SCREEN_H/2/PPD]])\n", "extent_deg = [-SCREEN_W/2/PPD, SCREEN_W/2/PPD, SCREEN_H/2/PPD, -SCREEN_H/2/PPD]\n", "axes[1].imshow(h2.T, extent=extent_deg, aspect=\"equal\",\n", " cmap=\"hot\", interpolation=\"gaussian\")\n", "axes[1].set_xlabel(\"Horizontal (deg)\")\n", "axes[1].set_ylabel(\"Vertical (deg)\")\n", "axes[1].set_title(\"Fixation density in degrees of visual angle\")\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Single Trial Scanpath" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Pick a trial from the first participant\n", "scanpath_dir = PROJECT_ROOT / \"data/scanpaths\"\n", "pid_dirs = sorted(d for d in scanpath_dir.iterdir() if d.is_dir())\n", "pid_dir = pid_dirs[0]\n", "trial_file = sorted(pid_dir.glob(\"*.csv\"))[0]\n", "\n", "scanpath = load_csv(trial_file)\n", "# Filter to right eye\n", "sp_r = [f for f in scanpath if f[\"eye\"] == \"R\"]\n", "\n", "sp_x = [float(f[\"x_px\"]) for f in sp_r]\n", "sp_y = [float(f[\"y_px\"]) for f in sp_r]\n", "sp_dur = [float(f[\"duration_ms\"]) for f in sp_r]\n", "\n", "fig, ax = plt.subplots(figsize=(10, 5.625)) # 16:9 aspect\n", "ax.set_xlim(0, SCREEN_W)\n", "ax.set_ylim(SCREEN_H, 0) # Invert Y\n", "ax.set_aspect(\"equal\")\n", "\n", "# Draw scanpath\n", "ax.plot(sp_x, sp_y, \"b-\", alpha=0.3, linewidth=1)\n", "scatter = ax.scatter(sp_x, sp_y, s=[d/5 for d in sp_dur],\n", " c=range(len(sp_x)), cmap=\"viridis\", alpha=0.7,\n", " edgecolors=\"black\", linewidths=0.5)\n", "\n", "# Number the fixations\n", "for i, (x, y) in enumerate(zip(sp_x, sp_y)):\n", " ax.annotate(str(i+1), (x, y), fontsize=7, ha=\"center\", va=\"center\",\n", " color=\"white\", fontweight=\"bold\")\n", "\n", "ax.set_xlabel(\"X (pixels)\")\n", "ax.set_ylabel(\"Y (pixels)\")\n", "ax.set_title(f\"Scanpath: {trial_file.stem} (right eye, {len(sp_r)} fixations)\\n\"\n", " f\"Display: 3840×2160 px, 27\\\" 4K at 70 cm\")\n", "plt.colorbar(scatter, label=\"Fixation order\", ax=ax)\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Saliency Map Example" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "saliency_dir = PROJECT_ROOT / \"data/saliency_maps/by_polygon\"\n", "if saliency_dir.exists():\n", " # Find first available saliency map\n", " poly_dirs = sorted(d for d in saliency_dir.iterdir() if d.is_dir())\n", " if poly_dirs:\n", " npy_files = sorted(poly_dirs[0].glob(\"*_fixmap.npy\"))\n", " if npy_files:\n", " smap = np.load(npy_files[0])\n", " fig, ax = plt.subplots(figsize=(10, 5.625))\n", " im = ax.imshow(smap, cmap=\"hot\", aspect=\"equal\")\n", " ax.set_xlabel(\"X (pixels)\")\n", " ax.set_ylabel(\"Y (pixels)\")\n", " ax.set_title(f\"Saliency map: {poly_dirs[0].name}/{npy_files[0].stem}\\n\"\n", " f\"Resolution: {smap.shape[1]}×{smap.shape[0]} px, \"\n", " f\"σ = 1.0 deg = {PPD:.1f} px\")\n", " plt.colorbar(im, label=\"Fixation density\", ax=ax)\n", " plt.tight_layout()\n", " plt.show()\n", " else:\n", " print(\"No .npy saliency maps found.\")\n", " else:\n", " print(\"No polygon directories found.\")\n", "else:\n", " print(\"Saliency map directory not found. Run generate_saliency_maps.py first.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 8. Category Comparison" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Fixation stats by stimulus category\n", "by_category = defaultdict(list)\n", "for f in fixations:\n", " cat = f.get(\"category\", \"\")\n", " if cat and f[\"eye\"] == \"R\":\n", " by_category[cat].append(float(f[\"duration_ms\"]))\n", "\n", "cats = sorted(by_category.keys())\n", "means = [np.mean(by_category[c]) for c in cats]\n", "stds = [np.std(by_category[c]) / np.sqrt(len(by_category[c])) for c in cats]\n", "\n", "fig, ax = plt.subplots(figsize=(8, 4))\n", "ax.bar(cats, means, yerr=stds, color=\"steelblue\", edgecolor=\"white\", capsize=3)\n", "ax.set_ylabel(\"Mean fixation duration (ms)\")\n", "ax.set_title(\"Fixation Duration by Stimulus Category (right eye)\")\n", "plt.xticks(rotation=30, ha=\"right\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "**Notes:**\n", "- All pixel coordinates are on a 3840×2160 display\n", "- Conversion to degrees: `x_deg = (x_px - 1920) / 78.5`, `y_deg = (y_px - 1080) / 78.5`\n", "- See `docs/data_dictionary.md` for full field descriptions\n", "- See `docs/acquisition_protocol.md` for equipment and procedure details" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 4 }