|
"""NEO nodes implementation in ngclib repository""" |
|
from pathlib import Path |
|
import numpy as np |
|
from codecs import encode |
|
|
|
def _cmap_hex_to_rgb(hex_list): |
|
res = [] |
|
for hex_data in hex_list: |
|
r = int(hex_data[1: 3], 16) |
|
g = int(hex_data[3: 5], 16) |
|
b = int(hex_data[5: 7], 16) |
|
res.append([r, g, b]) |
|
return np.array(res) |
|
|
|
def _act_to_cmap(act_file: Path) -> np.ndarray: |
|
"""converts the .act file to a matplotlib cmap representation""" |
|
with open(act_file, "rb") as act: |
|
raw_data = act.read() |
|
hex_data = encode(raw_data, "hex") |
|
total_colors_count = int(hex_data[-7:-4], 16) |
|
total_colors_count = 256 |
|
|
|
|
|
colors = [hex_data[i: i + 6].decode() for i in range(0, total_colors_count * 6, 6)] |
|
|
|
|
|
hex_colors = [f"#{i}" for i in colors if len(i)] |
|
rgb_colors = _cmap_hex_to_rgb(hex_colors) |
|
return rgb_colors |
|
|
|
class NEONode: |
|
"""NEO nodes implementation in ngclib repository""" |
|
def __init__(self, node_type: str, name: str): |
|
|
|
valid_node_types = ["AerosolOpticalDepth", "Albedo", "CarbonMonoxide", "Chlorophyll", "CloudFraction", |
|
"CloudOpticalThickness", "CloudParticleRadius", "CloudWaterContent", "Fire", |
|
"LeafAreaIndex", "NetRadiation", "NitrogenDioxide", "OutgoingLongwaveRadiation", "Ozone", |
|
"ReflectedShortwaveRadiation", "SeaSurfaceTemperature", "SnowCover", "SolarInsolation", |
|
"Temperature", "TemperatureAnomaly", "Vegetation", "WaterVapor"] |
|
assert node_type in valid_node_types, f"Node type '{node_type}' not in {valid_node_types}" |
|
self.node_type = node_type |
|
self.name = name |
|
self.cmap = _act_to_cmap(Path(__file__).absolute().parent / "cmaps" / f"{self.node_type}.act") |
|
|
|
def load_from_disk(self, x: np.ndarray) -> np.ndarray: |
|
y: np.ndarray = np.float32(x) |
|
if y.shape[0] == 1: |
|
y = y[0] |
|
if len(y.shape) == 2: |
|
y = np.expand_dims(y, axis=-1) |
|
y[np.isnan(y)] = 0 |
|
return y.astype(np.float32) |
|
|
|
def save_to_disk(self, x: np.ndarray) -> np.ndarray: |
|
return x.clip(0, 1) |
|
|
|
def plot_fn(self, x: np.ndarray | None) -> np.ndarray | None: |
|
if x is None: |
|
return x |
|
y = np.clip(x, 0, 1) |
|
y = y * 255 |
|
y[y == 0] = 255 |
|
y = y.astype(np.uint).squeeze() |
|
y_rgb = self.cmap[y].astype(np.uint8) |
|
return y_rgb |
|
|
|
def __repr__(self): |
|
return self.name |
|
|
|
def __str__(self): |
|
return f"NEONode({self.name})" |
|
|