|
"""NEO nodes implementation in ngclib repository""" |
|
from pathlib import Path |
|
import numpy as np |
|
from codecs import encode |
|
from overrides import overrides |
|
import torch as tr |
|
|
|
from .multitask_dataset import NpzRepresentation |
|
|
|
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(NpzRepresentation): |
|
"""NEO nodes implementation""" |
|
def __init__(self, node_type: str, name: str): |
|
self.node_type = node_type |
|
self.name = name |
|
act_path = Path(__file__).absolute().parent / "cmaps" / f"{self.node_type}.act" |
|
assert act_path.exists(), f"Node type '{node_type}' not valid. No act file found: '{act_path}'" |
|
self.cmap = _act_to_cmap(act_path) |
|
|
|
@overrides |
|
def load_from_disk(self, path: Path) -> tr.Tensor: |
|
data = np.load(path, allow_pickle=False) |
|
y = data if isinstance(data, np.ndarray) else data["arr_0"] |
|
y = y[0] if y.shape[0] == 1 else y |
|
y = np.expand_dims(y, axis=-1) if len(y.shape) == 2 else y |
|
y[y == 0] = float("nan") |
|
return tr.from_numpy(y).float() |
|
|
|
@overrides |
|
def save_to_disk(self, data: tr.Tensor, path: Path): |
|
return super().save_to_disk(data.clip(0, 1), path) |
|
|
|
def plot_fn(self, x: tr.Tensor) -> np.ndarray: |
|
y = np.clip(x.cpu().detach().numpy(), 0, 1) |
|
y = y * 255 |
|
y[np.isnan(y)] = 255 |
|
y = y.astype(np.uint).squeeze() |
|
y_rgb = self.cmap[y].astype(np.uint8) |
|
return y_rgb |
|
|