Meehai's picture
exist
be13523
raw
history blame
2.62 kB
"""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() # 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(NpzRepresentation):
"""NEO nodes implementation in ngclib repository"""
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"] # in case on npz, we need this as well
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 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.numpy(), 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