File size: 11,138 Bytes
b7fe6bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
"""Visual inspection for 64x32x32 tactile events.

Single-event examples:
    python scripts/visualize_dataset.py --input data/train/sample.npz
    python scripts/visualize_dataset.py --input data/train/sample.npz --mode frame --frame 20
    python scripts/visualize_dataset.py --input data/train/sample.npz --mode animation
    python scripts/visualize_dataset.py --input data/train/sample.npz --mode animation --output event.gif

Batch examples:
    python scripts/visualize_dataset.py --input data/train --mode batch --count 16
    python scripts/visualize_dataset.py --input data --mode batch --recursive \
        --projection frame --frame 32 --output batch.png

With --output, figures are written to disk (without opening an interactive
window) unless --show is also specified. Batch aggregation is ONLY for visual
inspection; the event data are not changed and all 64 frames remain available.
"""

import argparse
import json
import logging
import math
from pathlib import Path

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
import numpy as np

LOG = logging.getLogger("visualize_dataset")
EXPECTED_SHAPE = (64, 32, 32)


def load_frames(path: Path) -> np.ndarray | None:
    if not path.is_file() or path.suffix.lower() != ".npz":
        LOG.error("NPZ file does not exist: %s", path)
        return None
    with np.load(path, allow_pickle=False) as data:
        if "frames" not in data.files:
            LOG.error("Missing 'frames' array: %s", path)
            return None
        frames = data["frames"]
    if frames.shape != EXPECTED_SHAPE:
        LOG.error("Wrong shape %s, expected %s: %s", frames.shape, EXPECTED_SHAPE, path)
        return None
    if frames.dtype != np.float32:
        LOG.error("Wrong dtype %s, expected float32: %s", frames.dtype, path)
        return None
    if not np.isfinite(frames).all():
        LOG.error("Non-finite frame values: %s", path)
        return None
    return frames


def get_response_label(path: Path) -> str:
    json_path = path.with_suffix(".json")
    if not json_path.is_file():
        return "unlabeled"
    obj = json.loads(json_path.read_text(encoding="utf-8"))
    if not isinstance(obj, dict) or not isinstance(obj.get("targets"), dict):
        return "unlabeled"
    label = obj["targets"].get("deformation_response")
    if label in ("rigid", "deformable"):
        return label
    return "unlabeled"


def collect_npz(input_dir: Path, recursive: bool) -> list[Path]:
    files = input_dir.rglob("*.npz") if recursive else input_dir.glob("*.npz")
    return sorted(p for p in files if p.is_file())


def draw_sequence(path: Path, frames: np.ndarray, columns: int) -> plt.Figure:
    n = len(frames)
    rows = math.ceil(n / columns)
    fig, axes = plt.subplots(rows, columns, figsize=(columns * 1.6, rows * 1.65))
    all_axes = np.asarray(axes).reshape(-1)
    last_image = None
    for i, ax in enumerate(all_axes):
        if i < n:
            last_image = ax.imshow(frames[i], cmap="magma", vmin=0.0,
                                   vmax=1.0, origin="lower", interpolation="nearest")
            ax.set_title(f"t={i}", fontsize=9)
        ax.set_xticks([])
        ax.set_yticks([])
        if i >= n:
            ax.axis("off")
    fig.suptitle(f"{path.name} | {get_response_label(path)} | all 64 frames", fontsize=12)
    fig.subplots_adjust(top=0.94, bottom=0.04, left=0.03, right=0.88,
                        hspace=0.30, wspace=0.12)
    fig.colorbar(last_image, ax=all_axes.tolist(), fraction=0.012, pad=0.015,
                 label="response")
    return fig


def draw_frame(path: Path, frames: np.ndarray, frame: int) -> plt.Figure:
    fig, ax = plt.subplots(figsize=(5, 4.7))
    im = ax.imshow(frames[frame], cmap="magma", vmin=0.0, vmax=1.0,
                   origin="lower", interpolation="nearest")
    ax.set_title(f"{path.name}\n{get_response_label(path)} | frame {frame}/63")
    ax.set_xlabel("taxel x")
    ax.set_ylabel("taxel y")
    fig.colorbar(im, ax=ax, label="response")
    fig.tight_layout()
    return fig


def draw_batch(paths: list[Path], projection: str,
               frame: int, columns: int) -> plt.Figure | None:
    samples = []
    for path in paths:
        frames = load_frames(path)
        if frames is None:
            LOG.warning("Skipping invalid sample: %s", path)
            continue
        if projection == "max":
            image = frames.max(axis=0)
        elif projection == "mean":
            image = frames.mean(axis=0)
        else:
            image = frames[frame]
        samples.append((path, image))

    if not samples:
        LOG.error("No valid NPZ data to visualize")
        return None
    rows = math.ceil(len(samples) / columns)
    fig, axes = plt.subplots(rows, columns,
                             figsize=(columns * 3.0, rows * 3.1))
    all_axes = np.asarray(axes).reshape(-1)
    last_image = None
    for i, ax in enumerate(all_axes):
        if i < len(samples):
            path, response = samples[i]
            last_image = ax.imshow(response, cmap="magma", vmin=0.0,
                                   vmax=1.0, origin="lower", interpolation="nearest")
            title = path.stem
            if len(title) > 39:
                title = title[:18] + "…" + title[-17:]
            ax.set_title(f"{get_response_label(path)}\n{title}", fontsize=8)
        else:
            ax.axis("off")
        ax.set_xticks([])
        ax.set_yticks([])
    summary = f"frame {frame}" if projection == "frame" else f"temporal {projection} (visual only)"
    fig.suptitle(f"Tactile event batch ({len(samples)} samples) | {summary}", fontsize=12)
    fig.subplots_adjust(top=0.90, bottom=0.04, left=0.03, right=0.89,
                        hspace=0.34, wspace=0.15)
    fig.colorbar(last_image, ax=all_axes.tolist(), fraction=0.015, pad=0.016,
                 label="response")
    return fig


def draw_animation(path: Path, frames: np.ndarray, interval: int):
    fig, ax = plt.subplots(figsize=(5, 4.7))
    im = ax.imshow(frames[0], cmap="magma", vmin=0.0, vmax=1.0,
                   origin="lower", interpolation="nearest")
    ax.set_xlabel("taxel x")
    ax.set_ylabel("taxel y")
    fig.colorbar(im, ax=ax, label="response")
    fig.tight_layout()
    label = get_response_label(path)

    def update(t: int):
        im.set_data(frames[t])
        ax.set_title(f"{path.name}\n{label} | frame {t}/63")
        return (im,)

    animation = FuncAnimation(fig, update, frames=frames.shape[0],
                              interval=interval, blit=False, repeat=True)
    return fig, animation


def output_plot(fig: plt.Figure, output: Path | None, show: bool) -> None:
    if output is not None:
        output.parent.mkdir(parents=True, exist_ok=True)
        fig.savefig(output, dpi=160)
        LOG.info("Saved: %s", output)
    if show or output is None:
        plt.show()
    plt.close(fig)


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--input", type=Path, required=True, help="NPZ file or directory")
    parser.add_argument("--mode", choices=("auto", "frame", "sequence", "animation", "batch"),
                        default="auto", help="auto: one file => sequence, directory => batch")
    parser.add_argument("--frame", type=int, default=32, help="Frame index 0..63 for frame mode")
    parser.add_argument("--projection", choices=("max", "mean", "frame"), default="max",
                        help="Batch thumbnail method (default: temporal max)")
    parser.add_argument("--count", type=int, default=16, help="Max number of batch samples")
    parser.add_argument("--offset", type=int, default=0, help="Skip first N sorted batch files")
    parser.add_argument("--columns", type=int, default=None, help="Grid columns (auto: 8 sequence, 4 batch)")
    parser.add_argument("--recursive", action="store_true", help="Search subdirectories for NPZ files")
    parser.add_argument("--interval", type=int, default=80, help="Animation frame interval, milliseconds")
    parser.add_argument("--output", type=Path, help="Save PNG/PDF/SVG figure or GIF animation")
    parser.add_argument("--show", action="store_true", help="Show GUI even when --output is set")
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    input_path = args.input.expanduser()
    if not input_path.exists():
        LOG.error("Input path does not exist: %s", input_path)
        return 1

    mode = args.mode
    if mode == "auto":
        mode = "batch" if input_path.is_dir() else "sequence"
    if args.count < 1 or args.offset < 0 or args.interval < 1:
        LOG.error("count and interval must be positive, offset nonnegative")
        return 1
    if args.columns is not None and args.columns < 1:
        LOG.error("columns must be positive")
        return 1
    if not (0 <= args.frame < EXPECTED_SHAPE[0]):
        LOG.error("frame index must be 0..63")
        return 1

    output = args.output.expanduser() if args.output else None
    if mode == "animation" and output is not None and output.suffix.lower() != ".gif":
        LOG.error("Animation output must be .gif")
        return 1
    if mode != "animation" and output is not None and output.suffix.lower() not in (".png", ".pdf", ".svg"):
        LOG.error("Static figure output must end with .png, .pdf or .svg")
        return 1

    if mode == "batch":
        if not input_path.is_dir():
            LOG.error("Batch mode requires a directory")
            return 1
        candidates = collect_npz(input_path, args.recursive)
        selected = candidates[args.offset:args.offset + args.count]
        if not selected:
            LOG.error("No NPZ files at the requested batch offset: %s", input_path)
            return 1
        LOG.info("Selected %d of %d files (offset=%d)", len(selected), len(candidates), args.offset)
        fig = draw_batch(selected, args.projection, args.frame, args.columns or 4)
        if fig is None:
            return 1
        output_plot(fig, output, args.show)
        return 0

    if not input_path.is_file() or input_path.suffix.lower() != ".npz":
        LOG.error("Single-event modes require one .npz file")
        return 1
    frames = load_frames(input_path)
    if frames is None:
        return 1

    if mode == "animation":
        fig, anim = draw_animation(input_path, frames, args.interval)
        if output is not None:
            output.parent.mkdir(parents=True, exist_ok=True)
            anim.save(output, writer=PillowWriter(fps=1000.0 / args.interval))
            LOG.info("Saved: %s", output)
        if args.show or output is None:
            plt.show()
        plt.close(fig)
        return 0
    fig = (draw_frame(input_path, frames, args.frame)
           if mode == "frame" else draw_sequence(input_path, frames, args.columns or 8))
    output_plot(fig, output, args.show)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())