File size: 2,673 Bytes
b8c97f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
"""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