File size: 2,669 Bytes
5e6866e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""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"] # in case on npz, we need this as well
        return tr.from_numpy(data) # can be uint8, float16, float32 etc.

    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 # guaranteed to be (H, W, C) at this point
        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() # guaranteed to be (H, W, 3) at this point hopefully
        _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})"