| """Small API for the processed earth_data_pack.h5 file.""" |
| from __future__ import annotations |
|
|
| from pathlib import Path |
| import h5py |
| import numpy as np |
|
|
|
|
| class EarthDataPack: |
| def __init__(self, path: str | Path): |
| self.path = Path(path) |
| self.h5 = h5py.File(self.path, "r") |
| self.aligned = self.h5["aligned"] |
|
|
| def close(self) -> None: |
| self.h5.close() |
|
|
| def __enter__(self): |
| return self |
|
|
| def __exit__(self, exc_type, exc, tb): |
| self.close() |
|
|
| @property |
| def shape(self) -> tuple[int, int]: |
| return tuple(self.aligned["elevation_m"].shape) |
|
|
| def field(self, name: str, rows=slice(None), cols=slice(None)) -> np.ndarray: |
| return self.aligned[name][rows, cols] |
|
|
| def conditioning(self, rows=slice(None), cols=slice(None)) -> np.ndarray: |
| elevation = self.field("elevation_m", rows, cols).astype(np.float32) |
| temperature = self.field("temperature_mean_c", rows, cols).astype(np.float32) |
| seasonality = self.field("temperature_seasonality_c", rows, cols).astype(np.float32) * 100.0 |
| precipitation = self.field("precipitation_mm_year", rows, cols).astype(np.float32) |
| precipitation_cv = self.field("precipitation_cv_percent", rows, cols).astype(np.float32) |
| elevation_signed_sqrt = np.sign(elevation) * np.sqrt(np.abs(elevation)) |
| return np.stack([ |
| elevation_signed_sqrt, |
| temperature, |
| seasonality, |
| precipitation, |
| precipitation_cv, |
| ], axis=0) |
|
|
| def world_xy_to_pixel(self, x_km: float, y_km: float) -> tuple[int, int]: |
| height, width = self.shape |
| col = int(np.floor((x_km % float(self.h5.attrs["canvas_width_km"])) / float(self.h5.attrs["pixel_km_x"]))) % width |
| row = int(np.clip(np.floor(y_km / float(self.h5.attrs["pixel_km_y"])), 0, height - 1)) |
| return row, col |
|
|
| def patch(self, center_x_km: float, center_y_km: float, width_cells: int, height_cells: int) -> dict[str, np.ndarray]: |
| height, width = self.shape |
| center_row, center_col = self.world_xy_to_pixel(center_x_km, center_y_km) |
| rows = np.clip(np.arange(center_row - height_cells // 2, center_row - height_cells // 2 + height_cells), 0, height - 1) |
| cols = np.arange(center_col - width_cells // 2, center_col - width_cells // 2 + width_cells) % width |
| result = {} |
| row_start = int(rows.min()) |
| row_end = int(rows.max()) + 1 |
| local_rows = rows - row_start |
| for name in self.aligned: |
| strip = self.aligned[name][row_start:row_end, :] |
| result[name] = strip[local_rows][:, cols] |
| return result |
|
|