Ir para o conteúdo

tempest_fastapi_sdk.geo

Geolocalização sem API paga: distância, rotas, geometria e geocoding.

« Web, UI e utilitários


geo

Geolocation — distance, routing, geometry and geocoding, no paid API.

Layers, all sharing the same schemas:

  • Offline math (zero deps, zero network): :func:haversine_km, the spatial helpers in :mod:geometry (:func:bounding_box, :func:within_radius, :func:nearest, :func:destination_point, :func:initial_bearing, :func:point_in_polygon, :func:polygon_area_km2, :func:path_length_km), decimal spatial grid tiling in :mod:grid (:class:GridCellSchema, :func:round_to_grid, :func:cell_for, :func:generate_grid, :func:neighbor_cells), plus :func:estimate_travel for a road distance / per-mode time.
  • Real routing (free, open-source): :class:OSRMBackend for routes, routes through stops (:meth:OSRMBackend.route_through, with :func:estimate_route_through as the offline fallback), route geometry and distance/duration matrices; :class:NominatimBackend for forward/reverse geocoding. Both take an injected httpx.AsyncClient (install the [geo] extra for httpx); the rest imports without it.
  • Caching: :class:CachedGeocodingBackend wraps any :class:GeocodingBackend in front of a pluggable :class:GeocodeCacheStore — :class:InMemoryGeocodeCacheStore for tests and dev, :class:RedisGeocodeCacheStore for a shared Redis.
  • Live position: :class:LivePositionStore keeps the latest :class:LivePositionSchema per channel in Redis (throttle, least movement, TTL, :meth:LivePositionStore.clear) and delivers accepted positions over an SSE broker to the recipients an audience callback names, optionally with each one's ETA; :func:make_live_position_router receives them behind mandatory authorize and channel_active dependencies.
  • Fleet traffic: :class:RoadGraph (from an OSM excerpt with :func:road_graph_from_overpass / :func:load_road_graph), :func:match_to_roads (HMM map-matching, a port of tempest-react-sdk's), :class:TrafficAggregator (median speed per road stretch, published only k-anonymously, start and end of every trip cut, rotating hashes) and :func:make_traffic_router; map-matching quality per window, k-anonymous (quality= + :func:make_match_quality_router); :class:OffRoadDensity + :func:infer_road_candidates turn off-road density into road candidates for human review.
  • Database: :class:GeoPointMixin (model) + :class:GeoRepositoryMixin (portable radius search) / :class:PostGISRepositoryMixin (ST_DWithin).
  • Database, paginated: :meth:GeoRepositoryMixin.paginate_nearby computes :func:haversine_distance_sql in SQL and pages there, each item a :class:NearbyMatch (row, distance_km).
  • Brazil: :func:uf_centroid (offline state centres), :func:cep_to_coordinate (CEP via a geocoder), :func:extract_cep (CEP from free text) and :func:resolve_br_coordinate (CEP → address → state centroid). Every IBGE municipality offline, with code and coordinate: :func:municipality_by_ibge_code, :func:search_municipalities (typos included) and :func:find_municipalities_in_text ("moro em sao jose dos campos - sp").

Motorcycle/bus/bicycle/pedestrian are derived from the car result by scaling the duration (see :data:DEFAULT_MODE_DURATION_FACTORS).

CEP_PATTERN module-attribute

CEP_PATTERN: Pattern[str] = re.compile('\\b(\\d{5})-?(\\d{3})\\b')

A CEP written anywhere in free text, with or without the dash.

Word boundaries on both ends keep it from matching eight digits inside a longer run (a phone number, a document number): "123456789" does not match, "CEP 01310-100, sala 4" does.

BR_MAP_LEVELS module-attribute

BR_MAP_LEVELS: Final[int] = 5

How many shades :func:render_br_map_svg splits the state values into.

BR_MAP_MAX_RADIUS module-attribute

BR_MAP_MAX_RADIUS: Final[float] = 28.0

Radius, in SVG units, of the bubble of the largest point.

BR_MAP_MIN_RADIUS module-attribute

BR_MAP_MIN_RADIUS: Final[float] = 3.0

Radius, in SVG units, of the bubble of the smallest positive point.

BR_MAP_PADDING module-attribute

BR_MAP_PADDING: Final[float] = 10.0

Blank margin, in SVG units, around the outline of the country.

BR_MAP_WIDTH module-attribute

BR_MAP_WIDTH: Final[float] = 1000.0

Width of the map's SVG viewBox; the height follows the projection.

DEFAULT_GEOCODE_CACHE_KEY_PREFIX module-attribute

DEFAULT_GEOCODE_CACHE_KEY_PREFIX: str = 'geocoding'

First segment of every key the wrapper builds.

DEFAULT_GEOCODE_CACHE_PRECISION module-attribute

DEFAULT_GEOCODE_CACHE_PRECISION: int = 3

Decimal places a reverse coordinate is rounded to before keying.

Three places is a ~111 m grid (measured with :func:~tempest_fastapi_sdk.geo.haversine_km at 10⁻³ of a degree of latitude); more places fragment the cache without making the answer better, since a street resolves to the same building.

DEFAULT_GEOCODE_CACHE_TTL_SECONDS module-attribute

DEFAULT_GEOCODE_CACHE_TTL_SECONDS: int = 2592000

Default entry lifetime: 30 days.

Long enough that a whole device fleet settles into hits, short enough that a map edit or a corrected place reaches users within a month. Place resolutions are stable on that horizon — the coordinates of a doorway do not move — while a week would re-buy quota every month and "forever" would pin a wrong answer.

DEFAULT_NOMINATIM_BASE_URL module-attribute

DEFAULT_NOMINATIM_BASE_URL: str = 'https://nominatim.openstreetmap.org'

Public OSM Nominatim server. Rate-limited (~1 req/s), best-effort.

DEFAULT_LIVE_POSITION_CLEARED_EVENT module-attribute

DEFAULT_LIVE_POSITION_CLEARED_EVENT: Final[str] = 'live_position_cleared'

SSE event name :meth:LivePositionStore.clear sends to the audience.

DEFAULT_LIVE_POSITION_EVENT module-attribute

DEFAULT_LIVE_POSITION_EVENT: Final[str] = 'live_position'

SSE event name of an accepted position.

DEFAULT_LIVE_POSITION_INTERVAL_SECONDS module-attribute

DEFAULT_LIVE_POSITION_INTERVAL_SECONDS: Final[float] = 5.0

Least time between two accepted positions on one channel.

DEFAULT_LIVE_POSITION_KEY_PREFIX module-attribute

DEFAULT_LIVE_POSITION_KEY_PREFIX: Final[str] = 'geo:live'

First segment of every Redis key :class:LivePositionStore writes.

DEFAULT_LIVE_POSITION_MIN_DISTANCE_M module-attribute

DEFAULT_LIVE_POSITION_MIN_DISTANCE_M: Final[float] = 10.0

Least movement, in meters, for a new position to be accepted.

About the accuracy of a phone GPS in the open: below it, the "movement" is mostly noise.

DEFAULT_LIVE_POSITION_TTL_SECONDS module-attribute

DEFAULT_LIVE_POSITION_TTL_SECONDS: Final[int] = 300

How long the latest position lives without a new one: five minutes.

Long enough to survive a tunnel or a dead zone, short enough that a phone that stopped sending (app killed, trip abandoned without :meth:clear) stops showing a stale marker on its own.

LIVE_POSITION_MAX_CLOCK_SKEW module-attribute

LIVE_POSITION_MAX_CLOCK_SKEW: Final[timedelta] = timedelta(seconds=30)

How far in the future recorded_at may be before it is refused.

A phone's clock drifts a few seconds from the server's; refusing anything strictly ahead of now would drop honest positions. Thirty seconds absorbs that drift and still refuses a timestamp that is plainly wrong.

AudienceResolver module-attribute

AudienceResolver = Callable[[str], Awaitable[Sequence[str]]]

Maps a channel id to the SSE channels (usually user ids) that may see it.

EtaTargetsResolver module-attribute

EtaTargetsResolver = Callable[[str], Awaitable[Mapping[str, Coordinate]]]

Maps a channel id to each recipient's target point ({user_id: point}).

LIVE_POSITION_INACTIVE_ERROR module-attribute

LIVE_POSITION_INACTIVE_ERROR: Final[str] = 'Channel is not accepting positions'

Message of the 409 answered when channel_active says False.

BR_CITY_MAX_LENGTH module-attribute

BR_CITY_MAX_LENGTH: int = 64

Width of the city column; the longest IBGE name has 32 characters.

ROAD_MATCH_DEFAULTS module-attribute

ROAD_MATCH_DEFAULTS: Final[RoadMatchOptions] = RoadMatchOptions()

Default tuning: sigma 7 m, beta 3 m, radius 200 m, 16 roads, detour 100 m, plus 2 m of detour per second between timed fixes, capped at 60 s.

Ported from tempest-react-sdk's ROAD_MATCH_DEFAULTS, chosen there by sweeping every knob on the Kubicka et al. dataset (100 real drives, 247 251 fixes, node scripts/bench-map-matching.mjs): 92.33% of fixes on the right road, 98.53% without the three drives through yards missing from OSM.

detour_per_second_m and max_interval_s were chosen there on the same drives thinned to one fix every 5-300 s and on public OpenStreetMap traces of five Brazilian city centres (node scripts/bench-br-osm.mjs, PR #678): 2 m/s is the largest rate that leaves the 1 Hz result where it was, and a 60 s cap keeps the long gaps of a 1 Hz trace from widening the search.

MATCH_QUALITY_REFERENCE_BRAZIL_OSM module-attribute

MATCH_QUALITY_REFERENCE_BRAZIL_OSM: Final[MatchQualityReferenceSchema] = (
    MatchQualityReferenceSchema(
        name="brazil-osm",
        source="tempest-react-sdk#667, Brazil validation (2026-11-19): public OSM GPS traces of Sao Paulo, Rio, Teresina, Sao Carlos and Parnaiba, 161 vehicle runs, 19 806 positions; node scripts/bench-br-osm.mjs",
        note="Measured over whole runs, without the 200 m trim; the aggregator measures released stretches, so straight stretches at a stretch edge are shorter.",
        positions=19806,
        straight_km=119.7,
        breaks_per_1000_positions=1.06,
        matched_share=1.0,
        inferred_share=0.551,
        snap_distance_median_m=3.7,
        snap_distance_p90_m=11.6,
        sampling_interval_median_s=1.0,
        sampling_interval_p90_s=4.0,
        parallel_switches_per_km=0.109,
    )
)

Public OSM traces of five Brazilian cities, as matched in #667.

Ported from tempest-react-sdk#667 (comment "Validação no Brasil", column "Brasil (todas)", measured 2026-11-19).

MATCH_QUALITY_REFERENCE_KUBICKA module-attribute

MATCH_QUALITY_REFERENCE_KUBICKA: Final[MatchQualityReferenceSchema] = (
    MatchQualityReferenceSchema(
        name="kubicka",
        source="tempest-react-sdk#667, phase 2 (2026-11-19): Kubicka et al., Zenodo 57731, 100 drives, 247 251 fixes; node scripts/bench-map-matching.mjs",
        note="breaks: 48 in 247 251 fixes. The snap distance there is position to the true route, not to the matched point.",
        positions=247251,
        breaks_per_1000_positions=0.19,
        snap_distance_median_m=3.7,
        sampling_interval_median_s=1.0,
    )
)

The Kubicka et al. dataset (worldwide, ~1 Hz), as matched in #667.

Ported from tempest-react-sdk#667 (comment "Fase 2" and the Brazil table's Kubicka column, measured 2026-11-19).

MATCH_QUALITY_REFERENCES module-attribute

Every reference :func:make_match_quality_router answers with.

BR_CITY_NICKNAMES module-attribute

BR_CITY_NICKNAMES: dict[str, int] = {
    "bh": 3106200,
    "beagá": 3106200,
    "sampa": 3550308,
    "floripa": 4205407,
    "poa": 4314902,
    "bsb": 5300108,
    "jampa": 2507507,
    "sjc": 3549904,
    "rio": 3304557,
}

Common nicknames and abbreviations, normalized on lookup, to IBGE codes.

Belo Horizonte, São Paulo, Florianópolis, Porto Alegre, Brasília, João Pessoa, São José dos Campos and Rio de Janeiro. A short list on purpose: every entry is a word most Brazilians read as that city. In a text it is a one-word name like any other, so it needs a sign of being a place — a locative cue before it ("vou pra bh"), an uppercase first letter ("Rio"), a state after it, or being the whole text ("bh") — and "o bh do time" scores below the default min_score.

BRASILIA_IBGE_CODE module-attribute

BRASILIA_IBGE_CODE: int = 5300108

IBGE code of Brasília, the single municipality of the Federal District.

OSM_DRIVABLE_HIGHWAYS module-attribute

OSM_DRIVABLE_HIGHWAYS: Final[frozenset[str]] = frozenset(
    {
        "motorway",
        "motorway_link",
        "trunk",
        "trunk_link",
        "primary",
        "primary_link",
        "secondary",
        "secondary_link",
        "tertiary",
        "tertiary_link",
        "unclassified",
        "residential",
        "living_street",
        "service",
        "road",
    }
)

highway values kept by default: roads a motor vehicle drives.

Footways, cycleways, paths, steps and tracks are left out; pass highways=None to keep every way that has a highway tag.

OSM_GEOJSON_COORDINATE_DIGITS module-attribute

OSM_GEOJSON_COORDINATE_DIGITS: Final[int] = 7

Decimals a GeoJSON vertex is rounded to before vertices are joined.

Seven decimals is ~1 cm, the precision OSM stores coordinates at.

OSM_GRAPH_CACHE_SIZE module-attribute

OSM_GRAPH_CACHE_SIZE: Final[int] = 8

Graphs :func:load_road_graph keeps in memory, least recently used out.

DEFAULT_OVERPASS_AMENITY_TYPES module-attribute

DEFAULT_OVERPASS_AMENITY_TYPES: Final[tuple[str, ...]] = (
    "restaurant",
    "cafe",
    "bar",
    "pub",
    "fast_food",
    "ice_cream",
    "pharmacy",
    "clinic",
    "hospital",
    "dentist",
    "doctors",
    "veterinary",
    "bank",
    "fuel",
    "school",
    "library",
    "cinema",
    "theatre",
    "post_office",
    "marketplace",
)

Default OSM amenity values queried alongside shop elements.

DEFAULT_OVERPASS_RETRY_STATUSES module-attribute

DEFAULT_OVERPASS_RETRY_STATUSES: Final[frozenset[int]] = frozenset({429, 502, 503, 504})

HTTP status codes retried by default against an Overpass server.

DEFAULT_OVERPASS_URL module-attribute

DEFAULT_OVERPASS_URL: Final[str] = 'https://overpass-api.de/api/interpreter'

Public OpenStreetMap Overpass API interpreter endpoint.

ROAD_GRID_CELL_M module-attribute

ROAD_GRID_CELL_M: Final[float] = 50.0

Edge length of a cell of the spatial index, in metres.

Ported from tempest-react-sdk's ROAD_GRID_CELL_M. Each segment is registered in the cells it passes through (sampled at this step), so a long motorway segment costs cells along its length, not across its bounding box.

DEFAULT_DENSITY_BLOCK_CELLS module-attribute

DEFAULT_DENSITY_BLOCK_CELLS: Final[int] = 5

Side of a k-anonymity block, in cells: 5 x 5 m = 25 m.

k is decided per block, not per 5 m cell: with GPS noise a device spreads its points over several cells across the road, so k distinct devices in one 5 m cell is rare where k in a 25 m block is not. Measured on the synthetic street of scripts/bench_geo_traffic.py (k 5, sigma 5 m): deciding per cell, 20 trips a day gave no candidate and 40 recovered the street; per block, 12 trips recover 77% of it and 20 all of it. Counts stay per cell.

DEFAULT_DENSITY_CELL_M module-attribute

DEFAULT_DENSITY_CELL_M: Final[float] = 5.0

Side of a density cell, metres: finer than a lane, coarser than GPS noise.

DEFAULT_DENSITY_EPOCH_SECONDS module-attribute

DEFAULT_DENSITY_EPOCH_SECONDS: Final[int] = 86400

Epoch of the density hashes: one day, then only counts remain.

DEFAULT_OFF_ROAD_M module-attribute

DEFAULT_OFF_ROAD_M: Final[float] = 20.0

Distance from every road beyond which a position counts as off-road.

The phase-0 measurement of tempest-react-sdk#667 (Kubicka et al., 247 251 fixes) found 9.4% of fixes farther than 20 m from any road of their OSM excerpt, and 90.6% within it: the raw signal of a road the base lacks.

DEFAULT_OSRM_MAX_POINTS module-attribute

DEFAULT_OSRM_MAX_POINTS: int = 500

Most points :meth:OSRMBackend.route_through sends in one request.

Matches the public demo at router.project-osrm.org, measured on 2026-11-18: a /route request with 500 coordinates answered "Ok" and one with 501 answered {"code": "TooBig", "message": "Number of entries 501 is higher than current maximum (500)"}. A self-hosted osrm-routed sets its own cap with --max-viaroute-size; pass max_points to :class:OSRMBackend to match it, so the refusal is a local ValueError naming the limit instead of a round trip that fails.

DEFAULT_GRID_DECIMAL_PLACES module-attribute

DEFAULT_GRID_DECIMAL_PLACES: int = 2

Default number of decimal places for spatial grid cells (~1.11 km per step).

DEFAULT_TRAFFIC_EVENT module-attribute

DEFAULT_TRAFFIC_EVENT: Final[str] = 'traffic_updated'

SSE event name :meth:TrafficAggregator.flush sends after a new snapshot.

DEFAULT_TRAFFIC_PRIVACY module-attribute

DEFAULT_TRAFFIC_PRIVACY: Final[TrafficPrivacy] = TrafficPrivacy()

k 5, 5-minute window, 200 m trim, 5-minute trip gap, 50 m accuracy.

DEFAULT_TRAFFIC_SNAPSHOT_KEY module-attribute

DEFAULT_TRAFFIC_SNAPSHOT_KEY: Final[str] = 'geo:traffic:snapshot'

Redis key :class:RedisTrafficSnapshotStore writes the snapshot under.

TRAFFIC_MIN_DEVICES_FLOOR module-attribute

TRAFFIC_MIN_DEVICES_FLOOR: Final[int] = 2

Least min_devices accepted: one device per edge is not anonymity.

TrafficAudienceResolver module-attribute

TrafficAudienceResolver = Callable[[], Awaitable[Sequence[str]]]

Answers the SSE channels (usually user ids) told that traffic changed.

TrafficDimensionsResolver module-attribute

TrafficDimensionsResolver = Callable[..., Awaitable[Mapping[str, str] | None]]

FastAPI dependency answering a trip's coarse quality dimensions, or None.

Given to make_live_position_router(traffic_dimensions=...).

TRAFFIC_INVALID_BBOX_ERROR module-attribute

TRAFFIC_INVALID_BBOX_ERROR: Final[str] = (
    "min_latitude must not exceed max_latitude, nor min_longitude max_longitude"
)

Message of the 422 answered for an inverted bounding box.

BRMapLegendEntry dataclass

BRMapLegendEntry(level: int, low: int, high: int)

One shade of the state fill, with the values it covers.

Attributes:

Name Type Description
level int

The shade, 1 (lightest) to levels (darkest); the state's CSS class is tempest-br-map__state--l{level}.

low int

The smallest value shaded at this level.

high int

The largest value shaded at this level.

BRMapPoint dataclass

BRMapPoint(label: str, coordinate: Coordinate, value: int)

One bubble on the map.

Attributes:

Name Type Description
label str

What the bubble's tooltip names ("São Paulo (SP)").

coordinate Coordinate

Where it is drawn.

value int

What it counts; sets the bubble's area. 0 or less draws nothing.

CachedGeocodingBackend

CachedGeocodingBackend(
    *,
    backend: GeocodingBackend,
    store: GeocodeCacheStore,
    precision: int = DEFAULT_GEOCODE_CACHE_PRECISION,
    ttl_seconds: int = DEFAULT_GEOCODE_CACHE_TTL_SECONDS,
    key_prefix: str = DEFAULT_GEOCODE_CACHE_KEY_PREFIX,
    cache_misses: bool = False,
)

A :class:~tempest_fastapi_sdk.geo.GeocodingBackend that answers from a cache.

Wraps any backend — :class:~tempest_fastapi_sdk.geo.NominatimBackend being the one worth wrapping — and consults store before touching the network. Parameters are keyword-only.

Privacy: reverse rounds the coordinate to precision places before building the key and before calling the wrapped backend, so the exact GPS reading never leaves the process — not in the key, not on the wire. geocode keys by a SHA-256 of the trimmed, casefolded query, so the text a user typed never appears in a key either.

Failure policy: any exception from store.get/store.set is logged at WARNING and the lookup continues as if the cache were empty — the cache is quota protection, not a source of truth. An exception from the wrapped backend propagates unchanged.

Attributes:

Name Type Description
precision int

Decimal places used to round the coordinate.

ttl_seconds int

Lifetime given to every entry this backend writes.

key_prefix str

First segment of every key it builds.

cache_misses bool

Whether "the backend found nothing" is cached too.

Wrap a backend with a cache in front of it.

Parameters:

Name Type Description Default
backend GeocodingBackend

Where to go on a miss. Its exceptions are the caller's to handle, unchanged.

required
store GeocodeCacheStore

Where entries live. Any object with the two :class:GeocodeCacheStore methods.

required
precision int

Decimal places of the coordinate rounding in reverse (3 ≈ 111 m, 4 ≈ 11 m, 5 ≈ 1 m). The rounded value is both the key and what the backend is asked.

DEFAULT_GEOCODE_CACHE_PRECISION
ttl_seconds int

Lifetime of each entry. Defaults to 30 days (:data:DEFAULT_GEOCODE_CACHE_TTL_SECONDS), long enough that a device fleet settles into hits and short enough that a corrected place is not pinned forever.

DEFAULT_GEOCODE_CACHE_TTL_SECONDS
key_prefix str

Namespace for every key (<prefix>:reverse:v1:… / <prefix>:search:v1:…).

DEFAULT_GEOCODE_CACHE_KEY_PREFIX
cache_misses bool

When True, a None answer is stored as the empty string too, so "nobody can find this place" stops costing a request. Default False: an answer that may change (a new place opening) is re-asked, and the rare miss is not worth caching.

False

geocode async

geocode(query: str) -> GeocodeResult | None

Resolve free text through the cache, then the wrapped backend.

Parameters:

Name Type Description Default
query str

The address or place text. Passed to the backend unchanged; only the key is normalized (trimmed and casefolded, then hashed).

required

Returns:

Type Description
GeocodeResult | None

The cached or freshly resolved

GeocodeResult | None

class:~tempest_fastapi_sdk.geo.GeocodeResult, or None

GeocodeResult | None

when nothing matched.

Raises:

Type Description
Exception

Whatever the wrapped backend raises — the cache never turns a backend failure into a miss or a partial result, so a caller can rely on its usual error handling.

reverse async

reverse(coordinate: Coordinate) -> GeocodeResult | None

Resolve a coordinate through the cache, then the wrapped backend.

The coordinate is rounded to precision places first: the rounded value is both the cache key and what the backend receives, so two readings of the same house share one entry and the exact reading stays in this process.

Parameters:

Name Type Description Default
coordinate Coordinate

The point to reverse-geocode.

required

Returns:

Type Description
GeocodeResult | None

The cached or freshly resolved

GeocodeResult | None

class:~tempest_fastapi_sdk.geo.GeocodeResult, or None

GeocodeResult | None

when nothing matched.

Raises:

Type Description
Exception

Whatever the wrapped backend raises — the cache never turns a backend failure into a miss or a partial result, so a caller can rely on its usual error handling.

GeocodeCacheStore

Bases: Protocol

Where :class:CachedGeocodingBackend keeps serialized answers.

Both methods deal in strings: the value is a JSON payload, so anything that can hold text can be a store — Redis, an in-process dict, the cache a service already runs. Implement the two methods and the wrapper does the rest.

get async

get(key: str) -> str | None

Return the payload stored under key.

Parameters:

Name Type Description Default
key str

The cache key the wrapper built.

required

Returns:

Type Description
str | None

The stored payload, or None when there is no live entry —

str | None

expired counts as no entry.

Raises:

Type Description
Exception

Any store failure. The wrapper logs it and treats it as a miss, never as an error to the caller.

set async

set(key: str, value: str, ttl_seconds: int) -> None

Store value under key for ttl_seconds.

Parameters:

Name Type Description Default
key str

The cache key the wrapper built.

required
value str

The payload to keep.

required
ttl_seconds int

How long the entry stays live.

required

Raises:

Type Description
Exception

Any store failure. The wrapper logs it and drops the write, the answer still reaching the caller.

InMemoryGeocodeCacheStore

InMemoryGeocodeCacheStore()

A :class:GeocodeCacheStore holding entries in this process.

Expiry is checked on read against :func:time.monotonic, so a wall-clock adjustment never keeps an entry alive or kills one early. The methods do not await, so under asyncio there is no interleaving point and no lock is needed. State is per worker: reach for :class:RedisGeocodeCacheStore the moment more than one process serves traffic.

Start with an empty store.

get async

get(key: str) -> str | None

Return the live payload under key, dropping it when expired.

Parameters:

Name Type Description Default
key str

The cache key to read.

required

Returns:

Type Description
str | None

The stored payload, or None when absent or past its TTL.

set async

set(key: str, value: str, ttl_seconds: int) -> None

Store value under key, expiring after ttl_seconds.

Parameters:

Name Type Description Default
key str

The cache key to write.

required
value str

The payload to keep.

required
ttl_seconds int

How long the entry stays live. 0 expires it on the next read.

required

RedisGeocodeCacheStore

RedisGeocodeCacheStore(client: _GeocodeRedisClient, *, prefix: str = '')

A :class:GeocodeCacheStore over an async Redis client.

Takes the client rather than a manager, like every Redis store the SDK ships: pass AsyncRedisManager.client_proxy when the store is built before the lifespan runs, or AsyncRedisManager.client once inside. Requires the [cache] extra at the call site, never at import time.

Attributes:

Name Type Description
prefix str

Prepended to every key, for services that namespace their own Redis keys. The wrapper's keys already start with geocoding:, so the default adds nothing.

Wrap a connected (or proxy) async Redis client.

Parameters:

Name Type Description Default
client _GeocodeRedisClient

Anything with async get/set shaped like redis.asyncio.Redis — typically AsyncRedisManager.client_proxy.

required
prefix str

Optional namespace prepended to every key.

''

get async

get(key: str) -> str | None

Read the key, decoding a bytes reply to text.

Parameters:

Name Type Description Default
key str

The cache key to read.

required

Returns:

Type Description
str | None

The stored payload, or None on a miss. A client built with

str | None

decode_responses=False (the default) answers bytes, which

str | None

are decoded here so callers always see text.

set async

set(key: str, value: str, ttl_seconds: int) -> None

Write the key with ex=ttl_seconds.

Parameters:

Name Type Description Default
key str

The cache key to write.

required
value str

The payload to keep.

required
ttl_seconds int

How long the entry stays live.

required

GeoPointMixin

Mixin adding an indexed latitude / longitude point to a model.

Mix it into a concrete model alongside :class:~tempest_fastapi_sdk.BaseModel::

class StoreModel(GeoPointMixin, BaseModel):
    __tablename__ = "stores"
    name: Mapped[str] = mapped_column(String(120))

A composite index on (latitude, longitude) backs the bounding-box pre-filter of :meth:GeoRepositoryMixin.nearby.

Attributes:

Name Type Description
latitude float

Latitude in decimal degrees (WGS84).

longitude float

Longitude in decimal degrees (WGS84).

coordinate

coordinate() -> Coordinate

Return this row's point as a :class:Coordinate.

Returns:

Type Description
Coordinate

The row's latitude/longitude as a coordinate.

GeoRepositoryMixin

Repository mixin adding a database-agnostic radius search.

Mix into a :class:~tempest_fastapi_sdk.BaseRepository for a model that carries latitude / longitude columns (e.g. via :class:GeoPointMixin)::

class StoreRepository(GeoRepositoryMixin, BaseRepository[StoreModel]):
    ...

:meth:nearby first narrows rows to the radius' bounding box in SQL (indexed, cheap), then computes the exact Haversine distance in Python and drops the box corners that fall outside the circle.

nearby async

nearby(
    center: Coordinate,
    radius_km: float,
    *,
    extra_filters: dict[str, Any] | None = None,
    limit: int | None = None,
    latitude_field: str = "latitude",
    longitude_field: str = "longitude",
) -> list[Any]

Return rows within radius_km of center, nearest first.

Parameters:

Name Type Description Default
center Coordinate

The circle centre.

required
radius_km float

The inclusive radius in kilometres.

required
extra_filters dict[str, Any] | None

Optional additional repository filters (ANDed).

None
limit int | None

Optional cap on the number of rows returned.

None
latitude_field str

Name of the latitude column.

'latitude'
longitude_field str

Name of the longitude column.

'longitude'

Returns:

Type Description
list[Any]

The matching rows sorted by ascending distance ([] when none

list[Any]

match).

paginate_nearby async

paginate_nearby(
    center: Coordinate,
    radius_km: float,
    *,
    page: int = 1,
    page_size: int = 20,
    extra_filters: dict[str, Any] | None = None,
    query: Select[Any] | None = None,
    where: WhereClause | None = None,
    latitude_field: str = "latitude",
    longitude_field: str = "longitude",
) -> dict[str, Any]

Return one page of rows within radius_km, nearest first, in SQL.

Where :meth:nearby loads the whole bounding box and sorts in Python — so paginating it means paginating in memory — this method keeps everything in the database: the distance is :func:haversine_distance_sql, the radius is a WHERE on it (behind the indexable bounding-box pre-filter), and the sort, COUNT and OFFSET / LIMIT all run there. Ties on distance break on id, so pages stay stable.

Rows whose latitude or longitude is NULL never match. The bounding box is clamped at the antimeridian, exactly as in :meth:nearby, so a circle crossing longitude ±180 misses the far side.

Parameters:

Name Type Description Default
center Coordinate

The circle centre.

required
radius_km float

The inclusive radius in kilometres.

required
page int

The 1-indexed page number.

1
page_size int

Rows per page. Subject to the repository's max_page_size when one is set.

20
extra_filters dict[str, Any] | None

Repository filters ANDed with the radius (same vocabulary as :meth:~tempest_fastapi_sdk.BaseRepository.paginate).

None
query Select[Any] | None

A pre-built Select whose first entity is the model; None starts from select(model). The distance column is appended to it.

None
where WhereClause | None

A :class:~tempest_fastapi_sdk.Q condition tree ANDed with the rest.

None
latitude_field str

Name of the latitude column.

'latitude'
longitude_field str

Name of the longitude column.

'longitude'

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The SDK pagination envelope — items,

dict[str, Any]

total, page, page_size, pages — where each item

dict[str, Any]

is a :class:NearbyMatch (row, distance_km). items is

dict[str, Any]

[] (and total 0) when nothing is in range.

Raises:

Type Description
ValueError

When radius_km is negative, page or page_size is below 1, or either field name is not a mapped column of the model.

PageSizeTooLargeException

When the repository sets max_page_size and page_size exceeds it.

NearbyMatch

Bases: NamedTuple, Generic[RowT]

One row of :meth:GeoRepositoryMixin.paginate_nearby, with its distance.

A named tuple, so it unpacks (for row, distance_km in page["items"]) and reads by name (match.row, match.distance_km). The distance is the value the database computed and sorted by, not a second Python computation that could disagree at the radius boundary.

Attributes:

Name Type Description
row RowT

The model instance.

distance_km float

Great-circle distance from the search centre, in kilometres.

PostGISRepositoryMixin

Repository mixin whose radius search runs entirely in PostGIS.

Mix into a :class:~tempest_fastapi_sdk.BaseRepository when the database is PostgreSQL with the PostGIS extension enabled. :meth:nearby pushes the radius filter and distance sort into SQL via ST_DWithin / ST_Distance over geography points built from the plain latitude / longitude columns — no special column type and no geoalchemy2 dependency.

nearby async

nearby(
    center: Coordinate,
    radius_km: float,
    *,
    limit: int | None = None,
    latitude_field: str = "latitude",
    longitude_field: str = "longitude",
) -> list[Any]

Return rows within radius_km of center, nearest first.

Parameters:

Name Type Description Default
center Coordinate

The circle centre.

required
radius_km float

The inclusive radius in kilometres.

required
limit int | None

Optional cap on the number of rows returned.

None
latitude_field str

Name of the latitude column.

'latitude'
longitude_field str

Name of the longitude column.

'longitude'

Returns:

Type Description
list[Any]

The matching rows ordered by ascending distance.

Raises:

Type Description
ValueError

When either field name is not a mapped column. The two names are interpolated into a text() fragment — the centre coordinates and radius are bound parameters, but a column name cannot be — so they are checked against the mapper rather than trusted. Nothing stops a route from forwarding a query parameter here.

TravelModeEnum

Bases: BaseStrEnum

A way of travelling by road between two points.

Used to pick an average speed (offline heuristic) or to scale a car-only routing result (OSRM public demo). Values are lowercase so they can go straight into an OSRM profile or a query string.

TripRoleEnum

Bases: BaseStrEnum

The part a city plays in a trip request (:func:parse_trip_intent).

Values are the lowercase English words so they can key a JSON object the client reads ({"destination": "natal"}).

GeocodingBackend

Bases: Protocol

A source of forward and reverse geocoding.

geocode async

geocode(query: str) -> GeocodeResult | None

Resolve a free-text address/place to a coordinate, or None.

Parameters:

Name Type Description Default
query str

Free-form address to resolve.

required

Returns:

Type Description
GeocodeResult | None

GeocodeResult | None: The best match, or None when nothing matched.

reverse async

reverse(coordinate: Coordinate) -> GeocodeResult | None

Resolve a coordinate to a place, or None.

Parameters:

Name Type Description Default
coordinate Coordinate

The point to reverse-geocode.

required

Returns:

Type Description
GeocodeResult | None

GeocodeResult | None: The best match, or None when nothing matched.

NominatimBackend

NominatimBackend(
    *,
    http_client: AsyncClient,
    base_url: str = DEFAULT_NOMINATIM_BASE_URL,
    user_agent: str = "tempest-fastapi-sdk",
    language: str | None = None,
    country_codes: Sequence[str] | str | None = None,
    feature_type: str | None = None,
)

Geocode through a Nominatim (OpenStreetMap) HTTP server.

Both directions ask for format=jsonv2 with addressdetails=1, so the result carries the structured :class:~tempest_fastapi_sdk.geo.GeocodeAddress (city, state, country, postcode) and :class:~tempest_fastapi_sdk.geo.BoundingBox next to the free-text display_name.

Attributes:

Name Type Description
base_url str

Root URL of the Nominatim server (no trailing slash needed).

user_agent str

Value sent as the User-Agent header (required by the public instance's usage policy).

country_codes str | None

Normalized comma-separated ISO 3166-1 alpha-2 country codes applied as default countrycodes on forward searches, or None when unrestricted.

feature_type str | None

Default Nominatim featureType filter on forward searches (e.g. "settlement"), or None when unrestricted.

Initialize the backend.

Parameters:

Name Type Description Default
http_client AsyncClient

An httpx.AsyncClient the caller owns and closes.

required
base_url str

Root URL of the Nominatim server.

DEFAULT_NOMINATIM_BASE_URL
user_agent str

User-Agent header (identify your app).

'tempest-fastapi-sdk'
language str | None

Optional Accept-Language preference (e.g. "pt-BR").

None
country_codes Sequence[str] | str | None

Optional ISO 3166-1 alpha-2 country code filter (single string such as "BR" / "br,ar" or sequence such as ["BR", "AR"]), sent lowercased and comma-separated as countrycodes on geocode calls.

None
feature_type str | None

Optional Nominatim featureType filter (e.g. "country", "state", "city", "settlement") sent as featureType on geocode calls.

None

geocode async

geocode(
    query: str,
    *,
    country_codes: Sequence[str] | str | None = None,
    feature_type: str | None = None,
) -> GeocodeResult | None

Resolve a free-text address/place to a coordinate.

Parameters:

Name Type Description Default
query str

The address or place text (a street, city, CEP, …).

required
country_codes Sequence[str] | str | None

Optional per-call override for Nominatim's countrycodes query parameter. When omitted (None), falls back to :attr:country_codes. Passing an empty string or empty sequence disables the default filter for this call.

None
feature_type str | None

Optional per-call override for Nominatim's featureType query parameter (e.g. "settlement"). When omitted (None), falls back to :attr:feature_type. Passing an empty string disables the default filter for this call.

None

Returns:

Type Description
GeocodeResult | None

The best :class:~tempest_fastapi_sdk.geo.GeocodeResult, or

GeocodeResult | None

None when nothing matches.

Raises:

Type Description
RuntimeError

If the request fails.

Notes

Any transport or parse failure is normalised into the backend's own error type, so callers branch on one exception instead of on httpx internals.

reverse async

reverse(coordinate: Coordinate) -> GeocodeResult | None

Resolve a coordinate to the nearest known place.

Parameters:

Name Type Description Default
coordinate Coordinate

The point to reverse-geocode.

required

Returns:

Name Type Description
A GeocodeResult | None

class:~tempest_fastapi_sdk.geo.GeocodeResult, or None

GeocodeResult | None

when the server reports no match.

Raises:

Type Description
RuntimeError

If the request fails.

Notes

Any transport or parse failure is normalised into the backend's own error type, so callers branch on one exception instead of on httpx internals.

LiveEtaSchema

Bases: BaseSchema

Distance and time from the live position to one recipient's target.

Attributes:

Name Type Description
target Coordinate

The recipient's target point (a boarding stop, a door).

distance_km NonNegativeFloatField

Road distance to the target, in kilometers.

duration_minutes NonNegativeFloatField

Travel time to the target, in minutes.

source str

"osrm" (or whatever the routing backend stamps) when the matrix answered; "heuristic" when there is no backend or it failed and :func:~tempest_fastapi_sdk.geo.estimate_travel stood in.

LivePositionEventSchema

Bases: BaseSchema

The SSE payload one recipient gets for an accepted position.

Attributes:

Name Type Description
channel_id str

The channel (trip, delivery, vehicle) the position belongs to.

position LivePositionSchema

The accepted position.

eta LiveEtaSchema | None

This recipient's ETA to their own target, when the store was given eta_targets and the recipient has a target.

LivePositionSchema

Bases: BaseSchema

One position reported by a moving device.

Attributes:

Name Type Description
lat LatitudeField

Latitude in decimal degrees, within [-90, 90].

lng LongitudeField

Longitude in decimal degrees, within [-180, 180].

accuracy_m NonNegativeFloatField | None

Horizontal accuracy radius reported by the device, in meters.

speed_kmh NonNegativeFloatField | None

Ground speed, in km/h.

heading float | None

Direction of travel in degrees clockwise from true north, within [0, 360).

recorded_at AwareDatetime

When the device took the fix. Timezone-aware; refused when more than :data:LIVE_POSITION_MAX_CLOCK_SKEW ahead of the server clock.

coordinate property

coordinate: Coordinate

Return the position as a :class:Coordinate.

Returns:

Name Type Description
Coordinate Coordinate

lat/lng as latitude/longitude.

LivePositionStore

LivePositionStore(
    redis: _LivePositionRedisClient,
    *,
    key_prefix: str = DEFAULT_LIVE_POSITION_KEY_PREFIX,
    ttl_seconds: int = DEFAULT_LIVE_POSITION_TTL_SECONDS,
    min_interval_seconds: float = DEFAULT_LIVE_POSITION_INTERVAL_SECONDS,
    min_distance_m: float = DEFAULT_LIVE_POSITION_MIN_DISTANCE_M,
    broker: SSEBroker | None = None,
    audience: AudienceResolver | None = None,
    event_name: str = DEFAULT_LIVE_POSITION_EVENT,
    cleared_event_name: str = DEFAULT_LIVE_POSITION_CLEARED_EVENT,
    eta_targets: EtaTargetsResolver | None = None,
    routing: RoutingBackend | None = None,
    mode: TravelModeEnum = CAR,
    clock: Callable[[], float] = time,
)

Latest position per channel in Redis, delivered to a resolved audience.

Takes the client rather than a manager: pass AsyncRedisManager.client_proxy when the store is built before the lifespan runs, or AsyncRedisManager.client once inside.

The acceptance check reads the previous position and then writes the new one, two round trips with no lock between them. Two positions for the same channel arriving at the same instant can both pass the throttle; that costs one extra event, never a wrong position, and a channel has a single sender in the use this is built for.

Attributes:

Name Type Description
key_prefix str

First segment of every key.

ttl_seconds int

Lifetime of the latest position.

min_interval_seconds float

Throttle between accepted positions.

min_distance_m float

Least movement for a position to be accepted.

event_name str

SSE event name of an accepted position.

cleared_event_name str

SSE event name :meth:clear sends.

mode TravelModeEnum

Travel mode of the ETA.

Initialize the store.

Parameters:

Name Type Description Default
redis _LivePositionRedisClient

Async Redis client (from the [cache] extra) or a compatible one.

required
key_prefix str

First segment of every key ("<prefix>:<channel_id>"). Give each service its own when they share a Redis.

DEFAULT_LIVE_POSITION_KEY_PREFIX
ttl_seconds int

Lifetime of the latest position, renewed by every accepted position and by every refused-as-too-close one, so a sender standing still stays visible.

DEFAULT_LIVE_POSITION_TTL_SECONDS
min_interval_seconds float

Least server time between two accepted positions on one channel. 0 disables the throttle.

DEFAULT_LIVE_POSITION_INTERVAL_SECONDS
min_distance_m float

Least movement from the latest accepted position. 0 disables the check.

DEFAULT_LIVE_POSITION_MIN_DISTANCE_M
broker SSEBroker | None

Where accepted positions are published. None keeps the store silent (Redis only).

None
audience AudienceResolver | None

Called with the channel id on every delivery; answers the broker channels (usually user ids, the default channel of :func:~tempest_fastapi_sdk.make_sse_router) allowed to see it. Required with broker; an empty answer delivers to nobody.

None
event_name str

SSE event name of an accepted position.

DEFAULT_LIVE_POSITION_EVENT
cleared_event_name str

SSE event name :meth:clear sends.

DEFAULT_LIVE_POSITION_CLEARED_EVENT
eta_targets EtaTargetsResolver | None

Called with the channel id; answers each recipient's target point. Turns the ETA on. A recipient it names that audience does not is ignored: audience is the only authority on who sees what.

None
routing RoutingBackend | None

Backend whose matrix computes the ETA in one request. None, or a failing backend, falls back to :func:~tempest_fastapi_sdk.geo.estimate_travel.

None
mode TravelModeEnum

Travel mode of the ETA.

CAR
clock Callable[[], float]

Source of server time, in seconds since the epoch, for the throttle. Defaults to :func:time.time, comparable across workers.

time

Raises:

Type Description
ValueError

When broker and audience are not given together, when eta_targets or routing is given without a broker or without eta_targets, or when a threshold is negative or ttl_seconds is lower than 1.

latest async

latest(channel_id: str) -> LivePositionSchema | None

Return the latest accepted position of channel_id.

Parameters:

Name Type Description Default
channel_id str

The channel.

required

Returns:

Type Description
LivePositionSchema | None

LivePositionSchema | None: The position, or None when there

LivePositionSchema | None

is none (never sent, cleared, or expired).

publish async

publish(channel_id: str, position: LivePositionSchema) -> bool

Keep position as the latest of channel_id when it is worth it.

Refused, in order, when: it is not newer than the stored one (recorded_at not after it — a late or replayed fix); less than min_interval_seconds of server time passed since the last accepted one; it moved less than min_distance_m. A position refused for distance still renews the TTL, so a sender standing at a stop does not vanish. An accepted position is written with the TTL and, with a broker, delivered to the audience.

Parameters:

Name Type Description Default
channel_id str

The channel (trip, delivery, vehicle).

required
position LivePositionSchema

The reported position.

required

Returns:

Name Type Description
bool bool

Whether the position was accepted.

clear async

clear(channel_id: str) -> None

End tracking of channel_id: forget the position, tell the audience.

Call it when the trip (delivery, shift) ends. The latest position is deleted at once instead of lingering until the TTL, and, with a broker, every recipient gets :attr:cleared_event_name with {"channel_id": ...} so the client removes the marker.

Parameters:

Name Type Description Default
channel_id str

The channel.

required

LivePositionPublishResponseSchema

Bases: BaseSchema

What POST <prefix>/{channel_id}/position answers.

Attributes:

Name Type Description
accepted bool

Whether the store kept the position. False is not an error: the position was throttled, too close to the last one, or older than it.

BRCityCountSchema

Bases: BaseSchema

How many rows one city has.

Attributes:

Name Type Description
city_ibge_code int

The city's IBGE code.

city str

Its official name.

state str

Its state's acronym.

latitude float

Its municipal seat, or the territory centroid for the five municipalities whose source seat lies outside their territory.

longitude float

Same point as latitude.

count int

Rows with that city.

BRLocationDistributionSchema

Bases: BaseSchema

Rows of a model per state and per city.

Attributes:

Name Type Description
total int

Rows counted.

located int

Rows with a state.

unlocated int

Rows with no state.

states list[BRStateCountSchema]

One entry per state with rows, largest first.

cities list[BRCityCountSchema]

One entry per city with rows, largest first; a row with a state and no IBGE code counts in states only.

state_counts

state_counts() -> dict[str, int]

Return the count of each state, for the map.

Returns:

Type Description
dict[str, int]

dict[str, int]: {"SP": 840, ...}.

BRLocationMixin

Mixin adding a Brazilian city and state to a model.

Mix it into a concrete model alongside :class:~tempest_fastapi_sdk.BaseModel (or BaseUserModel)::

class UserModel(BRLocationMixin, BaseUserModel):
    __tablename__ = "users"

The three columns are nullable, so an existing table gains them with a plain migration and old rows stay valid until they are filled. state and city_ibge_code are indexed: they are what :func:br_location_distribution groups by.

Write through :meth:set_br_location, which stores the official spelling and the IBGE code; assigning the columns by hand skips the check and leaves the row off the city map when the code is missing.

Attributes:

Name Type Description
city str | None

The official IBGE name of the city.

state str | None

The state's two-letter acronym ("SP").

city_ibge_code int | None

The city's seven-digit IBGE code.

set_br_location

set_br_location(
    city: str, state: UFEnum | str, *, typo_cutoff: float | None = None
) -> Municipality

Set the city and state, checked against the IBGE municipalities.

Parameters:

Name Type Description Default
city str

The city name, in any case and with or without accents.

required
state UFEnum | str

The state, as enum or acronym.

required
typo_cutoff float | None

Accept a near spelling at this similarity or above (see :func:resolve_br_municipality).

None

Returns:

Name Type Description
Municipality Municipality

The municipality stored.

Raises:

Type Description
UnknownMunicipalityError

When the state has no such municipality; the row is left unchanged.

clear_br_location

clear_br_location() -> None

Forget the city and state.

br_municipality

br_municipality() -> Municipality | None

Return the stored city's municipality record.

Returns:

Type Description
Municipality | None

Municipality | None: The record, or None when no IBGE code

Municipality | None

is stored.

BRLocationSchema

Bases: BaseSchema

A Brazilian city and state, checked at the API edge.

The city must exist in the state; an unknown one fails validation, so a FastAPI route answers 422 before the handler runs. On success city holds the official spelling and city_ibge_code is filled.

Attributes:

Name Type Description
city str

The city; replaced by its official IBGE name.

state UFEnum

The state.

city_ibge_code int | None

Filled by validation; any value sent is overwritten.

BRStateCountSchema

Bases: BaseSchema

How many rows one state has.

Attributes:

Name Type Description
state str

The state's acronym.

count int

Rows with that state.

UnknownMunicipalityError

UnknownMunicipalityError(city: str, state: str)

Bases: ValueError

The state has no municipality by that name.

Attributes:

Name Type Description
city str

The name that was looked up.

state str

The state it was looked up in.

Build the error.

Parameters:

Name Type Description Default
city str

The name that was looked up.

required
state str

The state it was looked up in.

required

MatchedFix dataclass

MatchedFix(
    edge: RoadEdge,
    edge_index: int,
    reversed: bool,
    directed: int,
    point: Coordinate,
    distance_m: float,
    offset_m: float,
    inferred: bool,
)

Where one fix landed on the network.

Attributes:

Name Type Description
edge RoadEdge

The edge object.

edge_index int

Index of the edge in graph.edges.

reversed bool

Driven end → start.

directed int

Directed edge index in the graph.

point Coordinate

The fix projected onto the edge.

distance_m float

Metres from the fix to point.

offset_m float

Metres from the start of the edge, in the direction of travel, to point.

inferred bool

True for a fix the model skipped (within the spacing of the previous kept fix), projected onto that fix's edge.

MatchedRoute dataclass

MatchedRoute(edges: list[RoadTraversal], first_fix: int, last_fix: int)

One unbroken run of the matched route.

Attributes:

Name Type Description
edges list[RoadTraversal]

Edges driven, in order, consecutive repeats collapsed, including the ones recovered between fixes.

first_fix int

Index of the first fix of this run.

last_fix int

Index of the last fix of this run.

RoadMatchOptions dataclass

RoadMatchOptions(
    sigma_m: float = 7.0,
    beta_m: float = 3.0,
    radius_m: float = 200.0,
    max_candidates: int = 16,
    max_detour_m: float = 100.0,
    detour_per_second_m: float = 2.0,
    max_interval_s: float = 60.0,
    min_spacing_m: float | None = None,
)

Tuning of the hidden Markov model behind :func:match_to_roads.

Attributes:

Name Type Description
sigma_m float

GPS noise, standard deviation in metres.

beta_m float

Scale of the transition, in metres: a move costs |straight - network| / beta_m.

radius_m float

Roads farther than this from a fix are not candidates.

max_candidates int

At most this many nearest roads per fix.

max_detour_m float

A transition whose network distance exceeds the straight line by more than this is impossible; bounds the shortest-path search.

detour_per_second_m float

Extra detour allowed per second between two timed fixes, in metres: the bound becomes straight + max_detour_m + detour_per_second_m * min(dt, max_interval_s). A sparse source (a fix every 5-30 s) turns corners and goes round blocks between fixes, so a bound fixed for 1 Hz breaks the chain on real drives. Applies only when both fixes have a timestamp; 0 turns it off.

max_interval_s float

Intervals longer than this, in seconds, grant no more detour: the slack stops at detour_per_second_m * max_interval_s.

min_spacing_m float | None

A fix closer than this to the previous kept fix skips the model. None is 2 * sigma_m.

spacing_m property

spacing_m: float

The pre-filter distance actually used.

Returns:

Name Type Description
float float

min_spacing_m, or 2 * sigma_m when unset.

RoadMatchResult dataclass

RoadMatchResult(
    matches: list[MatchedFix | None],
    routes: list[MatchedRoute],
    breaks: int,
    dropped: int,
    unmatched: int,
)

Output of :func:match_to_roads.

Attributes:

Name Type Description
matches list[MatchedFix | None]

One per input fix, same order; None when no road was in reach.

routes list[MatchedRoute]

One per unbroken chain.

breaks int

Times the chain broke and restarted.

dropped int

Fixes skipped by the spacing rule.

unmatched int

Fixes with no road within radius_m.

RoadTraversal dataclass

RoadTraversal(edge: RoadEdge, edge_index: int, reversed: bool)

A directed pass over one of the graph's edges.

Attributes:

Name Type Description
edge RoadEdge

The edge object.

edge_index int

Index of the edge in graph.edges.

reversed bool

True when a two-way edge is driven end → start.

MatchQualityCellSchema

Bases: MatchQualityIndicatorsSchema

The indicators of one published cell of a window.

Attributes:

Name Type Description
dimensions dict[str, str]

The cell's dimension values; empty for the total and for other.

devices int

Distinct devices in the cell, at least the k.

MatchQualityIndicatorsSchema

Bases: BaseSchema

The map-matching quality indicators, as tempest-react-sdk#667 defines them.

Every rate has the denominator the reference measurements used, so a window compares directly with :data:MATCH_QUALITY_REFERENCE_KUBICKA and :data:MATCH_QUALITY_REFERENCE_BRAZIL_OSM. None means not measured (or no denominator).

Attributes:

Name Type Description
positions int

Positions measured.

straight_km float

Kilometres of straight track (the denominator of parallel_switches_per_km).

breaks_per_1000_positions float | None

Times the matched chain broke (no possible move between two positions) per 1000 positions.

matched_share float | None

Share of positions with a road within the candidate radius (0 to 1).

inferred_share float | None

Share of positions the matcher skipped by spacing and projected on the previous one's edge.

snap_distance_median_m float | None

Median distance from a position to its matched point, metres.

snap_distance_p90_m float | None

90th percentile of it.

sampling_interval_median_s float | None

Median time between two consecutive kept positions of a trip, seconds.

sampling_interval_p90_s float | None

90th percentile of it.

parallel_switches_per_km float | None

Switches of matched road to a parallel one while the GPS track is straight, per km of straight track.

MatchQualityOptions dataclass

MatchQualityOptions(
    window_seconds: int = DEFAULT_MATCH_QUALITY_WINDOW_SECONDS,
    dimensions: tuple[str, ...] = (),
    max_cells: int = 64,
    max_value_length: int = 32,
)

How :class:~tempest_fastapi_sdk.geo.TrafficAggregator measures quality.

The k of every cell is the aggregator's TrafficPrivacy.min_devices.

Attributes:

Name Type Description
window_seconds int

Length of a window. Windows are aligned to the epoch (floor(now / window_seconds)); only closed ones are published.

dimensions tuple[str, ...]

Names of the coarse dimensions the app may give a trip (("os", "app_version")). A trip without a value for one is counted under "unknown".

max_cells int

Most cells a window holds. Trips of a new combination past it are counted only in the total.

max_value_length int

Longest dimension value accepted.

MatchQualityReferenceSchema

Bases: MatchQualityIndicatorsSchema

A published measurement to compare a window with.

Attributes:

Name Type Description
name str

Short name.

source str

Where the numbers come from, with the command.

note str

What differs from the aggregator's own measure.

MatchQualityReportSchema

Bases: BaseSchema

What GET <prefix> of :func:make_match_quality_router answers.

Attributes:

Name Type Description
snapshot MatchQualitySnapshotSchema

The last closed window.

references list[MatchQualityReferenceSchema]

The measurements to compare it with.

MatchQualitySnapshotSchema

Bases: BaseSchema

The quality of the last closed window, k-anonymous by construction.

overall minus the published cells is exactly other: cells below k are suppressed together (and, when their union is still below k, with the smallest published cells) so the difference never isolates a group smaller than k.

Attributes:

Name Type Description
window_start datetime | None

Start of the window; None before the first window closed.

window_end datetime | None

End of the window.

min_devices int | None

The k it was published under.

dimensions list[str]

The dimension names cells are split by.

overall MatchQualityCellSchema | None

Every measured position of the window; None with fewer than k devices.

cells list[MatchQualityCellSchema]

One per published combination of dimension values.

other MatchQualityCellSchema | None

The suppressed cells together, when there are any.

MatchQualityTracker

MatchQualityTracker(options: MatchQualityOptions, *, min_devices: int)

The open window of quality cells and the last published one.

Owned by :class:~tempest_fastapi_sdk.geo.TrafficAggregator (pass quality= there); usable alone to measure a matcher on stretches you already matched.

Attributes:

Name Type Description
options MatchQualityOptions

The window and the dimensions.

min_devices int

k of every published cell.

Start with no window open and nothing published.

Parameters:

Name Type Description Default
options MatchQualityOptions

The window and the dimensions.

required
min_devices int

k of every published cell (>= 2).

required

Raises:

Type Description
ValueError

When min_devices is below 2.

open_cells property

open_cells: int

Cells of the open window.

Returns:

Name Type Description
int int

How many dimension combinations the open window holds.

cell_of

cell_of(dimensions: Mapping[str, str]) -> tuple[str, ...]

Validate a trip's dimensions into its cell key.

Parameters:

Name Type Description Default
dimensions Mapping[str, str]

Values of declared dimensions.

required

Returns:

Type Description
str

tuple[str, ...]: The values in declared order, "unknown" for

...

the ones not given.

Raises:

Type Description
ValueError

When a name is not declared, or a value is empty or longer than max_value_length.

roll

roll(now: float) -> None

Close the open window when now is past it, and publish it.

Closing computes the published aggregate and drops the salt, the device hashes and the counters.

Parameters:

Name Type Description Default
now float

Server time, epoch seconds.

required

record

record(
    now: float,
    pseudonym: bytes,
    cell: tuple[str, ...],
    graph: RoadGraph,
    points: Sequence[QualityTrackPoint],
    result: RoadMatchResult,
    *,
    skip: int,
) -> None

Fold one matched stretch into its cell of the open window.

Parameters:

Name Type Description Default
now float

Server time, epoch seconds.

required
pseudonym bytes

The device pseudonym (already an HMAC); only its HMAC under the window salt is kept.

required
cell tuple[str, ...]

From :meth:cell_of (() without dimensions).

required
graph RoadGraph

The network the stretch was matched on.

required
points Sequence[QualityTrackPoint]

The stretch, in time order.

required
result RoadMatchResult

match_to_roads of points.

required
skip int

Leading positions already measured with the previous stretch (the tail it was joined to): their match and position are not counted again, but the step from them is.

required

snapshot

snapshot(now: float) -> MatchQualitySnapshotSchema

The last closed window's aggregate.

Parameters:

Name Type Description Default
now float

Server time, epoch seconds (closes a finished window first).

required

Returns:

Name Type Description
MatchQualitySnapshotSchema MatchQualitySnapshotSchema

The aggregate; empty (window_start

MatchQualitySnapshotSchema

None) before the first window closed.

QualityHistogram

QualityHistogram(bounds: Sequence[float])

A histogram with fixed buckets: memory independent of the count.

Buckets are right-closed: (bounds[i - 1], bounds[i]]; values above the last bound go to one overflow bucket. :meth:quantile answers by nearest rank (the same rule as tempest-react-sdk's benchmarks) with the upper bound of the bucket holding that rank, clamped to the largest value seen — so it overestimates by less than one bucket width, and is exact for values that sit on a bound.

Attributes:

Name Type Description
bounds tuple[float, ...]

Upper bounds, increasing.

counts list[int]

One count per bucket plus the overflow.

total int

Values added.

largest float

Largest value added (-inf when empty).

Start empty.

Parameters:

Name Type Description Default
bounds Sequence[float]

Bucket upper bounds, increasing.

required

Raises:

Type Description
ValueError

When bounds is empty or not increasing.

add

add(value: float) -> None

Count one value.

Parameters:

Name Type Description Default
value float

The value; NaN is ignored.

required

merge

merge(other: QualityHistogram) -> None

Add another histogram with the same bounds into this one.

Parameters:

Name Type Description Default
other QualityHistogram

The histogram to add.

required

Raises:

Type Description
ValueError

When the bounds differ.

quantile

quantile(q: float) -> float | None

The q-quantile by nearest rank, at bucket resolution.

Parameters:

Name Type Description Default
q float

Quantile in [0, 1].

required

Returns:

Type Description
float | None

float | None: The bucket's upper bound clamped to the largest

float | None

value (the largest value for the overflow bucket); None when

float | None

empty.

Raises:

Type Description
ValueError

When q is outside [0, 1].

QualityTrackPoint dataclass

QualityTrackPoint(x: float, y: float, t: float)

One position of a released stretch, on the graph's plane.

Attributes:

Name Type Description
x float

Plane x, metres.

y float

Plane y, metres.

t float

Device time, epoch seconds.

Municipality dataclass

Municipality(
    ibge_code: int,
    name: str,
    uf: UFEnum,
    coordinate: Coordinate,
    capital: bool,
    aliases: tuple[str, ...] = (),
    point: Literal["seat", "centroid"] = "seat",
)

A Brazilian municipality.

Attributes:

Name Type Description
ibge_code int

The seven-digit IBGE code.

name str

The official IBGE name.

uf UFEnum

Its state.

coordinate Coordinate

The seat (the town hall's city), or the territory centroid when point says so.

capital bool

Whether it is the state capital.

aliases tuple[str, ...]

Other spellings in use ("Açu" for "Assú").

point Literal['seat', 'centroid']

What coordinate is. "centroid" for the five municipalities whose source seat lies outside their own boundary (Pau D'Arco/PA, São Caitano/PE, São Sebastião da Vargem Alegre/MG, Cerro Azul/PR and Alto Paraíso/PR), the same five and the same coordinates tempest-react-sdk ships with point: "centroid".

MunicipalityMatch dataclass

MunicipalityMatch(
    municipality: Municipality,
    score: float,
    matched_text: str,
    start: int,
    end: int,
    uf_confirmed: bool,
)

A municipality found for a name or in a text.

Attributes:

Name Type Description
municipality Municipality

The match.

score float

1.0 for an exact name with its state confirmed, lower for typos, a missing state or a one-word match with no sign of being a place.

matched_text str

The text that matched, as written.

start int

Offset of matched_text in the input.

end int

Offset just past it.

uf_confirmed bool

Whether the input named the municipality's state next to it.

BoundingBoxPlacesBackend

Bases: PlacesBackend, Protocol

A :class:PlacesBackend that also supports bounding-box queries.

search_bbox async

search_bbox(bbox: BoundingBox) -> list[PlaceSchema]

Find points of interest inside an axis-aligned bounding box.

Parameters:

Name Type Description Default
bbox BoundingBox

Geographic rectangle to query.

required

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Matching places inside bbox. Empty when

list[PlaceSchema]

nothing matches.

OverpassPlacesBackend

OverpassPlacesBackend(
    *,
    user_agent: str,
    base_url: str = DEFAULT_OVERPASS_URL,
    client: HTTPClient | AsyncClient | None = None,
    amenity_types: Sequence[str] = DEFAULT_OVERPASS_AMENITY_TYPES,
    retry_policy: RetryPolicy | None = None,
)

Async Overpass API client implementing :class:PlacesBackend.

Queries OpenStreetMap points of interest (named shop and configured amenity nodes and ways) by radius (:meth:search_nearby), by rectangular bounding box (:meth:search_bbox), or fetches full OSM tags for a single element (:meth:fetch_tags).

When client is omitted, the backend creates and owns an :class:httpx.AsyncClient — use async with backend: or call :meth:aclose when finished. When client is supplied by the caller (either :class:~tempest_fastapi_sdk.HTTPClient or :class:httpx.AsyncClient), ownership stays with the caller and :meth:aclose is a no-op.

Attributes:

Name Type Description
base_url str

Overpass interpreter URL.

user_agent str

Identifying User-Agent header sent on every call.

amenity_types tuple[str, ...]

Validated OSM amenity tag values queried alongside shop elements.

retry_policy RetryPolicy

Backoff and status policy used when running over an :class:httpx.AsyncClient.

Initialize the Overpass places client.

Parameters:

Name Type Description Default
user_agent str

Mandatory identifying User-Agent header (for example "myapp/1.0 (https://myapp.example.com)"). Blank strings and generic HTTP client tokens (python-httpx, curl, wget, ...) raise ValueError because public Overpass rejects them with HTTP 406.

required
base_url str

Overpass API interpreter URL. Defaults to :data:DEFAULT_OVERPASS_URL.

DEFAULT_OVERPASS_URL
client HTTPClient | AsyncClient | None

Optional pre-built client owned by the caller. When None, the backend creates and owns an :class:httpx.AsyncClient. When an :class:~tempest_fastapi_sdk.HTTPClient is passed, retries and circuit breaking are handled by that client.

None
amenity_types Sequence[str]

OSM amenity tag values to query alongside shop elements. Every item must match ^[a-z0-9_]+$ to prevent Overpass QL injection. Pass an empty sequence to query only shop elements.

DEFAULT_OVERPASS_AMENITY_TYPES
retry_policy RetryPolicy | None

Retry policy applied when using an :class:httpx.AsyncClient (injected or owned). Defaults to 3 attempts with exponential backoff on {429, 502, 503, 504}.

None

Raises:

Type Description
ValueError

When user_agent is empty or generic, base_url is blank, any amenity_types entry is invalid, or retry_policy.max_attempts < 1.

aclose async

aclose() -> None

Close the underlying httpx.AsyncClient if this backend owns it.

search_nearby async

search_nearby(
    coordinate: Coordinate, *, radius_m: int = 800, timeout_s: int = 45
) -> list[PlaceSchema]

Search named shops and amenities around coordinate.

Parameters:

Name Type Description Default
coordinate Coordinate

Center coordinate (WGS84).

required
radius_m int

Search radius in meters. Must be strictly positive. Defaults to 800.

800
timeout_s int

Overpass server timeout in seconds. Must be strictly positive. Defaults to 45.

45

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Parsed places within the search radius. Empty

list[PlaceSchema]

when nothing matches.

Raises:

Type Description
ValueError

When radius_m <= 0 or timeout_s <= 0.

HTTPStatusError

When Overpass responds with a non-success status after retries.

HTTPError

When a network error persists across retries.

search_bbox async

search_bbox(bbox: BoundingBox, *, timeout_s: int = 180) -> list[PlaceSchema]

Search named shops and amenities inside bbox in a single query.

Parameters:

Name Type Description Default
bbox BoundingBox

Axis-aligned geographic bounding box.

required
timeout_s int

Overpass server timeout in seconds. Must be strictly positive. Defaults to 180.

180

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Parsed places inside bbox. Empty when

list[PlaceSchema]

nothing matches.

Raises:

Type Description
ValueError

When timeout_s <= 0 or bbox has inverted bounds.

HTTPStatusError

When Overpass responds with a non-success status after retries.

HTTPError

When a network error persists across retries.

fetch_tags async

fetch_tags(osm_id: str, *, timeout_s: int = 30) -> dict[str, str]

Fetch raw OSM tags for a single element identified by osm_id.

Parameters:

Name Type Description Default
osm_id str

Canonical OSM identifier ("node/123", "way/456" or "relation/789"). Strictly validated before interpolating into Overpass QL.

required
timeout_s int

Overpass server timeout in seconds. Must be strictly positive. Defaults to 30.

30

Returns:

Type Description
dict[str, str]

dict[str, str]: Mapping of OSM tag keys to string values, or an

dict[str, str]

empty dictionary when the element is absent or has no tags.

Raises:

Type Description
ValueError

When osm_id is malformed or timeout_s <= 0.

HTTPStatusError

When Overpass responds with a non-success status after retries.

HTTPError

When a network error persists across retries.

PlacesBackend

Bases: Protocol

Protocol for searching points of interest around a coordinate.

:class:OverpassPlacesBackend implements this seam against an Overpass API server, and :class:~tempest_fastapi_sdk.testing.fakes.FakePlacesBackend implements it in memory for offline tests.

search_nearby async

search_nearby(coordinate: Coordinate, *, radius_m: int = 800) -> list[PlaceSchema]

Find points of interest within radius_m meters of coordinate.

Parameters:

Name Type Description Default
coordinate Coordinate

Center point of the search.

required
radius_m int

Search radius in meters. Defaults to 800.

800

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Matching places. Empty when nothing matches.

PlaceSchema

Bases: BaseSchema

Normalized point of interest shared across places backends.

Optional fields default to None (or empty collections) so OpenStreetMap Overpass, Google Places and scraper adapters can populate only the fields each source provides while exposing one contract to callers.

Attributes:

Name Type Description
source str

Provider identifier (for example "overpass").

external_id str

Provider-scoped identifier (for Overpass, "<type>/<id>" such as "node/12345" or "way/67890").

name str

Human-readable place name.

coordinate Coordinate | None

Geographic coordinate of the place (WGS84), when supplied by the provider (may be None on partial detail lookups whose field mask omits coordinates).

address str | None

Formatted street address assembled from provider fields, when available.

categories list[str]

Provider category labels (for Overpass, shop and amenity tag values).

phone str | None

Contact phone number, when available.

website_uri str | None

Public website URL, when available.

rating float | None

Aggregate user rating, when the provider supplies one.

neighborhood str | None

Suburb or neighborhood name, when available.

city str | None

City or municipality name, when available.

state str | None

State or region name, when available.

postal_code str | None

Postal code, when available.

raw_data dict[str, JsonValue]

Raw provider payload preserved for downstream inspection or enrichment.

RoadCandidate

Bases: NamedTuple

A matching candidate: a directed edge and a point projected onto it.

Attributes:

Name Type Description
dir int

Directed edge index.

px float

Projection, plane x in metres.

py float

Projection, plane y in metres.

offset float

Metres from the start of the directed edge to the projection.

distance float

Metres from the point to the projection.

RoadEdge dataclass

RoadEdge(
    start: int,
    end: int,
    two_way: bool | None = None,
    id: str | None = None,
    data: Mapping[str, Any] = dict(),
)

One road segment between two nodes of a :class:RoadGraph.

A road drawn as a polyline is several edges, one per consecutive pair of its vertices: the matcher works on straight segments.

Attributes:

Name Type Description
start int

Index of the start node ("from" on the wire).

end int

Index of the end node ("to" on the wire).

two_way bool | None

Whether the road can also be driven end → start. None takes the graph's default. OpenStreetMap's oneway=no is True here.

id str | None

Stable identifier, the key traffic is reported under ("way/123:4" from :func:road_graph_from_overpass).

data Mapping[str, Any]

Any other field of the app (road class, name, speed limit), returned untouched.

to_dict

to_dict() -> dict[str, Any]

Serialize in the tempest-react-sdk RoadEdge shape.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: {"from", "to", "twoWay"?, "id"?, **data}.

from_dict classmethod

from_dict(raw: Mapping[str, Any]) -> RoadEdge

Parse an edge in the tempest-react-sdk RoadEdge shape.

Parameters:

Name Type Description Default
raw Mapping[str, Any]

{"from", "to", "twoWay"?, "id"?, ...}.

required

Returns:

Name Type Description
RoadEdge RoadEdge

The edge; unknown keys land in data.

Raises:

Type Description
ValueError

When from/to are not integers.

RoadGraph

RoadGraph(
    nodes: Sequence[Coordinate], edges: Sequence[RoadEdge], *, two_way: bool = False
)

A road network ready for matching: nodes, edges, index and adjacency.

Build it once per region and reuse it for every trace — building is the expensive part; querying is cheap. The plane is equirectangular around the centre of the nodes' bounding box: within a city the scale error is a fraction of a percent. Graphs that cross the antimeridian are not supported — split them.

Attributes:

Name Type Description
nodes tuple[Coordinate, ...]

The nodes as given.

edges tuple[RoadEdge, ...]

The edges as given; matches point back into this tuple.

two_way bool

Default for edges that leave two_way unset.

directed_edge_count int

Directed edges after two-way roads are split into both directions.

Build the graph.

Parameters:

Name Type Description Default
nodes Sequence[Coordinate]

Road network vertices, WGS84.

required
edges Sequence[RoadEdge]

Road segments, directed start → end unless two-way.

required
two_way bool

Default for edges that leave two_way unset. False — every edge one-way — is how a source that already lists both directions as separate edges arrives.

False

Raises:

Type Description
ValueError

When an edge refers to a node index that does not exist.

is_two_way

is_two_way(edge_index: int) -> bool

Return whether an input edge is driven in both directions.

Parameters:

Name Type Description Default
edge_index int

Index into :attr:edges.

required

Returns:

Name Type Description
bool bool

The edge's two_way, or the graph default.

reverse_of

reverse_of(directed: int) -> int

Return the opposite direction of a directed edge.

Parameters:

Name Type Description Default
directed int

Directed edge index.

required

Returns:

Name Type Description
int int

The other direction, or -1 on a one-way road.

to_plane

to_plane(coordinate: Coordinate) -> tuple[float, float]

Project a coordinate onto the graph's plane.

Parameters:

Name Type Description Default
coordinate Coordinate

WGS84 point.

required

Returns:

Type Description
tuple[float, float]

tuple[float, float]: (x, y) in metres.

from_plane

from_plane(x: float, y: float) -> Coordinate

Inverse of :meth:to_plane.

Parameters:

Name Type Description Default
x float

Plane x, metres.

required
y float

Plane y, metres.

required

Returns:

Name Type Description
Coordinate Coordinate

The WGS84 point.

node_xy

node_xy(node: int) -> tuple[float, float]

Return a node on the plane.

Parameters:

Name Type Description Default
node int

Node index.

required

Returns:

Type Description
tuple[float, float]

tuple[float, float]: (x, y) in metres.

project_onto

project_onto(directed: int, x: float, y: float) -> RoadCandidate

Project a plane point onto a directed edge, clamped to the segment.

Parameters:

Name Type Description Default
directed int

Directed edge index.

required
x float

Point x, metres.

required
y float

Point y, metres.

required

Returns:

Name Type Description
RoadCandidate RoadCandidate

The candidate for that edge.

candidates_near

candidates_near(x: float, y: float, radius: float, limit: int) -> list[RoadCandidate]

The roads within radius of a point, nearest first, per direction.

limit counts roads (input edges), not directions: a two-way road yields two candidates. Ties keep the scan order of the grid, the same as the TypeScript original, so both pick the same candidates.

Parameters:

Name Type Description Default
x float

Point x, metres.

required
y float

Point y, metres.

required
radius float

Search radius, metres.

required
limit int

Maximum number of roads kept.

required

Returns:

Type Description
list[RoadCandidate]

list[RoadCandidate]: The candidates, nearest road first.

shortest_paths

shortest_paths(
    source: int, targets: Iterable[int], limit: float
) -> tuple[dict[int, float], dict[int, int]]

Bounded Dijkstra from one node until every target is settled.

Stops once every target is settled or the nearest unsettled node is farther than limit.

Parameters:

Name Type Description Default
source int

Start node.

required
targets Iterable[int]

Nodes whose distance is wanted.

required
limit float

Search bound, metres (math.inf for none).

required

Returns:

Type Description
dict[int, float]

tuple[dict[int, float], dict[int, int]]: Distance of every node

dict[int, int]

reached, and the directed edge each was reached by (absent for

tuple[dict[int, float], dict[int, int]]

the source).

path_to

path_to(prev: Mapping[int, int], node: int) -> list[int]

Directed edges of the shortest path to node, in travel order.

Parameters:

Name Type Description Default
prev Mapping[int, int]

The predecessor map of :meth:shortest_paths.

required
node int

A node it reached.

required

Returns:

Type Description
list[int]

list[int]: Directed edge indices; empty when node is the

list[int]

source.

distance_to_road_m

distance_to_road_m(coordinate: Coordinate, radius_m: float) -> float | None

Distance from a point to the nearest road, within radius_m.

Parameters:

Name Type Description Default
coordinate Coordinate

The point.

required
radius_m float

Search radius, metres.

required

Returns:

Type Description
float | None

float | None: Metres to the nearest edge, or None when no

float | None

edge is within radius_m.

edge_coordinates

edge_coordinates(directed: int) -> tuple[Coordinate, Coordinate]

Start and end of a directed edge, in travel order.

Parameters:

Name Type Description Default
directed int

Directed edge index.

required

Returns:

Type Description
tuple[Coordinate, Coordinate]

tuple[Coordinate, Coordinate]: (start, end).

edge_key

edge_key(directed: int) -> str

Stable key of a directed edge: its id (or index) and direction.

Parameters:

Name Type Description Default
directed int

Directed edge index.

required

Returns:

Name Type Description
str str

"<id>" forward, "<id>~" reversed; <id> falls back

str

to "#<index>" when the edge has no id.

extract

extract(bbox: BoundingBox) -> RoadGraph

The sub-graph of edges with an end inside bbox — one tile.

Nodes are re-indexed; edge id and data are kept, so traffic keyed by :meth:edge_key still lines up with the tile.

Parameters:

Name Type Description Default
bbox BoundingBox

The tile.

required

Returns:

Name Type Description
RoadGraph RoadGraph

The tile's graph, same two_way default.

to_dict

to_dict() -> dict[str, Any]

Serialize in the tempest-react-sdk createRoadGraph input shape.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: ``{"nodes": [{"latitude", "longitude"}],

dict[str, Any]

"edges": [{"from", "to", ...}], "twoWay": bool}``.

from_dict classmethod

from_dict(raw: Mapping[str, Any]) -> RoadGraph

Build a graph from the tempest-react-sdk createRoadGraph shape.

Parameters:

Name Type Description Default
raw Mapping[str, Any]

{"nodes", "edges", "twoWay"?}.

required

Returns:

Name Type Description
RoadGraph RoadGraph

The graph.

OffRoadDensity

OffRoadDensity(
    reference: Coordinate,
    *,
    cell_m: float = DEFAULT_DENSITY_CELL_M,
    off_road_m: float = DEFAULT_OFF_ROAD_M,
    min_devices: int = 5,
    block_cells: int = DEFAULT_DENSITY_BLOCK_CELLS,
    epoch_seconds: int = DEFAULT_DENSITY_EPOCH_SECONDS,
)

k-anonymous density of off-road positions on a fixed metric grid.

The grid is anchored at reference (equirectangular, metres), not at any graph, so a persisted density stays valid when the road extract is reloaded or redrawn.

Attributes:

Name Type Description
reference Coordinate

Origin of the grid.

cell_m float

Side of a cell, metres.

off_road_m float

Distance from every road beyond which a position is counted.

min_devices int

Distinct devices a privacy block needs in one epoch for its cells to be committed.

block_cells int

Side of a privacy block, in cells: k-anonymity is decided per block (block_cells * cell_m metres, 25 m by default), counts are kept per cell.

epoch_seconds int

Length of an epoch (life of a salt).

cells dict[Cell, tuple[int, int]]

Committed (points, devices) per cell; devices sums the per-epoch distinct counts of the cell's block.

Start an empty density.

Parameters:

Name Type Description Default
reference Coordinate

Origin of the grid (the city centre).

required
cell_m float

Side of a cell, metres.

DEFAULT_DENSITY_CELL_M
off_road_m float

Off-road threshold, metres.

DEFAULT_OFF_ROAD_M
min_devices int

k for a block to be committed (>= 2).

5
block_cells int

Side of a privacy block, in cells (>= 1).

DEFAULT_DENSITY_BLOCK_CELLS
epoch_seconds int

Length of an epoch, seconds.

DEFAULT_DENSITY_EPOCH_SECONDS

Raises:

Type Description
ValueError

When min_devices is below 2 or a size is not positive.

cell_of

cell_of(coordinate: Coordinate) -> Cell

The cell a coordinate falls in.

Parameters:

Name Type Description Default
coordinate Coordinate

The point.

required

Returns:

Name Type Description
Cell Cell

Column and row.

centre_of

centre_of(cell: Cell) -> Coordinate

The coordinate of a cell's centre.

Parameters:

Name Type Description Default
cell Cell

Column and row.

required

Returns:

Name Type Description
Coordinate Coordinate

Its centre.

add

add(device_key: bytes, coordinate: Coordinate, t: float) -> None

Count one off-road position (the aggregator calls this).

Parameters:

Name Type Description Default
device_key bytes

The device pseudonym (already an HMAC).

required
coordinate Coordinate

The position.

required
t float

Device time, epoch seconds.

required

roll

roll(now: float) -> None

Commit every epoch that ended before now; drop its hashes.

Blocks with fewer than min_devices distinct devices in the epoch are discarded with their cells, not carried over.

Parameters:

Name Type Description Default
now float

Server time, epoch seconds.

required

to_dict

to_dict() -> dict[str, Any]

The committed counts, safe to persist (no device data).

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Grid parameters and ``[[col, row, points,

dict[str, Any]

devices], ...]``.

from_dict classmethod

from_dict(raw: Mapping[str, Any]) -> OffRoadDensity

Restore what :meth:to_dict wrote.

Parameters:

Name Type Description Default
raw Mapping[str, Any]

The persisted dict.

required

Returns:

Name Type Description
OffRoadDensity OffRoadDensity

The density, with its committed cells.

RoadCandidateSchema

Bases: BaseSchema

A road the fleet drives that the graph does not have — for review.

Attributes:

Name Type Description
status Literal['candidate']

Always "candidate": nothing enters the map without a person accepting it.

coordinates list[Coordinate]

The inferred centreline.

length_m float

Its length.

points int

Off-road positions behind it.

devices int

Largest committed device count of its cells (per-epoch distinct devices, summed over epochs).

novel_fraction float

Share of the line farther than off_road_m from every road of the graph.

OSRMBackend

OSRMBackend(
    *,
    http_client: AsyncClient,
    base_url: str = DEFAULT_OSRM_BASE_URL,
    mode_duration_factors: dict[TravelModeEnum, float] | None = None,
    mode_profiles: dict[TravelModeEnum, str] | None = None,
    max_points: int = DEFAULT_OSRM_MAX_POINTS,
)

Route trips through an OSRM HTTP server.

Attributes:

Name Type Description
base_url str

Root URL of the OSRM server (no trailing slash needed).

max_points int

Most points :meth:route_through sends in one request.

Initialize the backend.

Parameters:

Name Type Description Default
http_client AsyncClient

An httpx.AsyncClient the caller owns and closes.

required
base_url str

Root URL of the OSRM server.

DEFAULT_OSRM_BASE_URL
mode_duration_factors dict[TravelModeEnum, float] | None

Optional per-mode duration multiplier map applied to the car duration for non-car modes.

None
mode_profiles dict[TravelModeEnum, str] | None

Optional per-mode OSRM profile map (override when self-hosting foot/bike profiles); falls back to :data:DEFAULT_MODE_PROFILES (all driving).

None
max_points int

Most points :meth:route_through accepts; defaults to :data:DEFAULT_OSRM_MAX_POINTS. Raise it only when your own server allows more.

DEFAULT_OSRM_MAX_POINTS

Raises:

Type Description
ValueError

If max_points is lower than 2.

route async

route(
    origin: Coordinate,
    destination: Coordinate,
    *,
    mode: TravelModeEnum = CAR,
    with_geometry: bool = False,
) -> TravelEstimate

Fetch a real road route and scale it for the requested mode.

The route is fetched from OSRM; distance is used as-is and the duration is multiplied by the mode's duration factor. Pass with_geometry=True to also decode the route polyline into :attr:TravelEstimate.geometry.

Parameters:

Name Type Description Default
origin Coordinate

The starting coordinate.

required
destination Coordinate

The ending coordinate.

required
mode TravelModeEnum

The travel mode to estimate for.

CAR
with_geometry bool

Whether to include the decoded route geometry.

False

Returns:

Name Type Description
A TravelEstimate

class:TravelEstimate with source="osrm".

Raises:

Type Description
RuntimeError

If the request fails, OSRM finds no route, or the route lacks its distance / duration.

Notes

Any transport or parse failure is normalised into the backend's own error type, so callers branch on one exception instead of on httpx internals.

route_through async

route_through(
    points: Sequence[Coordinate],
    *,
    mode: TravelModeEnum = CAR,
    with_geometry: bool = False,
) -> RouteThroughResult

Fetch one road route through every point, in order, in one request.

Sends all points to OSRM's /route service, which answers the whole route plus one leg per consecutive pair. Distances are used as-is; every duration (total and per leg) is multiplied by the mode's duration factor, exactly like :meth:route. The legs carry no geometry; with_geometry=True decodes the full route polyline into :attr:RouteThroughResult.geometry.

Parameters:

Name Type Description Default
points Sequence[Coordinate]

The ordered points (origin, stops, destination). Between 2 and :attr:max_points.

required
mode TravelModeEnum

The travel mode to estimate for.

CAR
with_geometry bool

Whether to include the decoded route geometry.

False

Returns:

Name Type Description
A RouteThroughResult

class:RouteThroughResult with source="osrm" and

RouteThroughResult

len(points) - 1 legs, each with source="osrm".

Raises:

Type Description
ValueError

If fewer than two points, or more than :attr:max_points, are given. Raised before any request.

RuntimeError

If the request fails, OSRM finds no route, the answer does not carry one leg per stretch, or a leg or the route lacks its distance / duration.

Notes

Any transport or parse failure is normalised into the backend's own error type, so callers branch on one exception instead of on httpx internals.

matrix async

matrix(
    sources: list[Coordinate],
    destinations: list[Coordinate] | None = None,
    *,
    mode: TravelModeEnum = CAR,
) -> DistanceMatrix

Fetch a many-to-many distance/duration matrix in one request.

Uses the OSRM table service. When destinations is None the matrix is square (every source to every other source), matching OSRM's default. Durations are scaled per mode like :meth:route.

Parameters:

Name Type Description Default
sources list[Coordinate]

The origin coordinates (matrix rows).

required
destinations list[Coordinate] | None

The destination coordinates (matrix columns); defaults to sources (a full square matrix).

None
mode TravelModeEnum

The travel mode to estimate for.

CAR

Returns:

Name Type Description
A DistanceMatrix

class:DistanceMatrix with distances_km and

DistanceMatrix

durations_minutes grids.

Raises:

Type Description
ValueError

If sources is empty.

RuntimeError

If the request fails or OSRM returns no table.

Notes

Any transport or parse failure is normalised into the backend's own error type, so callers branch on one exception instead of on httpx internals.

RoutingBackend

Bases: Protocol

A source of real road distance and duration between points.

:class:OSRMBackend implements it against an OSRM server and :class:~tempest_fastapi_sdk.testing.fakes.FakeRoutingBackend offline.

route async

route(
    origin: Coordinate, destination: Coordinate, *, mode: TravelModeEnum = CAR
) -> TravelEstimate

Return a road :class:TravelEstimate for the given trip.

Parameters:

Name Type Description Default
origin Coordinate

Where the trip starts.

required
destination Coordinate

Where it ends.

required
mode TravelModeEnum

The travel mode to estimate for.

CAR

Returns:

Name Type Description
TravelEstimate TravelEstimate

Distance and duration for that leg.

route_through async

route_through(
    points: Sequence[Coordinate],
    *,
    mode: TravelModeEnum = CAR,
    with_geometry: bool = False,
) -> RouteThroughResult

Return a route through two or more points, with one leg per stretch.

Parameters:

Name Type Description Default
points Sequence[Coordinate]

The ordered points (origin, stops, destination).

required
mode TravelModeEnum

The travel mode to estimate for.

CAR
with_geometry bool

Whether to include the route geometry.

False

Returns:

Name Type Description
RouteThroughResult RouteThroughResult

Totals plus one leg per consecutive pair.

matrix async

matrix(
    sources: list[Coordinate],
    destinations: list[Coordinate] | None = None,
    *,
    mode: TravelModeEnum = CAR,
) -> DistanceMatrix

Return a many-to-many distance/duration matrix.

Parameters:

Name Type Description Default
sources list[Coordinate]

The origin coordinates (rows).

required
destinations list[Coordinate] | None

The destination coordinates (columns); None means sources.

None
mode TravelModeEnum

The travel mode to estimate for.

CAR

Returns:

Name Type Description
DistanceMatrix DistanceMatrix

Distances and durations per pair.

BoundingBox

Bases: BaseSchema

An axis-aligned latitude/longitude box (a coarse spatial pre-filter).

A box is cheap to test in SQL (lat BETWEEN ? AND ? AND lon BETWEEN ? AND ?), so it is the fast first pass of a radius search: narrow to the box in the database, then refine with the exact :func:~tempest_fastapi_sdk.geo.haversine_km distance.

Attributes:

Name Type Description
min_latitude LatitudeField

Southern edge, decimal degrees.

max_latitude LatitudeField

Northern edge, decimal degrees.

min_longitude LongitudeField

Western edge, decimal degrees.

max_longitude LongitudeField

Eastern edge, decimal degrees.

contains

contains(point: Coordinate) -> bool

Return whether point falls inside the box (edges included).

Parameters:

Name Type Description Default
point Coordinate

The coordinate to test.

required

Returns:

Type Description
bool

True when the point is within the box, edges inclusive.

Coordinate

Bases: BaseSchema

A geographic point in decimal degrees (WGS84).

Attributes:

Name Type Description
latitude LatitudeField

Latitude in decimal degrees, constrained to [-90, 90].

longitude LongitudeField

Longitude in decimal degrees, constrained to [-180, 180].

DistanceMatrix

Bases: BaseSchema

A many-to-many distance/duration matrix between coordinate sets.

distances_km[i][j] and durations_minutes[i][j] describe the trip from sources[i] to destinations[j].

Attributes:

Name Type Description
sources list[Coordinate]

The origin coordinates, in row order.

destinations list[Coordinate]

The destination coordinates, in column order.

distances_km list[list[float]]

Road distance per (source, destination) pair.

durations_minutes list[list[float]]

Travel time per (source, destination) pair.

mode TravelModeEnum

The travel mode the matrix was computed for.

source_label str

How the matrix was produced (e.g. "osrm").

GeocodeAddress

Bases: BaseSchema

Structured address parts of a resolved place.

Parsed from the address object a Nominatim entry carries when the request asks for addressdetails=1. Every field is optional: the backend returns only what it knows about the matched place, so a coordinate in open country can yield a country and nothing else.

Attributes:

Name Type Description
city str | None

Municipality-level name. Nominatim spells it under four different keys — city, town, village and municipality — and a single entry can carry several at once (a village inside its town), so this is the first key present in that order, largest settlement first. Measured on payloads from nominatim.openstreetmap.org: Teresina/PI answers city, Coivaras/PI answers town, São José da Tenda/PI answers town alongside village and hamlet.

state str | None

First-level subdivision name (e.g. "Piauí"), from address.state.

state_code str | None

Short subdivision code, the part after the - of address["ISO3166-2-lvl4"] ("BR-PI" → "PI"). None when the key is absent or carries no separator. A string, not an enum: the geocoder is worldwide.

country str | None

Country name as spelled by the backend ("Brasil"), from address.country.

country_code str | None

ISO 3166-1 alpha-2 code uppercased ("br" → "BR"), from address.country_code.

postcode str | None

Postal code of the place, from address.postcode.

GeocodeResult

Bases: BaseSchema

A resolved place from a geocoding backend.

Attributes:

Name Type Description
coordinate Coordinate

The resolved point.

display_name str

Human-readable label the backend returned.

place_type str | None

Optional backend-specific place category (e.g. "city", "house"), when available.

address GeocodeAddress | None

Structured address parts, when the backend returned an address object — for Nominatim, whenever the request carried addressdetails=1. None otherwise, which is what keeps this field backwards compatible with backends that never send one.

bounding_box BoundingBox | None

Geographic extent enclosing the resolved place, when the backend provides one (Nominatim's boundingbox array of [south, north, west, east]). None for backends that only return a point coordinate.

GridCellSchema

Bases: BaseSchema

An immutable, hashable cell on a decimal-degree spatial grid.

Uses :class:decimal.Decimal so adjacent cell coordinates never suffer binary floating-point drift and can serve reliably as dict keys or set members for deduplication and tile caching.

Attributes:

Name Type Description
latitude Decimal

Quantized cell latitude in decimal degrees, in [-90, 90].

longitude Decimal

Quantized cell longitude in decimal degrees, in [-180, 180].

to_coordinate

to_coordinate() -> Coordinate

Convert this grid cell to a float-backed :class:Coordinate.

Returns:

Name Type Description
Coordinate Coordinate

The cell anchor as a :class:Coordinate.

RouteThroughResult

Bases: BaseSchema

A road route through two or more points, with one leg per stretch.

legs[i] is the trip from points[i] to points[i + 1], so a route through N points has N - 1 legs and their distances and durations add up to the totals (up to the routing server's own rounding).

Attributes:

Name Type Description
mode TravelModeEnum

The travel mode the route was computed for.

distance_km NonNegativeFloatField

Total road distance in kilometers.

duration_minutes NonNegativeFloatField

Total travel time in minutes.

source str

How the route was produced — "osrm" or "heuristic" (the offline :func:~tempest_fastapi_sdk.geo.estimate_route_through).

geometry list[Coordinate]

The whole route as ordered coordinates. Empty unless the caller asked for it; the offline estimate draws straight lines between the points.

legs list[TravelEstimate]

One :class:TravelEstimate per consecutive pair of points.

TravelEstimate

Bases: BaseSchema

An estimated road trip between two coordinates for a single mode.

Attributes:

Name Type Description
mode TravelModeEnum

The travel mode the estimate was computed for.

distance_km NonNegativeFloatField

Road distance in kilometers (never negative).

duration_minutes NonNegativeFloatField

Estimated travel time in minutes (never negative).

source str

How the estimate was produced — "heuristic" (offline Haversine + circuity factor + average speed) or "osrm" (real road routing via an OSRM server).

InMemoryTrafficSnapshotStore

InMemoryTrafficSnapshotStore(*, clock: Callable[[], float] = monotonic)

A :class:TrafficSnapshotStore in this process (tests, one worker).

Start empty.

Parameters:

Name Type Description Default
clock Callable[[], float]

Monotonic seconds, for the TTL.

monotonic

save async

save(snapshot: TrafficSnapshotSchema, ttl_seconds: int) -> None

Replace the snapshot.

Parameters:

Name Type Description Default
snapshot TrafficSnapshotSchema

The new snapshot.

required
ttl_seconds int

Seconds it stays readable.

required

load async

load() -> TrafficSnapshotSchema | None

Return the snapshot while it is fresh.

Returns:

Type Description
TrafficSnapshotSchema | None

TrafficSnapshotSchema | None: The snapshot, or None.

RedisTrafficSnapshotStore

RedisTrafficSnapshotStore(
    client: _GeocodeRedisClient, *, key: str = DEFAULT_TRAFFIC_SNAPSHOT_KEY
)

A :class:TrafficSnapshotStore over an async Redis client, one key.

Takes the client, like every Redis store the SDK ships; nothing here imports redis. Only the snapshot is written — no position, no trip, no hash.

Attributes:

Name Type Description
key str

The Redis key.

Wrap a connected (or proxy) async Redis client.

Parameters:

Name Type Description Default
client _GeocodeRedisClient

redis.asyncio.Redis or a compatible client (AsyncRedisManager.client_proxy).

required
key str

The Redis key. Give each service its own.

DEFAULT_TRAFFIC_SNAPSHOT_KEY

save async

save(snapshot: TrafficSnapshotSchema, ttl_seconds: int) -> None

Write the snapshot as JSON with ex=ttl_seconds.

Parameters:

Name Type Description Default
snapshot TrafficSnapshotSchema

The new snapshot.

required
ttl_seconds int

Seconds it stays readable.

required

load async

load() -> TrafficSnapshotSchema | None

Read and validate the snapshot.

A value that does not validate is logged (key only) and treated as absent; the next flush overwrites it.

Returns:

Type Description
TrafficSnapshotSchema | None

TrafficSnapshotSchema | None: The snapshot, or None.

TrafficAggregator

TrafficAggregator(
    graph: RoadGraph,
    *,
    privacy: TrafficPrivacy = DEFAULT_TRAFFIC_PRIVACY,
    match_options: RoadMatchOptions = ROAD_MATCH_DEFAULTS,
    store: TrafficSnapshotStore | None = None,
    broker: SSEBroker | None = None,
    audience: TrafficAudienceResolver | None = None,
    event_name: str = DEFAULT_TRAFFIC_EVENT,
    density: OffRoadDensity | None = None,
    quality: MatchQualityOptions | None = None,
    clock: Callable[[], float] = time,
)

Speed per road from fleet positions, published only k-anonymously.

Feed it with :meth:add_position (every position of every device), end trips with :meth:end_trip when known, and call :meth:flush periodically (every 30-60 s): it releases what is far enough behind each device, matches it to the roads, expires silent trips, and saves the new snapshot to the store, telling the SSE audience.

:meth:add_position and :meth:process are synchronous CPU work with no await inside, so under asyncio they never interleave.

Attributes:

Name Type Description
graph RoadGraph

The road network.

privacy TrafficPrivacy

The rules.

match_options RoadMatchOptions

Map-matching tuning.

event_name str

SSE event name of an update.

Initialize the aggregator.

Parameters:

Name Type Description Default
graph RoadGraph

The road network positions are matched to.

required
privacy TrafficPrivacy

Trim radius, k, window and cleaning.

DEFAULT_TRAFFIC_PRIVACY
match_options RoadMatchOptions

Map-matching tuning.

ROAD_MATCH_DEFAULTS
store TrafficSnapshotStore | None

Where :meth:flush saves the snapshot. None keeps it only in :meth:snapshot.

None
broker SSEBroker | None

Where :meth:flush announces a new snapshot.

None
audience TrafficAudienceResolver | None

Who is told. Required with broker: the SDK never decides who sees what.

None
event_name str

SSE event name of an update.

DEFAULT_TRAFFIC_EVENT
density OffRoadDensity | None

Collects the released positions that are off every road, for road inference. Its grid uses graph's plane.

None
quality MatchQualityOptions | None

Also measure the map-matching quality of every released stretch, published only per window and k-anonymously (k is privacy.min_devices) in :meth:snapshot.

None
clock Callable[[], float]

Server time, epoch seconds.

time

Raises:

Type Description
ValueError

When broker and audience are not given together.

active_trips property

active_trips: int

Trips currently held in memory.

Returns:

Name Type Description
int int

How many devices have an open trip.

add_position

add_position(
    device_id: str,
    position: LivePositionSchema,
    *,
    dimensions: Mapping[str, str] | None = None,
) -> bool

Take one position of a device.

Dropped (answer False) when: accuracy_m is worse than max_accuracy_m; it is not newer than the previous one; it implies a move faster than max_speed_kmh; or it is within trim_radius_m of where the trip started. A position after trip_gap_seconds of silence ends the previous trip (its pending stretch is dropped) and starts a new one.

Parameters:

Name Type Description Default
device_id str

The device (vehicle, phone). Hashed at once.

required
position LivePositionSchema

The position.

required
dimensions Mapping[str, str] | None

Coarse values of the quality dimensions declared in MatchQualityOptions ({"os": "android"}) for this device's trip; the latest given applies to the whole trip. None keeps them.

None

Returns:

Name Type Description
bool bool

Whether it was kept for aggregation.

Raises:

Type Description
ValueError

When dimensions is given without quality=, or names an undeclared dimension or a value out of bounds.

end_trip

end_trip(device_id: str) -> None

End a device's trip now (the trip, delivery or shift is over).

What is still pending and within trim_radius_m of the last position is dropped; the rest is aggregated. The trip state is forgotten.

Parameters:

Name Type Description Default
device_id str

The device.

required

process

process() -> int

Release, match and aggregate what is far enough behind each device.

Also ends trips silent for trip_gap_seconds, prunes samples older than the window and forgets salts no sample can use.

Returns:

Name Type Description
int int

Positions aggregated in this call.

snapshot

snapshot() -> TrafficSnapshotSchema

The k-anonymous edges of the current window.

Returns:

Name Type Description
TrafficSnapshotSchema TrafficSnapshotSchema

Edges with at least min_devices

TrafficSnapshotSchema

distinct devices, sorted by edge_id.

quality_snapshot

quality_snapshot() -> MatchQualitySnapshotSchema | None

The map-matching quality of the last closed quality window.

Returns:

Type Description
MatchQualitySnapshotSchema | None

MatchQualitySnapshotSchema | None: The k-anonymous aggregate

MatchQualitySnapshotSchema | None

(empty before the first window closed); None without

MatchQualitySnapshotSchema | None

quality=.

flush async

Process, publish the snapshot to the store and tell the audience.

Returns:

Name Type Description
TrafficSnapshotSchema TrafficSnapshotSchema

The snapshot just published.

TrafficEdgeSchema

Bases: BaseSchema

Traffic on one directed road edge in the window.

Attributes:

Name Type Description
edge_id str

:meth:RoadGraph.edge_key — the edge id, with a trailing ~ when driven against its drawing order.

start Coordinate

Where the directed edge starts.

end Coordinate

Where it ends.

speed_kmh float

Median of the speed samples.

devices int

Distinct devices in the window (a lower bound), at least the aggregator's min_devices.

speed_limit_kmh float | None

The edge's numeric maxspeed tag, when it has one.

TrafficPrivacy dataclass

TrafficPrivacy(
    min_devices: int = 5,
    window_seconds: int = 300,
    trim_radius_m: float = 200.0,
    trip_gap_seconds: float = 300.0,
    max_accuracy_m: float = 50.0,
    max_speed_kmh: float = 200.0,
    min_edge_coverage_m: float = 10.0,
)

The privacy and cleaning rules of a :class:TrafficAggregator.

The distinct-device count of an edge is taken per salt epoch (each epoch is window_seconds long and has its own salt) and the window's count is the largest of the epochs it overlaps: hashes of two epochs never match, so adding them would count a device twice; the maximum can only under-count.

Attributes:

Name Type Description
min_devices int

k of k-anonymity: an edge is published only when this many distinct devices drove it in the window.

window_seconds int

Sliding window of the snapshot, and the life of each hash salt.

trim_radius_m float

Positions this close to the start of a trip, or to where the device is when the trip ends, are never aggregated.

trip_gap_seconds float

Silence after which a device's trip is over (its pending stretch is dropped) and the next position starts a new one.

max_accuracy_m float

Positions reporting a worse accuracy_m are dropped.

max_speed_kmh float

A position implying a faster move from the previous kept one is an outlier and is dropped; speed samples above it are discarded.

min_edge_coverage_m float

Least distance driven on an edge for a pass to become a speed sample.

TrafficSnapshotSchema

Bases: BaseSchema

What the aggregator publishes: the k-anonymous edges of a window.

Attributes:

Name Type Description
generated_at datetime | None

When the snapshot was computed; None in the empty answer the router gives before any snapshot was published (or after the last one expired).

window_seconds int | None

Length of the window it covers.

min_devices int | None

The k it was published under.

edges list[TrafficEdgeSchema]

Edges with at least min_devices devices.

quality MatchQualitySnapshotSchema | None

The map-matching quality of the last closed quality window, when the aggregator measures it (quality=). Served by :func:~tempest_fastapi_sdk.geo.make_match_quality_router; :meth:within leaves it out.

within

The same snapshot restricted to edges with an end inside bbox.

Parameters:

Name Type Description Default
bbox BoundingBox

The area.

required

Returns:

Name Type Description
TrafficSnapshotSchema TrafficSnapshotSchema

A copy with the matching edges and no

TrafficSnapshotSchema

quality (city-wide, read from its own route).

TrafficSnapshotStore

Bases: Protocol

Where the published snapshot lives for readers on any worker.

save async

save(snapshot: TrafficSnapshotSchema, ttl_seconds: int) -> None

Replace the snapshot.

Parameters:

Name Type Description Default
snapshot TrafficSnapshotSchema

The new snapshot.

required
ttl_seconds int

How long it stays readable without a newer one.

required

load async

load() -> TrafficSnapshotSchema | None

Return the current snapshot.

Returns:

Type Description
TrafficSnapshotSchema | None

The snapshot, or None when there is none (or it expired).

RoadGraphTileSchema

Bases: BaseSchema

A tile of the road network, in createRoadGraph input shape.

Attributes:

Name Type Description
nodes list[Coordinate]

Vertices; edges refer to them by index.

edges list[dict[str, Any]]

{"from", "to", "twoWay"?, "id"?, ...} per edge.

two_way bool

Default for edges without twoWay ("twoWay" on the wire).

CityMention dataclass

CityMention(spoken: str, candidates: tuple[Municipality, ...])

A city recognized in the phrase.

Attributes:

Name Type Description
spoken str

The normalized name that matched; on a phonetic collision or a similarity tie, the normalized words said.

candidates tuple[Municipality, ...]

The municipalities it may be; more than one for a homonym the phrase did not settle, or for names the spoken words cannot tell apart.

resolved property

resolved: Municipality | None

Return the municipality when a single candidate is left.

Returns:

Type Description
Municipality | None

Municipality | None: The only candidate, or None.

name property

name: str | None

Return the official name every candidate shares.

A homonym ("Batalha" in PI and AL) has one name and a search may filter by it; a phonetic collision has different names, and picking one would be a guess.

Returns:

Type Description
str | None

str | None: The shared name, or None when they differ.

TripCityIndex dataclass

TripCityIndex(
    by_name: dict[str, tuple[Municipality, ...]],
    by_vocalized: dict[str, tuple[str, ...]],
    fuzzy: dict[int, FuzzyIndex[str]],
    max_words: int,
    restricted: bool,
    fuzzy_cache: dict[tuple[str, int], tuple[float, tuple[str, ...]]] = dict(),
)

The municipalities a trip phrase may name, indexed for the parser.

Build it with :func:build_trip_city_index and reuse it across phrases; the country-wide index is built once per process.

Attributes:

Name Type Description
by_name dict[str, tuple[Municipality, ...]]

Normalized name to the municipalities with it (more than one is a homonym).

by_vocalized dict[str, tuple[str, ...]]

Phonetic key (:func:vocalized_key) to the names that share it; more than one is a collision, which becomes an ambiguity.

fuzzy dict[int, FuzzyIndex[str]]

The names by word count, searchable with typos; a piece only competes with names of its own length, so a typo lookup scans one bucket, not the country.

max_words int

Words in the longest name.

restricted bool

Whether the index holds a chosen subset rather than the whole country. A subset accepts a lowercase one-word city with no preposition ("picos sobral"); the whole country does not, because "estou feliz" would be the town of Feliz (RS).

fuzzy_cache dict[tuple[str, int], tuple[float, tuple[str, ...]]]

Similarity results already computed, per phrase and word count.

TripIntent dataclass

TripIntent(
    origin: CityMention | None = None,
    destination: CityMention | None = None,
    departure_date: date | None = None,
    period: str | None = None,
    period_start: time | None = None,
    period_end: time | None = None,
    unresolved_date: str | None = None,
    unrecognized: dict[TripRoleEnum, str] = dict(),
    departure_now: bool = False,
)

What a trip phrase asks for.

Attributes:

Name Type Description
origin CityMention | None

The origin city.

destination CityMention | None

The destination city.

departure_date date | None

The departure date.

period str | None

The part of the day said ("manha", "noite"...), a key of :data:~tempest_fastapi_sdk.geo.trip_vocabulary.PERIODS.

period_start time | None

Start of that part of the day.

period_end time | None

End of it.

unresolved_date str | None

A date said that does not exist ("30/02", "dia 31 de abril"), for the app to ask instead of searching with no date.

unrecognized dict[TripRoleEnum, str]

Role to the words said after its preposition that matched no city ({"destination": "natal"} when Natal is outside municipalities). Only a role left without a city is reported.

departure_now bool

Whether the phrase asked to leave now ("agora", "já", "o quanto antes"... the :data:~tempest_fastapi_sdk.geo.trip_vocabulary.NOW_PHRASES) and departure_date is today. The parser receives a date, not a clock, so it sets no time: the caller keeps only the trips that leave from its own current time on. An explicit date in the phrase wins: one other than today ("agora ... amanhã") or one that does not exist makes this False, while one that falls on today ("hoje agora") keeps it True.

cep_to_coordinate async

cep_to_coordinate(
    cep: str, *, geocoder: GeocodingBackend, country: str = "Brasil"
) -> Coordinate | None

Resolve a Brazilian CEP (postal code) to a coordinate via geocoding.

Composes an injected :class:~tempest_fastapi_sdk.geo.GeocodingBackend: the CEP (plus country) is geocoded and the resolved point returned. Nominatim resolves Brazilian CEPs directly, so no separate CEP-lookup service is required.

Parameters:

Name Type Description Default
cep str

The postal code (with or without a dash, e.g. "01310-100").

required
geocoder GeocodingBackend

The geocoding backend to resolve the CEP.

required
country str

Country appended to the query to disambiguate.

'Brasil'

Returns:

Type Description
Coordinate | None

The resolved :class:Coordinate, or None when nothing matches.

extract_cep

extract_cep(*texts: str | None) -> str | None

Return the first CEP written in the given texts, normalized.

Built for address data typed into a single free-text field — the postal code sits somewhere inside "Av. Paulista, 1578 - 01310-200" and no column holds it. Texts are scanned in the order given, so pass the most trustworthy field first.

Parameters:

Name Type Description Default
*texts str | None

The texts to scan; None and empty strings are skipped.

()

Returns:

Type Description
str | None

str | None: The CEP as "00000-000", or None when no text

str | None

carries one. Only the shape is checked — whether the CEP exists is

str | None

a question for a geocoder.

resolve_br_coordinate async

resolve_br_coordinate(
    *,
    geocoder: GeocodingBackend | None,
    uf: UFEnum | str,
    address: str | None = None,
    city: str | None = None,
    complement: str | None = None,
    country: str = "Brasil",
) -> Coordinate | None

Resolve the best known point for a Brazilian address.

Tries three sources, most precise first, and returns the first that answers:

  1. the CEP found in address or complement (see :func:extract_cep), through :func:cep_to_coordinate;
  2. the full address — "address, city, UFEnum, country" with the empty parts left out — geocoded as one query (skipped when both address and city are empty);
  3. the state centroid (:func:uf_centroid), offline, which always answers for a valid UFEnum.

A geocoder failure is not an error here: any exception from geocoder.geocode is logged at WARNING (with the traceback) and the chain moves to the next step, so the worst outcome is the state centroid. Retrying belongs on the geocoder you inject — wrap its geocode with :func:~tempest_fastapi_sdk.async_retry — because this function only sees the failure after your retries are spent.

Parameters:

Name Type Description Default
geocoder GeocodingBackend | None

The backend for steps 1 and 2. None skips straight to the state centroid — the offline path, for tests and for deployments without geocoding.

required
uf UFEnum | str

The state, as a member or a sigla (case-insensitive).

required
address str | None

The street address, free text.

None
city str | None

The city name.

None
complement str | None

Extra address text, scanned for a CEP after address but not sent in the address query.

None
country str

Country appended to both geocoding queries.

'Brasil'

Returns:

Type Description
Coordinate | None

Coordinate | None: The resolved point, or None when nothing

Coordinate | None

matched and uf is not a valid federative unit.

uf_centroid

uf_centroid(uf: UFEnum | str) -> Coordinate

Return the approximate geographic centre of a Brazilian state.

Parameters:

Name Type Description Default
uf UFEnum | str

A :class:~tempest_fastapi_sdk.utils.UFEnum member or a state sigla (case-insensitive, e.g. "sp").

required

Returns:

Type Description
Coordinate

The state's approximate centre as a :class:Coordinate.

Raises:

Type Description
ValueError

If uf is not a valid federative unit.

br_map_height

br_map_height() -> float

Return the height of the map's SVG viewBox.

Returns:

Name Type Description
float float

The height, for a width of :data:BR_MAP_WIDTH.

br_map_legend

br_map_legend(
    state_values: Mapping[UFEnum | str, int], *, levels: int = BR_MAP_LEVELS
) -> list[BRMapLegendEntry]

Return the shades a set of state values uses, with their ranges.

The scale is logarithmic: shade n covers the values up to peak ** (n / levels) not covered by the shade before it. A shade no integer falls in (several when the peak is small) is left out.

Parameters:

Name Type Description Default
state_values Mapping[UFEnum | str, int]

The value of each state.

required
levels int

How many shades to split into.

BR_MAP_LEVELS

Returns:

Type Description
list[BRMapLegendEntry]

list[BRMapLegendEntry]: The shades, lightest first; empty when no

list[BRMapLegendEntry]

state has a positive value.

Raises:

Type Description
ValueError

When levels is below 1.

br_state_outlines cached

br_state_outlines() -> dict[UFEnum, tuple[tuple[Coordinate, ...], ...]]

Return every state's outline, parsed once.

Returns:

Type Description
dict[UFEnum, tuple[tuple[Coordinate, ...], ...]]

dict[UFEnum, tuple[tuple[Coordinate, ...], ...]]: The rings of each

dict[UFEnum, tuple[tuple[Coordinate, ...], ...]]

state, in the order the source lists them; a ring is not closed

dict[UFEnum, tuple[tuple[Coordinate, ...], ...]]

(its last vertex is not a repeat of the first). A state with islands

dict[UFEnum, tuple[tuple[Coordinate, ...], ...]]

has more than one ring.

project_br

project_br(coordinate: Coordinate) -> tuple[float, float]

Return where a coordinate lands on the map.

The projection is equirectangular, with longitude squeezed by the cosine of the country's middle latitude so the map is not stretched sideways. North is up.

Parameters:

Name Type Description Default
coordinate Coordinate

The point.

required

Returns:

Type Description
float

tuple[float, float]: (x, y) in the viewBox of

float

func:render_br_map_svg, 0 to :data:BR_MAP_WIDTH wide and

tuple[float, float]

0 to :func:br_map_height tall for a point inside Brazil or at

tuple[float, float]

any of its municipalities.

render_br_map_svg

render_br_map_svg(
    state_values: Mapping[UFEnum | str, int],
    points: Sequence[BRMapPoint] = (),
    *,
    levels: int = BR_MAP_LEVELS,
    title: str = "Brazil",
    value_label: str = "",
) -> str

Draw Brazil with each state shaded by its value and a bubble per point.

The markup carries class names only, no colours, so the page's stylesheet paints it: every state is tempest-br-map__state plus tempest-br-map__state--l{n} (l0 for no value, then l1..l{levels}), and every bubble tempest-br-map__point. Each shape has a <title> the browser shows on hover. Every text is HTML-escaped, so a label from the database cannot inject markup.

Bubbles are drawn largest first, so a small one is never hidden under a big one; the area grows with the value (radius from :data:BR_MAP_MIN_RADIUS to :data:BR_MAP_MAX_RADIUS, by square root).

Parameters:

Name Type Description Default
state_values Mapping[UFEnum | str, int]

The value of each state, by enum or acronym; a missing state counts as 0.

required
points Sequence[BRMapPoint]

The bubbles.

()
levels int

How many shades the state values split into.

BR_MAP_LEVELS
title str

The SVG's accessible name.

'Brazil'
value_label str

Word after each number in the tooltips ("users"); empty shows the number alone.

''

Returns:

Name Type Description
str str

An <svg> element.

Raises:

Type Description
ValueError

When levels is below 1, or a key of state_values is not a Brazilian state.

uf_at

uf_at(coordinate: Coordinate) -> UFEnum | None

Return the state a coordinate falls in.

Parameters:

Name Type Description Default
coordinate Coordinate

The point.

required

Returns:

Type Description
UFEnum | None

UFEnum | None: The state whose outline contains the point, or

UFEnum | None

None for a point outside Brazil (or in the sea between an island

UFEnum | None

and the coast). The outlines are the IBGE's lowest quality, so a

UFEnum | None

point a few kilometres from a border can land in the neighbour.

haversine_distance_sql

haversine_distance_sql(
    latitude: SQLColumnExpression[float],
    longitude: SQLColumnExpression[float],
    center: Coordinate,
) -> ColumnElement[float]

Build the Haversine great-circle distance as a SQL expression.

Uses only sin, cos, asin and sqrt plus arithmetic — no PostGIS, no radians() (degrees are converted by multiplying with a bound constant). Plain PostgreSQL has all four; SQLite has them when built with its math functions (SQLITE_ENABLE_MATH_FUNCTIONS, SQLite 3.35+). Check yours with SELECT sin(1), asin(1), sqrt(4); the SQLite 3.47.1 inside the CPython 3.13.3 that uv installs answers it.

The haversine term is clamped to [0, 1] with a CASE before sqrt / asin. Floating-point error pushes it past 1: for random antipodal pairs it came out as 1.0000000000000002 in about 4% of 2,000,000 draws on PostgreSQL 16, and on SQLite 3.47.1 too. sqrt happens to round that value back to 1.0, so neither engine failed in those draws — but asin of anything above 1 is NULL on SQLite and ERROR: input is out of range on PostgreSQL (both measured), and the clamp keeps the result from depending on that rounding. The centre's cosine is computed in Python and bound, so each row pays one cos.

Parameters:

Name Type Description Default
latitude SQLColumnExpression[float]

The latitude column (or expression), in degrees.

required
longitude SQLColumnExpression[float]

The longitude column (or expression), in degrees.

required
center Coordinate

The point distances are measured from.

required

Returns:

Type Description
ColumnElement[float]

ColumnElement[float]: The distance in kilometres, same formula and

ColumnElement[float]

Earth radius (:data:~tempest_fastapi_sdk.geo.EARTH_RADIUS_KM) as

ColumnElement[float]

func:~tempest_fastapi_sdk.geo.haversine_km.

make_geo_point_model

make_geo_point_model(*, tablename: str, class_name: str = 'GeoPointModel') -> type[Any]

Build a minimal concrete model with a geographic point at runtime.

A convenience for tests and scripts — production projects should hand-write a model mixing :class:GeoPointMixin into :class:~tempest_fastapi_sdk.BaseModel. The generated class inherits id / is_active / timestamps from BaseModel and latitude / longitude from :class:GeoPointMixin.

Parameters:

Name Type Description Default
tablename str

__tablename__ for the generated class.

required
class_name str

Python class name.

'GeoPointModel'

Returns:

Type Description
type[Any]

A concrete mapped class with latitude / longitude columns.

haversine_km

haversine_km(origin: Coordinate, destination: Coordinate) -> float

Compute the great-circle distance between two coordinates.

Uses the Haversine formula, which treats the Earth as a sphere. This is the straight-line ("as the crow flies") distance, not the road distance — feed it through a circuity factor (see :func:tempest_fastapi_sdk.geo.estimate_travel) for a road estimate.

Parameters:

Name Type Description Default
origin Coordinate

The starting coordinate.

required
destination Coordinate

The ending coordinate.

required

Returns:

Type Description
float

The great-circle distance in kilometers (always non-negative).

duration_factor

duration_factor(
    mode: TravelModeEnum, factors: dict[TravelModeEnum, float] | None = None
) -> float

Return the duration multiplier (relative to a car) for a mode.

Parameters:

Name Type Description Default
mode TravelModeEnum

The travel mode to look up.

required
factors dict[TravelModeEnum, float] | None

Optional override map; falls back to :data:DEFAULT_MODE_DURATION_FACTORS and then to 1.0.

None

Returns:

Type Description
float

The multiplier applied to a car's travel time for this mode.

estimate_route_through

estimate_route_through(
    points: Sequence[Coordinate],
    mode: TravelModeEnum = CAR,
    *,
    with_geometry: bool = False,
    circuity_factor: float = DEFAULT_CIRCUITY_FACTOR,
    car_speed_kmh: float = DEFAULT_CAR_SPEED_KMH,
    mode_duration_factors: dict[TravelModeEnum, float] | None = None,
) -> RouteThroughResult

Estimate a route through several points offline, leg by leg.

The offline counterpart of :meth:~tempest_fastapi_sdk.geo.OSRMBackend.route_through: each consecutive pair goes through :func:estimate_travel, and the totals are the sums of the legs. Use it when no OSRM server is reachable, or as the fallback after one fails.

Parameters:

Name Type Description Default
points Sequence[Coordinate]

The ordered points the route passes through (origin, stops, destination). At least two.

required
mode TravelModeEnum

The travel mode to estimate for.

CAR
with_geometry bool

Whether to fill :attr:RouteThroughResult.geometry with the points themselves — straight lines between them, since there is no road network offline.

False
circuity_factor float

Ratio of road distance to straight-line distance, forwarded to :func:estimate_travel.

DEFAULT_CIRCUITY_FACTOR
car_speed_kmh float

Blended average car speed in km/h, forwarded to :func:estimate_travel.

DEFAULT_CAR_SPEED_KMH
mode_duration_factors dict[TravelModeEnum, float] | None

Optional per-mode duration multiplier map, forwarded to :func:estimate_travel.

None

Returns:

Name Type Description
A RouteThroughResult

class:RouteThroughResult with source="heuristic" and one leg

RouteThroughResult

per consecutive pair, each leg also source="heuristic".

Raises:

Type Description
ValueError

If fewer than two points are given, or if car_speed_kmh or circuity_factor is not positive.

estimate_travel

estimate_travel(
    origin: Coordinate,
    destination: Coordinate,
    mode: TravelModeEnum = CAR,
    *,
    circuity_factor: float = DEFAULT_CIRCUITY_FACTOR,
    car_speed_kmh: float = DEFAULT_CAR_SPEED_KMH,
    mode_duration_factors: dict[TravelModeEnum, float] | None = None,
) -> TravelEstimate

Estimate road distance and travel time offline for a single mode.

Road distance is the Haversine distance scaled by circuity_factor. Travel time is that distance at the car's average speed, then scaled by the mode's duration factor (see :data:DEFAULT_MODE_DURATION_FACTORS).

Parameters:

Name Type Description Default
origin Coordinate

The starting coordinate.

required
destination Coordinate

The ending coordinate.

required
mode TravelModeEnum

The travel mode to estimate for. Defaults to :attr:TravelModeEnum.CAR.

CAR
circuity_factor float

Ratio of road distance to straight-line distance.

DEFAULT_CIRCUITY_FACTOR
car_speed_kmh float

Blended average car speed in km/h; must be positive.

DEFAULT_CAR_SPEED_KMH
mode_duration_factors dict[TravelModeEnum, float] | None

Optional per-mode duration multiplier map.

None

Returns:

Name Type Description
A TravelEstimate

class:TravelEstimate with source="heuristic".

Raises:

Type Description
ValueError

If car_speed_kmh or circuity_factor is not positive.

bounding_box

bounding_box(center: Coordinate, radius_km: float) -> BoundingBox

Return the smallest lat/long box enclosing a radius around a point.

The box over-covers the circle (it is the circle's bounding square), so use it as a coarse pre-filter — narrow rows to the box in SQL, then refine with :func:~tempest_fastapi_sdk.geo.haversine_km. Longitude span widens with latitude; near the poles it is clamped to the full [-180, 180] range.

Parameters:

Name Type Description Default
center Coordinate

The circle centre.

required
radius_km float

The radius in kilometres; must be non-negative.

required

Returns:

Name Type Description
A BoundingBox

class:~tempest_fastapi_sdk.geo.BoundingBox enclosing the circle.

Raises:

Type Description
ValueError

If radius_km is negative.

destination_point

destination_point(
    origin: Coordinate, bearing_degrees: float, distance_km: float
) -> Coordinate

Project a point distance_km from origin along a bearing.

The inverse of :func:initial_bearing — handy for circular geofences and "X km due north" style computations. Uses the spherical direct (forward) geodesic formula.

Parameters:

Name Type Description Default
origin Coordinate

The starting coordinate.

required
bearing_degrees float

The compass bearing to travel (0 = north).

required
distance_km float

The distance to travel in kilometres.

required

Returns:

Type Description
Coordinate

The destination :class:~tempest_fastapi_sdk.geo.Coordinate.

Notes

Longitude is normalised back into [-180, 180]; a bearing that crosses the antimeridian would otherwise return a value outside the valid range.

initial_bearing

initial_bearing(origin: Coordinate, destination: Coordinate) -> float

Return the initial compass bearing from origin to destination.

Parameters:

Name Type Description Default
origin Coordinate

The starting coordinate.

required
destination Coordinate

The target coordinate.

required

Returns:

Type Description
float

The forward azimuth in degrees, normalised to [0, 360) (0 = north,

float

90 = east).

nearest

nearest(
    center: Coordinate,
    points: Iterable[T],
    *,
    k: int = 1,
    key: Callable[[T], Coordinate] | None = None,
) -> list[T]

Return the k items closest to center, nearest first.

Parameters:

Name Type Description Default
center Coordinate

The reference point.

required
points Iterable[T]

The items to rank.

required
k int

How many closest items to return; must be positive.

1
key Callable[[T], Coordinate] | None

Extracts a coordinate from an item; identity when None.

None

Returns:

Type Description
list[T]

Up to k items sorted by ascending distance from center.

Raises:

Type Description
ValueError

If k is not positive.

path_length_km

path_length_km(points: list[Coordinate]) -> float

Return the total great-circle length of a path through points.

Sums the :func:~tempest_fastapi_sdk.geo.haversine_km distance between each consecutive pair. A path of 0 or 1 points has length 0.0.

Parameters:

Name Type Description Default
points list[Coordinate]

The ordered path vertices.

required

Returns:

Type Description
float

The path length in kilometres.

point_in_polygon

point_in_polygon(point: Coordinate, polygon: list[Coordinate]) -> bool

Return whether point lies inside polygon (ray casting).

The polygon is an ordered ring of vertices; the closing edge (last → first) is implicit, so do not repeat the first vertex. Treats coordinates as planar, which is accurate for city/neighbourhood-scale geofences. Points exactly on an edge are not guaranteed either way.

Parameters:

Name Type Description Default
point Coordinate

The coordinate to test.

required
polygon list[Coordinate]

The polygon vertices (at least 3), not self-closed.

required

Returns:

Type Description
bool

True when the point is inside the polygon.

Raises:

Type Description
ValueError

If the polygon has fewer than 3 vertices.

polygon_area_km2

polygon_area_km2(polygon: list[Coordinate]) -> float

Return the area of a polygon on the sphere, in square kilometres.

Uses the spherical-excess shoelace formula. The polygon is an ordered ring (not self-closed); winding direction does not matter (the absolute value is returned).

Parameters:

Name Type Description Default
polygon list[Coordinate]

The polygon vertices (at least 3), not self-closed.

required

Returns:

Type Description
float

The enclosed area in square kilometres.

Raises:

Type Description
ValueError

If the polygon has fewer than 3 vertices.

within_radius

within_radius(
    center: Coordinate,
    points: Iterable[T],
    radius_km: float,
    *,
    key: Callable[[T], Coordinate] | None = None,
) -> list[T]

Return the items whose coordinate is within radius_km of center.

Works on any objects: pass key to extract a :class:~tempest_fastapi_sdk.geo.Coordinate from each item (omit it when the items already are coordinates). Returns [] when nothing matches, in line with the SDK collection convention.

Parameters:

Name Type Description Default
center Coordinate

The circle centre.

required
points Iterable[T]

The items to filter.

required
radius_km float

The inclusive radius in kilometres.

required
key Callable[[T], Coordinate] | None

Extracts a coordinate from an item; identity when None.

None

Returns:

Type Description
list[T]

The matching items, in input order.

cell_for

cell_for(
    coordinate: Coordinate, *, decimal_places: int = DEFAULT_GRID_DECIMAL_PLACES
) -> GridCellSchema

Snap a :class:Coordinate to its containing :class:GridCellSchema.

Parameters:

Name Type Description Default
coordinate Coordinate

Geographic point to quantize.

required
decimal_places int

Number of decimal places for the grid resolution. Defaults to :data:DEFAULT_GRID_DECIMAL_PLACES.

DEFAULT_GRID_DECIMAL_PLACES

Returns:

Type Description
GridCellSchema

The quantized :class:GridCellSchema for coordinate.

Raises:

Type Description
ValueError

When decimal_places < 0.

generate_grid

generate_grid(
    bbox: BoundingBox, *, decimal_places: int = DEFAULT_GRID_DECIMAL_PLACES
) -> list[GridCellSchema]

Generate all grid cells covering bbox from southwest to northeast.

Steps strictly in :class:decimal.Decimal increments of 10 ** -decimal_places so there is zero floating-point drift and no duplicate cells. Both edges (rounded southwest corner through rounded northeast corner) are included.

Parameters:

Name Type Description Default
bbox BoundingBox

Non-inverted geographic bounding box to tile.

required
decimal_places int

Number of decimal places for the grid resolution. Defaults to :data:DEFAULT_GRID_DECIMAL_PLACES.

DEFAULT_GRID_DECIMAL_PLACES

Returns:

Type Description
list[GridCellSchema]

Ordered list of unique :class:GridCellSchema instances sweeping

list[GridCellSchema]

latitude from south to north and longitude from west to east.

Raises:

Type Description
ValueError

When decimal_places < 0 or bbox is inverted (min_latitude > max_latitude or min_longitude > max_longitude).

neighbor_cells

neighbor_cells(
    cell: GridCellSchema, *, decimal_places: int = DEFAULT_GRID_DECIMAL_PLACES
) -> list[GridCellSchema]

Return cell together with its 8 surrounding cells (3x3 neighborhood).

Ordered from southwest to northeast (south-to-north rows, west-to-east columns). Offsets that would fall outside valid WGS84 bounds (latitude [-90, 90], longitude [-180, 180]) are omitted rather than wrapping or emitting invalid cells, so interior cells return 9 entries while pole or antimeridian boundary cells return 6 or 4 entries.

Parameters:

Name Type Description Default
cell GridCellSchema

Center grid cell.

required
decimal_places int

Number of decimal places defining the step size. Defaults to :data:DEFAULT_GRID_DECIMAL_PLACES.

DEFAULT_GRID_DECIMAL_PLACES

Returns:

Type Description
list[GridCellSchema]

List of valid :class:GridCellSchema cells within the 3x3

list[GridCellSchema]

neighborhood (up to 9 cells, including the quantized center cell).

Raises:

Type Description
ValueError

When decimal_places < 0.

round_to_grid

round_to_grid(
    value: float | Decimal, *, decimal_places: int = DEFAULT_GRID_DECIMAL_PLACES
) -> Decimal

Quantize a coordinate component onto the grid using ROUND_HALF_UP.

Converts value via Decimal(str(value)) before quantizing so binary float artifacts do not shift boundary values, and normalizes -0.00 to 0.00 so zero never splits a key into two representations.

Parameters:

Name Type Description Default
value float | Decimal

Latitude or longitude component to quantize.

required
decimal_places int

Number of decimal places for the grid resolution. Defaults to :data:DEFAULT_GRID_DECIMAL_PLACES (2, ~1.11 km per step of latitude).

DEFAULT_GRID_DECIMAL_PLACES

Returns:

Type Description
Decimal

The quantized :class:decimal.Decimal coordinate component.

Raises:

Type Description
ValueError

When decimal_places < 0 or value is not finite (NaN or Infinity).

make_live_position_router

make_live_position_router(
    store: LivePositionStore | Callable[[Request], LivePositionStore],
    *,
    authorize: Callable[..., Coroutine[Any, Any, Any]],
    channel_active: Callable[..., Coroutine[Any, Any, bool]],
    traffic: TrafficAggregator | None = None,
    traffic_dimensions: TrafficDimensionsResolver | None = None,
    prefix: str = "/live",
    tag: str = "Live position",
    docs_locale: str | None = None,
) -> APIRouter

Build the router that receives positions for store.

Mounts POST <prefix>/{channel_id}/position, body :class:~tempest_fastapi_sdk.geo.LivePositionSchema, answering :class:LivePositionPublishResponseSchema.

Both dependencies are ordinary FastAPI dependencies: they can declare channel_id: str to receive the path parameter and depend on the service's current-user dependency. authorize runs first and refuses by raising (ForbiddenException for a user who is not the channel's publisher); its return value is ignored. channel_active then answers True or False.

Parameters:

Name Type Description Default
store LivePositionStore | Callable[[Request], LivePositionStore]

The store, or a factory called with each request that returns it (lambda request: request.app.state.live_positions).

required
authorize Callable[..., Coroutine[Any, Any, Any]]

Dependency that raises unless the caller may publish on channel_id. Mandatory.

required
channel_active Callable[..., Coroutine[Any, Any, bool]]

Dependency answering whether channel_id accepts positions now. Mandatory.

required
traffic TrafficAggregator | None

Also hands every authorized position of an active channel to this aggregator, the channel id as the device — throttled or not, since the matcher wants every fix. The aggregator hashes the id at once and publishes only k-anonymous traffic.

None
traffic_dimensions TrafficDimensionsResolver | None

Dependency answering the coarse quality dimensions of the trip ({"os": "android"}, read from a header the app sends, for instance), handed to traffic.add_position; needs traffic built with quality=. Values the aggregator refuses (an undeclared name, a value too long) are dropped with a warning and the position is still aggregated.

None
prefix str

URL prefix. Defaults to "/live".

'/live'
tag str

OpenAPI tag. Defaults to "Live position".

'Live position'
docs_locale str | None

Language of the OpenAPI summary and description — "en-US" or "pt-BR". None reads API_DOCS_LOCALE.

None

Returns:

Name Type Description
APIRouter APIRouter

The router, ready for app.include_router.

Raises:

Type Description
ValueError

When authorize or channel_active is None, or traffic_dimensions comes without traffic.

br_location_distribution async

br_location_distribution(
    session: AsyncSession,
    model: type[BRLocationMixin],
    *,
    where: ColumnElement[bool] | None = None,
    city_limit: int | None = None,
) -> BRLocationDistributionSchema

Count a model's rows per state and per city.

Three aggregate queries — the total, a GROUP BY state and a GROUP BY city_ibge_code — so the cost does not grow with the number of rows loaded into Python. A code the shipped municipalities do not know (a row written by hand) is left out of cities.

Parameters:

Name Type Description Default
session AsyncSession

The session to query on.

required
model type[BRLocationMixin]

A model with the mixin's columns.

required
where ColumnElement[bool] | None

An extra filter (UserModel.is_active.is_(True)).

None
city_limit int | None

Keep only the largest cities; None keeps all.

None

Returns:

Name Type Description
BRLocationDistributionSchema BRLocationDistributionSchema

The counts.

Raises:

Type Description
TypeError

When model does not have the mixin's columns.

resolve_br_municipality

resolve_br_municipality(
    city: str, state: UFEnum | str, *, typo_cutoff: float | None = None
) -> Municipality

Return the municipality a city name and a state point at.

Case, accents and punctuation do not matter ("sao paulo", "SÃO PAULO"), and older IBGE spellings count.

Parameters:

Name Type Description Default
city str

The city name.

required
state UFEnum | str

The state, as enum or acronym.

required
typo_cutoff float | None

Accept the most similar name in the state at this similarity or above when no name matches exactly (see :func:~tempest_fastapi_sdk.geo.municipality_by_name). None (default) is exact only.

None

Returns:

Name Type Description
Municipality Municipality

The municipality.

Raises:

Type Description
UnknownMunicipalityError

When the state has no such municipality, or state is not a Brazilian state.

match_to_roads

match_to_roads(
    fixes: Sequence[Coordinate],
    graph: RoadGraph,
    options: RoadMatchOptions = ROAD_MATCH_DEFAULTS,
    *,
    timestamps: Sequence[float | None] | None = None,
) -> RoadMatchResult

Match a GPS trace to a road network (Newson & Krumm 2009).

  • Breaks: when no transition is possible (a gap, a missing road), the chain restarts at that fix instead of failing; routes gets one entry per chain and breaks counts them.
  • Close fixes (within the spacing of the last kept one) skip the model and are projected onto that fix's edge, inferred=True.
  • No road in reach: the match is None and the fix counts in unmatched; it does not break the chain.
  • Sparse fixes: pass timestamps and the detour allowed between two fixes grows by detour_per_second_m per second of interval (capped at max_interval_s). Without them the bound is the fixed max_detour_m, tuned for 1 Hz, and a fix every 5-30 s breaks the chain where the vehicle turned a corner or went round a block in between. A missing (None) or nan time, a repeated one or one that goes back grants no slack, so an untimed trace gives exactly the result it gave before.

Synchronous and CPU-bound; from async code run it with asyncio.to_thread when the trace is long.

Parameters:

Name Type Description Default
fixes Sequence[Coordinate]

The trace, in time order.

required
graph RoadGraph

The network.

required
options RoadMatchOptions

Model tuning; defaults in :data:ROAD_MATCH_DEFAULTS.

ROAD_MATCH_DEFAULTS
timestamps Sequence[float | None] | None

Capture time of each fix, epoch seconds (datetime.timestamp()), same length as fixes; None for a fix without one.

None

Returns:

Name Type Description
RoadMatchResult RoadMatchResult

The match of every fix, the route, and what was

RoadMatchResult

skipped.

Raises:

Type Description
ValueError

When timestamps does not have one entry per fix.

br_municipalities cached

br_municipalities() -> tuple[Municipality, ...]

Return every Brazilian municipality, ordered by IBGE code.

Parsed from the bundled data on first call and cached.

Returns:

Type Description
tuple[Municipality, ...]

tuple[Municipality, ...]: The 5571 municipalities.

find_municipalities_in_text

find_municipalities_in_text(
    text: str, *, limit: int | None = 5, cutoff: float = 0.85, min_score: float = 0.6
) -> list[MunicipalityMatch]

Find the municipalities a free-form text mentions.

Every run of up to :data:MAX_NAME_TOKENS words is looked up, exactly first and then with typos (cutoff). A state written right after the name ("Campinas/SP", "Campinas - São Paulo", "campinas SP") keeps only the homonyms in that state and marks them uf_confirmed; a state written there that the name does not exist in drops the match. Overlapping matches keep the best (longer on a tie), so "são josé dos campos" is one city, not São José plus Campos; and the words of a state that confirmed a match are not a city of their own, so "Campinas, São Paulo" is Campinas alone.

Scores: the name similarity, times 0.9 when no state confirms it, times :data:UNCUED_SINGLE_WORD_FACTOR for a one-word name that does not look like a place ("estou feliz").

Parameters:

Name Type Description Default
text str

What the user wrote.

required
limit int | None

Most matches to return; None for all.

5
cutoff float

Lowest name similarity for a typo, in (0, 1].

0.85
min_score float

Drop matches scoring below this.

0.6

Returns:

Type Description
list[MunicipalityMatch]

list[MunicipalityMatch]: Best first, then in text order. Homonyms

list[MunicipalityMatch]

with no state to tell them apart come back together, same score.

municipality_by_ibge_code

municipality_by_ibge_code(code: int) -> Municipality | None

Return the municipality with this IBGE code.

Parameters:

Name Type Description Default
code int

The seven-digit IBGE code.

required

Returns:

Type Description
Municipality | None

Municipality | None: The municipality, or None for an unknown code.

municipality_by_name

municipality_by_name(
    name: str, uf: UFEnum | str, *, typo_cutoff: float | None = None
) -> Municipality | None

Return the municipality with this name in a state.

Case, accents and punctuation do not matter ("SAO LUIS" is São Luís), and IBGE aliases count ("Assu"). For linking a name stored by a service (a route's city and state) to its IBGE record.

Parameters:

Name Type Description Default
name str

The municipality name.

required
uf UFEnum | str

Its state, as enum or acronym.

required
typo_cutoff float | None

When set and no name matches exactly, accept the most similar name in the state at this similarity or above, if it is the only best one. Old datasets spell some towns differently ("Alvorada do Oeste" for "Alvorada D'Oeste", "Camacã" for "Camacan"); 0.85 links them. None (default) is exact only.

None

Returns:

Type Description
Municipality | None

Municipality | None: The municipality, or None when the state

Municipality | None

has none by that name (or uf is not a Brazilian state).

search_municipalities

search_municipalities(
    name: str,
    *,
    uf: UFEnum | str | None = None,
    limit: int | None = 5,
    cutoff: float = 0.8,
) -> list[MunicipalityMatch]

Find the municipalities whose name looks like name.

Parameters:

Name Type Description Default
name str

A municipality name as typed: any case, accents or not, typos included ("sao paolo"). Aliases, nicknames (:data:BR_CITY_NICKNAMES) and the Federal District's regions are names too.

required
uf UFEnum | str | None

Keep only this state.

None
limit int | None

Most matches to return; None for all.

5
cutoff float

Lowest name similarity accepted, in (0, 1].

0.8

Returns:

Type Description
list[MunicipalityMatch]

list[MunicipalityMatch]: Best first. Homonyms tie: "Bom Jesus"

list[MunicipalityMatch]

without uf returns every Bom Jesus with the same score.

list[MunicipalityMatch]

uf_confirmed is True when uf was given.

load_road_graph

load_road_graph(
    path: str | PathLike[str],
    *,
    highways: frozenset[str] | None = OSM_DRIVABLE_HIGHWAYS,
) -> RoadGraph

Read an OSM extract from disk, cached by path, size and mtime.

The same file loaded twice returns the same :class:RoadGraph object; rewriting the file (new size or mtime) rebuilds it. At most :data:OSM_GRAPH_CACHE_SIZE graphs stay cached. Synchronous: call it at startup or through asyncio.to_thread.

Parameters:

Name Type Description Default
path str | PathLike[str]

A .json / .geojson file in either shape :func:road_graph_from_osm_json reads.

required
highways frozenset[str] | None

highway values to keep. Only the default is cached; another filter always rebuilds.

OSM_DRIVABLE_HIGHWAYS

Returns:

Name Type Description
RoadGraph RoadGraph

The graph.

Raises:

Type Description
ValueError

When the file is neither shape.

road_graph_from_geojson

road_graph_from_geojson(
    data: Mapping[str, Any], *, highways: frozenset[str] | None = OSM_DRIVABLE_HIGHWAYS
) -> RoadGraph

Build a graph from a GeoJSON FeatureCollection of road lines.

A feature without a highway property is kept only with highways=None (a hand-drawn network has no OSM tags). The way id is the feature id, properties["@id"] or properties["id"], else the feature's position in the collection.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The parsed FeatureCollection.

required
highways frozenset[str] | None

highway values to keep.

OSM_DRIVABLE_HIGHWAYS

Returns:

Name Type Description
RoadGraph RoadGraph

The graph.

road_graph_from_osm_json

road_graph_from_osm_json(
    data: Mapping[str, Any], *, highways: frozenset[str] | None = OSM_DRIVABLE_HIGHWAYS
) -> RoadGraph

Build a graph from either Overpass JSON or GeoJSON, by its shape.

Parameters:

Name Type Description Default
data Mapping[str, Any]

{"elements": ...} (Overpass) or {"type": "FeatureCollection", ...} (GeoJSON).

required
highways frozenset[str] | None

highway values to keep.

OSM_DRIVABLE_HIGHWAYS

Returns:

Name Type Description
RoadGraph RoadGraph

The graph.

Raises:

Type Description
ValueError

When the document is neither shape.

road_graph_from_overpass

road_graph_from_overpass(
    data: Mapping[str, Any], *, highways: frozenset[str] | None = OSM_DRIVABLE_HIGHWAYS
) -> RoadGraph

Build a graph from an Overpass API [out:json] answer.

Only nodes some kept way uses become graph nodes. A way that names a node the answer does not carry (query without >;) loses the edges touching it instead of failing.

Parameters:

Name Type Description Default
data Mapping[str, Any]

The parsed answer ({"elements": [...]}).

required
highways frozenset[str] | None

highway values to keep. Defaults to :data:OSM_DRIVABLE_HIGHWAYS; None keeps all.

OSM_DRIVABLE_HIGHWAYS

Returns:

Name Type Description
RoadGraph RoadGraph

The graph.

parse_overpass_places

parse_overpass_places(payload: Mapping[str, JsonValue]) -> list[PlaceSchema]

Parse an Overpass API [out:json] payload into :class:PlaceSchema items.

Elements without a non-empty tags.name or without a valid WGS84 coordinate (top-level lat/lon for nodes, or center.lat/lon for ways and relations queried with out center;) are silently discarded.

Parameters:

Name Type Description Default
payload Mapping[str, JsonValue]

Decoded JSON body returned by the Overpass API interpreter ({"elements": [...]}).

required

Returns:

Type Description
list[PlaceSchema]

list[PlaceSchema]: Normalized places with source="overpass" and

list[PlaceSchema]

external_id="<type>/<id>".

decode_polyline

decode_polyline(encoded: str, *, precision: int = 5) -> list[Coordinate]

Decode an encoded-polyline string into coordinates.

Parameters:

Name Type Description Default
encoded str

The encoded polyline string.

required
precision int

Decimal digits of precision used when encoding (must match the encoder — 5 or 6).

5

Returns:

Type Description
list[Coordinate]

The decoded coordinates, in order ([] for an empty string).

encode_polyline

encode_polyline(points: list[Coordinate], *, precision: int = 5) -> str

Encode coordinates into an encoded-polyline string.

Parameters:

Name Type Description Default
points list[Coordinate]

The ordered coordinates to encode.

required
precision int

Decimal digits of precision (5 = Google/OSRM default, 6 = polyline6).

5

Returns:

Type Description
str

The encoded polyline string ("" for no points).

infer_road_candidates

infer_road_candidates(
    density: OffRoadDensity,
    graph: RoadGraph,
    *,
    min_points: int = 3,
    min_length_m: float = 40.0,
    min_novel_fraction: float = 0.8,
    connect_m: float | None = None,
) -> list[RoadCandidateSchema]

Turn committed off-road density into road candidates for review.

Cells with at least min_points positions are closed (3x3), thinned (Zhang-Suen), traced into lines between junctions, simplified (Douglas-Peucker at one cell), joined at each end to the road within connect_m and kept when at least min_length_m long and at least min_novel_fraction of the line is farther than density.off_road_m from every road of graph.

Parameters:

Name Type Description Default
density OffRoadDensity

Committed density (only k-anonymous cells).

required
graph RoadGraph

The base network the candidates are diffed against.

required
min_points int

Least positions for a cell to count.

3
min_length_m float

Shorter lines are dropped (spurs, noise).

40.0
min_novel_fraction float

Least share of the line off every road.

0.8
connect_m float | None

An end of a line within this distance of a road is extended to its projection on that road, so the candidate shows where it joins the network (the stretch near a crossing street is never off-road, so the density alone stops short of it). None is 2 * density.off_road_m; 0 disables it.

None

Returns:

Type Description
list[RoadCandidateSchema]

list[RoadCandidateSchema]: Candidates, longest first.

road_candidates_geojson

road_candidates_geojson(candidates: Sequence[RoadCandidateSchema]) -> dict[str, Any]

Candidates as a GeoJSON FeatureCollection for JOSM/QGIS review.

Parameters:

Name Type Description Default
candidates Sequence[RoadCandidateSchema]

The candidates.

required

Returns:

Type Description
dict[str, Any]

dict[str, Any]: One LineString feature per candidate, its

dict[str, Any]

numbers in properties.

make_match_quality_router

make_match_quality_router(
    store: TrafficSnapshotStore | Callable[[Request], TrafficSnapshotStore],
    *,
    authorize: Callable[..., Coroutine[Any, Any, Any]],
    prefix: str = "/traffic/quality",
    tag: str = "Traffic",
    docs_locale: str | None = None,
) -> APIRouter

Build the router that serves the map-matching quality from store.

GET <prefix> answers a :class:MatchQualityReportSchema: the quality of the last closed window that :meth:TrafficAggregator.flush saved in the snapshot, and the reference measurements of tempest-react-sdk#667 to compare it with. It is a separate router so the operations team can read it under a narrower authorize than traffic.

Parameters:

Name Type Description Default
store TrafficSnapshotStore | Callable[[Request], TrafficSnapshotStore]

The store :meth:TrafficAggregator.flush saves to, or a factory called with each request.

required
authorize Callable[..., Coroutine[Any, Any, Any]]

Dependency that raises unless the caller may read the quality. Mandatory.

required
prefix str

URL prefix. Defaults to "/traffic/quality".

'/traffic/quality'
tag str

OpenAPI tag.

'Traffic'
docs_locale str | None

Language of the OpenAPI text, "en-US" or "pt-BR"; None reads API_DOCS_LOCALE.

None

Returns:

Name Type Description
APIRouter APIRouter

The router, ready for app.include_router.

Raises:

Type Description
ValueError

When authorize is None.

make_traffic_router

make_traffic_router(
    store: TrafficSnapshotStore | Callable[[Request], TrafficSnapshotStore],
    *,
    authorize: Callable[..., Coroutine[Any, Any, Any]],
    graph: RoadGraph | None = None,
    prefix: str = "/traffic",
    tag: str = "Traffic",
    docs_locale: str | None = None,
) -> APIRouter

Build the router that serves traffic from store.

Parameters:

Name Type Description Default
store TrafficSnapshotStore | Callable[[Request], TrafficSnapshotStore]

The store :meth:TrafficAggregator.flush saves to, or a factory called with each request.

required
authorize Callable[..., Coroutine[Any, Any, Any]]

Dependency that raises unless the caller may read traffic. Mandatory.

required
graph RoadGraph | None

When given, also mounts GET <prefix>/graph serving tiles of it.

None
prefix str

URL prefix. Defaults to "/traffic".

'/traffic'
tag str

OpenAPI tag.

'Traffic'
docs_locale str | None

Language of the OpenAPI text, "en-US" or "pt-BR"; None reads API_DOCS_LOCALE.

None

Returns:

Name Type Description
APIRouter APIRouter

The router, ready for app.include_router.

Raises:

Type Description
ValueError

When authorize is None.

build_trip_city_index

build_trip_city_index(
    municipalities: Iterable[Municipality] | None = None,
) -> TripCityIndex

Index municipalities for :func:parse_trip_intent.

Every name of :func:spoken_names, the nicknames of :data:~tempest_fastapi_sdk.geo.BR_CITY_NICKNAMES whose city is in the set, and the Federal District's administrative regions when Brasília is.

Parameters:

Name Type Description Default
municipalities Iterable[Municipality] | None

The cities to recognize, such as the ones a service has routes for. None is the whole country, built once and cached.

None

Returns:

Name Type Description
TripCityIndex TripCityIndex

The index.

parse_trip_intent

parse_trip_intent(
    text: str,
    today: date,
    *,
    municipalities: Iterable[Municipality] | TripCityIndex | None = None,
) -> TripIntent

Read origin, destination, date and part of the day from a trip phrase.

Origin and destination come from prepositions and verbs ("de X", "pra Y", "saindo de X", "indo para Y", "X pra Y"); without them, the cities said count in order (first origin, second destination), by exact name only. Dates: hoje, amanhã, depois de amanhã, a weekday ("próxima sexta", "sexta que vem"), "dia 20", "dia 20 de outubro", "20/10"; periods: madrugada, manhã, tarde, noite. A "leave now" phrase ("agora", "já", "o quanto antes"...) with no other date is today, with :attr:TripIntent.departure_now set.

Parameters:

Name Type Description Default
text str

The phrase as typed or transcribed.

required
today date

The reference date for hoje, amanhã, weekdays and "dia N".

required
municipalities Iterable[Municipality] | TripCityIndex | None

The cities that may be recognized. None is the whole country. A service passes the cities it serves (or a prebuilt :func:build_trip_city_index, reused across phrases), and a real city outside them comes back in unrecognized.

None

Returns:

Name Type Description
TripIntent TripIntent

What was recognized; None is what the phrase did not

TripIntent

say or could not be read.

EARTH_RADIUS_KM module-attribute

EARTH_RADIUS_KM: float = 6371.0088

DEFAULT_CIRCUITY_FACTOR module-attribute

DEFAULT_CIRCUITY_FACTOR: float = 1.3

DEFAULT_CAR_SPEED_KMH module-attribute

DEFAULT_CAR_SPEED_KMH: float = 50.0

DEFAULT_MODE_DURATION_FACTORS module-attribute

DEFAULT_MODE_DURATION_FACTORS: dict[TravelModeEnum, float] = {
    TravelModeEnum.CAR: 1.0,
    TravelModeEnum.MOTORCYCLE: 0.95,
    TravelModeEnum.BUS: 1.6,
    TravelModeEnum.BICYCLE: 3.3,
    TravelModeEnum.PEDESTRIAN: 10.0,
}

DEFAULT_OSRM_BASE_URL module-attribute

DEFAULT_OSRM_BASE_URL: str = 'https://router.project-osrm.org'

DEFAULT_MODE_PROFILES module-attribute

DEFAULT_MODE_PROFILES: dict[TravelModeEnum, str] = {
    TravelModeEnum.CAR: "driving",
    TravelModeEnum.MOTORCYCLE: "driving",
    TravelModeEnum.BUS: "driving",
    TravelModeEnum.BICYCLE: "driving",
    TravelModeEnum.PEDESTRIAN: "driving",
}

DEFAULT_OSRM_MAX_POINTS module-attribute

DEFAULT_OSRM_MAX_POINTS: int = 500

Most points :meth:OSRMBackend.route_through sends in one request.

Matches the public demo at router.project-osrm.org, measured on 2026-11-18: a /route request with 500 coordinates answered "Ok" and one with 501 answered {"code": "TooBig", "message": "Number of entries 501 is higher than current maximum (500)"}. A self-hosted osrm-routed sets its own cap with --max-viaroute-size; pass max_points to :class:OSRMBackend to match it, so the refusal is a local ValueError naming the limit instead of a round trip that fails.

DEFAULT_NOMINATIM_BASE_URL module-attribute

DEFAULT_NOMINATIM_BASE_URL: str = 'https://nominatim.openstreetmap.org'

Public OSM Nominatim server. Rate-limited (~1 req/s), best-effort.

DEFAULT_GEOCODE_CACHE_PRECISION module-attribute

DEFAULT_GEOCODE_CACHE_PRECISION: int = 3

Decimal places a reverse coordinate is rounded to before keying.

Three places is a ~111 m grid (measured with :func:~tempest_fastapi_sdk.geo.haversine_km at 10⁻³ of a degree of latitude); more places fragment the cache without making the answer better, since a street resolves to the same building.

DEFAULT_GEOCODE_CACHE_TTL_SECONDS module-attribute

DEFAULT_GEOCODE_CACHE_TTL_SECONDS: int = 2592000

Default entry lifetime: 30 days.

Long enough that a whole device fleet settles into hits, short enough that a map edit or a corrected place reaches users within a month. Place resolutions are stable on that horizon — the coordinates of a doorway do not move — while a week would re-buy quota every month and "forever" would pin a wrong answer.

DEFAULT_GEOCODE_CACHE_KEY_PREFIX module-attribute

DEFAULT_GEOCODE_CACHE_KEY_PREFIX: str = 'geocoding'

First segment of every key the wrapper builds.

UF_CENTROIDS module-attribute

UF_CENTROIDS: dict[UFEnum, Coordinate] = {
    UFEnum.AC: Coordinate(latitude=-9.0, longitude=-70.5),
    UFEnum.AL: Coordinate(latitude=-9.55, longitude=-36.6),
    UFEnum.AP: Coordinate(latitude=1.4, longitude=-51.8),
    UFEnum.AM: Coordinate(latitude=-3.9, longitude=-63.0),
    UFEnum.BA: Coordinate(latitude=-12.5, longitude=-41.7),
    UFEnum.CE: Coordinate(latitude=-5.1, longitude=-39.5),
    UFEnum.DF: Coordinate(latitude=-15.78, longitude=-47.9),
    UFEnum.ES: Coordinate(latitude=-19.6, longitude=-40.7),
    UFEnum.GO: Coordinate(latitude=-15.9, longitude=-49.7),
    UFEnum.MA: Coordinate(latitude=-5.1, longitude=-45.2),
    UFEnum.MT: Coordinate(latitude=-13.0, longitude=-55.9),
    UFEnum.MS: Coordinate(latitude=-20.5, longitude=-54.7),
    UFEnum.MG: Coordinate(latitude=-18.5, longitude=-44.5),
    UFEnum.PA: Coordinate(latitude=-4.0, longitude=-52.9),
    UFEnum.PB: Coordinate(latitude=-7.2, longitude=-36.7),
    UFEnum.PR: Coordinate(latitude=-24.6, longitude=-51.6),
    UFEnum.PE: Coordinate(latitude=-8.4, longitude=-37.9),
    UFEnum.PI: Coordinate(latitude=-7.4, longitude=-42.5),
    UFEnum.RJ: Coordinate(latitude=-22.25, longitude=-42.7),
    UFEnum.RN: Coordinate(latitude=-5.8, longitude=-36.6),
    UFEnum.RS: Coordinate(latitude=-30.0, longitude=-53.5),
    UFEnum.RO: Coordinate(latitude=-10.9, longitude=-63.4),
    UFEnum.RR: Coordinate(latitude=2.1, longitude=-61.4),
    UFEnum.SC: Coordinate(latitude=-27.2, longitude=-50.5),
    UFEnum.SP: Coordinate(latitude=-22.2, longitude=-48.7),
    UFEnum.SE: Coordinate(latitude=-10.6, longitude=-37.4),
    UFEnum.TO: Coordinate(latitude=-10.2, longitude=-48.3),
}

LOCATIVE_CUES module-attribute

LOCATIVE_CUES: frozenset[str] = frozenset(
    {
        "em",
        "de",
        "da",
        "do",
        "para",
        "pra",
        "pro",
        "ate",
        "moro",
        "morando",
        "vivo",
        "cidade",
        "municipio",
        "natural",
        "nasci",
        "perto",
        "proximo",
        "regiao",
    }
)

Normalized words that, right before a name, make it read as a place.

MAX_NAME_TOKENS module-attribute

MAX_NAME_TOKENS: int = 7

Longest municipality name, in words (São José do Vale do Rio Preto).

STATE_SEPARATORS module-attribute

STATE_SEPARATORS: frozenset[str] = frozenset({'', '-', '/', ',', '–', '—', '(', ')'})

What may sit between a name and the state that follows it (spaces stripped).

UNCUED_SINGLE_WORD_FACTOR module-attribute

UNCUED_SINGLE_WORD_FACTOR: float = 0.5

Score factor for a one-word match with no sign of being a place.

"Feliz", "Natal" and "Alegre" are municipalities and everyday words. A lowercase single word with no locative cue before it (:data:LOCATIVE_CUES), no state after it, and other words around it is kept at half the score, so "estou feliz" ranks below the default min_score while "moro em feliz", "Feliz/RS" and a text that is only "feliz" (a form's city field) do not.

CEP_PATTERN module-attribute

CEP_PATTERN: Pattern[str] = re.compile('\\b(\\d{5})-?(\\d{3})\\b')

A CEP written anywhere in free text, with or without the dash.

Word boundaries on both ends keep it from matching eight digits inside a longer run (a phone number, a document number): "123456789" does not match, "CEP 01310-100, sala 4" does.

LIVE_POSITION_MAX_CLOCK_SKEW module-attribute

LIVE_POSITION_MAX_CLOCK_SKEW: Final[timedelta] = timedelta(seconds=30)

How far in the future recorded_at may be before it is refused.

A phone's clock drifts a few seconds from the server's; refusing anything strictly ahead of now would drop honest positions. Thirty seconds absorbs that drift and still refuses a timestamp that is plainly wrong.

DEFAULT_LIVE_POSITION_KEY_PREFIX module-attribute

DEFAULT_LIVE_POSITION_KEY_PREFIX: Final[str] = 'geo:live'

First segment of every Redis key :class:LivePositionStore writes.

DEFAULT_LIVE_POSITION_TTL_SECONDS module-attribute

DEFAULT_LIVE_POSITION_TTL_SECONDS: Final[int] = 300

How long the latest position lives without a new one: five minutes.

Long enough to survive a tunnel or a dead zone, short enough that a phone that stopped sending (app killed, trip abandoned without :meth:clear) stops showing a stale marker on its own.

DEFAULT_LIVE_POSITION_INTERVAL_SECONDS module-attribute

DEFAULT_LIVE_POSITION_INTERVAL_SECONDS: Final[float] = 5.0

Least time between two accepted positions on one channel.

DEFAULT_LIVE_POSITION_MIN_DISTANCE_M module-attribute

DEFAULT_LIVE_POSITION_MIN_DISTANCE_M: Final[float] = 10.0

Least movement, in meters, for a new position to be accepted.

About the accuracy of a phone GPS in the open: below it, the "movement" is mostly noise.

DEFAULT_LIVE_POSITION_EVENT module-attribute

DEFAULT_LIVE_POSITION_EVENT: Final[str] = 'live_position'

SSE event name of an accepted position.

DEFAULT_LIVE_POSITION_CLEARED_EVENT module-attribute

DEFAULT_LIVE_POSITION_CLEARED_EVENT: Final[str] = 'live_position_cleared'

SSE event name :meth:LivePositionStore.clear sends to the audience.

AudienceResolver module-attribute

AudienceResolver = Callable[[str], Awaitable[Sequence[str]]]

Maps a channel id to the SSE channels (usually user ids) that may see it.

EtaTargetsResolver module-attribute

EtaTargetsResolver = Callable[[str], Awaitable[Mapping[str, Coordinate]]]

Maps a channel id to each recipient's target point ({user_id: point}).

LIVE_POSITION_INACTIVE_ERROR module-attribute

LIVE_POSITION_INACTIVE_ERROR: Final[str] = 'Channel is not accepting positions'

Message of the 409 answered when channel_active says False.

ROAD_GRID_CELL_M module-attribute

ROAD_GRID_CELL_M: Final[float] = 50.0

Edge length of a cell of the spatial index, in metres.

Ported from tempest-react-sdk's ROAD_GRID_CELL_M. Each segment is registered in the cells it passes through (sampled at this step), so a long motorway segment costs cells along its length, not across its bounding box.

ROAD_MATCH_DEFAULTS module-attribute

ROAD_MATCH_DEFAULTS: Final[RoadMatchOptions] = RoadMatchOptions()

Default tuning: sigma 7 m, beta 3 m, radius 200 m, 16 roads, detour 100 m, plus 2 m of detour per second between timed fixes, capped at 60 s.

Ported from tempest-react-sdk's ROAD_MATCH_DEFAULTS, chosen there by sweeping every knob on the Kubicka et al. dataset (100 real drives, 247 251 fixes, node scripts/bench-map-matching.mjs): 92.33% of fixes on the right road, 98.53% without the three drives through yards missing from OSM.

detour_per_second_m and max_interval_s were chosen there on the same drives thinned to one fix every 5-300 s and on public OpenStreetMap traces of five Brazilian city centres (node scripts/bench-br-osm.mjs, PR #678): 2 m/s is the largest rate that leaves the 1 Hz result where it was, and a 60 s cap keeps the long gaps of a 1 Hz trace from widening the search.

OSM_DRIVABLE_HIGHWAYS module-attribute

OSM_DRIVABLE_HIGHWAYS: Final[frozenset[str]] = frozenset(
    {
        "motorway",
        "motorway_link",
        "trunk",
        "trunk_link",
        "primary",
        "primary_link",
        "secondary",
        "secondary_link",
        "tertiary",
        "tertiary_link",
        "unclassified",
        "residential",
        "living_street",
        "service",
        "road",
    }
)

highway values kept by default: roads a motor vehicle drives.

Footways, cycleways, paths, steps and tracks are left out; pass highways=None to keep every way that has a highway tag.

OSM_GEOJSON_COORDINATE_DIGITS module-attribute

OSM_GEOJSON_COORDINATE_DIGITS: Final[int] = 7

Decimals a GeoJSON vertex is rounded to before vertices are joined.

Seven decimals is ~1 cm, the precision OSM stores coordinates at.

OSM_GRAPH_CACHE_SIZE module-attribute

OSM_GRAPH_CACHE_SIZE: Final[int] = 8

Graphs :func:load_road_graph keeps in memory, least recently used out.

DEFAULT_TRAFFIC_EVENT module-attribute

DEFAULT_TRAFFIC_EVENT: Final[str] = 'traffic_updated'

SSE event name :meth:TrafficAggregator.flush sends after a new snapshot.

DEFAULT_TRAFFIC_PRIVACY module-attribute

DEFAULT_TRAFFIC_PRIVACY: Final[TrafficPrivacy] = TrafficPrivacy()

k 5, 5-minute window, 200 m trim, 5-minute trip gap, 50 m accuracy.

DEFAULT_TRAFFIC_SNAPSHOT_KEY module-attribute

DEFAULT_TRAFFIC_SNAPSHOT_KEY: Final[str] = 'geo:traffic:snapshot'

Redis key :class:RedisTrafficSnapshotStore writes the snapshot under.

TRAFFIC_MIN_DEVICES_FLOOR module-attribute

TRAFFIC_MIN_DEVICES_FLOOR: Final[int] = 2

Least min_devices accepted: one device per edge is not anonymity.

TrafficAudienceResolver module-attribute

TrafficAudienceResolver = Callable[[], Awaitable[Sequence[str]]]

Answers the SSE channels (usually user ids) told that traffic changed.

TrafficDimensionsResolver module-attribute

TrafficDimensionsResolver = Callable[..., Awaitable[Mapping[str, str] | None]]

FastAPI dependency answering a trip's coarse quality dimensions, or None.

Given to make_live_position_router(traffic_dimensions=...).

TRAFFIC_INVALID_BBOX_ERROR module-attribute

TRAFFIC_INVALID_BBOX_ERROR: Final[str] = (
    "min_latitude must not exceed max_latitude, nor min_longitude max_longitude"
)

Message of the 422 answered for an inverted bounding box.

DEFAULT_MATCH_QUALITY_WINDOW_SECONDS module-attribute

DEFAULT_MATCH_QUALITY_WINDOW_SECONDS: Final[int] = 3600

Length of a quality window: one hour, so a cell gathers k devices.

MATCH_QUALITY_MAX_DIMENSIONS module-attribute

MATCH_QUALITY_MAX_DIMENSIONS: Final[int] = 4

Most coarse dimensions a quality cell can be split by.

MATCH_QUALITY_REFERENCES module-attribute

Every reference :func:make_match_quality_router answers with.

MATCH_QUALITY_REFERENCE_KUBICKA module-attribute

MATCH_QUALITY_REFERENCE_KUBICKA: Final[MatchQualityReferenceSchema] = (
    MatchQualityReferenceSchema(
        name="kubicka",
        source="tempest-react-sdk#667, phase 2 (2026-11-19): Kubicka et al., Zenodo 57731, 100 drives, 247 251 fixes; node scripts/bench-map-matching.mjs",
        note="breaks: 48 in 247 251 fixes. The snap distance there is position to the true route, not to the matched point.",
        positions=247251,
        breaks_per_1000_positions=0.19,
        snap_distance_median_m=3.7,
        sampling_interval_median_s=1.0,
    )
)

The Kubicka et al. dataset (worldwide, ~1 Hz), as matched in #667.

Ported from tempest-react-sdk#667 (comment "Fase 2" and the Brazil table's Kubicka column, measured 2026-11-19).

MATCH_QUALITY_REFERENCE_BRAZIL_OSM module-attribute

MATCH_QUALITY_REFERENCE_BRAZIL_OSM: Final[MatchQualityReferenceSchema] = (
    MatchQualityReferenceSchema(
        name="brazil-osm",
        source="tempest-react-sdk#667, Brazil validation (2026-11-19): public OSM GPS traces of Sao Paulo, Rio, Teresina, Sao Carlos and Parnaiba, 161 vehicle runs, 19 806 positions; node scripts/bench-br-osm.mjs",
        note="Measured over whole runs, without the 200 m trim; the aggregator measures released stretches, so straight stretches at a stretch edge are shorter.",
        positions=19806,
        straight_km=119.7,
        breaks_per_1000_positions=1.06,
        matched_share=1.0,
        inferred_share=0.551,
        snap_distance_median_m=3.7,
        snap_distance_p90_m=11.6,
        sampling_interval_median_s=1.0,
        sampling_interval_p90_s=4.0,
        parallel_switches_per_km=0.109,
    )
)

Public OSM traces of five Brazilian cities, as matched in #667.

Ported from tempest-react-sdk#667 (comment "Validação no Brasil", column "Brasil (todas)", measured 2026-11-19).

SNAP_DISTANCE_BUCKETS_M module-attribute

SNAP_DISTANCE_BUCKETS_M: Final[tuple[float, ...]] = _bounds(
    (5.0, 0.1), (20.0, 0.25), (50.0, 1.0), (200.0, 5.0), (500.0, 50.0)
)

Upper bounds of the position → matched point histogram, metres.

0.1 m wide up to 5 m, 0.25 m up to 20 m, 1 m up to 50 m, 5 m up to 200 m (the default candidate radius), 50 m up to 500 m; above, one overflow bucket.

SAMPLING_INTERVAL_BUCKETS_S module-attribute

SAMPLING_INTERVAL_BUCKETS_S: Final[tuple[float, ...]] = _bounds(
    (2.0, 0.25), (10.0, 0.5), (30.0, 1.0), (120.0, 5.0), (300.0, 30.0)
)

Upper bounds of the sampling interval histogram, seconds.

Whole seconds are bounds up to 30 s, so a 1 Hz or 2 s source reads exactly.

STRAIGHT_HALF_M module-attribute

STRAIGHT_HALF_M: Final[float] = 75.0

Track length before and after a position that decides if it is straight.

Ported from tempest-react-sdk's scripts/bench-br-osm.mjs (STRAIGHT_HALF_M).

STRAIGHT_MAX_TURN_DEG module-attribute

STRAIGHT_MAX_TURN_DEG: Final[float] = 10.0

Largest bearing change, over :data:STRAIGHT_HALF_M each side, of a straight stretch.

Ported from tempest-react-sdk's scripts/bench-br-osm.mjs (STRAIGHT_MAX_TURN_DEG).

PARALLEL_MAX_DEG module-attribute

PARALLEL_MAX_DEG: Final[float] = 20.0

Largest angle between two edges for a switch between them to be parallel.

Ported from tempest-react-sdk's scripts/bench-br-osm.mjs (PARALLEL_MAX_DEG).

PARALLEL_MIN_OFFSET_M module-attribute

PARALLEL_MIN_OFFSET_M: Final[float] = 8.0

Least distance from the new matched point to the old edge's line for a switch to count as parallel (a collinear continuation does not).

Ported from tempest-react-sdk's scripts/bench-br-osm.mjs (PARALLEL_MIN_OFFSET_M).

UNKNOWN_DIMENSION_VALUE module-attribute

UNKNOWN_DIMENSION_VALUE: Final[str] = 'unknown'

Value of a declared dimension the app did not give for a trip.

DEFAULT_DENSITY_CELL_M module-attribute

DEFAULT_DENSITY_CELL_M: Final[float] = 5.0

Side of a density cell, metres: finer than a lane, coarser than GPS noise.

DEFAULT_DENSITY_BLOCK_CELLS module-attribute

DEFAULT_DENSITY_BLOCK_CELLS: Final[int] = 5

Side of a k-anonymity block, in cells: 5 x 5 m = 25 m.

k is decided per block, not per 5 m cell: with GPS noise a device spreads its points over several cells across the road, so k distinct devices in one 5 m cell is rare where k in a 25 m block is not. Measured on the synthetic street of scripts/bench_geo_traffic.py (k 5, sigma 5 m): deciding per cell, 20 trips a day gave no candidate and 40 recovered the street; per block, 12 trips recover 77% of it and 20 all of it. Counts stay per cell.

DEFAULT_DENSITY_EPOCH_SECONDS module-attribute

DEFAULT_DENSITY_EPOCH_SECONDS: Final[int] = 86400

Epoch of the density hashes: one day, then only counts remain.

DEFAULT_OFF_ROAD_M module-attribute

DEFAULT_OFF_ROAD_M: Final[float] = 20.0

Distance from every road beyond which a position counts as off-road.

The phase-0 measurement of tempest-react-sdk#667 (Kubicka et al., 247 251 fixes) found 9.4% of fixes farther than 20 m from any road of their OSM excerpt, and 90.6% within it: the raw signal of a road the base lacks.

DEFAULT_OVERPASS_URL module-attribute

DEFAULT_OVERPASS_URL: Final[str] = 'https://overpass-api.de/api/interpreter'

Public OpenStreetMap Overpass API interpreter endpoint.

DEFAULT_OVERPASS_AMENITY_TYPES module-attribute

DEFAULT_OVERPASS_AMENITY_TYPES: Final[tuple[str, ...]] = (
    "restaurant",
    "cafe",
    "bar",
    "pub",
    "fast_food",
    "ice_cream",
    "pharmacy",
    "clinic",
    "hospital",
    "dentist",
    "doctors",
    "veterinary",
    "bank",
    "fuel",
    "school",
    "library",
    "cinema",
    "theatre",
    "post_office",
    "marketplace",
)

Default OSM amenity values queried alongside shop elements.

DEFAULT_OVERPASS_RETRY_STATUSES module-attribute

DEFAULT_OVERPASS_RETRY_STATUSES: Final[frozenset[int]] = frozenset({429, 502, 503, 504})

HTTP status codes retried by default against an Overpass server.

DEFAULT_GRID_DECIMAL_PLACES module-attribute

DEFAULT_GRID_DECIMAL_PLACES: int = 2

Default number of decimal places for spatial grid cells (~1.11 km per step).