"""Fit orientation-conditional image subspaces and generate their held-out report.""" from pathlib import Path import csv import hashlib import json import math import numpy as np from PIL import Image ROOT = Path(__file__).resolve().parent SIZE = 20 LABELS = [0, 45, 90, 135] RANK = 4 TRAIN_PER_CLASS = 96 TEST_PER_CLASS = 120 TRAIN_SEED = 1462 TEST_SEED = 96311 def synthesize(seed, count): rng = np.random.default_rng(seed) axis = np.arange(SIZE) - (SIZE - 1) / 2 y, x = np.meshgrid(axis, axis, indexing="ij") patches = [] for angle in LABELS: class_patches = [] for _ in range(count): orientation = np.deg2rad(angle + rng.uniform(-26, 26)) frequency = rng.uniform(0.075, 0.16) phase = rng.uniform(-math.pi, math.pi) amplitude = rng.uniform(0.22, 0.43) bias = rng.uniform(0.35, 0.65) noise = rng.normal(0, rng.uniform(0.065, 0.22), (SIZE, SIZE)) position = x * math.cos(orientation) + y * math.sin(orientation) signal = bias + amplitude * np.cos(2 * np.pi * frequency * position + phase) + noise class_patches.append(np.rint(255 * np.clip(signal, 0, 1)).astype(np.uint8)) patches.append(class_patches) return np.asarray(patches) def unit_rows(patches): values = patches.reshape(-1, SIZE * SIZE).astype(np.float64) values -= values.mean(axis=1, keepdims=True) return values / np.maximum(np.linalg.norm(values, axis=1, keepdims=True), 1e-12) def fit(patches): result = [] for group in patches: _, _, vt = np.linalg.svd(unit_rows(group), full_matrices=False) filters = vt[:RANK].copy() for f in filters: if f[np.argmax(np.abs(f))] < 0: f *= -1 result.append(filters) return np.round(result, 9) def score(weights, patches): inputs = unit_rows(patches) projections = np.einsum("np,ckp->nck", inputs, weights) return (projections ** 2).sum(axis=-1) def wilson(k, n): z = 1.959963984540054 p = k/n d = 1 + z*z/n c = (p + z*z/(2*n))/d h = z*math.sqrt(p*(1-p)/n + z*z/(4*n*n))/d return [c-h, c+h] def save(name, obj): payload = json.dumps(obj, separators=(",", ":"), ensure_ascii=False) (ROOT/name).write_text(payload+"\n") return payload def main(): train = synthesize(TRAIN_SEED, TRAIN_PER_CLASS) holdout = synthesize(TEST_SEED, TEST_PER_CLASS) (ROOT/"holdout.u8").write_bytes(holdout.tobytes()) weights = fit(train) scores = score(weights, holdout) predictions = scores.argmax(axis=1) truth = np.repeat(np.arange(len(LABELS)), TEST_PER_CLASS) counts = np.zeros((4, 4), dtype=int) np.add.at(counts, (truth, predictions), 1) per_class = [{"label": LABELS[i], "correct": int(k), "total": TEST_PER_CLASS, "wilson95": wilson(k, TEST_PER_CLASS)} for i, k in enumerate(counts.diagonal())] study = {"size": SIZE, "labels": LABELS, "rank": RANK, "trainSeed": TRAIN_SEED, "testSeed": TEST_SEED, "trainPerClass": TRAIN_PER_CLASS, "testPerClass": TEST_PER_CLASS, "trainingInputSHA256": hashlib.sha256(train.tobytes()).hexdigest(), "testInputSHA256": hashlib.sha256(holdout.tobytes()).hexdigest(), "correct": int(np.sum(predictions == truth)), "total": int(truth.size), "confusion": counts.tolist(), "perClass": per_class} save("results.json", study) weight_file = {"labels": LABELS, "size": SIZE, "rank": RANK, "weights": weights.tolist()} save("weights.json", weight_file) all_images = holdout.reshape(-1, SIZE, SIZE) selection = [] for i in range(len(LABELS)): good = np.flatnonzero((truth == i) & (predictions == i)) bad = np.flatnonzero((truth == i) & (predictions != i)) if good.size: selection.append(int(good[0])) if bad.size: selection.append(int(bad[0])) examples = [] for index in selection: pixels = all_images[index] Image.fromarray(pixels).resize((320, 320), Image.Resampling.NEAREST).save(ROOT/f"sample-{index}.png") examples.append({"index": index, "truth": int(truth[index]), "prediction": int(predictions[index]), "scores": np.round(scores[index], 10).tolist(), "pixels": pixels.flatten().tolist()}) save("examples.json", examples) js = "window.HuemnOrientationData="+json.dumps({"model": weight_file, "examples": examples},separators=(",", ":"))+";\n" (ROOT/"model-data.js").write_text(js) for i, label in enumerate(LABELS): strip = Image.new("RGB", (4*108 + 3*4,108), (17,20,23)) for k, basis in enumerate(weights[i]): amplitude = basis.reshape(SIZE, SIZE).copy() amplitude /= np.max(np.abs(amplitude)) ink = np.array([12., 15., 22.]) neutral = np.array([111., 115., 132.]) pale = np.array([188., 227., 233.]) rgb = np.where(amplitude[...,None] >= 0, neutral + (pale-neutral)*amplitude[...,None], neutral + (neutral-ink)*amplitude[...,None]) tile = Image.fromarray(np.uint8(np.rint(rgb))).resize((108,108), Image.Resampling.NEAREST) strip.paste(tile,(k*112,0)) strip.save(ROOT/f"basis-{label}.png") with (ROOT/"holdout.csv").open("w",newline="") as file: writer=csv.writer(file);writer.writerow(["index","true_orientation_deg","predicted_orientation_deg",*[f"energy_{x}" for x in LABELS]]) for n, row in enumerate(scores): writer.writerow([n,LABELS[truth[n]],LABELS[predictions[n]],*[f"{e:.9f}" for e in row]]) print(study["correct"],"/",study["total"],"correct");print(counts);print(selection) print("Per-class intervals",per_class) if __name__ == "__main__": main()