"""Measure saved CaveWorld3D predictions against registered RGB observations. Run on the training host with lpips==0.1.4, its official SqueezeNet v1.1 backbone, torch, torchvision, scikit-image, scipy, numpy, Pillow and OpenCV. Inputs are read-only. Each output row is one clip or one registered view. """ import argparse import hashlib import json import sys from pathlib import Path import cv2 import lpips import numpy as np import torch from PIL import Image from skimage.color import deltaE_ciede2000, rgb2lab def load(path): return json.loads(path.read_text()) def rgb(path): return np.array(Image.open(path).convert("RGB")) def mask_from(path): return np.array(Image.open(path).convert("L")) > 127 def fingerprint(image): return hashlib.sha256(np.ascontiguousarray(image).tobytes()).hexdigest() def luma(image): return (image.astype("f4") @ np.array([0.2126, 0.7152, 0.0722], "f4")) / 255 def patches(mask, size=96, count=6): """Select an even spread of nonoverlapping tiles using the real mask only.""" h, w = mask.shape choices = [(y, x) for y in range(0, h - size + 1, size) for x in range(0, w - size + 1, size) if mask[y:y + size, x:x + size].all()] if len(choices) <= count: return choices return [choices[i] for i in np.linspace(0, len(choices) - 1, count, dtype=int)] class Perception: def __init__(self): self.device = "cuda" if torch.cuda.is_available() else "cpu" self.net = lpips.LPIPS(net="squeeze", version="0.1", verbose=False).to(self.device).eval() @torch.inference_mode() def distance(self, reference, pred): def inputs(a): return torch.from_numpy(np.stack(a)).permute(0, 3, 1, 2).to(self.device).float().div_(127.5).sub_(1) return self.net(inputs(reference), inputs(pred)).flatten().cpu().numpy() def narrow_patch_scores(truth, movie, mask, metric): size=64 scores=[] count=0 for a,b,m in zip(truth,movie,mask): h,w=m.shape valid=[(y,x) for y in range(0,h-size+1,16) for x in range(0,w-size+1,16) if m[y:y+size,x:x+size].all()] if not valid: continue # Keep spatially separated patches. Coordinate selection sees only the input footprint. chosen=[] for y,x in valid: if all(abs(y-iy)>=size or abs(x-ix)>=size for iy,ix in chosen): chosen.append((y,x)) chosen=[chosen[j] for j in np.linspace(0,len(chosen)-1,min(6,len(chosen)),dtype=int)] values=metric.distance([a[y:y+size,x:x+size] for y,x in chosen],[b[y:y+size,x:x+size] for y,x in chosen]) scores.append(float(values.mean())) count+=len(chosen) return dict(lpips_novel64=mean(scores),narrow_patch_frames=len(scores),narrow_patch_count=count) PREWITT = np.array([[1, 0, -1]] * 3, "f4") / 3 def gradient(image): # Original GMSD uses 0..255 grayscale, 2x2 mean and decimation before Prewitt. reduced = cv2.blur(image, (2, 2), anchor=(0, 0))[::2, ::2] return np.hypot(cv2.filter2D(reduced, -1, PREWITT), cv2.filter2D(reduced, -1, PREWITT.T)) def mean(values): keep = [float(x) for x in values if x is not None and np.isfinite(x)] return float(np.mean(keep)) if keep else None def frame_score(truth, pred, mask, metric): if pred.shape != truth.shape or truth.shape[:2] != mask.shape or not mask.any(): raise ValueError("Unmatched image dimensions or empty novel mask") t, p = luma(truth), luma(pred) err = p - t delta = (pred.astype("f4") - truth.astype("f4")) / 255 mse = float(np.square(delta).mean()) out = dict(mae_novel=float(np.abs(delta[mask]).mean()), psnr_full=-10 * np.log10(max(mse, 1e-12)), novel_fraction=float(mask.mean()), lpips_full=float(metric.distance([truth], [pred])[0])) xy = patches(mask) out["lpips_patches"] = len(xy) out["lpips_novel96"] = mean(metric.distance([truth[y:y+96, x:x+96] for y, x in xy], [pred[y:y+96, x:x+96] for y, x in xy])) if xy else None # A fixed pixel grid limits color conversion costs, identically for all methods. keep = mask[::2, ::2] laboratory = [rgb2lab(im[::2, ::2][keep].astype("f4") / 255) for im in (truth, pred)] out["de00_novel"] = float(deltaE_ciede2000(*laboratory).mean()) if keep.any() else None g, h = [gradient(cv2.cvtColor(im, cv2.COLOR_RGB2GRAY).astype("f4")) for im in (truth, pred)] gm = (2 * g * h + 170) / (g * g + h * h + 170) valid = cv2.erode(mask.astype("u1"), np.ones((7, 7), "u1"))[::2, ::2].astype(bool) out["gmsd_full"] = float(gm.std()) out["gmsd_novel"] = float(gm[valid].std()) if valid.any() else None interiors = cv2.erode(mask.astype("u1"), np.ones((9, 9), "u1")).astype(bool) hp = [(a - cv2.GaussianBlur(a, (9, 9), 1.5))[interiors] for a in (t, p)] out["hp_novel"] = float(np.corrcoef(*hp)[0, 1]) if interiors.any() and min(a.std() for a in hp)>1e-7 else None for label, band in (("shadow", t < .12), ("mid", (t >= .12) & (t < .70)), ("bright", t >= .70)): pixels = err[mask & band] out[label + "_pixels"] = int(pixels.size) out[label + "_mae"] = float(np.abs(pixels).mean()) if pixels.size else None out[label + "_bias"] = float(pixels.mean()) if pixels.size else None return out def flow(a, b): gray = [cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) for im in (a, b)] return cv2.calcOpticalFlowFarneback(*gray, None, .5, 3, 15, 3, 5, 1.2, 0) def early_panel(args, out, percept): from compare_scene_checkpoints import CASES from compare_voyager_lineage import load_case from rotation_fusion import read_coefficients root, base = args.lineage, args.controls weights = load(root / "weights.json")["checkpoints"] scores = {(r["case"], r["method"]): r["metrics"] for r in load(root / "report/scores.json")["rows"] if r["seed"] == 0} fusion = read_coefficients(base / "code/rotation_fusion.json") for case in CASES: truth, visible, tracks, evidence = load_case(root, base, case, weights, scores, fusion) gt_flow = [flow(t, u) for t, u in zip(truth, truth[1:])] for stage in weights: name = stage["id"] for rendering, movie in tracks[name].items(): narrow = narrow_patch_scores(truth,movie,~visible,percept) if args.mode=="patch": write(out,dict(protocol="V13",case=case,method=name,rendering=rendering,**narrow)) continue frames = [frame_score(t, p, ~m, percept) for t, p, m in zip(truth, movie, visible)] row = {k: mean(f[k] for f in frames) for k in frames[0]} row.update(narrow) row["lpips_patch_frames"] = sum(f["lpips_novel96"] is not None for f in frames) row["lpips_patch_count"] = sum(f["lpips_patches"] for f in frames) row["tof_px"] = mean(np.linalg.norm(flow(x, y) - g, axis=2).mean() for x, y, g in zip(movie, movie[1:], gt_flow)) row["frames"], row["transitions"] = len(frames), len(gt_flow) row.update(protocol="V13", case=case, method=name, rendering=rendering, seed=0, width=truth.shape[2], height=truth.shape[1], evidence=evidence["models"][name], reference=evidence["common"]["target_pixels_sha256"], source=str(root / "eval" / name)) if abs(row["mae_novel"] - scores[case, name+"_"+rendering]["unseen_mae"]) > .04: raise ValueError("Macro/micro MAE mismatch outside plausible range") write(out, row) def write(stream, row): stream.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n") stream.flush() def field_panel(args, out, percept): c = {k: Path(v) for k,v in load(args.config).items() if k in {"p","tex","run","prev","old","ref","site"}} def score_dir(protocol, case, view, seed, truth_path, mask_path, methods): truth, mask = rgb(truth_path), mask_from(mask_path) for method, file in methods.items(): pred = rgb(file) scored = frame_score(truth, pred, mask, percept) scored.update(protocol=protocol, case=case, view=view, seed=seed, method=method, width=truth.shape[1], height=truth.shape[0], source=str(file), truth_file=str(truth_path), mask_file=str(mask_path), reference=fingerprint(truth), mask_hash=fingerprint(mask), prediction_hash=fingerprint(pred)) write(out, scored) if args.mode == "site": for section in ("locked", "additional", "confirmation"): for f in sorted((args.site / section).glob("*/unmetered.png")): d = f.parent methods = {x.stem:x for x in d.glob("*.png") if x.stem not in ("real","mask")} score_dir("M_"+section,"face",d.name,None,d/"real.png",d/"mask.png",methods) return if args.mode == "fusion": for f in sorted((c["tex"]/"formal_color").glob("*/seed_*/aligned/*/real.png")): d=f.parent case,seed,_,view=d.relative_to(c["tex"]/"formal_color").parts src=c["p"]/"formal"/case/seed if case=="face": pred=src/"aligned_fusion"/view/"fusion.png" if not pred.exists():continue archive=load(src/"score_fusion/sweep.json")["views"][view]["models"]["fusion"] elif case in ("wall","steel"): pred=src/"score_fusion/fusion.png" if not pred.exists():continue official=load(src/"score_fusion/scores.json") archive=official["variants"]["fusion"]["novel"] if case=="wall" else official["fusion"] else:continue m=mask_from(d/"mask.png") absolute=np.abs(rgb(pred).astype("f4")-rgb(f).astype("f4"))/255 if m.sum()!=archive["pixels"] or abs(absolute[m].mean()-archive["mae"])>2e-5: raise ValueError(("fusion alignment",case,seed,view)) score_dir("S",case,view,int(seed.split("_")[1]),f,d/"mask.png",{"legacy_fusion":pred}) return if args.mode == "panorama": for seed in (0,42,143): d=c["tex"]/"formal_color"/"wall"/f"seed_{seed}"/"aligned"/"endpoint" old=c["p"]/"formal"/"wall"/f"seed_{seed}"/"score" block=c["site"]/"legacy_native"/"wall"/f"score_{seed}" if seed==143: block=c["site"]/"release"/"paired" if not np.array_equal(mask_from(d/"mask.png"),mask_from(block/"novel_mask.png")): raise ValueError(("panorama mask",seed)) if not np.array_equal(rgb(old/"official.png"),rgb(block/"official.png")): raise ValueError(("panorama control",seed)) models={"legacy_field72":block/("field72.png" if seed==143 else "trained.png")} if seed==143: models.update({k:block/(k+".png") for k in ("official_layered","trained_layered")}) score_dir("S","wall","endpoint",seed,d/"real.png",d/"mask.png",models) return for f in sorted((c["tex"] / "formal_color").glob("*/seed_*/aligned/*/parent.png")): d = f.parent case, seed, _, view = d.relative_to(c["tex"] / "formal_color").parts methods = {x.stem:x for x in d.glob("*.png") if x.stem not in ("real","mask")} methods["sensor"] = c["run"] / "single_evaluation" / case / seed / view / "sensor.png" classic = c["p"] / "formal" / case / seed / "aligned" / view if (classic / "real.png").exists(): if fingerprint(rgb(classic/"real.png")) == fingerprint(rgb(d/"real.png")) and np.array_equal(mask_from(classic/"mask.png"),mask_from(d/"mask.png")): methods.update({"legacy_"+p.stem:p for p in classic.glob("*.png") if p.stem not in ("real","mask")}) if case == "wall": classic = c["p"] / "formal" / case / seed / "score" # Both the real-image mask and the serialized old180 prediction must match. old = classic / "old180.png" if old.exists() and np.array_equal(rgb(old),rgb(f)) and np.array_equal(mask_from(classic/"novel_mask.png"),mask_from(d/"mask.png")): methods.update({"legacy_"+p.stem:p for p in classic.glob("*.png") if p.stem not in ("novel_mask","mask","real")}) score_dir("S",case,view,int(seed.split("_")[1]),d/"real.png",d/"mask.png",methods) for d in sorted((c["tex"]/"blind").glob("*/aligned")): methods = {x.stem:x for x in d.glob("*.png") if x.stem not in ("real","mask")} name = d.parent.name methods["sensor"] = c["run"]/"single_evaluation"/"blind"/name/"sensor.png" score_dir("B",name,"center",None,d/"real.png",d/"mask.png",methods) for d in sorted((c["prev"]/"grounded").glob("*/aligned/*")): if (d/"real.png").exists(): score_dir("N", d.parent.parent.name,d.name,143,d/"real.png",d/"mask.png", {x:d/(x+".png") for x in ("parent","native")}) for section in ("locked","additional","confirmation"): base = c["run"]/"final_eval"/section for f in sorted(base.glob("*/unmetered.png")): d = f.parent methods = {x.stem:x for x in d.glob("*.png") if x.stem not in ("real","mask")} for prefix, old_dir in (("history_",c["tex"]/"site_color"/"aligned"/d.name), ("photo_",c["run"]/"photo_eval"/section/d.name)): old_truth = old_dir/"real.png" if old_truth.exists() and np.array_equal(rgb(old_truth),rgb(d/"real.png")) and np.array_equal(mask_from(old_dir/"mask.png"),mask_from(d/"mask.png")): methods.update({prefix+x.stem:x for x in old_dir.glob("*.png") if x.stem not in ("real","mask")}) score_dir("M_"+section,"face",d.name,None,d/"real.png",d/"mask.png",methods) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("mode",choices=("early","field","site","patch","panorama","fusion")) parser.add_argument("--lineage",type=Path) parser.add_argument("--controls",type=Path) parser.add_argument("--config",type=Path) parser.add_argument("--site",type=Path,help="All-camera lossless output from render_cave_radiance.py evaluate") parser.add_argument("--output",required=True,type=Path) a = parser.parse_args() cv2.setNumThreads(1) torch.set_num_threads(2) if a.mode in ("early","patch"): sys.path[:0] = [str(a.lineage),str(a.controls/"code")] score = Perception() with a.output.open("x") as out: (early_panel if a.mode in ("early","patch") else field_panel)(a,out,score) if __name__ == "__main__": main()