File size: 13,242 Bytes
19591f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Exact equal-weight mean selection in arbitrary finite dimension.

All arithmetic is rational. The unrestricted routine is constructive, not an
instance optimizer. Rule-constrained enumeration is an exact small-instance
oracle and deliberately does not inherit unrestricted constants.
"""
from collections import Counter
from fractions import Fraction as Q
from itertools import combinations_with_replacement
import argparse
import json
from pathlib import Path


def rat(value):
    return value if isinstance(value, Q) else Q(str(value))


def dot(a, b):
    return sum((x*y for x, y in zip(a, b)), Q(0))


def norm2(a):
    return dot(a, a)


def sub(a, b):
    return tuple(x-y for x, y in zip(a, b))


def validate_points(points):
    z = [tuple(map(rat, row)) for row in points]
    if not z or not z[0] or any(len(row) != len(z[0]) for row in z):
        raise ValueError('Need nonempty, equally sized coordinate rows')
    return z


def moments(points, weights):
    d = len(points[0])
    mu = tuple(sum((p*x[j] for p,x in zip(weights,points)), Q(0)) for j in range(d))
    variance = sum((p*norm2(sub(x,mu)) for p,x in zip(weights,points)), Q(0))
    return mu, variance


def affine_dependence(points):
    """Return a nonzero exact affine dependence, or None if independent."""
    cols = len(points)
    rows = len(points[0])+1
    a = [[Q(1)]*cols] + [[x[j] for x in points] for j in range(rows-1)]
    pivots = []
    row = 0
    for col in range(cols):
        pivot = next((i for i in range(row, rows) if a[i][col]), None)
        if pivot is None:
            continue
        a[row], a[pivot] = a[pivot], a[row]
        v = a[row][col]
        a[row] = [x/v for x in a[row]]
        for i in range(rows):
            if i != row and a[i][col]:
                v = a[i][col]
                a[i] = [x-v*y for x,y in zip(a[i],a[row])]
        pivots.append(col)
        row += 1
        if row == rows:
            break
    free = next((i for i in range(cols) if i not in pivots), None)
    if free is None:
        return None
    direction = [Q(0)]*cols
    direction[free] = Q(1)
    for i,col in enumerate(pivots):
        direction[col] = -a[i][free]
    return direction


def compress_stream(points):
    """One pass; preserve the mean and never increase the second moment.

    At termination, resident original points are affinely independent, hence
    there are at most r+1 of them when the stream has affine rank r.
    """
    resident = []
    count = 0
    sums = None
    second = Q(0)
    for raw in points:
        x = tuple(map(rat, raw))
        if sums is None:
            if not x:
                raise ValueError('Empty coordinate row')
            sums = [Q(0)]*len(x)
        if len(x) != len(sums):
            raise ValueError('Coordinate dimensions differ')
        resident = [(i,z,p*Q(count,count+1)) for i,z,p in resident]
        resident.append((count,x,Q(1,count+1)))
        count += 1
        sums = [s+y for s,y in zip(sums,x)]
        second += norm2(x)
        while True:
            direction = affine_dependence([z for _,z,_ in resident])
            if direction is None:
                break
            if sum(a*norm2(z) for a,(_,z,_) in zip(direction,resident)) > 0:
                direction = [-a for a in direction]
            step = min(p/(-a) for a,(_,_,p) in zip(direction,resident) if a < 0)
            resident = [(i,z,p+step*a) for a,(i,z,p) in zip(direction,resident)
                        if p+step*a > 0]
    if not count:
        raise ValueError('Input has no points')
    mu = tuple(s/count for s in sums)
    variance = second/count - norm2(mu)
    return resident, mu, variance, count


def coefficient(rank, n):
    """Proved universal upper coefficient U_r(n), not an unknown sharp value."""
    if not isinstance(n,int) or isinstance(n,bool) or n < 1:
        raise ValueError('n must be a positive integer')
    if rank < 0:
        raise ValueError('rank must be nonnegative')
    if rank == 0:
        return Q(0)
    if n == 1:
        return Q(1)
    if rank <= 2:
        return Q(1,2*n-1)
    pair = max(Q(1,3), Q(rank-1,2*rank))
    if n <= rank:
        return (n-2+4*pair)/n**2
    base = (rank-2+4*pair)/rank**2
    return rank*base/(n*(1+base)-rank*base)


def mean_of_counts(points, counts, n):
    return tuple(sum((c*points[i][j] for i,c in counts.items()),Q(0))/n
                 for j in range(len(points[0])))


def select_atomic(points, weights, n):
    """Pair certificate, conditional padding, and exact mass peeling.

    The support-size parameter r=m-1 makes the theorem valid in any ambient
    Hilbert space, even if the input support is not affinely independent.
    """
    z = validate_points(points)
    p = list(map(rat,weights))
    if len(z) != len(p) or any(w < 0 for w in p) or sum(p) != 1:
        raise ValueError('Weights must be probabilities with matching length')
    if not isinstance(n,int) or isinstance(n,bool) or n < 1:
        raise ValueError('n must be a positive integer')
    active = [i for i,w in enumerate(p) if w]
    rank = len(active)-1
    remaining = n
    frames = []
    trace = []
    while True:
        mu,variance = moments(z,p)
        bound = coefficient(rank,remaining)
        radius = {i:norm2(sub(z[i],mu)) for i in active}
        closest = min(active,key=lambda i:(radius[i],i))
        if radius[closest] <= bound*variance:
            counts = Counter({closest:remaining})
            trace.append({'step':'repeat','budget':remaining,'index':closest})
            break
        if remaining == 1:
            raise AssertionError('Nearest-point variance inequality failed')
        if remaining == 2:
            pair = min(combinations_with_replacement(active,2),
                       key=lambda ij:(norm2(sub(tuple((a+b)/2 for a,b in zip(z[ij[0]],z[ij[1]])),mu)),ij))
            counts = Counter(pair)
            trace.append({'step':'pair','budget':2,'indices':list(pair)})
            break
        if remaining >= rank+1:
            hub = max(active,key=lambda i:(p[i],-i))
            if p[hub] < Q(1,remaining):
                raise AssertionError('Peeling mass threshold failed')
            frames.append(('peel',hub,remaining,None,None))
            trace.append({'step':'peel','budget':remaining,'index':hub})
            p = [(remaining*w-(1 if i==hub else 0))/(remaining-1) for i,w in enumerate(p)]
            active = [i for i,w in enumerate(p) if w]
        else:
            frames.append(('pad',None,remaining,mu,tuple(active)))
            trace.append({'step':'pad','budget':remaining})
        remaining -= 1
    for kind,hub,budget,mu,available in reversed(frames):
        if kind == 'peel':
            counts[hub] += 1
        else:
            total = tuple(sum(c*z[i][j] for i,c in counts.items()) for j in range(len(z[0])))
            hub = min(available,key=lambda i:(norm2(sub(tuple((s+x)/budget for s,x in zip(total,z[i])),mu)),i))
            counts[hub] += 1
    return dict(sorted(counts.items())), trace


def residual_candidate(points, weights, n):
    """Floor exact counts and apply the atomic theorem to fractional mass.

    Fewer than m slots remain. The bound is k^2 U_(s-1)(k) W_q/n^2,
    where s is the positive residual support size and W_q its variance.
    """
    z = points
    floor_counts = [int(n*p) for p in weights]
    residual = [n*p-k for p,k in zip(weights,floor_counts)]
    k = n-sum(floor_counts)
    counts = Counter({i:a for i,a in enumerate(floor_counts) if a})
    if k == 0:
        return dict(counts), Q(0)
    q = [a/k for a in residual]
    nu,w = moments(z,q)
    available = [i for i,p in enumerate(q) if p]
    residual_counts,_ = select_atomic(z,q,k)
    counts.update(residual_counts)
    return dict(sorted(counts.items())), Q(k*k,n*n)*coefficient(len(available)-1,k)*w


def select(points,n):
    resident,mu,variance,N = compress_stream(points)
    z = [x for _,x,_ in resident]
    p = [w for _,_,w in resident]
    rank = len(resident)-1
    upper = coefficient(rank,n)
    atomic_mu,atomic_variance = moments(z,p)
    assert atomic_mu == mu and atomic_variance <= variance
    rounding_counts,rounding_bound = residual_candidate(z,p,n)
    rounding_h = mean_of_counts(z,rounding_counts,n)
    rounding_error = norm2(sub(rounding_h,mu))
    if rounding_error <= upper*atomic_variance:
        counts,h,error,trace = rounding_counts,rounding_h,rounding_error,[]
        method = 'floor-residual-atomic-selection'
    else:
        counts,trace = select_atomic(z,p,n)
        h = mean_of_counts(z,counts,n)
        error = norm2(sub(h,mu))
        method = 'pair-padding-peeling'
    assert error <= upper*variance
    mapped = {resident[i][0]:v for i,v in counts.items()}
    return {'N':N,'n':n,'ambient_dimension':len(mu),'resident_affine_rank':rank,
            'counts':mapped,'mean':[str(v) for v in mu],
            'selected_mean':[str(v) for v in h], 'variance':str(variance),
            'squared_mean_error':str(error),'guaranteed_upper_coefficient':str(upper),
            'full_data_loss_ratio':str(1+error/variance) if variance else '1',
            'compressed_indices':[i for i,_,_ in resident],
            'compressed_weights':[str(p) for _,_,p in resident],
            'compressed_points':[[str(v) for v in x] for _,x,_ in resident],
            'compressed_variance':str(atomic_variance),
            'residual_rounding_bound':str(rounding_bound),
            'selected_method':method,'construction_trace':trace,
            'replacement_allowed':True,'is_instance_optimal':False}


def compositions(n,m,prefix=()):
    if m == 1:
        yield prefix+(n,)
    else:
        for k in range(n+1):
            yield from compositions(n-k,m-1,prefix+(k,))


def exact_rule_selection(points,n,weights=None,rules=None,max_states=500000):
    """Exhaustive optimum over rational linear count rules and integer caps.

    Rules: lower/upper per-row count arrays; linear list with a, sense, rhs.
    A linear row acts on integer counts. This supports exact quotas and costs.
    Bounds and enumeration cap are enforced before claiming an optimum.
    """
    from math import comb
    z = validate_points(points)
    if not isinstance(n,int) or isinstance(n,bool) or n < 1:
        raise ValueError('n must be a positive integer')
    m = len(z)
    states = comb(n+m-1,m-1)
    if states > max_states:
        raise ValueError(f'Exact enumeration needs {states} states; limit is {max_states}')
    p = [Q(1,m)]*m if weights is None else list(map(rat,weights))
    if len(p)!=m or any(v<0 for v in p) or sum(p)!=1:
        raise ValueError('Invalid probability vector')
    rules = rules or {}
    lower = rules.get('lower',[0]*m)
    upper = rules.get('upper',[n]*m)
    if len(lower)!=m or len(upper)!=m or any(not isinstance(x,int) for x in lower+upper):
        raise ValueError('Count bounds need integer arrays of matching length')
    linear = []
    for rule in rules.get('linear',[]):
        a = list(map(rat,rule['a']))
        if len(a)!=m or rule['sense'] not in ('<=','>=','=='):
            raise ValueError('Invalid linear count rule')
        linear.append((a,rule['sense'],rat(rule['rhs'])))
    mu,variance = moments(z,p)
    best = None
    feasible = 0
    for c in compositions(n,m):
        if any(v<lo or v>hi for v,lo,hi in zip(c,lower,upper)):
            continue
        valid = True
        for a,sense,rhs in linear:
            v = dot(a,c)
            if (sense=='<=' and v>rhs) or (sense=='>=' and v<rhs) or (sense=='==' and v!=rhs):
                valid = False
                break
        if not valid:
            continue
        feasible += 1
        h = mean_of_counts(z,{i:v for i,v in enumerate(c) if v},n)
        error = norm2(sub(h,mu))
        if best is None or (error,c)<(best[0],best[1]):
            best = error,c,h
    if best is None:
        return {'status':'INFEASIBLE','enumerated_states':states,'feasible_states':0}
    error,c,h = best
    return {'status':'OPTIMAL','n':n,'enumerated_states':states,'feasible_states':feasible,
            'counts':{i:v for i,v in enumerate(c) if v},'mean':[str(x) for x in mu],
            'selected_mean':[str(x) for x in h],'variance':str(variance),
            'squared_mean_error':str(error),'is_instance_optimal':True,
            'unrestricted_guarantee_applies':not bool(rules)}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('input',type=Path)
    parser.add_argument('--output',type=Path)
    parser.add_argument('--exact',action='store_true',help='Enumerate all count vectors; honor rules')
    args = parser.parse_args()
    data = json.loads(args.input.read_text(),parse_float=Q)
    if args.exact:
        result = exact_rule_selection(data['points'],data['n'],data.get('weights'),data.get('rules'))
    else:
        if data.get('rules') or data.get('weights') is not None:
            raise ValueError('Weighted or constrained CLI input requires --exact')
        result = select(iter(data['points']),data['n'])
    text = json.dumps(result,indent=2)+'\n'
    if args.output:
        args.output.write_text(text)
    else:
        print(text,end='')


if __name__ == '__main__':
    main()