13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583 | class Hysets(HydroDataset):
"""HYsets dataset class extending RainfallRunoff.
This class provides access to the HYsets dataset, which contains hourly
hydrological and meteorological data for various watersheds.
Attributes:
region: Geographic region identifier
download: Whether to download data automatically
ds_description: Dictionary containing dataset file paths
"""
def __init__(
self, uri: str, region: Optional[str] = None, download: bool = False
) -> None:
"""Initialize HYsets dataset.
Args:
uri: Path to the data directory
region: Geographic region identifier (optional)
download: Whether to download data automatically (default: False)
"""
super().__init__(uri)
self.region = region
self.download = download
# cloud path: aqua_fetch cannot read S3, use cache_*_to_zarr instead
if str(uri).startswith("s3://"):
return
self.aqua_fetch = HYSETS(uri)
# OSS relative paths (folder HYSETS); default source for every dynamic
# feature is ERA5, stored in one big NetCDF
_STATIC_REL = "HYSETS/HYSETS_watershed_properties.txt"
_ERA5_NC_REL = "HYSETS/HYSETS_2023_update_ERA51.nc"
# AquaFetch HYSETS.static_map
_STATIC_RENAME = {
"Drainage_Area_km2": "area_km2",
"Centroid_Lat_deg_N": "lat",
"Slope_deg": "slope_degrees",
"Centroid_Lon_deg_E": "long",
}
# AquaFetch HYSETS.dyn_map resolved to cleaned names (nc dynamic_features
# coord uses the raw keys; "total_runoff" has no mapping and is ignored)
_DYN_RENAME = {
"10m_u_component_of_wind": "windspeedu_mps",
"10m_v_component_of_wind": "windspeedv_mps",
"2m_dewpoint": "dptemp_c_mean_2m",
"2m_tasmax": "airtemp_c_2m_max",
"2m_tasmin": "airtemp_c_2m_min",
"discharge": "q_cms_obs",
"evaporation": "evap_mm",
"snow_density": "snowdensity_kgm3",
"snow_evaporation": "evap_mm_snow",
"snow_water_equivalent": "swe_mm",
"snowfall": "snowfall_mm",
"snowmelt": "snowmelt_mm",
"surface_downwards_solar_radiation": "solrad_wm2",
"surface_downwards_thermal_radiation": "lwdownrad_wm2",
"surface_net_solar_radiation": "solradnet_wm2",
"surface_net_thermal_radiation": "lwnetrad_wm2",
"surface_pressure": "airpres_hpa",
"surface_runoff": "q_mm_obs",
"total_cloud_cover": "cloudcover",
"total_precipitation": "pcp_mm",
}
def read_object_ids(self) -> np.ndarray:
if self._is_cloud():
fs = self._make_s3fs()
uri = str(self.data_source_dir).rstrip("/")
with fs.open(f"{uri}/{self._STATIC_REL}".removeprefix("s3://")) as fh:
idx = pd.read_csv(fh, index_col="Watershed_ID", sep=",",
usecols=["Watershed_ID"]).index
return np.array(sorted((str(i) for i in idx), key=lambda x: int(x)))
return super().read_object_ids()
def cache_attributes_to_zarr(self) -> None:
import zarr
fs = self._make_s3fs()
uri = str(self.data_source_dir).rstrip("/")
with fs.open(f"{uri}/{self._STATIC_REL}".removeprefix("s3://")) as fh:
static = pd.read_csv(fh, index_col="Watershed_ID", sep=",")
static.index = static.index.astype(str)
static = static.rename(columns=self._STATIC_RENAME)
static.columns = self._clean_feature_names(list(static.columns))
static = static.loc[:, ~static.columns.duplicated(keep="first")]
# p_mean is derived from the precipitation timeseries (matches local)
static["p_mean"] = self._p_mean_from_precip(static.index)
zarr_name = self._attributes_cache_filename.replace(".nc", ".zarr")
out, opts = self._zarr_path_and_opts(zarr_name)
ids = static.index.tolist()
n = len(ids)
root = zarr.open_group(out, mode="w", storage_options=opts, zarr_format=2)
for col in static.columns:
vals = static[col].values.astype(str) if static[col].dtype == object else static[col].values
arr = root.create_array(col, shape=(n,), chunks=(n,), dtype=vals.dtype)
arr[:] = vals
arr.attrs["_ARRAY_DIMENSIONS"] = ["basin"]
basin_arr = root.create_array("basin", shape=(n,), chunks=(n,), dtype=str)
basin_arr[:] = ids
basin_arr.attrs["_ARRAY_DIMENSIONS"] = ["basin"]
root.attrs["coordinates"] = "basin"
self._write_zarr_units(root, "static")
print(f"Attributes zarr written to: {out}")
def cache_timeseries_to_zarr(self, batch_size: int = 200) -> None:
import zarr
fs = self._make_s3fs()
uri = str(self.data_source_dir).rstrip("/")
nc_path = f"{uri}/{self._ERA5_NC_REL}".removeprefix("s3://")
stations = self.read_object_ids().tolist() # Watershed_IDs as strings
n = len(stations)
all_times = pd.date_range(self.default_t_range[0], self.default_t_range[1], freq="D")
nt = len(all_times)
times_ns = all_times.asi8
cleaned_var_lst = []
for info in self._dynamic_variable_mapping.values():
for s in info["sources"].values():
if s["specific_name"] not in cleaned_var_lst:
cleaned_var_lst.append(s["specific_name"])
zarr_name = self._timeseries_cache_filename.replace(".nc", ".zarr")
out, opts = self._zarr_path_and_opts(zarr_name)
chunk_t = min(nt, 365)
chunk_b = min(batch_size, n)
root = zarr.open_group(out, mode="a", storage_options=opts, zarr_format=2)
if "basin" not in root:
for vn in cleaned_var_lst:
arr = root.create_array(vn, shape=(n, nt), chunks=(chunk_b, chunk_t),
dtype="float64", fill_value=np.nan)
arr.attrs["_ARRAY_DIMENSIONS"] = ["basin", "time"]
time_arr = root.create_array("time", shape=(nt,), chunks=(chunk_t,), dtype="int64")
time_arr[:] = times_ns
time_arr.attrs["_ARRAY_DIMENSIONS"] = ["time"]
time_arr.attrs["units"] = "nanoseconds since 1970-01-01"
time_arr.attrs["calendar"] = "proleptic_gregorian"
basin_arr = root.create_array("basin", shape=(n,), chunks=(n,), dtype=str)
basin_arr[:] = stations
basin_arr.attrs["_ARRAY_DIMENSIONS"] = ["basin"]
prog = root.create_array("_progress", shape=(n,), chunks=(n,), dtype="int8", fill_value=0)
prog[:] = 0
prog.attrs["_ARRAY_DIMENSIONS"] = ["basin"]
root.attrs["coordinates"] = "basin time"
progress = root["_progress"]
# Open the 13 GB ERA5 NetCDF over S3 with h5py directly. xr.open_dataset
# would eagerly scan the metadata of all 14425 variables on open (one per
# station), which over S3 means tens of thousands of tiny range reads and
# effectively hangs. h5py opens lazily (only the superblock + root group)
# and reads each dataset's header on first access, so we pay that cost
# spread across the batch loop (with visible progress) instead of upfront.
import h5py
print(f"Opening ERA5 NetCDF over S3 (lazy, h5py): {nc_path}", flush=True)
raw_file = fs.open(nc_path, "rb", block_size=8 * 1024 * 1024, cache_type="readahead")
h5 = h5py.File(raw_file, "r")
raw_feats = [
v.decode() if isinstance(v, bytes) else str(v)
for v in h5["dynamic_features"][:]
]
# nc time axis is a contiguous daily series 1950-01-01..2023-12-31, which
# equals default_t_range's date_range -> align positionally (no decoding).
if h5["0"].shape[0] != nt:
raise RuntimeError(
f"nc time length {h5['0'].shape[0]} != expected {nt}; "
"positional time alignment invalid"
)
# map each raw feature column index -> cleaned specific name
feat_targets = {} # col_index -> cleaned name (only mapped ones)
for idx, feat in enumerate(raw_feats):
cleaned = self._clean_feature_names([self._DYN_RENAME.get(feat, feat)])[0]
if cleaned in cleaned_var_lst:
feat_targets[idx] = cleaned
print(f" opened. {n} stations x {nt} timesteps x {len(feat_targets)} vars", flush=True)
n_batches = (n + batch_size - 1) // batch_size
for start in range(0, n, batch_size):
end = min(start + batch_size, n)
bnum = start // batch_size + 1
if all(progress[start:end]):
print(f"Batch {bnum}/{n_batches}: already done, skipping", flush=True)
continue
print(f"Batch {bnum}/{n_batches}: {end-start} stations ...", flush=True)
buffers = {vn: np.full((end - start, nt), np.nan) for vn in cleaned_var_lst}
for j, stn in enumerate(tqdm(stations[start:end], desc=f"batch {bnum}")):
var = str(int(stn) - 1) # nc data_vars are 0-based watershed idx
try:
arr = h5[var][:] # (nt, n_features), positional time
for idx, vn in feat_targets.items():
buffers[vn][j] = arr[:, idx].astype("float64")
except Exception as e:
print(f" WARN {stn}: {e}", flush=True)
for vn in cleaned_var_lst:
root[vn][start:end, :] = buffers[vn]
progress[start:end] = 1
print(f"Batch {bnum}/{n_batches}: done", flush=True)
h5.close()
raw_file.close()
self._write_zarr_units(root, "dynamic")
print(f"Timeseries zarr written to: {out}", flush=True)
@property
def _attributes_cache_filename(self):
return "hysets_attributes.nc"
@property
def _timeseries_cache_filename(self):
return "hysets_timeseries.nc"
@property
def default_t_range(self):
return ["1950-01-01", "2023-12-31"]
def cache_attributes_xrdataset(self):
"""Override base method to add calculated p_mean from precipitation timeseries.
This method:
1. Calls parent method to create base attribute cache
2. Reads precipitation timeseries data
3. Calculates mean precipitation (p_mean) for each basin
4. Adds p_mean to the attribute dataset
5. Saves the updated cache
"""
# Step 1: Create base attribute cache using parent method
print("Creating base attribute cache...")
super().cache_attributes_xrdataset()
# Step 2: Load the base cache file
cache_file = self.cache_dir.joinpath(self._attributes_cache_filename)
with xr.open_dataset(cache_file) as ds_attr:
ds_attr = ds_attr.load() # Load into memory
print("Calculating p_mean from precipitation timeseries...")
# Step 3: Read precipitation timeseries for all basins
basin_ids = self.read_object_ids().tolist()
try:
# Read full precipitation timeseries
prcp_ts = self.read_ts_xrdataset(
gage_id_lst=basin_ids,
t_range=self.default_t_range,
var_lst=["precipitation"],
)
# Step 4: Calculate temporal mean for each basin
# The result is a DataArray with dimension (basin,)
p_mean_values = prcp_ts["precipitation"].mean(dim="time")
# Add units attribute
p_mean_values.attrs["units"] = "mm/day"
p_mean_values.attrs["description"] = (
"Mean daily precipitation (calculated from timeseries)"
)
# Step 5: Add p_mean to the attribute dataset
ds_attr["p_mean"] = p_mean_values
print(f"Successfully calculated p_mean for {len(basin_ids)} basins")
except Exception as e:
print(f"Warning: Could not calculate p_mean from precipitation data: {e}")
print("Creating p_mean with NaN values as placeholder")
# Create p_mean with NaN values if calculation fails
p_mean_nan = xr.DataArray(
np.full(len(basin_ids), np.nan),
coords={"basin": basin_ids},
dims=["basin"],
attrs={
"units": "mm/day",
"description": "Mean daily precipitation (not available)",
},
)
ds_attr["p_mean"] = p_mean_nan
# Step 6: Save the updated cache file
print(f"Saving updated attribute cache with p_mean to: {cache_file}")
ds_attr.to_netcdf(cache_file, mode="w")
print("Successfully saved attribute cache with p_mean")
_subclass_static_definitions = {
"area": {"specific_name": "area_km2", "unit": "km^2"},
"p_mean": {"specific_name": "p_mean", "unit": "mm/day"},
}
_dynamic_variable_mapping = {
StandardVariable.STREAMFLOW: {
"default_source": "observations_cms",
"sources": {
"observations_cms": {"specific_name": "q_cms_obs", "unit": "m^3/s"},
"observations_mm": {"specific_name": "q_mm_obs", "unit": "mm/day"},
},
},
StandardVariable.PRECIPITATION: {
"default_source": "observations",
"sources": {"observations": {"specific_name": "pcp_mm", "unit": "mm/day"}},
},
StandardVariable.TEMPERATURE_MAX: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "airtemp_c_2m_max", "unit": "°C"}
},
},
StandardVariable.TEMPERATURE_MIN: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "airtemp_c_2m_min", "unit": "°C"}
},
},
StandardVariable.TEMPERATURE_MEAN: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "dptemp_c_mean_2m", "unit": "°C"}
},
},
StandardVariable.SOLAR_RADIATION: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "solrad_wm2", "unit": "W/m^2"},
"net": {"specific_name": "solradnet_wm2", "unit": "W/m^2"},
},
},
StandardVariable.EVAPORATION: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "evap_mm", "unit": "mm/day"},
"snow": {"specific_name": "evap_mm_snow", "unit": "mm/day"},
},
},
StandardVariable.SNOW_WATER_EQUIVALENT: {
"default_source": "observations",
"sources": {"observations": {"specific_name": "swe_mm", "unit": "mm"}},
},
StandardVariable.SURFACE_PRESSURE: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "airpres_hpa", "unit": "hPa"}
},
},
StandardVariable.U_WIND_SPEED: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "windspeedu_mps", "unit": "m/s"}
},
},
StandardVariable.V_WIND_SPEED: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "windspeedv_mps", "unit": "m/s"}
},
},
StandardVariable.LONGWAVE_SOLAR_RADIATION: {
"default_source": "downward",
"sources": {
"downward": {"specific_name": "lwdownrad_wm2", "unit": "W/m^2"},
"net": {"specific_name": "lwnetrad_wm2", "unit": "W/m^2"},
},
},
StandardVariable.SNOW_DENSITY: {
"default_source": "observations",
"sources": {
"observations": {"specific_name": "snowdensity_kgm3", "unit": "kg/m^3"}
},
},
}
def cache_timeseries_xrdataset(self, batch_size=1000):
"""Cache timeseries to NetCDF in batches (14425 stations × hourly data)."""
if not hasattr(self, "aqua_fetch"):
raise NotImplementedError("aqua_fetch attribute is required")
unit_lookup = {}
if hasattr(self, "_dynamic_variable_mapping"):
for std_name, mapping_info in self._dynamic_variable_mapping.items():
for source, source_info in mapping_info["sources"].items():
unit_lookup[source_info["specific_name"]] = source_info["unit"]
gage_id_lst = self.read_object_ids().tolist()
total_stations = len(gage_id_lst)
original_var_lst = self.aqua_fetch.dynamic_features
cleaned_var_lst = self._clean_feature_names(original_var_lst)
var_name_mapping = dict(zip(original_var_lst, cleaned_var_lst))
n_batches = (total_stations + batch_size - 1) // batch_size
print(
f"Start batch processing {total_stations} stations, "
f"{batch_size} stations per batch ({n_batches} batches)"
)
self.cache_dir.mkdir(parents=True, exist_ok=True)
batch_num = 1
for batch_idx in range(0, total_stations, batch_size):
batch_end = min(batch_idx + batch_size, total_stations)
batch_stations = gage_id_lst[batch_idx:batch_end]
print(
f"\nProcessing batch {batch_num}/{n_batches} "
f"(stations {batch_idx}-{batch_end - 1})"
)
try:
batch_data = self.aqua_fetch.fetch_stations_features(
stations=batch_stations,
dynamic_features=original_var_lst,
static_features=None,
st=self.default_t_range[0],
en=self.default_t_range[1],
as_dataframe=False,
)
dynamic_data = (
batch_data[1] if isinstance(batch_data, tuple) else batch_data
)
new_data_vars = {}
time_coord = dynamic_data.coords["time"]
for original_var in tqdm(
original_var_lst,
desc=f"Variables (batch {batch_num})",
total=len(original_var_lst),
):
cleaned_var = var_name_mapping[original_var]
var_data = []
for station in batch_stations:
if station in dynamic_data.data_vars:
station_data = dynamic_data[station].sel(
dynamic_features=original_var
)
if "dynamic_features" in station_data.coords:
station_data = station_data.drop("dynamic_features")
var_data.append(station_data)
if var_data:
combined = xr.concat(var_data, dim="basin")
combined["basin"] = batch_stations
combined.attrs["units"] = unit_lookup.get(
cleaned_var, "unknown"
)
new_data_vars[cleaned_var] = combined
batch_ds = xr.Dataset(
data_vars=new_data_vars,
coords={"basin": batch_stations, "time": time_coord},
)
batch_filepath = self.cache_dir.joinpath(
f"batch{batch_num:03d}_hysets_timeseries.nc"
)
batch_ds.to_netcdf(batch_filepath)
print(f"Saved batch {batch_num} -> {batch_filepath}")
except Exception as e:
print(f"Batch {batch_num} processing failed: {e}")
import traceback
traceback.print_exc()
continue
batch_num += 1
print(f"\nAll batches processed! Total {batch_num - 1} batch files saved")
def read_ts_xrdataset(
self,
gage_id_lst: list = None,
t_range: list = None,
var_lst: list = None,
sources: dict = None,
**kwargs,
) -> xr.Dataset:
"""Read timeseries from the batch-saved cache (standard names + sources)."""
if self._is_cloud():
# cloud: base class opens the zarr and handles selection/renaming
return super().read_ts_xrdataset(
gage_id_lst=gage_id_lst, t_range=t_range,
var_lst=var_lst, sources=sources, **kwargs,
)
if (
not hasattr(self, "_dynamic_variable_mapping")
or not self._dynamic_variable_mapping
):
raise NotImplementedError(
"This dataset does not support the standardized variable mapping."
)
if var_lst is None:
var_lst = list(self._dynamic_variable_mapping.keys())
if t_range is None:
t_range = self.default_t_range
target_vars_to_fetch = []
rename_map = {}
for std_name in var_lst:
if std_name not in self._dynamic_variable_mapping:
raise ValueError(
f"'{std_name}' is not a recognized standard variable for this dataset."
)
mapping_info = self._dynamic_variable_mapping[std_name]
is_explicit_source = sources and std_name in sources
sources_to_use = []
if is_explicit_source:
provided_sources = sources[std_name]
if isinstance(provided_sources, list):
sources_to_use.extend(provided_sources)
else:
sources_to_use.append(provided_sources)
else:
sources_to_use.append(mapping_info["default_source"])
needs_suffix = is_explicit_source and len(sources_to_use) > 1
for source in sources_to_use:
if source not in mapping_info["sources"]:
raise ValueError(
f"Source '{source}' is not available for variable '{std_name}'."
)
actual_var_name = mapping_info["sources"][source]["specific_name"]
target_vars_to_fetch.append(actual_var_name)
output_name = f"{std_name}_{source}" if needs_suffix else std_name
rename_map[actual_var_name] = output_name
import glob
batch_pattern = str(self.cache_dir / "batch*_hysets_timeseries.nc")
batch_files = sorted(glob.glob(batch_pattern))
if not batch_files:
print("No batch cache files found, starting cache creation...")
self.cache_timeseries_xrdataset()
batch_files = sorted(glob.glob(batch_pattern))
if not batch_files:
raise FileNotFoundError("Cache creation failed, no batch files found")
if gage_id_lst is None:
gage_id_lst = self.read_object_ids().tolist()
gage_id_lst = [str(gid) for gid in gage_id_lst]
relevant_datasets = []
for batch_file in batch_files:
try:
ds_batch = xr.open_dataset(batch_file)
batch_basins = [str(b) for b in ds_batch.basin.values]
common_basins = list(set(gage_id_lst) & set(batch_basins))
if common_basins:
missing_vars = [
v for v in target_vars_to_fetch if v not in ds_batch.data_vars
]
if missing_vars:
ds_batch.close()
raise ValueError(
f"Batch {os.path.basename(batch_file)} missing: {missing_vars}"
)
ds_selected = ds_batch[target_vars_to_fetch].sel(
basin=common_basins, time=slice(t_range[0], t_range[1])
)
relevant_datasets.append(ds_selected)
ds_batch.close()
except Exception as e:
print(f"Failed to read batch file {batch_file}: {e}")
continue
if not relevant_datasets:
raise ValueError(
f"Specified stations not found in any batch files: {gage_id_lst}"
)
if len(relevant_datasets) == 1:
final_ds = relevant_datasets[0]
else:
final_ds = xr.concat(relevant_datasets, dim="basin")
final_ds = final_ds.rename(rename_map)
existing_basins = [b for b in gage_id_lst if b in final_ds.basin.values]
if existing_basins:
final_ds = final_ds.sel(basin=existing_basins)
return final_ds
|