Datasets:
Formats:
parquet
Size:
1K - 10K
Tags:
computer-vision
orbit-recovery
projected-mra
periodic-translation
image-reconstruction
bispectrum
License:
File size: 20,499 Bytes
8f0b027 | 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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | #!/usr/bin/env python3
"""Reproduce Xoryn II population checks, image experiment, and figures."""
from argparse import ArgumentParser
from itertools import product
import json
from pathlib import Path
import numpy as np
from sympy import Matrix, ZZ
from sympy.matrices.normalforms import smith_normal_form
from grid import Grid, OneTap, recover_sparse, restore_two_taps, signed_graph_nullity
def relative_orbit_error(observed, recovered, phase):
distance = np.linalg.norm(observed[..., None, :] * phase - recovered[..., None, :], axis=-1)
return distance.min(axis=-1) / np.linalg.norm(observed, axis=-1)
def population_checks(rng):
shapes = [(2,2), (2,3), (2,8), (3,3), (3,5), (4,4), (4,11), (5,5), (6,6), (7,12),
(8,8), (9,9), (11,11), (2,2,2), (2,2,5), (2,3,4), (3,3,3), (3,4,5), (4,5,6)]
one_error, linear_error, sparse_error = [], [], []
number_of_equations = 0
for shape in shapes:
grid = Grid(shape)
plan = OneTap(grid)
phase = grid.phases(grid.points)
for _ in range(4):
z = np.fft.fftn(rng.normal(size=shape), norm="ortho").ravel()
views = z*phase
moments = plan.estimates(views.real, views.imag @ plan.weights)
linear_error.append(float(np.max(abs(moments-grid.product(z, plan.rows)), initial=0)))
magnitude = np.sqrt(np.maximum(0, (views.real**2).mean(axis=0)
* np.where(grid.real, 1, 2)))
recovered = plan.recover(magnitude, moments, views.real[:,0].mean())
one_error.append(float(relative_orbit_error(z, recovered, phase)))
for density in (.35, .65, 1):
z = np.fft.fftn(rng.normal(size=shape), norm="ortho").ravel()
mask = rng.random(grid.size) < density
z *= mask[grid.representative]
error, constraints = restore_two_taps(grid, z)
sparse_error.append(error)
number_of_equations += constraints
assert max(linear_error + one_error + sparse_error) < 1e-9
return {"grids": shapes, "one_tap_cases": len(one_error),
"max_reconstruction_relative_error": max(one_error),
"max_selected_moment_error": max(linear_error),
"two_tap_cases": len(sparse_error), "tested_imaginary_coordinates": number_of_equations,
"max_two_tap_error": max(sparse_error)}
def relation_order(frequencies, p):
frequencies = np.asarray(frequencies)
size = len(frequencies)
candidates = np.array(tuple(product(range(-p, p+1), repeat=size)))
degree = np.abs(candidates).sum(axis=1)
useful = (degree > 0) & (degree <= p) & np.all((candidates @ frequencies)%p == 0, axis=1)
independent = any((int(a[0])*int(b[1])-int(a[1])*int(b[0]))%p != 0
for a in frequencies for b in frequencies)
expected = p**(2 if independent else 1)
for d in range(2,p+1):
rows = candidates[useful & (degree <= d)]
if len(rows) < size:
continue
diagonal = smith_normal_form(Matrix(rows.tolist()), domain=ZZ).diagonal()
index = abs(int(np.prod(diagonal)))
if index == expected:
return d
raise AssertionError("relations through p must generate")
def coded_higher_order(rng):
p = 5
grid = Grid((p,p))
phase = grid.phases(grid.points)
k, l = grid.anchors
z = np.zeros(grid.size, dtype=complex)
z[k], z[l] = .8*np.exp(.38j), 1.2*np.exp(.51j)
z[grid.minus[[k,l]]] = z[[k,l]].conj()
views = phase*z
C, S = views[:, [k,l]].real, views[:, [k,l]].imag
codes = np.array(tuple(product((-1,1), repeat=2)))
Q = (S @ codes.T) / np.sqrt(2)
power = np.abs(z[k])**2
fourth_cosine = C[:,0]**4
# (C+iS)^5 = C^5 - 10 C^3 S^2 + 5 C S^4
# + i S (5 C^4 - 10 C^2 S^2 + S^4).
s2 = power - C[:,0]**2
real = np.mean(C[:,0]**5 - 10*C[:,0]**3*s2 + 5*C[:,0]*s2**2)
imag_poly = 5*fourth_cosine - 10*C[:,0]**2*s2 + s2**2
weighted = np.sqrt(2)*np.mean(imag_poly[:,None] * Q * codes[:,0])
error = abs((real + 1j*weighted) - z[k]**5)
assert error < 1e-12
degrees = {}
for prime in (5,7):
g = Grid((prime,prime))
counts = {}
example = relation_order(g.points[g.anchors], prime)
assert example == prime
for _ in range(30):
support = rng.choice(g.odd, size=rng.integers(2,5), replace=False)
value = relation_order(g.points[support], prime)
counts[str(value)] = counts.get(str(value),0) + 1
degrees[str(prime)] = {"random_supports_by_order": counts, "two_anchor_order": example}
return {"fifth_moment_error": float(error), "orders": degrees}
def evaluate_distance(grid, w, anchor, block=16):
# Distances to a character from Fourier correlation, and to sampled cubic rows.
spectrum = (np.fft.fftn(w.reshape(grid.shape))/grid.size).ravel()
d_orbit = np.sqrt(max(0,2-2*np.max(spectrum.real)))
total = 0
full_frequency = np.arange(grid.size)
for start in range(0,len(anchor),block):
a = anchor[start:start+block, None]
b = full_frequency[None, :]
ab = grid.add(a,b)
total += np.sum(abs(w[a]*w[b]*w[ab].conj()-1)**2)
d_anchor = np.sqrt(total/(len(anchor)*grid.size))
d_double = np.sqrt(np.mean(abs(w*w*w[grid.add(full_frequency,full_frequency)].conj()-1)**2))
return float(d_orbit), float(d_anchor), float(d_double)
def stability_checks(rng):
results = []
for shape in [(17,17),(32,32),(64,64),(128,128)]:
grid = Grid(shape)
log_size = int(np.ceil(8*np.log(2*grid.size)))
anchor = rng.integers(0,grid.size,size=log_size)
freq = np.bincount(anchor, minlength=grid.size).reshape(shape) / len(anchor)
bias = np.fft.fftn(freq).real.ravel()
delta = float(np.sqrt(2-2*np.max(bias[1:])))
assert delta >= 1
scale = 2*np.sqrt(2)*(3+np.sqrt(np.count_nonzero(grid.real)))/delta
ratios = []
for epsilon in (.005,.05,.25,1,3):
for _ in range(4):
a = rng.normal(size=grid.size)
w = np.exp(1j*epsilon*(a-a[grid.minus]))
d, A, B = evaluate_distance(grid,w,anchor)
ratios.append(d/(B+scale*A))
w = np.full(grid.size,-1.+0.j)
w[anchor] = w[grid.minus[anchor]] = w[0] = 1
d,A,B = evaluate_distance(grid,w,anchor)
ratios.append(d/(B+scale*A))
assert max(ratios) <= 1+1e-9
results.append({"shape": shape, "anchors": len(anchor), "anchor_separation": delta,
"max_proven_bound_ratio": max(ratios), "sign_flip_example": {
"translation_distance": d, "anchor_only_error": A, "doubling_error": B}})
return results
def exact_digit_support(grid, images):
"""A Fourier value at an eighth root is zero exactly when its cyclotomic remainder is zero."""
powers = (grid.points @ grid.points.T) % 8
residues = np.arange(4)
basis = (powers[:,:,None] == residues).astype(np.int32)
basis -= (powers[:,:,None] == residues+4).astype(np.int32)
coefficients = np.einsum("np,kpr->nkr",images.reshape(-1,64).astype(np.int32),basis)
support = (coefficients != 0).any(axis=-1)
support[:,0] = False
return support
def image_evidence(rng, dataset):
images = dataset["digits"]
grid = Grid((8,8))
plan = OneTap(grid)
phase = grid.phases(grid.points)
z = np.fft.fft2(images, axes=(1,2), norm="ortho").reshape(-1,grid.size)
z[:,0] = 0
z *= np.sqrt(grid.size)/np.linalg.norm(z,axis=1,keepdims=True)
support = exact_digit_support(grid,images)
assert np.array_equal(support,abs(z)>1e-10)
valid = np.flatnonzero(support[:,1:].all(axis=1))
reconstruction_errors = []
for start in range(0,len(valid),32):
coefficients = z[valid[start:start+32]]
view = coefficients[:,None,:]*phase
m = plan.estimates(view.real,view.imag@plan.weights)
magnitude = np.sqrt(np.maximum(0,(view.real**2).mean(axis=1)*np.where(grid.real,1,2)))
rec = plan.recover(magnitude,m)
reconstruction_errors.extend(relative_orbit_error(coefficients,rec,phase).tolist())
assert max(reconstruction_errors)<2e-8
sparse = np.flatnonzero(~support[:,1:].all(axis=1))
patterns, membership = np.unique(support[sparse],axis=0,return_inverse=True)
sparse_errors = []
for i,mask in enumerate(patterns):
coefficients = z[sparse[membership==i]].copy()
coefficients[:,~mask] = 0
rec = recover_sparse(grid,coefficients,mask,phase)
sparse_errors.extend(relative_orbit_error(coefficients,rec,phase).tolist())
assert max(sparse_errors)<2e-8
# A predeclared balanced test compares each known template with its point inversion.
nontrivial = relative_orbit_error(z[valid],z[valid].conj(),phase)>1e-8
test = rng.choice(valid[nontrivial],size=512,replace=False)
labels = np.tile([1,-1],len(test))
prototypes = np.repeat(z[test],2,axis=0)
actual = np.where(labels[:,None]>0,prototypes,prototypes.conj())
rows = plan.rows[plan.uses_tap]
truth = grid.product(prototypes, rows).imag
b,c = grid.representative[rows[:,1]],grid.representative[rows[:,2]]
a = rows[:,0]
tap_factor = plan.tap_factors[plan.uses_tap]
accuracy = []
for count in (32,128):
for sigma in (.5,1,2,4):
prediction, full = [],[]
for j in range(0,len(labels),32):
k = min(j+32,len(labels))
view = actual[j:k,None,:]*phase[rng.integers(grid.size,size=(k-j,count))]
re_noise = rng.normal(0,sigma,size=(k-j,count,grid.size))
im_noise = rng.normal(0,sigma,size=re_noise.shape)
cosine = (view.real+re_noise)[...,grid.representative]
positive_sine = (view.imag+im_noise)[...,grid.representative]
sine = positive_sine*grid.sign*np.where(grid.real,0,1)
tap = sine@plan.weights
mixed = (tap[...,None]*(cosine[...,b]*cosine[...,c]-sigma**2*(b==c))).mean(axis=1)
score = (mixed*tap_factor*truth[j:k]).sum(axis=1)
prediction.extend(np.where(score>=0,1,-1))
uncompressed = cosine+1j*sine
F = grid.product(uncompressed, rows).mean(axis=1).imag
full.extend(np.where((F*truth[j:k]).sum(axis=1)>=0,1,-1))
accuracy.append({"views_per_trial": count, "coordinate_noise_sd": sigma,
"one_tap_accuracy": float(np.mean(prediction==labels)),
"full_view_accuracy": float(np.mean(full==labels)),
"cosine_only_bayes_accuracy": .5})
exemplar = test[:3]
example = {"template_indices": exemplar.tolist(),
"digit_labels": dataset["digit_labels"][exemplar].tolist()}
results={"dataset_images": len(images), "full_support_images": len(valid),
"reconstruction_max_relative_error": max(reconstruction_errors),
"sparse_support_images": len(sparse), "sparse_support_patterns": len(patterns),
"sparse_max_relative_error": max(sparse_errors),
"reconstruction_median_relative_error": float(np.median(reconstruction_errors)),
"one_tap_readings_per_view": int((grid.size+np.count_nonzero(grid.real))//2+1),
"full_readings_per_view": grid.size, "templates_in_recognition_test": len(test),
"trials_per_noisy_setting": len(labels), "recognition": accuracy, "example": example}
return results, images[exemplar]
def rgb_evidence(dataset):
grid = Grid((32,32))
plan = OneTap(grid)
phase = grid.phases(grid.points)
weight = np.ones(3)/np.sqrt(3)
factor_real = np.where(grid.real,1,2)
factor_imag = np.where(grid.real,0,grid.sign*2*np.sqrt(len(grid.odd)))
corners = dataset["rgb_corners"].tolist()
cases = []
best_examples = {}
for crops, filename in zip(dataset["rgb_crops"], dataset["rgb_names"]):
for source, (y,x) in zip(crops, corners):
patch = source.astype(float)/255
z = np.fft.fft2(patch, axes=(0,1),norm="ortho").reshape(grid.size,3)
anchor = z@weight
if np.min(abs(anchor[1:])) <= 1e-10:
cases.append({"source": Path(filename).name, "top_left": [y,x], "full_anchor": False})
continue
hviews = phase*anchor
c = hviews.real
tap_axis = hviews.imag@plan.weights
tap_dense = hviews[:,grid.odd].imag.sum(axis=1)/np.sqrt(len(grid.odd))
moments = plan.estimates(c,tap_axis)
magnitude = np.sqrt((c*c).mean(axis=0)*factor_real)
h_recovered = plan.recover(magnitude,moments,c[:,0].mean())
cos = (phase[:,:,None]*z).real
cross_re = np.einsum("pk,pkc->kc",c,cos)/grid.size*factor_real[:,None]
cross_im = np.einsum("p,pkc->kc",tap_dense,cos)/grid.size*factor_imag[:,None]
recovered = np.empty_like(z)
recovered[1:] = (cross_re[1:]+1j*cross_im[1:]).conj()/h_recovered[1:,None].conj()
recovered[0] = cos[:,0].mean(axis=0)
align = np.argmin(np.linalg.norm(phase*anchor-h_recovered,axis=1))
aligned = recovered*phase[align,:,None].conj()
error = float(np.linalg.norm(aligned-z)/np.linalg.norm(z))
non_dc_error = float(np.linalg.norm(aligned[1:]-z[1:])/np.linalg.norm(z[1:]))
cases.append({"source": Path(filename).name, "top_left": [y,x],
"full_anchor": True, "relative_error": error,
"relative_non_dc_error": non_dc_error})
contrast = float(np.std(patch,axis=(0,1)).mean())
best = best_examples.get(filename)
if best is None or contrast > best[0]:
pixels = np.fft.ifft2(aligned.reshape(32,32,3),axes=(0,1),norm="ortho").real
best_examples[filename] = (contrast,(Path(filename).name,patch,pixels))
maximum = max(r["relative_error"] for r in cases if r["full_anchor"])
non_dc = max(r["relative_non_dc_error"] for r in cases if r["full_anchor"])
assert max(maximum, non_dc) < 1e-8
return {"shape": [32,32,3], "crops_tested": len(cases),
"crops_with_full_anchor": sum(r["full_anchor"] for r in cases),
"max_relative_error": maximum, "max_relative_non_dc_error": non_dc,
"full_readings_per_view": 3*grid.size,
"two_tap_readings_per_view": int(3*(grid.size+np.count_nonzero(grid.real))//2+2),
"cases": cases}, [entry[1] for entry in best_examples.values()]
def make_figure(path, images, results):
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams.update({"font.family":"DejaVu Sans","font.size":10,
"axes.spines.top":False,"axes.spines.right":False})
f = plt.figure(figsize=(11,3.65),facecolor="white")
gs = f.add_gridspec(2,5, width_ratios=[1,1,1,.28,4], wspace=.3, hspace=.15)
inversion = (-np.arange(8))%8
for j in range(3):
for row in range(2):
ax=f.add_subplot(gs[row,j])
im=images[j] if row==0 else images[j][np.ix_(inversion,inversion)]
ax.imshow(im,cmap="cividis",vmin=0,vmax=16,interpolation="nearest")
ax.axis("off")
if j==0:
ax.text(-.16,.5,"Original" if row==0 else "Inverted",rotation=90,
ha="center",va="center",transform=ax.transAxes,color="#253a4a")
ax=f.add_subplot(gs[:,4])
data=[r for r in results["recognition"] if r["views_per_trial"]==128]
x=[r["coordinate_noise_sd"] for r in data]
ax.plot(x,[r["one_tap_accuracy"]*100 for r in data],lw=2.1,marker="o",
color="#0d756a",label="One fixed sine reading")
ax.plot(x,[r["full_view_accuracy"]*100 for r in data],lw=2.0,marker="s",
color="#46658a",label="Full-view cubic score")
ax.axhline(50,lw=1.4,color="#a34731",linestyle="--",label="Folded-data Bayes limit")
ax.set(xticks=x,ylim=(45,102), xlabel="Noise SD per real coordinate",ylabel="Pair accuracy (%)")
ax.legend(loc="lower left",fontsize=8)
ax.grid(alpha=.25)
ax.set_title("Point-inversion recognition · 128 views",fontweight="bold",color="#15304a")
f.subplots_adjust(left=.07,right=.98,top=.88,bottom=.17)
f.savefig(path,bbox_inches="tight")
plt.close(f)
def make_rgb_figure(path, examples):
import matplotlib.pyplot as plt
f, axes = plt.subplots(1,2*len(examples),figsize=(8.8,2.35),facecolor="white")
for i,(name,original,recovered) in enumerate(examples):
for j,image in enumerate((original,recovered)):
ax = axes[2*i+j]
ax.imshow(np.clip(image,0,1),interpolation="nearest")
ax.axis("off")
title = name.split(".")[0].capitalize()+(" reference" if j==0 else " recovered")
ax.set_title(title,color="#15304a",fontsize=10,fontweight="bold")
f.subplots_adjust(wspace=.15,left=.02,right=.98,bottom=.02,top=.85)
f.savefig(path,bbox_inches="tight")
plt.close(f)
def write_report_table(path, results):
p = results["population"]
d = results["digits"]
c = results["rgb"]
number = lambda x: ("%0.2e" % x).replace("e-", r"\times10^{-") + "}"
rows = [r"\begin{tabularx}{\linewidth}{@{}Xr@{}}",
r"\toprule Result & Measurement\\ \midrule",
f"Fully supported recorded digits, out of {d['dataset_images']:,} & {d['full_support_images']:,}"+r"\\",
r"Largest noiseless relative translation-orbit error on these digits & " +
"$"+number(d["reconstruction_max_relative_error"])+"$"+r"\\",
f"Digit readings per view, one-tap versus full & {d['one_tap_readings_per_view']} versus {d['full_readings_per_view']}"+r"\\",
f"Remaining digits with spectral holes, recovered with two taps & {d['sparse_support_images']}"+r"\\",
r"Largest noiseless relative error on those digits & $"+
number(d["sparse_max_relative_error"])+"$"+r"\\",
f"Natural-image RGB crops reconstructed, out of {c['crops_tested']} & {c['crops_with_full_anchor']}"+r"\\",
r"Largest noiseless relative error on RGB crops, excluding DC & $"+
number(c["max_relative_non_dc_error"])+"$"+r"\\",
f"RGB readings per view, two-tap versus full & {c['two_tap_readings_per_view']:,} versus {c['full_readings_per_view']:,}"+r"\\",
f"Two-tap transfer across {p['two_tap_cases']} synthetic cases & {p['tested_imaginary_coordinates']:,} cubic coordinate checks"+r"\\",
r"\bottomrule\end{tabularx}", "",
r"\medskip\noindent\textbf{Noisy point-inversion decisions.} Each setting uses 1,024 balanced trials across 512 known digit templates.",
"",
r"{\small\begin{tabularx}{\linewidth}{@{}rcc>{\centering\arraybackslash}Xr@{}}",
r"\toprule Views & Noise SD & One fixed tap & Full-view cubic & Folded Bayes\\ \midrule"]
for r in d["recognition"]:
rows.append(f"{r['views_per_trial']} & {r['coordinate_noise_sd']:g} & "
f"{100*r['one_tap_accuracy']:.1f}"+r"\% & "+
f"{100*r['full_view_accuracy']:.1f}"+r"\% & 50.0\%\\")
rows += [r"\bottomrule\end{tabularx}}", ""]
path.write_text("\n".join(rows))
def main():
parser = ArgumentParser()
parser.add_argument("--output",type=Path,default=Path("."))
args = parser.parse_args()
args.output.mkdir(parents=True,exist_ok=True)
rng = np.random.default_rng(471826)
report = {"seed":471826,"population":population_checks(rng),
"tensor_nullities":[signed_graph_nullity(p) for p in (3,5,7,11,13,17)],
"sparse_coded":coded_higher_order(rng),"conditioning":stability_checks(rng)}
with np.load(Path(__file__).with_name("benchmark_inputs.npz"), allow_pickle=False) as dataset:
report["digits"],images = image_evidence(rng,dataset)
report["rgb"],examples = rgb_evidence(dataset)
(args.output/"results.json").write_text(json.dumps(report,indent=2)+"\n")
make_figure(args.output/"recognition.pdf",images,report["digits"])
make_rgb_figure(args.output/"rgb.pdf",examples)
write_report_table(args.output/"results_table.tex",report)
print(json.dumps(report,indent=2))
if __name__=="__main__":
main()
|