#!/usr/bin/env python3 """PolyCAT Dataset — Quickstart Example Demonstrates basic data loading and visualization for the PolyCAT dataset. Display setup: 27" 4K monitor (3840x2160) at 70 cm viewing distance (~78.5 px/deg). Requirements: pip install numpy pandas matplotlib Usage: python code/examples/quickstart.py """ import csv from collections import defaultdict from pathlib import Path import numpy as np PROJECT_ROOT = Path(__file__).resolve().parents[2] def load_csv(path): """Load a CSV file as a list of dicts.""" with open(path, "r") as f: return list(csv.DictReader(f)) def example_1_load_metadata(): """Example 1: Load and explore dataset metadata.""" print("=" * 60) print("Example 1: Dataset Metadata") print("=" * 60) # Load participants participants = load_csv(PROJECT_ROOT / "data" / "metadata" / "participants.csv") print(f"\nParticipants: {len(participants)}") for p in participants[:3]: print(f" {p['participant_id']}: " f"{p.get('total_trials_A', '?')} trials (Part A), " f"{p.get('total_trials_B', '?')} trials (Part B)") print(f" ... and {len(participants) - 3} more") # Load trials trials = load_csv(PROJECT_ROOT / "data" / "metadata" / "trials.csv") print(f"\nTotal trials: {len(trials)}") # Count by category categories = defaultdict(int) for t in trials: cat = t.get("category", "unknown") categories[cat] += 1 print(" By category:") for cat, count in sorted(categories.items()): print(f" {cat}: {count}") return participants, trials def example_2_load_fixations(): """Example 2: Load and summarize fixation data.""" print("\n" + "=" * 60) print("Example 2: Fixation Data") print("=" * 60) fixations = load_csv(PROJECT_ROOT / "data" / "fixations" / "fixations_all.csv") print(f"\nTotal fixations: {len(fixations):,}") # Group by participant by_pid = defaultdict(list) for f in fixations: by_pid[f["participant_id"]].append(f) print(f"Participants: {len(by_pid)}") # Summary per participant print("\nPer-participant fixation counts:") for pid in sorted(by_pid.keys())[:5]: fix_list = by_pid[pid] durations = [float(f["duration_ms"]) for f in fix_list] print(f" {pid}: {len(fix_list):,} fixations, " f"mean duration = {np.mean(durations):.0f} ms") print(f" ... and {len(by_pid) - 5} more") return fixations def example_3_single_trial_scanpath(): """Example 3: Load a single trial's scanpath.""" print("\n" + "=" * 60) print("Example 3: Single Trial Scanpath") print("=" * 60) # Find a participant's scanpath directory scanpath_dir = PROJECT_ROOT / "data" / "scanpaths" pid_dirs = sorted(d for d in scanpath_dir.iterdir() if d.is_dir()) if not pid_dirs: print("No scanpath files found. Run export_scanpaths.py first.") return # Pick first participant, first trial pid_dir = pid_dirs[0] scanpath_files = sorted(pid_dir.glob("*.csv")) if not scanpath_files: print(f"No scanpath files in {pid_dir}") return scanpath_file = scanpath_files[0] scanpath = load_csv(scanpath_file) print(f"\nParticipant: {pid_dir.name}") print(f"Trial: {scanpath_file.stem}") print(f"Fixations in scanpath: {len(scanpath)}") # Display note about coordinate interpretation print(f"\nNote: Coordinates are in pixels on a 3840x2160 display at 70 cm.") print(f" At ~78.5 px/deg, a 100 px distance = ~1.27 degrees of visual angle.") print("\nScanpath (right eye):") print(f" {'#':>3} {'X (px)':>8} {'Y (px)':>8} {'Duration':>10} {'Eye':>4}") print(f" {'-'*3:>3} {'-'*8:>8} {'-'*8:>8} {'-'*10:>10} {'-'*4:>4}") for fix in scanpath[:10]: print(f" {fix['fixation_index']:>3} " f"{float(fix['x_px']):>8.1f} " f"{float(fix['y_px']):>8.1f} " f"{float(fix['duration_ms']):>8.1f} ms " f"{fix['eye']:>4}") if len(scanpath) > 10: print(f" ... and {len(scanpath) - 10} more fixations") def example_4_fixation_heatmap(): """Example 4: Create a simple fixation heatmap (text-based).""" print("\n" + "=" * 60) print("Example 4: Fixation Spatial Distribution") print("=" * 60) # Load fixations for one participant fixations = load_csv(PROJECT_ROOT / "data" / "fixations" / "fixations_all.csv") # Get first participant's right-eye fixations first_pid = fixations[0]["participant_id"] pid_fix = [(float(f["x_px"]), float(f["y_px"])) for f in fixations if f["participant_id"] == first_pid and f["eye"] == "R"] print(f"\n{first_pid}: {len(pid_fix)} right-eye fixations") # Compute spatial statistics xs = np.array([p[0] for p in pid_fix]) ys = np.array([p[1] for p in pid_fix]) ppd = 78.5 # px/deg for 27" 4K at 70 cm cx, cy = 3840 / 2, 2160 / 2 # screen center # Distance from center in degrees dist_deg = np.sqrt(((xs - cx) / ppd)**2 + ((ys - cy) / ppd)**2) print(f"\nSpatial distribution:") print(f" X range: {xs.min():.0f} - {xs.max():.0f} px " f"({(xs.min() - cx) / ppd:.1f} to {(xs.max() - cx) / ppd:.1f} deg)") print(f" Y range: {ys.min():.0f} - {ys.max():.0f} px " f"({(ys.min() - cy) / ppd:.1f} to {(ys.max() - cy) / ppd:.1f} deg)") print(f" Mean eccentricity: {dist_deg.mean():.1f} deg") print(f" Median eccentricity: {np.median(dist_deg):.1f} deg") # Histogram of eccentricity bins = [0, 2, 4, 6, 8, 10, 15, 20, 25] counts, _ = np.histogram(dist_deg, bins=bins) print(f"\n Eccentricity distribution:") for i in range(len(counts)): bar = "#" * int(counts[i] / max(counts) * 30) print(f" {bins[i]:>4}-{bins[i+1]:>2} deg: {counts[i]:>5} {bar}") def example_5_polygon_info(): """Example 5: Explore polygon geometry.""" print("\n" + "=" * 60) print("Example 5: Polygon Apertures") print("=" * 60) poly_csv = PROJECT_ROOT / "data" / "manifests" / "polygon_geometry.csv" if not poly_csv.exists(): print(f" Polygon geometry file not found at {poly_csv}") return polygons = load_csv(poly_csv) print(f"\n{len(polygons)} unique polygon shapes") print(f"\nFirst 5 polygons:") for p in polygons[:5]: pid = p.get("polygon_id", "?") cx = p.get("center_x", "?") cy = p.get("center_y", "?") print(f" {pid}: center = ({cx}, {cy})") # Check for polygon JSON definitions poly_dir = PROJECT_ROOT / "data" / "stimuli" / "polygons" if poly_dir.exists(): json_files = list(poly_dir.glob("*.json")) print(f"\n{len(json_files)} polygon JSON vertex definition files") if json_files: import json with open(json_files[0]) as f: sample = json.load(f) print(f" Sample ({json_files[0].name}):") if isinstance(sample, list): print(f" {len(sample)} vertices") if sample: print(f" First vertex: {sample[0]}") elif isinstance(sample, dict): print(f" Keys: {list(sample.keys())}") def main(): print("PolyCAT Dataset — Quickstart Examples") print("Display: 27\" 4K (3840x2160) at 70 cm (~78.5 px/deg)") print() example_1_load_metadata() example_2_load_fixations() example_3_single_trial_scanpath() example_4_fixation_heatmap() example_5_polygon_info() print("\n" + "=" * 60) print("Quickstart complete!") print("=" * 60) print("\nFor visualization examples, see quickstart.ipynb") if __name__ == "__main__": main()