#!/usr/bin/env python3 """Build the Hub Parquet files from the frozen Xoryn II benchmark.""" import io import json from pathlib import Path import sys from datasets import ClassLabel, Features, Image, List, Value import numpy as np from PIL import Image as PillowImage import pyarrow as pa import pyarrow.parquet as parquet REPO = Path(__file__).resolve().parents[1] SOURCE = REPO / "source" sys.path.insert(0, str(SOURCE)) import verify # The published benchmark code, imported without running its CLI. class BenchmarkRng: """Record the selected recognition cohort while replaying the benchmark RNG.""" def __init__(self, seed, cohort_size): self.generator = np.random.default_rng(seed) self.cohort_size = cohort_size self.recognition_ids = None def __getattr__(self, name): return getattr(self.generator, name) def choice(self, population, size=None, replace=True, **kwargs): picked = self.generator.choice(population, size=size, replace=replace, **kwargs) if size == self.cohort_size and not replace: if self.recognition_ids is not None: raise RuntimeError("The recognition cohort was captured twice") self.recognition_ids = np.array(picked, copy=True) return picked def png(array): buffer = io.BytesIO() PillowImage.fromarray(array).save(buffer, format="PNG", compress_level=6) return {"bytes": buffer.getvalue(), "path": None} def encode(columns, features): return pa.Table.from_pydict(features.encode_batch(columns), schema=features.arrow_schema) def encode_rows(rows, features): return encode({name: [row[name] for row in rows] for name in features}, features) def build_digits(data, report): digits = data["digits"] grid = verify.Grid((8, 8)) support = verify.exact_digit_support(grid, digits) count = support.sum(axis=1) full = count == 63 record = report["digits"] if int(full.sum()) != record["full_support_images"]: raise ValueError("The exact support count differs from the manuscript") rng = BenchmarkRng(report["seed"], record["templates_in_recognition_test"]) verify.population_checks(rng) verify.coded_higher_order(rng) verify.stability_checks(rng) replay, _ = verify.image_evidence(rng, data) if (replay["example"] != record["example"] or replay["recognition"] != record["recognition"] or rng.recognition_ids is None): raise ValueError("The recognition cohort or scores do not match the published run") membership = np.isin(np.arange(len(digits)), rng.recognition_ids) if int(membership.sum()) != record["templates_in_recognition_test"] or not full[membership].all(): raise ValueError("Unexpected noisy-test cohort") features = Features( { "sample_id": Value("int32"), "image": Image(), "pixels": List(List(Value("uint8"), length=8), length=8), "label": ClassLabel(names=[str(i) for i in range(10)]), "non_dc_active_count": Value("int32"), "full_fourier_support": Value("bool"), "readings_per_view": Value("int32"), "in_noisy_recognition_test": Value("bool"), } ) # Round 255*x/16 to the nearest integer, using NumPy ties-to-even. display = np.rint(digits.astype(float) * (255 / 16)).astype(np.uint8) columns = { "sample_id": list(range(len(digits))), "image": [png(array) for array in display], "pixels": digits.tolist(), "label": data["digit_labels"].tolist(), "non_dc_active_count": count.tolist(), "full_fourier_support": full.tolist(), "readings_per_view": np.where(full, 35, 36).tolist(), "in_noisy_recognition_test": membership.tolist(), } return encode(columns, features) def build_rgb(data, report): features = Features( { "crop_id": Value("string"), "image": Image(), "source": Value("string"), "top_left_y": Value("int32"), "top_left_x": Value("int32"), "full_anchor": Value("bool"), "relative_error": Value("float64"), "relative_non_dc_error": Value("float64"), "readings_per_view": Value("int32"), } ) rgb = report["rgb"] outcomes = {(case["source"], *case["top_left"]): case for case in rgb["cases"]} rows = [] for name, crops in zip(data["rgb_names"].tolist(), data["rgb_crops"]): for crop, (y, x) in zip(crops, data["rgb_corners"].tolist()): outcome = outcomes.pop((name, y, x)) rows.append( { "crop_id": f"{Path(name).stem}-y{y}-x{x}", "image": png(crop), "source": name, "top_left_y": y, "top_left_x": x, "full_anchor": outcome["full_anchor"], "relative_error": outcome.get("relative_error"), "relative_non_dc_error": outcome.get("relative_non_dc_error"), "readings_per_view": rgb["two_tap_readings_per_view"], } ) if outcomes: raise ValueError("The frozen inputs do not contain every recorded RGB crop") return encode_rows(rows, features) def build_recognition(report): features = Features( { "views_per_trial": Value("int32"), "coordinate_noise_sd": Value("float64"), "one_tap_accuracy": Value("float64"), "full_view_accuracy": Value("float64"), "cosine_only_bayes_accuracy": Value("float64"), "trials": Value("int32"), "templates": Value("int32"), "one_tap_correct": Value("int32"), "full_view_correct": Value("int32"), } ) digits = report["digits"] trials = digits["trials_per_noisy_setting"] rows = [] for condition in digits["recognition"]: one_tap = round(condition["one_tap_accuracy"] * trials) full = round(condition["full_view_accuracy"] * trials) if one_tap / trials != condition["one_tap_accuracy"] or full / trials != condition["full_view_accuracy"]: raise ValueError("The stored accuracies do not match integer counts") rows.append( { **condition, "trials": trials, "templates": digits["templates_in_recognition_test"], "one_tap_correct": one_tap, "full_view_correct": full, } ) return encode_rows(rows, features) def main(): report = json.loads((SOURCE / "results.json").read_text(encoding="utf-8")) with np.load(SOURCE / "benchmark_inputs.npz", allow_pickle=False) as data: datasets = { "digits": build_digits(data, report), "rgb_crops": build_rgb(data, report), "recognition_results": build_recognition(report), } destination = REPO / "data" destination.mkdir(exist_ok=True) for key, dataset in datasets.items(): parquet.write_table(dataset, destination / f"{key}.parquet") print(f"{key}: {len(dataset):,} rows") if __name__ == "__main__": main()