forcingkit-client 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forcingkit_client/__init__.py +18 -0
- forcingkit_client/client.py +512 -0
- forcingkit_client/schema.py +56 -0
- forcingkit_client/store.py +73 -0
- forcingkit_client/trajectory.py +264 -0
- forcingkit_client-0.1.0.dist-info/METADATA +51 -0
- forcingkit_client-0.1.0.dist-info/RECORD +9 -0
- forcingkit_client-0.1.0.dist-info/WHEEL +4 -0
- forcingkit_client-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Lightweight client for a forcingkit service."""
|
|
2
|
+
|
|
3
|
+
from .client import AsyncClient, Client, ForcingkitError
|
|
4
|
+
from .schema import SchemaError, normalise
|
|
5
|
+
from .trajectory import interpolate_points, interpolate_trajectory, trajectory_window
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"AsyncClient",
|
|
9
|
+
"Client",
|
|
10
|
+
"ForcingkitError",
|
|
11
|
+
"SchemaError",
|
|
12
|
+
"interpolate_points",
|
|
13
|
+
"interpolate_trajectory",
|
|
14
|
+
"normalise",
|
|
15
|
+
"trajectory_window",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
"""Clients for a forcingkit service, synchronous (`Client`) and asynchronous (`AsyncClient`).
|
|
2
|
+
|
|
3
|
+
Store builds go through the service's job queue: the client submits a job, polls its status URL
|
|
4
|
+
and, once it has succeeded, opens the store named by the job's STAC Item over HTTP through a local
|
|
5
|
+
chunk cache. A second request for the same store is answered from the cache.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import hashlib
|
|
10
|
+
import io
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
import zipfile
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any, Callable, Dict, Optional, Sequence, TypeAlias
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
import xarray as xr
|
|
23
|
+
|
|
24
|
+
from .schema import normalise
|
|
25
|
+
from .store import open_remote
|
|
26
|
+
|
|
27
|
+
BBox: TypeAlias = Sequence[float] # (west, south, east, north), degrees
|
|
28
|
+
TimeLike: TypeAlias = str | datetime | pd.Timestamp | np.datetime64
|
|
29
|
+
|
|
30
|
+
DEFAULT_CACHE_DIR = "~/.cache/forcingkit-client"
|
|
31
|
+
ProgressCallback = Callable[[Dict[str, Any]], None]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ForcingkitError(RuntimeError):
|
|
35
|
+
"""A request the service refused or a job that failed; `detail` carries the server's text."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, message: str, status: Optional[int] = None, detail: Any = None):
|
|
38
|
+
super().__init__(message)
|
|
39
|
+
self.status = status
|
|
40
|
+
self.detail = detail
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def iso_utc(t: TimeLike) -> str:
|
|
44
|
+
"""`t` as an ISO 8601 UTC string without offset; naive times are taken as UTC."""
|
|
45
|
+
ts = pd.Timestamp(t)
|
|
46
|
+
if ts.tzinfo is not None:
|
|
47
|
+
ts = ts.tz_convert("UTC").tz_localize(None)
|
|
48
|
+
return ts.strftime("%Y-%m-%dT%H:%M:%S")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _bbox(bbox: BBox) -> Dict[str, float]:
|
|
52
|
+
west, south, east, north = (float(v) for v in bbox)
|
|
53
|
+
if not (south < north and west < east):
|
|
54
|
+
raise ValueError(f"bbox must be (west, south, east, north), got {tuple(bbox)}")
|
|
55
|
+
return {"min_lon": west, "min_lat": south, "max_lon": east, "max_lat": north}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _ocean_request(
|
|
59
|
+
bbox, start, hours, vertical_spacing_m, pad_cells, sponge_cells, **options
|
|
60
|
+
):
|
|
61
|
+
return {
|
|
62
|
+
"bbox": _bbox(bbox),
|
|
63
|
+
"start_date": iso_utc(start),
|
|
64
|
+
"duration_hours": int(hours),
|
|
65
|
+
"vertical_spacing_m": float(vertical_spacing_m),
|
|
66
|
+
# Model-boundary options a non-model caller rarely wants: one donor cell of padding so
|
|
67
|
+
# the store brackets the box, and no sponge.
|
|
68
|
+
"pad_cells": int(pad_cells),
|
|
69
|
+
"sponge_cells": int(sponge_cells),
|
|
70
|
+
**options,
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _atmosphere_request(bbox, start, hours, resolution_deg, margin_deg, cache_bust):
|
|
75
|
+
return {
|
|
76
|
+
"bbox": _bbox(bbox),
|
|
77
|
+
"start_time": iso_utc(start),
|
|
78
|
+
"hours": int(hours),
|
|
79
|
+
"resolution_deg": float(resolution_deg),
|
|
80
|
+
"margin_deg": float(margin_deg),
|
|
81
|
+
"cache_bust": bool(cache_bust),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _waves_request(bbox, start, hours, wfo, grid, cache_bust):
|
|
86
|
+
return {
|
|
87
|
+
"bbox": _bbox(bbox),
|
|
88
|
+
"start_time": iso_utc(start),
|
|
89
|
+
"hours": int(hours),
|
|
90
|
+
"source": "nwps",
|
|
91
|
+
"wfo": str(wfo),
|
|
92
|
+
"grid": str(grid),
|
|
93
|
+
"cache_bust": bool(cache_bust),
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _ndbc_dataset(data: Dict[str, Any]) -> xr.Dataset:
|
|
98
|
+
"""The /api/v1/ndbc payload as one Dataset on a shared time axis (outer join)."""
|
|
99
|
+
parts = []
|
|
100
|
+
products = data.get("products", {})
|
|
101
|
+
if "stdmet" in products:
|
|
102
|
+
p = products["stdmet"]
|
|
103
|
+
times = pd.to_datetime(p["times"]).tz_localize(None)
|
|
104
|
+
ds = xr.Dataset(coords={"time": times})
|
|
105
|
+
for name, units in p.get("units", {}).items():
|
|
106
|
+
ds[name] = ("time", np.asarray(p[name], dtype=np.float64))
|
|
107
|
+
ds[name].attrs["units"] = units
|
|
108
|
+
parts.append(ds)
|
|
109
|
+
if "adcp" in products:
|
|
110
|
+
p = products["adcp"]
|
|
111
|
+
times = pd.to_datetime(p["times"]).tz_localize(None)
|
|
112
|
+
ds = xr.Dataset(coords={"time": times})
|
|
113
|
+
for name, key in (
|
|
114
|
+
("current_u", "u"),
|
|
115
|
+
("current_v", "v"),
|
|
116
|
+
("current_depth", "depth_m"),
|
|
117
|
+
):
|
|
118
|
+
if len(p.get(key, [])) == len(times):
|
|
119
|
+
ds[name] = ("time", np.asarray(p[key], dtype=np.float64))
|
|
120
|
+
if "current_u" in ds:
|
|
121
|
+
ds["current_u"].attrs.update(
|
|
122
|
+
units="m s-1", standard_name="eastward_sea_water_velocity"
|
|
123
|
+
)
|
|
124
|
+
ds["current_v"].attrs.update(
|
|
125
|
+
units="m s-1", standard_name="northward_sea_water_velocity"
|
|
126
|
+
)
|
|
127
|
+
if "current_depth" in ds:
|
|
128
|
+
ds["current_depth"].attrs.update(units="m", positive="down")
|
|
129
|
+
parts.append(ds)
|
|
130
|
+
out = xr.merge(parts, join="outer") if parts else xr.Dataset()
|
|
131
|
+
out.attrs.update(
|
|
132
|
+
station_id=data.get("station_id"),
|
|
133
|
+
lat=data.get("lat"),
|
|
134
|
+
lon=data.get("lon"),
|
|
135
|
+
sources=list(data.get("sources", [])),
|
|
136
|
+
)
|
|
137
|
+
return out
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _bathymetry_key(bbox: BBox, resolution_m: float) -> str:
|
|
141
|
+
return hashlib.sha256(
|
|
142
|
+
f"{tuple(map(float, bbox))}_{float(resolution_m)}".encode()
|
|
143
|
+
).hexdigest()[:16]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _unpack_bathymetry(content: bytes, target: Path) -> xr.DataArray:
|
|
147
|
+
partial = target.with_suffix(".part")
|
|
148
|
+
with zipfile.ZipFile(io.BytesIO(content)) as z:
|
|
149
|
+
z.extractall(partial)
|
|
150
|
+
os.replace(partial, target)
|
|
151
|
+
return _open_bathymetry(target)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _open_bathymetry(target: Path) -> xr.DataArray:
|
|
155
|
+
# The archive holds either the store's contents or the store directory itself.
|
|
156
|
+
markers = (".zgroup", ".zmetadata", "zarr.json")
|
|
157
|
+
root = next(
|
|
158
|
+
(
|
|
159
|
+
p
|
|
160
|
+
for p in [target, *sorted(target.rglob("*"))]
|
|
161
|
+
if p.is_dir() and any((p / m).exists() for m in markers)
|
|
162
|
+
),
|
|
163
|
+
None,
|
|
164
|
+
)
|
|
165
|
+
if root is None:
|
|
166
|
+
raise ForcingkitError(f"bathymetry archive at {target} holds no Zarr store")
|
|
167
|
+
ds = xr.open_zarr(root)
|
|
168
|
+
name = next(iter(ds.data_vars))
|
|
169
|
+
return ds[name]
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class _Base:
|
|
173
|
+
def __init__(
|
|
174
|
+
self,
|
|
175
|
+
base_url: str,
|
|
176
|
+
cache_dir: str | Path = DEFAULT_CACHE_DIR,
|
|
177
|
+
poll_s: float = 5.0,
|
|
178
|
+
timeout_s: float = 3 * 3600.0,
|
|
179
|
+
on_progress: Optional[ProgressCallback] = None,
|
|
180
|
+
):
|
|
181
|
+
self.base_url = base_url.rstrip("/")
|
|
182
|
+
self.cache_dir = Path(cache_dir).expanduser()
|
|
183
|
+
self.poll_s = poll_s
|
|
184
|
+
self.timeout_s = timeout_s
|
|
185
|
+
self.on_progress = on_progress
|
|
186
|
+
|
|
187
|
+
def _url(self, path: str) -> str:
|
|
188
|
+
return f"{self.base_url}{path}"
|
|
189
|
+
|
|
190
|
+
def _local(self, href: str) -> str:
|
|
191
|
+
"""`href` re-rooted on this client's base URL: the service names itself as it saw the
|
|
192
|
+
request, which need not be an address this host can reach."""
|
|
193
|
+
return self._url(urlsplit(href).path)
|
|
194
|
+
|
|
195
|
+
@staticmethod
|
|
196
|
+
def _check(response: httpx.Response) -> Any:
|
|
197
|
+
if response.status_code >= 400:
|
|
198
|
+
try:
|
|
199
|
+
detail = response.json().get("detail")
|
|
200
|
+
except Exception:
|
|
201
|
+
detail = response.text
|
|
202
|
+
raise ForcingkitError(
|
|
203
|
+
f"{response.request.method} {response.request.url.path} failed "
|
|
204
|
+
f"({response.status_code}): {detail}",
|
|
205
|
+
status=response.status_code,
|
|
206
|
+
detail=detail,
|
|
207
|
+
)
|
|
208
|
+
return response.json()
|
|
209
|
+
|
|
210
|
+
def _settled(self, job: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
211
|
+
"""The job's STAC Item once it has succeeded, None while it runs; raises on failure."""
|
|
212
|
+
if self.on_progress is not None:
|
|
213
|
+
self.on_progress(job)
|
|
214
|
+
if job["status"] == "succeeded":
|
|
215
|
+
return job["result"]
|
|
216
|
+
if job["status"] == "failed":
|
|
217
|
+
raise ForcingkitError(
|
|
218
|
+
f"{job['kind']} job {job['job_id']} failed: {job['error']}",
|
|
219
|
+
detail=job["error"],
|
|
220
|
+
)
|
|
221
|
+
return None
|
|
222
|
+
|
|
223
|
+
def open_item(self, item: Dict[str, Any]) -> xr.Dataset:
|
|
224
|
+
"""Open the store a job's STAC Item describes, through the local cache, normalised."""
|
|
225
|
+
props = item["properties"]
|
|
226
|
+
ds = open_remote(
|
|
227
|
+
self._local(item["assets"]["zarr"]["href"]),
|
|
228
|
+
self.cache_dir,
|
|
229
|
+
item["id"],
|
|
230
|
+
str(props["forcingkit:store_version"]),
|
|
231
|
+
)
|
|
232
|
+
ds = normalise(ds)
|
|
233
|
+
ds.attrs.update(
|
|
234
|
+
{
|
|
235
|
+
"forcingkit_store_id": item["id"],
|
|
236
|
+
"forcingkit_store_version": str(props["forcingkit:store_version"]),
|
|
237
|
+
"forcingkit_donor": props.get("forcingkit:donor") or "",
|
|
238
|
+
"forcingkit_schema": props.get("forcingkit:schema") or "",
|
|
239
|
+
}
|
|
240
|
+
)
|
|
241
|
+
return ds
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class Client(_Base):
|
|
245
|
+
"""Synchronous client.
|
|
246
|
+
|
|
247
|
+
>>> fk = Client("http://localhost:9598")
|
|
248
|
+
>>> ocean = fk.ocean((-70.9, 41.3, -70.6, 41.6), "2025-07-01", 24)
|
|
249
|
+
"""
|
|
250
|
+
|
|
251
|
+
def __init__(
|
|
252
|
+
self,
|
|
253
|
+
base_url: str,
|
|
254
|
+
*args: Any,
|
|
255
|
+
http: Optional[httpx.Client] = None,
|
|
256
|
+
**kwargs: Any,
|
|
257
|
+
):
|
|
258
|
+
super().__init__(base_url, *args, **kwargs)
|
|
259
|
+
self._http = http or httpx.Client(timeout=httpx.Timeout(120.0, connect=10.0))
|
|
260
|
+
|
|
261
|
+
def close(self) -> None:
|
|
262
|
+
self._http.close()
|
|
263
|
+
|
|
264
|
+
def __enter__(self) -> "Client":
|
|
265
|
+
return self
|
|
266
|
+
|
|
267
|
+
def __exit__(self, *exc: Any) -> None:
|
|
268
|
+
self.close()
|
|
269
|
+
|
|
270
|
+
def _wait(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
271
|
+
job = self._check(self._http.post(self._url(path), json=payload))
|
|
272
|
+
deadline = time.monotonic() + self.timeout_s
|
|
273
|
+
while (item := self._settled(job)) is None:
|
|
274
|
+
if time.monotonic() > deadline:
|
|
275
|
+
raise ForcingkitError(
|
|
276
|
+
f"job {job['job_id']} still {job['status']} after {self.timeout_s:.0f} s"
|
|
277
|
+
)
|
|
278
|
+
time.sleep(self.poll_s)
|
|
279
|
+
job = self._check(self._http.get(self._local(job["status_url"])))
|
|
280
|
+
return item
|
|
281
|
+
|
|
282
|
+
def ocean(
|
|
283
|
+
self,
|
|
284
|
+
bbox: BBox,
|
|
285
|
+
start: TimeLike,
|
|
286
|
+
hours: int,
|
|
287
|
+
vertical_spacing_m: float = 2.0,
|
|
288
|
+
pad_cells: int = 1,
|
|
289
|
+
sponge_cells: int = 0,
|
|
290
|
+
**options: Any,
|
|
291
|
+
) -> xr.Dataset:
|
|
292
|
+
"""The parent ocean over `bbox` for `hours` from `start`: `u, v` (m/s), `temp` (deg C),
|
|
293
|
+
`salt`, `zeta` (m) on `(time, z, lat, lon)`, z in metres positive up. Further `options`
|
|
294
|
+
(`include_tides`, `allow_donor_fallback`, `cache_bust`, ...) pass through to the service."""
|
|
295
|
+
payload = _ocean_request(
|
|
296
|
+
bbox, start, hours, vertical_spacing_m, pad_cells, sponge_cells, **options
|
|
297
|
+
)
|
|
298
|
+
return self.open_item(self._wait("/api/v1/jobs/obc", payload))
|
|
299
|
+
|
|
300
|
+
def atmosphere(
|
|
301
|
+
self,
|
|
302
|
+
bbox: BBox,
|
|
303
|
+
start: TimeLike,
|
|
304
|
+
hours: int,
|
|
305
|
+
resolution_deg: float = 0.03,
|
|
306
|
+
margin_deg: float = 0.25,
|
|
307
|
+
cache_bust: bool = False,
|
|
308
|
+
) -> xr.Dataset:
|
|
309
|
+
"""HRRR surface atmosphere (10 m wind, 2 m temperature and humidity, pressure, radiation,
|
|
310
|
+
precipitation) hourly on a regular longitude-latitude grid."""
|
|
311
|
+
payload = _atmosphere_request(
|
|
312
|
+
bbox, start, hours, resolution_deg, margin_deg, cache_bust
|
|
313
|
+
)
|
|
314
|
+
return self.open_item(self._wait("/api/v1/jobs/atmosphere", payload))
|
|
315
|
+
|
|
316
|
+
def waves(
|
|
317
|
+
self,
|
|
318
|
+
bbox: BBox,
|
|
319
|
+
start: TimeLike,
|
|
320
|
+
hours: int,
|
|
321
|
+
wfo: str = "okx",
|
|
322
|
+
grid: str = "CG1",
|
|
323
|
+
cache_bust: bool = False,
|
|
324
|
+
) -> xr.Dataset:
|
|
325
|
+
"""NWPS surface waves (`hs`, `tp`, `dir` as direction of travel, `shts`, and the forcing
|
|
326
|
+
wind `ws`, `wdir`) hourly on the office's own grid, land as NaN. `start` must be on the
|
|
327
|
+
hour; NOMADS reaches back about five days unless the service has an archive."""
|
|
328
|
+
payload = _waves_request(bbox, start, hours, wfo, grid, cache_bust)
|
|
329
|
+
return self.open_item(self._wait("/api/v1/jobs/waves", payload))
|
|
330
|
+
|
|
331
|
+
def ndbc(
|
|
332
|
+
self,
|
|
333
|
+
station_id: str,
|
|
334
|
+
start: TimeLike,
|
|
335
|
+
end: TimeLike,
|
|
336
|
+
products: Sequence[str] = ("stdmet",),
|
|
337
|
+
) -> xr.Dataset:
|
|
338
|
+
"""Observations at an NDBC station: `stdmet` columns as named by NDBC, `adcp` as
|
|
339
|
+
`current_u`, `current_v` (m/s) and `current_depth` (m)."""
|
|
340
|
+
body = self._check(
|
|
341
|
+
self._http.post(
|
|
342
|
+
self._url("/api/v1/ndbc"),
|
|
343
|
+
json={
|
|
344
|
+
"station_id": station_id,
|
|
345
|
+
"start_time": iso_utc(start),
|
|
346
|
+
"end_time": iso_utc(end),
|
|
347
|
+
"products": list(products),
|
|
348
|
+
},
|
|
349
|
+
)
|
|
350
|
+
)
|
|
351
|
+
return _ndbc_dataset(body["data"])
|
|
352
|
+
|
|
353
|
+
def bathymetry(self, bbox: BBox, resolution_m: float = 10.0) -> xr.DataArray:
|
|
354
|
+
"""Fused topography and bathymetry (m, positive up) over `bbox`, cached locally."""
|
|
355
|
+
target = self.cache_dir / "bathymetry" / _bathymetry_key(bbox, resolution_m)
|
|
356
|
+
if target.exists():
|
|
357
|
+
return _open_bathymetry(target)
|
|
358
|
+
west, south, east, north = (float(v) for v in bbox)
|
|
359
|
+
response = self._http.get(
|
|
360
|
+
self._url("/api/v1/bathymetry/fuse"),
|
|
361
|
+
params={
|
|
362
|
+
"west": west,
|
|
363
|
+
"south": south,
|
|
364
|
+
"east": east,
|
|
365
|
+
"north": north,
|
|
366
|
+
"resolution": resolution_m,
|
|
367
|
+
"format": "zarr",
|
|
368
|
+
},
|
|
369
|
+
timeout=httpx.Timeout(self.timeout_s, connect=10.0),
|
|
370
|
+
)
|
|
371
|
+
if response.status_code >= 400:
|
|
372
|
+
self._check(response)
|
|
373
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
374
|
+
return _unpack_bathymetry(response.content, target)
|
|
375
|
+
|
|
376
|
+
def interpolate_trajectory(
|
|
377
|
+
self, lon, lat, time, z=None, **kwargs: Any
|
|
378
|
+
) -> xr.Dataset:
|
|
379
|
+
"""Forcing interpolated to each point of a trajectory; see
|
|
380
|
+
`forcingkit_client.trajectory.interpolate_trajectory`."""
|
|
381
|
+
from .trajectory import interpolate_trajectory
|
|
382
|
+
|
|
383
|
+
return interpolate_trajectory(self, lon, lat, time, z, **kwargs)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class AsyncClient(_Base):
|
|
387
|
+
"""Asynchronous client with the same methods as `Client`, for callers that must not block
|
|
388
|
+
their event loop (an application's main thread, for example)."""
|
|
389
|
+
|
|
390
|
+
def __init__(
|
|
391
|
+
self,
|
|
392
|
+
base_url: str,
|
|
393
|
+
*args: Any,
|
|
394
|
+
http: Optional[httpx.AsyncClient] = None,
|
|
395
|
+
**kwargs: Any,
|
|
396
|
+
):
|
|
397
|
+
super().__init__(base_url, *args, **kwargs)
|
|
398
|
+
self._http = http or httpx.AsyncClient(
|
|
399
|
+
timeout=httpx.Timeout(120.0, connect=10.0)
|
|
400
|
+
)
|
|
401
|
+
|
|
402
|
+
async def aclose(self) -> None:
|
|
403
|
+
await self._http.aclose()
|
|
404
|
+
|
|
405
|
+
async def __aenter__(self) -> "AsyncClient":
|
|
406
|
+
return self
|
|
407
|
+
|
|
408
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
409
|
+
await self.aclose()
|
|
410
|
+
|
|
411
|
+
async def _wait(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
412
|
+
job = self._check(await self._http.post(self._url(path), json=payload))
|
|
413
|
+
deadline = time.monotonic() + self.timeout_s
|
|
414
|
+
while (item := self._settled(job)) is None:
|
|
415
|
+
if time.monotonic() > deadline:
|
|
416
|
+
raise ForcingkitError(
|
|
417
|
+
f"job {job['job_id']} still {job['status']} after {self.timeout_s:.0f} s"
|
|
418
|
+
)
|
|
419
|
+
await asyncio.sleep(self.poll_s)
|
|
420
|
+
job = self._check(await self._http.get(self._local(job["status_url"])))
|
|
421
|
+
return item
|
|
422
|
+
|
|
423
|
+
async def ocean(
|
|
424
|
+
self,
|
|
425
|
+
bbox: BBox,
|
|
426
|
+
start: TimeLike,
|
|
427
|
+
hours: int,
|
|
428
|
+
vertical_spacing_m: float = 2.0,
|
|
429
|
+
pad_cells: int = 1,
|
|
430
|
+
sponge_cells: int = 0,
|
|
431
|
+
**options: Any,
|
|
432
|
+
) -> xr.Dataset:
|
|
433
|
+
payload = _ocean_request(
|
|
434
|
+
bbox, start, hours, vertical_spacing_m, pad_cells, sponge_cells, **options
|
|
435
|
+
)
|
|
436
|
+
item = await self._wait("/api/v1/jobs/obc", payload)
|
|
437
|
+
return await asyncio.to_thread(self.open_item, item)
|
|
438
|
+
|
|
439
|
+
async def atmosphere(
|
|
440
|
+
self,
|
|
441
|
+
bbox: BBox,
|
|
442
|
+
start: TimeLike,
|
|
443
|
+
hours: int,
|
|
444
|
+
resolution_deg: float = 0.03,
|
|
445
|
+
margin_deg: float = 0.25,
|
|
446
|
+
cache_bust: bool = False,
|
|
447
|
+
) -> xr.Dataset:
|
|
448
|
+
payload = _atmosphere_request(
|
|
449
|
+
bbox, start, hours, resolution_deg, margin_deg, cache_bust
|
|
450
|
+
)
|
|
451
|
+
item = await self._wait("/api/v1/jobs/atmosphere", payload)
|
|
452
|
+
return await asyncio.to_thread(self.open_item, item)
|
|
453
|
+
|
|
454
|
+
async def waves(
|
|
455
|
+
self,
|
|
456
|
+
bbox: BBox,
|
|
457
|
+
start: TimeLike,
|
|
458
|
+
hours: int,
|
|
459
|
+
wfo: str = "okx",
|
|
460
|
+
grid: str = "CG1",
|
|
461
|
+
cache_bust: bool = False,
|
|
462
|
+
) -> xr.Dataset:
|
|
463
|
+
payload = _waves_request(bbox, start, hours, wfo, grid, cache_bust)
|
|
464
|
+
item = await self._wait("/api/v1/jobs/waves", payload)
|
|
465
|
+
return await asyncio.to_thread(self.open_item, item)
|
|
466
|
+
|
|
467
|
+
async def ndbc(
|
|
468
|
+
self,
|
|
469
|
+
station_id: str,
|
|
470
|
+
start: TimeLike,
|
|
471
|
+
end: TimeLike,
|
|
472
|
+
products: Sequence[str] = ("stdmet",),
|
|
473
|
+
) -> xr.Dataset:
|
|
474
|
+
response = await self._http.post(
|
|
475
|
+
self._url("/api/v1/ndbc"),
|
|
476
|
+
json={
|
|
477
|
+
"station_id": station_id,
|
|
478
|
+
"start_time": iso_utc(start),
|
|
479
|
+
"end_time": iso_utc(end),
|
|
480
|
+
"products": list(products),
|
|
481
|
+
},
|
|
482
|
+
)
|
|
483
|
+
return _ndbc_dataset(self._check(response)["data"])
|
|
484
|
+
|
|
485
|
+
async def bathymetry(self, bbox: BBox, resolution_m: float = 10.0) -> xr.DataArray:
|
|
486
|
+
target = self.cache_dir / "bathymetry" / _bathymetry_key(bbox, resolution_m)
|
|
487
|
+
if target.exists():
|
|
488
|
+
return await asyncio.to_thread(_open_bathymetry, target)
|
|
489
|
+
west, south, east, north = (float(v) for v in bbox)
|
|
490
|
+
response = await self._http.get(
|
|
491
|
+
self._url("/api/v1/bathymetry/fuse"),
|
|
492
|
+
params={
|
|
493
|
+
"west": west,
|
|
494
|
+
"south": south,
|
|
495
|
+
"east": east,
|
|
496
|
+
"north": north,
|
|
497
|
+
"resolution": resolution_m,
|
|
498
|
+
"format": "zarr",
|
|
499
|
+
},
|
|
500
|
+
timeout=httpx.Timeout(self.timeout_s, connect=10.0),
|
|
501
|
+
)
|
|
502
|
+
if response.status_code >= 400:
|
|
503
|
+
self._check(response)
|
|
504
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
505
|
+
return await asyncio.to_thread(_unpack_bathymetry, response.content, target)
|
|
506
|
+
|
|
507
|
+
async def interpolate_trajectory(
|
|
508
|
+
self, lon, lat, time, z=None, **kwargs: Any
|
|
509
|
+
) -> xr.Dataset:
|
|
510
|
+
from .trajectory import interpolate_trajectory_async
|
|
511
|
+
|
|
512
|
+
return await interpolate_trajectory_async(self, lon, lat, time, z, **kwargs)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""One layout for every store the client returns.
|
|
2
|
+
|
|
3
|
+
The service writes two parent-ocean layouts. Schema `z-v3` (streamed donors) is already what the
|
|
4
|
+
client returns: `u, v, temp, salt` on `(time, z, lat, lon)` with `z` in metres, positive up, and
|
|
5
|
+
longitudes in -180..180. Older one-shot donors write `legacy` stores in the donor's own
|
|
6
|
+
conventions: `depth` positive down, `latitude`/`longitude` names, and for HYCOM longitudes in
|
|
7
|
+
0..360. `normalise` brings those to the z-v3 conventions and refuses any schema it does not know,
|
|
8
|
+
so a layout change fails here with a clear message instead of later on a variable name.
|
|
9
|
+
The atmosphere (`hrrr-atm-v1`) and waves (`nwps-waves-v1`) stores are written in that convention
|
|
10
|
+
too and pass through unchanged.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import xarray as xr
|
|
15
|
+
|
|
16
|
+
KNOWN_SCHEMAS = ("z-v3", "legacy", "hrrr-atm-v1", "nwps-waves-v1")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SchemaError(ValueError):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def wrap_lon(lon):
|
|
24
|
+
"""Longitudes into -180..180."""
|
|
25
|
+
return (np.asarray(lon, dtype=np.float64) + 180.0) % 360.0 - 180.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def normalise(ds: xr.Dataset) -> xr.Dataset:
|
|
29
|
+
schema = ds.attrs.get("schema", "legacy")
|
|
30
|
+
if schema not in KNOWN_SCHEMAS:
|
|
31
|
+
raise SchemaError(
|
|
32
|
+
f"store schema {schema!r} is not one this client knows ({', '.join(KNOWN_SCHEMAS)}); "
|
|
33
|
+
"upgrade forcingkit-client"
|
|
34
|
+
)
|
|
35
|
+
if schema != "legacy":
|
|
36
|
+
return ds
|
|
37
|
+
|
|
38
|
+
ds = ds.rename(
|
|
39
|
+
{
|
|
40
|
+
old: new
|
|
41
|
+
for old, new in (("latitude", "lat"), ("longitude", "lon"))
|
|
42
|
+
if old in ds.variables
|
|
43
|
+
}
|
|
44
|
+
)
|
|
45
|
+
for name in ("lat", "lon"):
|
|
46
|
+
if name not in ds.coords or ds[name].ndim != 1:
|
|
47
|
+
raise SchemaError(
|
|
48
|
+
f"legacy store has no 1-D {name} axis (a curvilinear donor grid); "
|
|
49
|
+
"this client reads regular longitude-latitude grids only"
|
|
50
|
+
)
|
|
51
|
+
if "depth" in ds.dims:
|
|
52
|
+
ds = ds.assign_coords(depth=-ds["depth"].astype(np.float64)).rename(depth="z")
|
|
53
|
+
ds["z"].attrs.update(units="m", positive="up", axis="Z")
|
|
54
|
+
ds = ds.sortby("z")
|
|
55
|
+
ds = ds.assign_coords(lon=wrap_lon(ds["lon"].values)).sortby("lon")
|
|
56
|
+
return ds
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Remote Zarr stores with a local, chunk-level cache.
|
|
2
|
+
|
|
3
|
+
The service serves each finished store read-only over HTTP. `CachingHTTPStore` is a local
|
|
4
|
+
directory store that, on a miss, fetches the key from the server and keeps it, so a store is
|
|
5
|
+
read remotely the first time and from disk afterwards, and only the chunks actually read are ever
|
|
6
|
+
transferred. The cache directory is keyed by store id and store version, so a store the server
|
|
7
|
+
rebuilt under the same id is fetched afresh.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import os
|
|
12
|
+
import threading
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Optional
|
|
15
|
+
|
|
16
|
+
import httpx
|
|
17
|
+
import xarray as xr
|
|
18
|
+
from zarr.storage import LocalStore
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CachingHTTPStore(LocalStore):
|
|
22
|
+
def __init__(self, root: str | Path, url: str, timeout_s: float = 120.0):
|
|
23
|
+
os.makedirs(root, exist_ok=True)
|
|
24
|
+
super().__init__(root, read_only=True)
|
|
25
|
+
self.url = url.rstrip("/")
|
|
26
|
+
self._timeout_s = timeout_s
|
|
27
|
+
self._http: Optional[httpx.Client] = None
|
|
28
|
+
self._lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
def _client(self) -> httpx.Client:
|
|
31
|
+
with self._lock:
|
|
32
|
+
if self._http is None:
|
|
33
|
+
self._http = httpx.Client(timeout=self._timeout_s)
|
|
34
|
+
return self._http
|
|
35
|
+
|
|
36
|
+
def _fetch(self, key: str) -> bool:
|
|
37
|
+
"""Copy `key` from the server into the cache; False when the server has no such key
|
|
38
|
+
(an unwritten chunk, which reads as the fill value)."""
|
|
39
|
+
response = self._client().get(f"{self.url}/{key}")
|
|
40
|
+
if response.status_code == 404:
|
|
41
|
+
return False
|
|
42
|
+
response.raise_for_status()
|
|
43
|
+
path = os.path.join(str(self.root), key)
|
|
44
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
45
|
+
partial = f"{path}.{os.getpid()}.{threading.get_ident()}.part"
|
|
46
|
+
with open(partial, "wb") as f:
|
|
47
|
+
f.write(response.content)
|
|
48
|
+
os.replace(partial, path)
|
|
49
|
+
return True
|
|
50
|
+
|
|
51
|
+
async def get(self, key: str, prototype: Any = None, byte_range: Any = None) -> Any:
|
|
52
|
+
if not os.path.exists(os.path.join(str(self.root), key)):
|
|
53
|
+
if not await asyncio.to_thread(self._fetch, key):
|
|
54
|
+
return None
|
|
55
|
+
return await super().get(key, prototype, byte_range)
|
|
56
|
+
|
|
57
|
+
def __eq__(self, other: object) -> bool:
|
|
58
|
+
return (
|
|
59
|
+
isinstance(other, CachingHTTPStore)
|
|
60
|
+
and other.url == self.url
|
|
61
|
+
and str(other.root) == str(self.root)
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def __hash__(self) -> int:
|
|
65
|
+
return hash((self.url, str(self.root)))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def open_remote(
|
|
69
|
+
url: str, cache_dir: str | Path, store_id: str, version: str
|
|
70
|
+
) -> xr.Dataset:
|
|
71
|
+
"""Open the store at `url` (a `.../stores/<id>.zarr` href) through the local cache."""
|
|
72
|
+
root = Path(cache_dir).expanduser() / "stores" / store_id / version
|
|
73
|
+
return xr.open_zarr(CachingHTTPStore(root, url), consolidated=True, zarr_format=2)
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""Forcing interpolated along a trajectory: a tagged animal, a vessel, a drifter.
|
|
2
|
+
|
|
3
|
+
The trajectory's bounding box (plus a margin) and time window (whole hours, plus an hour each side)
|
|
4
|
+
are fetched once as gridded stores, then each requested variable is interpolated linearly in time,
|
|
5
|
+
latitude, longitude and, for 3-D ocean fields, z. The result is a CF discrete sampling geometry of
|
|
6
|
+
feature type `trajectory`: one value per point and variable on an `obs` dimension.
|
|
7
|
+
|
|
8
|
+
Sampling density is the caller's choice. The gridded sources resolve hours and kilometres (HYCOM
|
|
9
|
+
is 3-hourly at 0.04 to 0.08 degrees), so a trajectory logged at many hertz loses nothing when
|
|
10
|
+
thinned to about one point a minute before it is passed here.
|
|
11
|
+
|
|
12
|
+
This suits trajectories whose bounding box is one modest store, such as a few hours to a few days
|
|
13
|
+
in one region. A track spanning ocean basins needs segmenting, which a later server-side
|
|
14
|
+
interpolation endpoint is meant to do.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
import pandas as pd
|
|
21
|
+
import xarray as xr
|
|
22
|
+
|
|
23
|
+
from .schema import wrap_lon
|
|
24
|
+
|
|
25
|
+
if TYPE_CHECKING:
|
|
26
|
+
from .client import AsyncClient, Client
|
|
27
|
+
|
|
28
|
+
OBS = "obs"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _prepare(lon, lat, time, z):
|
|
32
|
+
lon = wrap_lon(np.atleast_1d(lon))
|
|
33
|
+
lat = np.atleast_1d(np.asarray(lat, dtype=np.float64))
|
|
34
|
+
t = pd.to_datetime(np.atleast_1d(np.asarray(time)), utc=True).tz_convert(None)
|
|
35
|
+
z = (
|
|
36
|
+
np.zeros_like(lon)
|
|
37
|
+
if z is None
|
|
38
|
+
else np.atleast_1d(np.asarray(z, dtype=np.float64))
|
|
39
|
+
)
|
|
40
|
+
if z.size == 1:
|
|
41
|
+
z = np.full_like(lon, float(z[0]))
|
|
42
|
+
if not (lon.shape == lat.shape == t.shape == z.shape) or lon.ndim != 1:
|
|
43
|
+
raise ValueError(
|
|
44
|
+
"lon, lat, time and z must be 1-D and of one length, got "
|
|
45
|
+
f"{lon.shape}, {lat.shape}, {t.shape}, {z.shape}"
|
|
46
|
+
)
|
|
47
|
+
if len(lon) == 0:
|
|
48
|
+
raise ValueError("the trajectory has no points")
|
|
49
|
+
if np.any(z > 0):
|
|
50
|
+
raise ValueError("z is metres positive up: points below the surface have z < 0")
|
|
51
|
+
return lon, lat, pd.DatetimeIndex(t), z
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def trajectory_window(lon, lat, time, margin_deg: float = 0.1):
|
|
55
|
+
"""(bbox, start, hours) of the stores that cover a trajectory."""
|
|
56
|
+
t = pd.DatetimeIndex(time)
|
|
57
|
+
bbox = (
|
|
58
|
+
float(np.min(lon)) - margin_deg,
|
|
59
|
+
float(np.min(lat)) - margin_deg,
|
|
60
|
+
float(np.max(lon)) + margin_deg,
|
|
61
|
+
float(np.max(lat)) + margin_deg,
|
|
62
|
+
)
|
|
63
|
+
start = t.min().floor("h") - pd.Timedelta(hours=1)
|
|
64
|
+
end = t.max().ceil("h") + pd.Timedelta(hours=1)
|
|
65
|
+
return bbox, start, int((end - start) / pd.Timedelta(hours=1))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _bracket(da: xr.DataArray, dim: str, values: np.ndarray) -> xr.DataArray:
|
|
69
|
+
"""`da` cut to the cells around `values` on `dim`, so only what is needed is read."""
|
|
70
|
+
axis = da[dim].values
|
|
71
|
+
if axis.size < 2:
|
|
72
|
+
return da
|
|
73
|
+
if axis[0] > axis[-1]:
|
|
74
|
+
da = da.sortby(dim)
|
|
75
|
+
axis = da[dim].values
|
|
76
|
+
lo = max(int(np.searchsorted(axis, np.min(values), side="right")) - 1, 0)
|
|
77
|
+
hi = min(int(np.searchsorted(axis, np.max(values), side="left")) + 1, axis.size)
|
|
78
|
+
return da.isel({dim: slice(lo, hi)})
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def interpolate_points(
|
|
82
|
+
ds: xr.Dataset,
|
|
83
|
+
names: Sequence[str],
|
|
84
|
+
lon: np.ndarray,
|
|
85
|
+
lat: np.ndarray,
|
|
86
|
+
time: pd.DatetimeIndex,
|
|
87
|
+
z: np.ndarray,
|
|
88
|
+
) -> Dict[str, xr.DataArray]:
|
|
89
|
+
"""Each of `names` in `ds` interpolated (linearly) to the points; NaN outside the grid, on
|
|
90
|
+
land and below the sea floor. z above the shallowest level centre takes the shallowest value,
|
|
91
|
+
the convention the service uses between the surface and its top level."""
|
|
92
|
+
targets = {"lon": lon, "lat": lat, "time": time.values}
|
|
93
|
+
out = {}
|
|
94
|
+
for name in names:
|
|
95
|
+
if name not in ds.data_vars:
|
|
96
|
+
raise KeyError(
|
|
97
|
+
f"{name!r} not in store; it has {sorted(map(str, ds.data_vars))}"
|
|
98
|
+
)
|
|
99
|
+
da = ds[name]
|
|
100
|
+
points = {dim: v for dim, v in targets.items() if dim in da.dims}
|
|
101
|
+
if "z" in da.dims:
|
|
102
|
+
points["z"] = np.minimum(z, float(ds["z"].max()))
|
|
103
|
+
missing = set(da.dims) - set(points)
|
|
104
|
+
if missing:
|
|
105
|
+
raise ValueError(
|
|
106
|
+
f"{name!r} has dimensions {sorted(map(str, missing))} this cannot interpolate over"
|
|
107
|
+
)
|
|
108
|
+
for dim, values in points.items():
|
|
109
|
+
da = _bracket(da, dim, values)
|
|
110
|
+
da = da.load()
|
|
111
|
+
if "time" in points:
|
|
112
|
+
# Interpolate on float seconds: xarray's vectorised interpolation over a datetime axis
|
|
113
|
+
# returns NaN when the axis and the targets carry different datetime units.
|
|
114
|
+
origin = np.datetime64(pd.Timestamp(da["time"].values[0]), "ns")
|
|
115
|
+
|
|
116
|
+
def seconds(v: np.ndarray) -> np.ndarray:
|
|
117
|
+
return (v.astype("datetime64[ns]") - origin) / np.timedelta64(1, "s")
|
|
118
|
+
|
|
119
|
+
da = da.assign_coords(time=seconds(da["time"].values))
|
|
120
|
+
points["time"] = seconds(points["time"])
|
|
121
|
+
result = da.interp(
|
|
122
|
+
{dim: xr.DataArray(v, dims=OBS) for dim, v in points.items()},
|
|
123
|
+
method="linear",
|
|
124
|
+
)
|
|
125
|
+
result = result.drop_vars(
|
|
126
|
+
[c for c in result.coords if c != OBS], errors="ignore"
|
|
127
|
+
)
|
|
128
|
+
result.attrs = {
|
|
129
|
+
k: v
|
|
130
|
+
for k, v in da.attrs.items()
|
|
131
|
+
if k in ("units", "standard_name", "long_name")
|
|
132
|
+
}
|
|
133
|
+
result.attrs["n_missing"] = int(np.isnan(result.values).sum())
|
|
134
|
+
out[name] = result
|
|
135
|
+
return out
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _provenance(prefix: str, ds: xr.Dataset) -> Dict[str, Any]:
|
|
139
|
+
return {
|
|
140
|
+
f"forcingkit_{prefix}_{key}": ds.attrs.get(f"forcingkit_{key}", "")
|
|
141
|
+
for key in ("store_id", "store_version", "donor", "schema")
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def assemble(
|
|
146
|
+
values: Dict[str, xr.DataArray],
|
|
147
|
+
lon: np.ndarray,
|
|
148
|
+
lat: np.ndarray,
|
|
149
|
+
time: pd.DatetimeIndex,
|
|
150
|
+
z: np.ndarray,
|
|
151
|
+
trajectory_id: str,
|
|
152
|
+
attrs: Dict[str, Any],
|
|
153
|
+
) -> xr.Dataset:
|
|
154
|
+
"""The interpolated values as a CF trajectory (CF 1.11, section 9)."""
|
|
155
|
+
ds = xr.Dataset(
|
|
156
|
+
{name: (OBS, np.asarray(v.values), v.attrs) for name, v in values.items()},
|
|
157
|
+
coords={
|
|
158
|
+
"time": (OBS, time.values, {"standard_name": "time", "axis": "T"}),
|
|
159
|
+
"lat": (
|
|
160
|
+
OBS,
|
|
161
|
+
lat,
|
|
162
|
+
{"standard_name": "latitude", "units": "degrees_north", "axis": "Y"},
|
|
163
|
+
),
|
|
164
|
+
"lon": (
|
|
165
|
+
OBS,
|
|
166
|
+
lon,
|
|
167
|
+
{"standard_name": "longitude", "units": "degrees_east", "axis": "X"},
|
|
168
|
+
),
|
|
169
|
+
"z": (
|
|
170
|
+
OBS,
|
|
171
|
+
z,
|
|
172
|
+
{
|
|
173
|
+
"standard_name": "height",
|
|
174
|
+
"units": "m",
|
|
175
|
+
"positive": "up",
|
|
176
|
+
"axis": "Z",
|
|
177
|
+
},
|
|
178
|
+
),
|
|
179
|
+
},
|
|
180
|
+
)
|
|
181
|
+
ds["trajectory"] = xr.DataArray(
|
|
182
|
+
trajectory_id,
|
|
183
|
+
attrs={"cf_role": "trajectory_id", "long_name": "trajectory name"},
|
|
184
|
+
)
|
|
185
|
+
ds.attrs.update(
|
|
186
|
+
Conventions="CF-1.11",
|
|
187
|
+
featureType="trajectory",
|
|
188
|
+
source="forcingkit",
|
|
189
|
+
interpolation="linear in time, latitude, longitude and z",
|
|
190
|
+
**attrs,
|
|
191
|
+
)
|
|
192
|
+
return ds
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def interpolate_trajectory(
|
|
196
|
+
fk: "Client",
|
|
197
|
+
lon,
|
|
198
|
+
lat,
|
|
199
|
+
time,
|
|
200
|
+
z=None,
|
|
201
|
+
variables: Sequence[str] = ("u", "v"),
|
|
202
|
+
atmosphere: Sequence[str] = (),
|
|
203
|
+
margin_deg: float = 0.1,
|
|
204
|
+
trajectory_id: str = "trajectory",
|
|
205
|
+
**ocean_options: Any,
|
|
206
|
+
) -> xr.Dataset:
|
|
207
|
+
"""Ocean `variables` (from `fk.ocean`) and `atmosphere` variables (from `fk.atmosphere`, for
|
|
208
|
+
example `u10`, `v10`) interpolated to each point of a trajectory.
|
|
209
|
+
|
|
210
|
+
lon, lat: degrees; time: UTC (naive times are taken as UTC); z: metres, positive up, so 25 m
|
|
211
|
+
below the surface is -25 (default: the surface). Returns a CF trajectory Dataset with one
|
|
212
|
+
value per point and variable; each variable's `n_missing` counts points that fell on land,
|
|
213
|
+
below the sea floor or outside the grid, and the global attributes name the stores used.
|
|
214
|
+
"""
|
|
215
|
+
lon, lat, t, z = _prepare(lon, lat, time, z)
|
|
216
|
+
bbox, start, hours = trajectory_window(lon, lat, t, margin_deg)
|
|
217
|
+
values: Dict[str, xr.DataArray] = {}
|
|
218
|
+
attrs: Dict[str, Any] = {}
|
|
219
|
+
if variables:
|
|
220
|
+
ocean = fk.ocean(bbox, start, hours, **ocean_options)
|
|
221
|
+
values.update(interpolate_points(ocean, variables, lon, lat, t, z))
|
|
222
|
+
attrs.update(_provenance("ocean", ocean))
|
|
223
|
+
if atmosphere:
|
|
224
|
+
air = fk.atmosphere(bbox, start, hours)
|
|
225
|
+
values.update(interpolate_points(air, atmosphere, lon, lat, t, z))
|
|
226
|
+
attrs.update(_provenance("atmosphere", air))
|
|
227
|
+
return assemble(values, lon, lat, t, z, trajectory_id, attrs)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
async def interpolate_trajectory_async(
|
|
231
|
+
fk: "AsyncClient",
|
|
232
|
+
lon,
|
|
233
|
+
lat,
|
|
234
|
+
time,
|
|
235
|
+
z=None,
|
|
236
|
+
variables: Sequence[str] = ("u", "v"),
|
|
237
|
+
atmosphere: Sequence[str] = (),
|
|
238
|
+
margin_deg: float = 0.1,
|
|
239
|
+
trajectory_id: str = "trajectory",
|
|
240
|
+
**ocean_options: Any,
|
|
241
|
+
) -> xr.Dataset:
|
|
242
|
+
"""`interpolate_trajectory` for an `AsyncClient`."""
|
|
243
|
+
import asyncio
|
|
244
|
+
|
|
245
|
+
lon, lat, t, z = _prepare(lon, lat, time, z)
|
|
246
|
+
bbox, start, hours = trajectory_window(lon, lat, t, margin_deg)
|
|
247
|
+
values: Dict[str, xr.DataArray] = {}
|
|
248
|
+
attrs: Dict[str, Any] = {}
|
|
249
|
+
stores: list[tuple[str, Optional[xr.Dataset], Sequence[str]]] = []
|
|
250
|
+
if variables:
|
|
251
|
+
stores.append(
|
|
252
|
+
("ocean", await fk.ocean(bbox, start, hours, **ocean_options), variables)
|
|
253
|
+
)
|
|
254
|
+
if atmosphere:
|
|
255
|
+
stores.append(
|
|
256
|
+
("atmosphere", await fk.atmosphere(bbox, start, hours), atmosphere)
|
|
257
|
+
)
|
|
258
|
+
for prefix, ds, names in stores:
|
|
259
|
+
assert ds is not None
|
|
260
|
+
values.update(
|
|
261
|
+
await asyncio.to_thread(interpolate_points, ds, names, lon, lat, t, z)
|
|
262
|
+
)
|
|
263
|
+
attrs.update(_provenance(prefix, ds))
|
|
264
|
+
return assemble(values, lon, lat, t, z, trajectory_id, attrs)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: forcingkit-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Lightweight Python client for a forcingkit service: ocean, atmosphere and station forcing as xarray, and forcing interpolated along a trajectory.
|
|
5
|
+
Project-URL: Documentation, https://forcingkit.docs.lhzn.io/client.html
|
|
6
|
+
Project-URL: Issues, https://github.com/lhzn-io/forcingkit/issues
|
|
7
|
+
Project-URL: Source, https://github.com/lhzn-io/forcingkit
|
|
8
|
+
Author-email: Long Horizon Observatory <dfry@lhzn.io>
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Hydrology
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Requires-Dist: httpx>=0.27
|
|
18
|
+
Requires-Dist: numpy>=1.26
|
|
19
|
+
Requires-Dist: pandas>=2.2
|
|
20
|
+
Requires-Dist: scipy>=1.11
|
|
21
|
+
Requires-Dist: xarray>=2024.10
|
|
22
|
+
Requires-Dist: zarr>=3.0.8
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# forcingkit-client
|
|
26
|
+
|
|
27
|
+
A lightweight Python client for a [forcingkit](https://github.com/lhzn-io/forcingkit) service. It
|
|
28
|
+
returns ocean, atmosphere and station forcing as xarray objects, and interpolates forcing along a
|
|
29
|
+
trajectory (a tagged animal, a vessel, a drifter). It depends on `httpx`, `numpy`, `pandas`,
|
|
30
|
+
`scipy`, `xarray` and `zarr` only, none of the service's data-access stack, so it installs into a
|
|
31
|
+
simulator or an application's embedded Python (3.11 or newer).
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from forcingkit_client import Client
|
|
35
|
+
|
|
36
|
+
fk = Client("http://localhost:9598")
|
|
37
|
+
box = (-70.9, 41.3, -70.6, 41.6) # west, south, east, north
|
|
38
|
+
ocean = fk.ocean(box, "2025-07-01", 24) # u, v, temp, salt, zeta
|
|
39
|
+
air = fk.atmosphere(box, "2025-07-01", 24) # HRRR u10, v10, t2m, ...
|
|
40
|
+
|
|
41
|
+
# lon, lat, time, z: one value per point; z in metres, positive up
|
|
42
|
+
track = fk.interpolate_trajectory(
|
|
43
|
+
lon, lat, time, z, variables=("u", "v"), atmosphere=("u10", "v10")
|
|
44
|
+
)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Store builds run as jobs on the service; the client polls them and opens the finished store over
|
|
48
|
+
HTTP through a local cache (`~/.cache/forcingkit-client`), so only the chunks read are fetched,
|
|
49
|
+
once. `AsyncClient` has the same methods for callers that must not block an event loop.
|
|
50
|
+
|
|
51
|
+
Units are SI; z is metres, positive up. Documentation: <https://forcingkit.docs.lhzn.io/client.html>.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
forcingkit_client/__init__.py,sha256=3d_mp9YuTvXKAVBWKqPO7ML8Y74WPMHObYqCEh1EBRk,449
|
|
2
|
+
forcingkit_client/client.py,sha256=ePWvFVy0dFOHQXOAvZbUxbSLRHgpPB1BN8_2B6uswJY,18143
|
|
3
|
+
forcingkit_client/schema.py,sha256=1kwxP-C9hw8N_JKuSZL0e_S2xRZMsR5G4rvkD68BovM,2134
|
|
4
|
+
forcingkit_client/store.py,sha256=11vmUiL8jJoNcZmMhvI32nFedPioHTDV3nHAwB44U4g,2825
|
|
5
|
+
forcingkit_client/trajectory.py,sha256=NXolE4KHG0SaYavM_G6D5IWrSmZATXC2TTNHAPSxMhQ,9779
|
|
6
|
+
forcingkit_client-0.1.0.dist-info/METADATA,sha256=UHr2KYw0k7NqaZDJIpoOoQSCYguw-04IPLSgl4q0sE4,2336
|
|
7
|
+
forcingkit_client-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
forcingkit_client-0.1.0.dist-info/licenses/LICENSE,sha256=TOTzEeGGFgyjKRa2VqnH2UruUY9AsOBomfOhi2CJmpU,11337
|
|
9
|
+
forcingkit_client-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 lhzn.io
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|