Xoryn-II / source /grid.py
PureOne's picture
Release Xoryn II finite-grid image recovery benchmark
8f0b027 verified
Raw History Blame Contribute Delete
12.2 kB
"""Fourier sensing and recovery on finite product grids."""
from dataclasses import dataclass
from collections import deque
from itertools import combinations_with_replacement
import math
import numpy as np
class Grid:
def __init__(self, shape):
self.shape = tuple(shape)
self.size = math.prod(shape)
self.points = np.indices(shape).reshape(len(shape), -1).T
self.minus = self.index(-self.points)
self.representative = np.minimum(self.minus, np.arange(self.size))
self.real = self.minus == np.arange(self.size)
self.sign = np.where(self.representative == np.arange(self.size), 1, -1)
self.odd = np.flatnonzero(~self.real & (self.sign == 1))
self.anchors = self.index(np.eye(len(shape), dtype=int))
def index(self, points):
coordinates = np.moveaxis(np.asarray(points) % self.shape, -1, 0)
return np.ravel_multi_index(coordinates, self.shape)
def add(self, a, b):
return self.index(self.points[a] + self.points[b])
def phases(self, poses):
return np.exp(2j * np.pi * ((np.asarray(poses) / self.shape) @ self.points.T))
def product(self, z, rows):
a, b, c = np.asarray(rows).T
return z[..., a] * z[..., b] * z[..., c]
@dataclass(frozen=True)
class Step:
anchor: int
parent: int
child: int
row: int
class OneTap:
"""Select cubic rows so that all other sine contributions cancel exactly."""
def __init__(self, grid):
self.grid = grid
self.weights = np.zeros(grid.size)
active_anchors = grid.anchors[~grid.real[grid.anchors]]
if len(active_anchors):
self.weights[active_anchors] = 1 / np.sqrt(len(active_anchors))
rows = []
self.axis = []
for a, order in zip(grid.anchors, grid.shape):
harmonic = [int(grid.index(j * grid.points[a])) for j in range(order)]
q = order // 2
first = len(rows)
rows.extend((a, harmonic[j], harmonic[-j-1]) for j in range(1, q))
wrap = None
if order % 2:
wrap = len(rows)
rows.append((a, harmonic[q], harmonic[q]))
self.axis.append((harmonic, slice(first, first + q-1), wrap))
centered = np.where(grid.points <= np.array(grid.shape)//2,
grid.points, grid.points - grid.shape)
self.steps = []
for k in np.argsort(np.abs(centered).sum(axis=1), kind="stable"):
if grid.sign[k] < 0:
continue
axes = np.flatnonzero(centered[k])
if len(axes) < 2:
continue
long_axes = axes[np.array(grid.shape)[axes] > 2]
axis = (long_axes if len(long_axes) else axes)[-1]
a = grid.anchors[axis]
if centered[k, axis] < 0:
a = grid.minus[a]
parent = int(grid.index(grid.points[k] - grid.points[a]))
self.steps.append(Step(int(a), parent, int(k), len(rows)))
rows.append((a, parent, grid.minus[k]))
self.rows = np.asarray(rows, dtype=int).reshape(-1, 3)
self.cos_indices = grid.representative[self.rows]
powers = (~grid.real[self.rows]).sum(axis=1)
self.factors = 2.0 ** np.maximum(0, powers - 1)
first = self.rows[:, 0]
self.uses_tap = ~grid.real[first]
self.tap_factors = np.zeros(len(rows))
q = self.uses_tap
self.tap_factors[q] = self.factors[q] / (
grid.sign[first[q]] * self.weights[grid.representative[first[q]]]
)
def estimates(self, cosine, tap, sigma=0):
"""Views are axis -2 of cosine and axis -1 of tap."""
a, b, c = self.cos_indices.T
A, B, C = cosine[..., a], cosine[..., b], cosine[..., c]
var = sigma**2
real = (A*B*C - var*((a == b)*C + (a == c)*B + (b == c)*A)).mean(axis=-2)
imag = (tap[..., :, None] * (B*C - var*(b == c))).mean(axis=-2)
return real*self.factors + 1j*imag*self.tap_factors
def recover(self, magnitude, invariants, dc=0):
"""Returns one Fourier representative. Positive magnitudes are required."""
grid = self.grid
if np.any(np.abs(invariants) < 1e-60):
raise ValueError("a selected invariant is zero")
phase = invariants / abs(invariants)
unit = np.ones_like(magnitude, dtype=complex)
for harmonic, chain, wrap in self.axis:
order = len(harmonic)
q = order // 2
product = np.prod(phase[..., chain], axis=-1)
root_power = product**2
if wrap is not None:
root_power *= phase[..., wrap]
root = np.exp(1j*np.angle(root_power)/order)
unit[..., harmonic[1]] = root
for j, row in enumerate(range(chain.start, chain.stop), start=1):
unit[..., harmonic[j+1]] = root * unit[..., harmonic[j]] / phase[..., row]
for j in range(1, (order+1)//2):
unit[..., harmonic[-j]] = unit[..., harmonic[j]].conj()
if order % 2 == 0:
unit[..., harmonic[q]] = np.where(unit[..., harmonic[q]].real < 0, -1, 1)
for step in self.steps:
unit[..., step.child] = (
unit[..., step.anchor] * unit[..., step.parent] / phase[..., step.row]
)
twin = grid.minus[step.child]
if step.child == twin:
unit[..., twin] = np.where(unit[..., twin].real < 0, -1, 1)
else:
unit[..., twin] = unit[..., step.child].conj()
z = magnitude * unit
z[..., 0] = dc
return z
def completions(grid, i, j):
"""Return signed triples with a non-real third slot, modulo negation."""
if grid.real[i] and grid.real[j]:
return []
alternatives = (j, grid.minus[j]) if not grid.real[i] and not grid.real[j] else (j,)
result = []
for b in alternatives:
c = int(grid.minus[grid.add(i, b)])
if not grid.real[c]:
result.append((i, int(b), c))
return result
def dense_weights(grid):
ws = np.zeros((2, grid.size))
ws[0, grid.odd] = 1
ws[1, grid.odd] = np.linspace(1, 2, len(grid.odd))
if len(grid.odd):
ws /= np.linalg.norm(ws, axis=1, keepdims=True)
return ws
def restore_two_taps(grid, z):
ws = dense_weights(grid)
views = grid.phases(grid.points)*z
C = views.real
Q = views.imag @ ws.T
vertices = np.unique(grid.representative[np.flatnonzero(abs(z)>1e-13)])
vertices = vertices[vertices != 0]
error = 0.0
real_error = 0.0
constraints = 0
for i, j in combinations_with_replacement(vertices, 2):
rows = [row for row in completions(grid, i, j) if abs(z[row[2]]) > 1e-13]
if not rows:
continue
constraints += len(rows)
a, b, c = np.asarray(rows).T
F = 2.0 ** ((~grid.real[np.asarray(rows)]).sum(axis=1)-1)
W = ws[:,grid.representative[c]] * grid.sign[c] / F
rhs = (Q.T @ (C[:,i]*C[:,j])) / len(Q)
obs = np.linalg.lstsq(W, rhs, rcond=None)[0]
cube = z[a]*z[b]*z[c]
measured_real = F * (C[:,i,None]*C[:,j,None]*C[:,grid.representative[c]]).mean(axis=0)
real_error = max(real_error, float(np.max(abs(measured_real-cube.real))))
error = max(error, float(np.max(abs(obs-cube.imag))))
return max(error, real_error), constraints
def sparse_recovery_rows(grid, support):
"""Use intact coordinate cycles and paths in the active frequency graph."""
anchors = grid.anchors
if not support[anchors].all():
raise ValueError("the support is missing a unit generator")
rows, cycles, steps = [], [], []
for a, length in zip(anchors, grid.shape):
offsets = np.arange(length)[:,None]*grid.points[a]
lines = grid.index(grid.points[support,None,:] + offsets[None,:,:])
intact = lines[np.all(support[lines],axis=1)]
if not len(intact):
raise ValueError("the support has no intact cycle for a unit generator")
line = intact[0]
cycles.append(slice(len(rows),len(rows)+length))
rows.extend((int(a),int(b),int(grid.minus[c])) for b,c in zip(line,np.roll(line,-1)))
directions = np.unique(np.r_[anchors,grid.minus[anchors]])
reached = set(directions)
queue = deque(directions)
while queue:
parent = queue.popleft()
for a in directions:
child = int(grid.add(parent,a))
if not support[child] or child in reached:
continue
steps.append(Step(int(a),int(parent),child,len(rows)))
rows.append((int(a),int(parent),int(grid.minus[child])))
for new in (child,int(grid.minus[child])):
if new not in reached:
reached.add(new)
queue.append(new)
if len(reached) != support.sum():
raise ValueError("a component of the support is disconnected from all generators")
return np.array(rows), cycles, steps
def two_tap_products(grid, cosine, taps, weights, rows, support):
"""Decode specified complex products from exact mixed moments."""
order = np.argsort(grid.real[rows], axis=1, kind="stable")
rows = np.take_along_axis(rows, order, axis=1)
a,b,c = grid.representative[rows].T
factors = 2.0**np.maximum(0,(~grid.real[rows]).sum(axis=1)-1)
result = ((cosine[...,a]*cosine[...,b]*cosine[...,c]).mean(axis=-2)*factors).astype(complex)
for index, (target,i,j) in enumerate(zip(rows,b,c)):
if grid.real[target].all():
continue
candidates = [u for u in completions(grid,i,j) if support[u[2]]]
row = tuple(sorted(target))
negative = tuple(sorted(grid.minus[target]))
column = next(k for k,t in enumerate(candidates) if tuple(sorted(t)) in (row,negative))
sign = 1 if tuple(sorted(candidates[column])) == row else -1
signed = np.asarray(candidates)
completion = signed[:,2]
scales = 2.0**((~grid.real[signed]).sum(axis=1)-1)
matrix = weights[:,grid.representative[completion]]*grid.sign[completion]/scales
linear = np.linalg.pinv(matrix)[column]
rhs = (taps*(cosine[...,i]*cosine[...,j])[...,None]).mean(axis=-2)
result[...,index] += 1j * sign * (rhs@linear)
return result
def recover_sparse(grid, z, support, phase):
"""Population recovery for supports with intact basis cycles and paths."""
views = z[:,None,:]*phase
weights = dense_weights(grid)
cosine = views.real
measured = np.sqrt((cosine*cosine).mean(axis=1)*np.where(grid.real,1,2))
rows, cycles, steps = sparse_recovery_rows(grid,support)
moments = two_tap_products(grid,cosine,views.imag@weights.T,weights,rows,support)
normalized = moments / abs(moments)
unit = np.ones_like(z)
for a,length,cycle in zip(grid.anchors,grid.shape,cycles):
root = np.exp(1j*np.angle(np.prod(normalized[:,cycle],axis=-1))/length)
unit[:,a] = root
unit[:,grid.minus[a]] = root.conj()
for s in steps:
unit[:,s.child] = unit[:,s.anchor]*unit[:,s.parent]/normalized[:,s.row]
unit[:,grid.minus[s.child]] = unit[:,s.child].conj()
recovered = unit*measured
recovered[:,0] = cosine[:,0,0]
return recovered
def signed_graph_nullity(p):
grid = Grid((p, p))
support = grid.odd
parent = {}
ground = (0, 0, 0)
parent[ground] = ground
def root(v):
parent.setdefault(v, v)
while parent[v] != v:
parent[v] = parent[parent[v]]
v = parent[v]
return v
def canonical(row):
return min(tuple(sorted(row)), tuple(sorted(grid.minus[list(row)])))
for i,j in combinations_with_replacement(support, 2):
vertices = [canonical(row) for row in completions(grid, i, j)]
if len(vertices) == 1:
vertices.append(ground)
if len(vertices) == 2:
parent[root(vertices[0])] = root(vertices[1])
components = len({root(v) for v in parent}) - 1
assert components == (p-1)//2
return {"p": p, "ungrounded_components": components, "remaining_after_Q_cubed": components-1}