|
"""MultiTask representations stored as .npz files on the disk""" |
|
from __future__ import annotations |
|
from pathlib import Path |
|
import numpy as np |
|
import torch as tr |
|
|
|
class NpzRepresentation: |
|
"""Generic Task with data read from/saved to npz files. Tries to read data as-is from disk and store it as well""" |
|
def __init__(self, name: str): |
|
self.name = name |
|
|
|
def load_from_disk(self, path: Path) -> tr.Tensor: |
|
"""Reads the npz data from the disk and transforms it properly""" |
|
data = np.load(path, allow_pickle=False) |
|
data = data if isinstance(data, np.ndarray) else data["arr_0"] |
|
return tr.from_numpy(data) |
|
|
|
def save_to_disk(self, data: tr.Tensor, path: Path): |
|
"""stores this item to the disk which can then be loaded via `load_from_disk`""" |
|
np.save(path, data.cpu().detach().numpy(), allow_pickle=False) |
|
|
|
def plot_fn(self, x: tr.Tensor) -> np.ndarray: |
|
"""very basic implementation of converting this representation to a viewable image. You should overwrite this""" |
|
assert isinstance(x, tr.Tensor), type(x) |
|
if len(x.shape) == 2: |
|
x = x.unsqueeze(-1) |
|
assert len(x.shape) == 3, x.shape |
|
if x.shape[-1] != 3: |
|
x = x[..., 0:1] |
|
if x.shape[-1] == 1: |
|
x = x.repeat(1, 1, 3) |
|
x = x.nan_to_num(0).cpu().detach().numpy() |
|
_min, _max = x.min((0, 1), keepdims=True), x.max((0, 1), keepdims=True) |
|
if x.dtype != np.uint8: |
|
x = np.nan_to_num((x - _min) / (_max - _min) * 255, 0).astype(np.uint8) |
|
return x |
|
|
|
def normalize(self, x: tr.Tensor, x_min: tr.Tensor, x_max: tr.Tensor) -> tr.Tensor: |
|
"""normalizes a data point read with self.load_from_disk(path) using external min/max information""" |
|
return ((x - x_max) / (x_max - x_min)).nan_to_num(0, 0, 0) |
|
|
|
def standardize(self, x: tr.Tensor, x_mean: tr.Tensor, x_std: tr.Tensor) -> tr.Tensor: |
|
"""standardizes a data point read with self.load_from_disk(path) using external min/max information""" |
|
return ((x - x_mean) / x_std).nan_to_num(0, 0, 0) |
|
|
|
@property |
|
def n_channels(self) -> int: |
|
"""return the number of channels for this representation. Must be updated by each downstream representation""" |
|
raise NotImplementedError(f"n_channels is not implemented for {self}") |
|
|
|
def __repr__(self): |
|
return str(self) |
|
|
|
def __str__(self): |
|
return f"{str(type(self)).split('.')[-1][0:-2]}({self.name})" |