Meehai's picture
initial commit
fb0cb78
raw
history blame
3.03 kB
"""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() # Read binary data
hex_data = encode(raw_data, "hex") # Convert it to hexadecimal values
total_colors_count = int(hex_data[-7:-4], 16) # Get last 3 digits to get number of colors total
total_colors_count = 256
# Decode colors from hex to string and split it by 6 (because colors are #1c1c1c)
colors = [hex_data[i: i + 6].decode() for i in range(0, total_colors_count * 6, 6)]
# Add # to each item and filter empty items if there is a corrupted total_colors_count bit
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):
# all neo nodes have 1 dimension.
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: # pylint: disable=unsubscriptable-object
y = y[0] # pylint: disable=unsubscriptable-object
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})"