File size: 12,224 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
"""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}