The Complete Production SOP: How to Deploy and Run Uber H3 Hierarchical Hexagonal Spatial Indexing in Autonomous AI Agents
Production SOP to install and execute Uber H3 Hexagonal Spatial Indexing in Codex, Claude Code, Cursor, and Windsurf. Includes code, prompts, and debugging.
Technical Overview & Architectural Context
Autonomous coding agents frequently stumble when performing geospatial operations. When tasked with spatial joins, proximity queries, or regional clustering, agents default to legacy computational geometry: calculating pairwise Haversine distances in quadratic loops, computing planar Euclidean approximations across geodesic coordinates, or orchestrating expensive point-in-polygon ray-casting algorithms using heavy GIS stacks. These naive approaches collapse under scale, exhaust compute limits, and introduce floating-point boundary anomalies. Furthermore, LLMs hallucinate between Uber H3 API versions—routinely mixing deprecated v3 syntax (such as h3.geo_to_h3 or h3.k_ring) with H3 v4 bindings (such as h3.latlng_to_cell or h3.grid_disk). When agents attempt to aggregate metrics across zip codes or administrative boundaries, they create irregular spatial partitions with variable neighbor counts, resulting in distorted spatial autocorrelations and inaccurate downstream machine learning feature stores. The uber-h3-hexagonal-spatial-index skill establishes strict procedural boundaries. It forces agents to utilize discrete hexagonal hierarchical partitioning (resolutions 0 through 15), mandates deterministic API usage matching the installed library version, and enforces compact cell serialization for disk and network transport. By constraining the agent to standardized grid-disk traversals and hierarchical parent-child traversals, spatial queries execute as constant-time hash map lookups rather than compute-intensive geometric intersections.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into the agent runtime path.
Autonomous agent frameworks like Codex and Claude Code scan directory hierarchies for custom capabilities. Place the SKILL.md specification in the workspace configuration path (.claude/skills/ or .cursor/rules/) or the user-level global registry (~/.agents/skills/). This allows the agent to ingest the metadata, triggers, and execution guardrails before initiating spatial indexing tasks.
mkdir -p .agents/skills/uber-h3-hexagonal-spatial-index && curl -fsSL https://askills.dev/api/skills/uber-h3-hexagonal-spatial-index/raw -o .agents/skills/uber-h3-hexagonal-spatial-index/SKILL.md---
name: "uber-h3-hexagonal-spatial-index"
description: "Partition geographic coordinates into multi-resolution hexagonal grid cells using Uber H3."
metadata:
author: "Uber"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "lat lng to h3 index"
- "polygon polyfill h3"
- "h3 grid aggregation"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Uber H3 Hierarchical Hexagonal Spatial Indexing
Implements spatial analytics using Uber H3: converting lat/lng to H3 index tokens, finding k-ring neighbors, compacting and uncompacting cell sets, polyfilling polygons, and running high-speed spatial aggregations.
## When to Invoke
Invoke this skill whenever you need to:
- lat lng to h3 index
- polygon polyfill h3
- h3 grid aggregation
## Execution SOP & Rules
1. Target H3 v4 API syntax: use h3.latlng_to_cell(lat, lng, res) instead of deprecated v3 h3.geo_to_h3.
2. Neighbor searches must use h3.grid_disk(cell, k) or h3.grid_ring_unsafe(cell, k).
3. Polygon ingestion must use h3.polygon_to_cells(geo_polygon, res) with GeoJSON coordinate order [lng, lat].
4. Always compact collections using h3.compact_cells() when persisting boundaries to Parquet/JSON.
## Verification Checklist
- Verify H3 cell strings are valid hex using h3.is_valid_cell().
- Assert coordinate inputs fall within [-90.0, 90.0] latitude and [-180.0, 180.0] longitude.
- Confirm resolution is an integer between 0 and 15 inclusive.In Cursor and Windsurf, symlink the root SKILL.md directly to `.cursor/rules/h3-indexing.mdc` or `.windsurfrules` to save token budget by indexing triggers locally without repeating the full markdown in every prompt.
The frontmatter sets `net_access: false` and `fs_write: workspace`. If your script attempts to pull live GeoJSON over HTTP inside the agent runtime without workspace staging, the sandbox will abort execution.
Environment Secrets & Dependency Validation
Install the native Uber H3 bindings and verify binary compatibility within the isolated runtime.
Uber H3 relies on optimized C core bindings compiled for your host architecture (x86_64 or arm64). Ensure your virtual environment contains the modern H3 v4 bindings. Because this skill requires no external API keys (`Required Env Vars: []`), you only need to ensure the local compiler and wheel dependencies match without leaking sensitive credentials into execution transcripts.
python -m venv .venv && source .venv/bin/activate && pip install "h3>=4.1.0" pandas shapely pyarrowimport h3
import sys
test_lat, test_lng, res = 37.7749, -122.4194, 9
try:
# Verify H3 v4 API signature
cell = h3.latlng_to_cell(test_lat, test_lng, res)
assert h3.is_valid_cell(cell), f"Invalid H3 index: {cell}"
disk = h3.grid_disk(cell, 1)
assert len(disk) == 7, f"Expected 7 cells in k=1 ring, got {len(disk)}"
print(f"[SUCCESS] H3 runtime operational. Version: {h3.__version__}, Sample Cell: {cell}")
except AttributeError as e:
sys.exit(f"[FAIL] H3 v3/v4 API mismatch detected: {e}")
except Exception as e:
sys.exit(f"[FAIL] Unexpected error during verification: {e}")Freeze your workspace requirements with `pip freeze | grep h3 >> requirements.txt`. If the agent runs in a zero-dependency container, specify `h3-py` wheel installation explicitly to avoid invoking gcc during agent execution.
Do not pass longitude first into `latlng_to_cell`. GeoJSON standardizes on `[lng, lat]`, but H3 core functions take `(lat, lng)`. Swapping these coordinates results in cells being indexed in Antarctica or the Pacific Ocean.
Intent Matching & Trigger Invocation
Verify deterministic agent skill activation using explicit frontmatter trigger phrases.
Agent orchestrators monitor prompts for triggers specified in the SKILL.md (`lat lng to h3 index`, `polygon polyfill h3`, `h3 grid aggregation`). Construct your prompt using these exact phrases to invoke the deterministic SOP and avoid fallback heuristics.
claude-code "Run h3 grid aggregation on data/telemetry.csv using lat lng to h3 index at resolution 8"import h3
import pandas as pd
from pathlib import Path
def aggregate_telemetry_by_h3(input_path: Path, output_path: Path, resolution: int = 8) -> None:
"""Converts coordinate records into H3 cells and performs spatial density aggregation."""
df = pd.read_csv(input_path)
# Validate coordinates
valid_coords = df['latitude'].between(-90, 90) & df['longitude'].between(-180, 180)
df = df[valid_coords].copy()
# Map coordinates to H3 index
df['h3_cell'] = [h3.latlng_to_cell(lat, lng, resolution) for lat, lng in zip(df['latitude'], df['longitude'])]
# High-speed categorical aggregation
aggregated = df.groupby('h3_cell').agg(
ping_count=('h3_cell', 'count'),
avg_speed=('speed', 'mean') if 'speed' in df.columns else ('latitude', 'count')
).reset_index()
# Compute boundary polygon for downstream visualization
aggregated['hex_boundary_geojson'] = aggregated['h3_cell'].apply(
lambda c: h3.cell_to_boundary(c, geo_json=True)
)
output_path.parent.mkdir(parents=True, exist_ok=True)
aggregated.to_parquet(output_path, index=False)
print(f"Processed {len(df)} pings into {len(aggregated)} distinct H3 cells at resolution {resolution}.")Structure prompts by anchoring the trigger in the first imperative sentence: 'Use polygon polyfill h3 to index the service delivery zone GeoJSON at resolution 9.' This scores high on agent intent-matching heuristics.
Avoid ambiguous expressions like 'group by geographic proximity' or 'cluster locations'. These cause agents to default to Scikit-learn DBSCAN or K-Means instead of invoking Uber H3.
Verification, Linting & Output Quality Gate
Execute automated validation checks on indexed outputs before accepting deliverables.
Before the agent signs off on a spatial data transformation, it must execute a test harness that verifies cell validity, ensures zero empty index strings, checks resolution consistency, and guarantees that compacted geometries correctly reconstruct parent cells without data loss.
pytest tests/test_h3_indexing.py -vimport pytest
import h3
import pandas as pd
from pathlib import Path
def test_h3_output_integrity(tmp_path):
from h3_aggregator import aggregate_telemetry_by_h3
# Generate test fixture
raw_csv = tmp_path / "raw.csv"
out_parquet = tmp_path / "out.parquet"
pd.DataFrame({
'latitude': [37.7749, 37.7750, 40.7128],
'longitude': [-122.4194, -122.4195, -74.0060],
'speed': [15.2, 14.8, 30.1]
}).to_csv(raw_csv, index=False)
aggregate_telemetry_by_h3(raw_csv, out_parquet, resolution=8)
res_df = pd.read_parquet(out_parquet)
assert not res_df.empty, "Result dataframe should not be empty"
assert 'h3_cell' in res_df.columns, "H3 cell column missing"
# Validate individual H3 cells
for cell in res_df['h3_cell']:
assert h3.is_valid_cell(cell), f"Invalid H3 cell detected: {cell}"
assert h3.get_resolution(cell) == 8, f"Resolution mismatch: expected 8, got {h3.get_resolution(cell)}"Configure an agent verification rule in your CI pipeline requiring that all generated spatial artifacts include a parity assertion checking `len(h3.compact_cells(cells)) <= len(cells)`.
Compacted H3 cell sets contain mixed resolutions. Never assume a homogeneous resolution in data downstream of `h3.compact_cells()`.
Real-World Scenario: Urban Ride-Hailing Demand Heatmap and Multi-Tier Surge Pricing Grid
“Write a Python production pipeline in `src/surge_model.py`. Use lat lng to h3 index to aggregate 500k ride requests from `data/rides.csv` into H3 resolution 7 cells. For any cell exceeding 50 requests, use polygon polyfill h3 and h3 grid aggregation to find the 1-ring adjacent neighbors and expand the surge zone. Compact the result and export to `output/surge_zones.parquet`.”
Runtime Troubleshooting & Failure Modes
Root Cause: The autonomous agent generated code using legacy H3 v3 method names (`geo_to_h3`, `k_ring`, `polyfill`) while H3 v4.x is installed in the workspace environment.
# Replace legacy v3 calls with v4 equivalents:
# Deprecated: cell = h3.geo_to_h3(lat, lng, 8)
cell = h3.latlng_to_cell(lat, lng, 8)
# Deprecated: neighbors = h3.k_ring(cell, 1)
neighbors = h3.grid_disk(cell, 1)
# Deprecated: cells = h3.polyfill(geojson_dict, 8)
cells = h3.polygon_to_cells(h3.GeoPolygon(geojson_dict['coordinates']), 8)Root Cause: Coordinate tuple inversion. The agent passed longitude first `(lng, lat)` into `h3.latlng_to_cell()` instead of `(lat, lng)`, or failed to filter records containing corrupted coordinates (`lat > 90` or `lat < -90`).
# Enforce coordinate validation and strict order
def safe_latlng_to_cell(lat: float, lng: float, res: int) -> str:
if not (-90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0):
raise ValueError(f"Out of bounds coordinates: lat={lat}, lng={lng}")
return h3.latlng_to_cell(lat, lng, res)Frequently Asked Questions (Uber H3 Hierarchical Hexagonal Spatial Indexing SOP)
Q:Can I use Uber H3 Hierarchical Hexagonal Spatial Indexing across Codex, Claude Code, and Cursor simultaneously?
Yes. The SKILL.md file uses an agent-agnostic specification. Placing it in your workspace root under `.agents/skills/uber-h3-hexagonal-spatial-index/` allows Codex, Claude Code, Cursor, and Windsurf to consume the procedural instructions, triggers, and verification gates concurrently.
Q:How does Uber H3 Hierarchical Hexagonal Spatial Indexing prevent context window overflow during long agent sessions?
By prescribing precise H3 v4 API signatures, algorithmic patterns, and strict input/output verification steps, the skill prevents agents from entering multi-step trial-and-error loops, hallucinating deprecated v3 methods, or dumping verbose geometric debugging logs into the conversation context.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a Security Score of 98/100. It requires only standard workspace file read/write permissions (`fs_read: true`, `fs_write: 'workspace'`) to generate and persist index artifacts. It explicitly disables outbound network access (`net_access: false`) and shell root privileges.
Ready to equip your autonomous agent with Uber H3 Hierarchical Hexagonal Spatial Indexing?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.