File size: 6,439 Bytes
f8e2a2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""make_dev_roots.py - noisy copies of the agent's own dev roots in the run.sh input format (bench/agent/dev/).

    env/ref39/bin/python build/make_dev_roots.py        (after make_bundle.py; numpy 1.22.4)

bench/agent/dev/val/             the 6 val scenes x 14 illuminants of data/truedepth
bench/agent/dev/shift_proxy/<d>  the 8 approximate depth-shift roots of the val scenes (data/shift_proxy)
bench/agent/dev/shape_probe/     4 inputs of the VHSD size (1412 x 2120, D65, one illuminant per id, no ground truth):
                                 val measurements reflect-padded from 1080 x 2048, so run.sh can be tried on that shape
    env/ref39/bin/python build/make_dev_roots.py --only probe       (just the shape probe)
Noise = the reference evaluation noise (scene_eval_io.make_eps, public salt), so run.sh on these gives exactly what
dump.py --sigma 0.005 gives on the noise-free roots; scene names are kept, so evaluate.py scores the outputs directly.
"""
import argparse
import csv
import json
import os
import sys

import numpy as np

AGENT = "/data/a792144/metric_depth/bench/agent"
sys.path.insert(0, "/data/a792144/metric_depth/task/rsi-metric-depth-24h/environment/method")
from scene_eval_io import SIGMA, make_eps  # noqa: E402


def noisy_root(src, dst, scenes):
    with open(os.path.join(src, "manifest.json"), encoding="utf-8") as f:
        man = json.load(f)
    with open(os.path.join(src, "clear_stats.csv"), encoding="utf-8") as f:
        rows = list(csv.reader(f))
    j = rows[0].index("p995_all")
    peaks = {(r[0], r[1]): r[j] for r in rows[1:] if r}
    os.makedirs(dst, exist_ok=True)
    units, out = [], []
    for s in scenes:
        for il in man["illums"]:
            if (s, il) not in peaks:
                continue
            meas = np.load(os.path.join(src, man["layout"]["meas"].format(scene=s, illum=il))).astype(np.float32)
            x = meas + (SIGMA * float(peaks[(s, il)])) * make_eps(meas.shape, s, il)
            np.save(os.path.join(dst, f"{s}_{il}.npy"), np.clip(x, 0.0, None).astype(np.float32, copy=False))
            units.append([s, il])
            out.append([s, il, "", peaks[(s, il)]])
    with open(os.path.join(dst, "clear_stats.csv"), "w", encoding="utf-8", newline="") as f:
        csv.writer(f).writerows([["scene", "illum", "amax_all", "p995_all"], *out])
    with open(os.path.join(dst, "manifest.json"), "w", encoding="utf-8") as f:
        json.dump({"layout": {"meas": "{scene}_{illum}.npy"}, "scenes": list(scenes), "illums": list(man["illums"]),
                   "store_dtype": "float32", "units": units,
                   "note": f"Noisy copy of {src.replace(AGENT, '/data')} in the run.sh input format (reference "
                           "evaluation noise already added; normalise only). Ground truth: the source root."}, f, indent=1)
    print(f"{dst}: {len(units)} units", flush=True)


VHSD_SHAPE = (1412, 2120)
STAMP = 1767225600                                      # make_bundle.py's uniform mtime


def shape_probe(src, dst, scenes, illum="D65"):
    """VHSD-sized inputs without ground truth: each val measurement reflect-padded to 1412 x 2120, noised as above
    (the reference evaluation noise drawn for the padded shape), one id per scene with one illuminant (as VHSD)."""
    with open(os.path.join(src, "manifest.json"), encoding="utf-8") as f:
        man = json.load(f)
    with open(os.path.join(src, "clear_stats.csv"), encoding="utf-8") as f:
        rows = list(csv.reader(f))
    j = rows[0].index("p995_all")
    peaks = {(r[0], r[1]): r[j] for r in rows[1:] if r}
    if os.path.exists(dst):
        for f in os.listdir(dst):
            os.remove(os.path.join(dst, f))
    os.makedirs(dst, exist_ok=True)
    units, out = [], []
    for k, s in enumerate(scenes):
        meas = np.load(os.path.join(src, man["layout"]["meas"].format(scene=s, illum=illum))).astype(np.float32)
        dh, dw = VHSD_SHAPE[0] - meas.shape[1], VHSD_SHAPE[1] - meas.shape[2]
        meas = np.pad(meas, ((0, 0), (dh // 2, dh - dh // 2), (dw // 2, dw - dw // 2)), mode="reflect")
        pid = f"probe{k}"
        x = meas + (SIGMA * float(peaks[(s, illum)])) * make_eps(meas.shape, pid, illum)
        np.save(os.path.join(dst, f"{pid}_{illum}.npy"), np.clip(x, 0.0, None).astype(np.float32, copy=False))
        units.append([pid, illum])
        out.append([pid, illum, "", peaks[(s, illum)]])
    with open(os.path.join(dst, "clear_stats.csv"), "w", encoding="utf-8", newline="") as f:
        csv.writer(f).writerows([["scene", "illum", "amax_all", "p995_all"], *out])
    with open(os.path.join(dst, "manifest.json"), "w", encoding="utf-8") as f:
        json.dump({"layout": {"meas": "{scene}_{illum}.npy"}, "scenes": [u[0] for u in units], "illums": [illum],
                   "store_dtype": "float32", "units": units,
                   "note": "VHSD-shaped inputs (1412 x 2120, as the 18 VHSD units of the final grade) in the run.sh input "
                           "format: val measurements reflect-padded, reference evaluation noise already added. No ground "
                           "truth: for checking that run.sh handles this shape (output shape, dtype, dropped pixels, "
                           "time); /app/tools/selfcheck_run.sh runs it by default."}, f, indent=1)
    for f in os.listdir(dst):
        os.chmod(os.path.join(dst, f), 0o644)
        os.utime(os.path.join(dst, f), (STAMP, STAMP))
    os.chmod(dst, 0o755)
    print(f"{dst}: {len(units)} units of shape {VHSD_SHAPE}", flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--only", choices=["dev", "probe"], help="only the val + shift-proxy roots, or only the shape probe")
    a = ap.parse_args()
    if np.__version__ != "1.22.4":
        sys.exit("run with env/ref39 (numpy 1.22.4)")
    with open(os.path.join(AGENT, "splits", "val_list_custom_v2.txt"), encoding="utf-8") as f:
        val = sorted({ln.split("_")[0] for ln in f if ln.strip()})
    if a.only != "probe":
        noisy_root(os.path.join(AGENT, "truedepth"), os.path.join(AGENT, "dev", "val"), val)
        for d in sorted(os.listdir(os.path.join(AGENT, "shift_proxy"))):
            noisy_root(os.path.join(AGENT, "shift_proxy", d), os.path.join(AGENT, "dev", "shift_proxy", d), val)
    if a.only != "dev":
        shape_probe(os.path.join(AGENT, "truedepth"), os.path.join(AGENT, "dev", "shape_probe"), val[:4])


if __name__ == "__main__":
    main()