Skip to content

API Reference parrot.tools.dataset_manager.spatial.contracts

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.tools.dataset_manager.spatial.contracts

View source

Pure Pydantic contracts for spatial filtering (FEAT-219 Module 1).

These are I/O-free data models. They carry no driver or DSN information — the SpatialCompiler and DatasetManager.spatial_filter consume them.

Note: from __future__ import annotations is intentionally omitted here to ensure Pydantic v2 can resolve the Tuple[float, float] annotation at class definition time without requiring a manual model_rebuild() call.

Class DatasetSpatialProfile

Describes how a specific dataset exposes its geometry.

Each dataset that participates in spatial queries must have a profile registered in SPATIAL_PROFILE_REGISTRY. Profiles are I/O-free; they carry only structural metadata.

Fields:

Field Type Default Description
dataset str FK to a registered dataset name (must exist at execute time).
lat_col Optional[str] None Latitude column name (naive lat/lng pair).
lng_col Optional[str] None Longitude column name (naive lat/lng pair).
geom_col Optional[str] None Native geometry or geography column. Mutually exclusive with lat_col/lng_col when used for push-down — the compiler picks the appropriate path.
layer str Leaflet layer id / GeoJSON source discriminator.
property_cols List[str] Column names to include in GeoJSON feature.properties.
description_template str '' Python str.format_map template, e.g. "{name} ({type})".
geodesic bool True Declared hint. True = profile expects geodesic (native geography) precision; the compiler verifies this against the actual column type.
label_col Optional[str] None Property key for the marker label (e.g. 'name'). Used by StructuredMapRenderer to set MapLayer.label_field.
tooltip_template Optional[str] None Per-layer tooltip template distinct from description_template. Falls back to description_template when unset. Applied client-side over feature.properties via str.format_map.
column_titles Dict[str, str] column name when absent.' Optional human-readable column titles keyed by property column name. Renderer default = column name when absent.
column_formats Dict[str, str] Optional display format hints keyed by property column name. Allowed values: currency | percent | email | uri | enum | id | code.
default_data_shape Literal['geojson', 'rows'] 'geojson' Per-dataset default data payload shape for MapLayer.data_shape (G6). 'geojson' passes features through; 'rows' flattens to canonical row dicts.

Class SpatialFeatureCollection

GeoJSON FeatureCollection returned by DatasetManager.spatial_filter.

The shape is identical regardless of whether the query came from the LLM (NL→spec) or the frontend (deterministic). Frontend builds the map; this model carries data only.

Fields:

Field Type Default Description
type Literal['FeatureCollection'] 'FeatureCollection' GeoJSON type discriminator — always "FeatureCollection".
features List[Dict] List of GeoJSON Feature dicts. Each feature has at least geometry, properties (with data + description + source), and type.
total_count int 0 True count of matching features before capping. May be greater than len(features) when capped.
capped bool False True when the result was truncated at the hard cap.
geodesic_paths Dict[str, bool] Per-dataset flag recording whether the executed path was geodesic (True) or spherical-approximate (False).

Class SpatialFilterSpec

Describes a spatial radius filter request.

Backend-agnostic: carries no driver, DSN, or SQL. Emitted identically by the LLM (NL→spec mode) and the frontend (deterministic mode).

Fields:

Field Type Default Description
point Tuple[float, float] (lat, lng) in decimal degrees.
radius float Search radius in the specified unit.
unit Literal['mi', 'km', 'm'] 'mi' Distance unit — "mi", "km", or "m".
datasets List[str] Dataset names to query (resolved via DatasetManager._resolve_name).

Class SpatialLayerResult

Per-dataset slice of a spatial filter result (FEAT-221 G4).

Fields:

Field Type Default Description
layer str Leaflet layer id / GeoJSON source discriminator (from DatasetSpatialProfile).
features List[Dict] GeoJSON Feature dicts for this dataset.
total_count int 0 True count of matching features before capping.
capped bool False True when the result was truncated at the hard cap.
geodesic bool True Whether the executed path was geodesic (True) or spherical-approximate (False).

Class SpatialResult

Versioned per-dataset result returned by spatial_filter (FEAT-221 G4).

Replaces the merged SpatialFeatureCollection with per-dataset grouping. The as_feature_collection() method reproduces the legacy merged shape for backward-compatible callers (e.g. the transport handler).

Fields:

Field Type Default Description
version Literal[2] 2 Schema version — always 2 for this model.
layers Dict[str, SpatialLayerResult] Per-dataset results keyed by resolved dataset name.

Method SpatialResult.as_feature_collection

Reproduce the legacy merged SpatialFeatureCollection shape.

Concatenates all per-dataset features, sums total_count values, ORs the capped flags, and builds geodesic_paths from each layer's geodesic flag.

as_feature_collection() -> SpatialFeatureCollection

Returns: SpatialFeatureCollection — A SpatialFeatureCollection compatible with pre-FEAT-221 callers.

Method SpatialResult.from_dataframe

Build a single-layer SpatialResult from a pandas DataFrame.

Lets callers (e.g. PandasAgent) turn an arbitrary result DataFrame into the GeoJSON wire contract the STRUCTURED_MAP renderer consumes — no backend map rendering, no LLM call. Two input shapes are supported and auto-detected when the *_col arguments are omitted:

  • Coordinate pair — a latitude column (lat/latitude) and a longitude column (lon/lng/long/longitude); each row becomes a GeoJSON Point.
  • Geo-structure column — a geometry/geom column whose cells are GeoJSON geometry dicts, GeoJSON Feature dicts, WKT strings, or shapely geometries (anything exposing __geo_interface__). The geometry is preserved as-is, so Polygons, LineStrings, etc. survive.

Detection prefers a geometry column over a lat/lon pair. All columns except the resolved geo columns become each feature's properties. Rows whose geometry cannot be resolved (missing/NaN coords, unparseable WKT) are skipped.

from_dataframe(df: Any, *, lat_col: Optional[str] = None, lon_col: Optional[str] = None, geometry_col: Optional[str] = None, dataset: str = 'result', layer: str = 'result', property_cols: Optional[List[str]] = None, geodesic: bool = False) -> SpatialResult

Parameter Type Default Description
df Any A pandas DataFrame (or GeoDataFrame) of result rows.
lat_col Optional[str] None Latitude column name; auto-detected when omitted.
lon_col Optional[str] None Longitude column name; auto-detected when omitted.
geometry_col Optional[str] None Geometry column name; auto-detected when omitted.
dataset str 'result' Key under which the single layer is stored in layers.
layer str 'result' Leaflet layer id / GeoJSON source discriminator.
property_cols Optional[List[str]] None Columns to expose as feature properties. Defaults to every column except the resolved geo columns.
geodesic bool False Whether downstream paths should be treated as geodesic.

Returns: SpatialResult — A version-2 SpatialResult with a single SpatialLayerResult. The layer may have zero features when no row yields a geometry.

Raises:

  • ValueError — When neither a geometry column nor a lat/lon pair can be resolved from the DataFrame columns.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally