Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,123 @@ Callers loading a direct CID have no STAC resolution mapping and must pass
generator's `metadataGroup` is internal catalog-generation configuration and
does not influence client selection.

## Entity data usage

Gridded Zarr datasets come from `load_dataset`. Point-observation **entity**
datasets (GHCND and friends) live under `client.entities`, and read the same way:
degrees, ISO timestamps, chained selections.

"Entity" is the underlying library's word for the thing a row belongs to — a
weather station in GHCND, a buoy in NDBC. Not every dataset is keyed by a place,
so an entity need not have a position at all, and those simply never match a geo
query.

Entity support is built on
[`tabular-py`](https://github.com/dClimate/tabular-py), which installs
automatically as a dependency. It is imported as `tabular_py` but distributed as
`dclimate-tabular-py`, because PyPI normalises the name `tabular-py` onto an
unrelated existing project.

```python
async with dClimateClient() as client:
ghcnd = await client.entities.load("bafyr4i...")

# Every entity, with position and coverage window.
for e in await ghcnd.list_entities():
print(e.entity_id, e.latitude, e.longitude, e.start, e.end)

# Entities within 50 km of a point, over one week.
records = await (
ghcnd
.circle(40.75, -73.99, 50)
.time_range("2023-01-01", "2023-01-07")
.to_records("TMAX")
)
```

Reads go through the client's own IPFS transport, so pinning, retries, and
configured endpoints apply to entity reads too. Resolution is by CID for now;
STAC catalog support will follow.

Column names come from the dataset's own schema, uppercased — which is how every
dClimate dataset published so far names them, so `TMAX` and `PRCP` work as
documented. A dataset whose published names are not simply the uppercase of its
stored ones needs its own mapping, passed as `column_key`:

```python
# The reader's default. Pass a different one only for a dataset that needs it.
mixed = await client.entities.load("bafyr4i...", column_key=lambda f: f.name)
print([c.name for c in mixed.columns()]) # the schema's own names, verbatim
```

Each column also states the unit its values are in. Units are documentation,
never an instruction to convert: a GHCND `TMAX` declaring `degC_tenths` really
does return `194` for 19.4 °C.

An entity can additionally declare windows of its history that are *unknown*, as
distinct from empty — a fetch that failed, say. Without that, zero rows and "no
observations" are indistinguishable:

```python
plan = await ghcnd.select("USW00023174").time_range("2024-01-01", "2024-12-31").plan()
for entity_id, gaps in plan.gaps:
for gap in gaps:
print(entity_id, gap.reason) # e.g. "awdb: HTTP 500"
```

Selections return new instances, so a partial selection can be branched:

```python
week = ghcnd.time_range("2023-01-01", "2023-01-07")
nyc = await week.select("USW00094728").rows()
lax = await week.select("USW00023174").rows()
```

Two things differ from `GeotemporalData`, because the data model differs:

- **`nearest(lat, lon, max_km=...)` instead of a point selection.** A grid always
has a cell under any coordinate; entities are irregular, so the nearest one may
be far away. Pass `max_km` to make that a hard bound rather than a surprise.
- **`where(...)` has no gridded counterpart.** Row-level predicates are pushed
down to fragment statistics, so most fragments are skipped without being read:

```python
from tabular_py import gt

# `nearest` reads the entity index to find the match, so it is awaited --
# unlike the synchronous selections above.
hot_days = await (
(await ghcnd.nearest(29.98, -95.36))
.time_range("2025-01-01", "2025-12-31")
.where(gt("TMAX", 350)) # tenths of °C, so 35 °C
.rows()
)
```

`nearest` alone means the nearest *entity*, which is not always the nearest
*usable data*: near downtown Los Angeles the closest station is 0.63 km away and
has never recorded `TMAX`, while the closest that has is 5.4 km away. Ask for the
columns you need, and narrow them to a time range when "has ever reported" is not
good enough:

```python
# Resolves the dataset and the entity in one call.
nearest = await client.entities.nearest(
"bafyr4i...",
34.0522, -118.2437,
columns=["TMAX"],
within=("2024-01-01", "2024-12-31"),
max_km=50,
)
print(nearest.entity_id, nearest.km)
```

Entity failures arrive as this library's own errors, for the whole chain rather
than just `load`: an unknown column is an `InvalidSelectionError`, a well-formed
query that matched nothing is a `NoDataFoundError`, and bytes that do not
describe a readable dataset are a `DatasetCorruptError`. All descend from
`ZarrClientError`, so one `except` still covers the client.

## Siren API usage

The Python client also exposes a Siren REST client for metrics and regions.
Expand Down
17 changes: 17 additions & 0 deletions dclimate_client_py/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,17 @@
)
from .dclimate_zarr_errors import (
ConflictingResolutionSelectionError,
DatasetCorruptError,
DatasetNotFoundError,
InvalidSelectionError,
NoDataFoundError,
MultiresolutionSelectionRequiredError,
ResolutionNotAvailableError,
SirenApiError,
TabularNotInstalledError,
X402PaymentError,
X402NotInstalledError,
ZarrClientError,
)

_LAZY_IMPORTS = {
Expand All @@ -48,6 +54,8 @@
"dClimateClient": (".dclimate_client", "dClimateClient"),
"GeotemporalData": (".geotemporal_data", "GeotemporalData"),
"load_stac_catalog": (".stac_catalog", "load_stac_catalog"),
"EntitiesClient": (".entities", "EntitiesClient"),
"WrappedEntityDataset": (".entities", "WrappedEntityDataset"),
"list_available_datasets": (".stac_catalog", "list_available_datasets"),
}

Expand Down Expand Up @@ -88,6 +96,11 @@ def __dir__() -> list[str]:
"resolve_cid_from_stac_server",
"list_available_datasets_from_stac_server",
"STAC_SERVER_URL",
"ZarrClientError",
"DatasetCorruptError",
"DatasetNotFoundError",
"InvalidSelectionError",
"NoDataFoundError",
"MultiresolutionSelectionRequiredError",
"ResolutionNotAvailableError",
"ConflictingResolutionSelectionError",
Expand All @@ -105,4 +118,8 @@ def __dir__() -> list[str]:
"SirenApiError",
"X402PaymentError",
"X402NotInstalledError",
# Entities
"EntitiesClient",
"WrappedEntityDataset",
"TabularNotInstalledError",
]
51 changes: 51 additions & 0 deletions dclimate_client_py/dclimate_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
list_versions_from_url,
)
from .siren import SirenClient
from .entities import EntitiesClient
from .siren.types import (
SirenMetricDataPoint,
SirenMetricQuery,
Expand Down Expand Up @@ -170,6 +171,10 @@ def __init__(
if siren is not None:
self._siren_client = SirenClient(siren)

# Entity datasets. Unlike Siren this needs no configuration, so it is
# built on first access rather than here -- see the `entities` property.
self._entities_client: typing.Optional["EntitiesClient"] = None

async def __aenter__(self) -> "dClimateClient":
"""Initialize KuboCAS when entering async context."""
# Create KuboCAS with configured endpoints
Expand Down Expand Up @@ -217,6 +222,19 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
except BaseException as error:
cleanup_error = _merge_cleanup_error(cleanup_error, error)

try:
if self._entities_client is not None:
await self._entities_client.aclose()
except BaseException as error:
cleanup_error = _merge_cleanup_error(cleanup_error, error)
finally:
# Dropped, not just closed. It holds the `KuboCAS` closed below, and
# a closed `KuboCAS` never reopens -- so keeping this instance would
# make entity reads after the context fail on a dead transport
# instead of falling back to the gateway, which is what the
# `entities` property promises outside the context.
self._entities_client = None

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
try:
if self._kubo_cas is not None:
await self._kubo_cas.__aexit__(exc_type, exc_val, exc_tb)
Expand Down Expand Up @@ -848,6 +866,39 @@ async def get_dataset_version(
commit_id,
)

# ------------------------------------------------------------------
# Entity (point-observation) datasets
# ------------------------------------------------------------------

@property
def entities(self) -> EntitiesClient:
"""Entity datasets, e.g. ``await client.entities.load(cid)``.

Unlike :attr:`siren`, this needs no configuration -- it reads over the
transport the client already has, so requiring an option would be
ceremony with nothing behind it.

Reads prefer the client's own ``KuboCAS`` when the client is open, so
pinning, retries, and configured endpoints apply to entity reads too.
Outside the async context there is no ``KuboCAS`` yet, so this falls back
to the plain HTTP gateway -- which is why the instance is rebuilt if it
was first created before ``__aenter__``.
"""
cas = self._kubo_cas
current = self._entities_client
if current is None or current._cas is not cas:
replacement = EntitiesClient(
gateway_url=self._catalog_gateway_base_url,
cas=cas,
)
if current is not None:
# The replacement inherits any gateway sources the old instance
# opened. It is the only one `__aexit__` closes, so without this
# those connection pools would leak.
replacement._adopt_sources_from(current)
current = self._entities_client = replacement
return current

# ------------------------------------------------------------------
# Siren REST API methods
# ------------------------------------------------------------------
Expand Down
16 changes: 16 additions & 0 deletions dclimate_client_py/dclimate_zarr_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,18 @@ class ConflictingResolutionSelectionError(InvalidSelectionError):
"""Raised when both resolution and raw Zarr group are provided."""


class DatasetCorruptError(ZarrClientError):
"""Raised when the stored dataset is malformed, rather than the request against it.

Distinct from :class:`InvalidSelectionError` because the two point at
different culprits. An invalid selection is the caller's to fix by asking
differently; this says the bytes behind the CID are inconsistent, so no
rephrasing helps and the dataset's publisher is who needs to know. Reporting
it as a bad selection would send a caller hunting for a mistake in their own
query.
"""


class VariantNotFoundError(ZarrClientError):
"""Raised when specified variant is not found in dataset"""

Expand All @@ -112,3 +124,7 @@ class X402PaymentError(ZarrClientError):

class X402NotInstalledError(ZarrClientError):
"""Raised when x402 auth is configured but the x402 package is not installed"""


class TabularNotInstalledError(ZarrClientError):
"""Raised when entity data is requested but tabular-py is not installed"""
22 changes: 22 additions & 0 deletions dclimate_client_py/entities/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Entity (point-observation) dataset support, built on ``tabular_py``.

"Entity" is tabular's word for the thing a row belongs to -- a weather station in
GHCND, a buoy in NDBC -- and this namespace follows it rather than keeping an
older ``station`` vocabulary the layer beneath no longer uses.

``tabular_py`` is imported lazily, at load time rather than here. It is an
ordinary dependency, so it should always be present; deferring the import keeps
importing this library cheap, and keeps a broken or partial install from taking
down every other namespace along with entity support.
"""

from .entities_client import EntitiesClient
from .errors import translate_entity_error
from .wrap import WrappedEntityDataset, wrap_entity_dataset

__all__ = [
"EntitiesClient",
"WrappedEntityDataset",
"translate_entity_error",
"wrap_entity_dataset",
]
Loading
Loading