#!/usr/bin/env python3 """Exact scalar zero-mean transformation with three forced terminal sentinels. All arithmetic is rational or integer. The zero-endpoint orders of an input instance from zero correspond exactly to those of the output: each old order is followed by the three labeled sentinels in their designated order. """ from fractions import Fraction as F from math import prod def balance_scalar_centers(centers, rho=F(1, 2)): """Return a polynomial-bit exact-hitting reduction with sum(centers)==0. The output centers and all reachable states lie strictly in (-1/2,1/2). The guarantee concerns exact zero endpoints from initial state zero. With the designated sentinel suffix, the new endpoint equals gain times the old endpoint, where gain = rho**3 * denominator_scale / R. """ t = list(map(F, centers)) rho = F(rho) if not t: raise ValueError('at least one input center is required') if not 0 < rho < 1: raise ValueError('rho must be strictly between zero and one') N = len(t) K = N + 3 r, s = rho.numerator, rho.denominator weights = [r**(K-p)*s**(p-1) for p in range(1, K+1)] T = sum(weights) U = sum(weights[:N]) A, B, C = weights[N:] v1 = (0, C-B, A-C, B-A) v2 = (B-A, U-N*B, N*A-U, 0) V = max(map(abs, v1+v2)) L = 2*T*V + 1 markers = tuple(x+L*y for x,y in zip(v1,v2)) S = sum(t) data = t + [-B*S/(B-A), A*S/(B-A), F(0)] P = prod(x.denominator for x in data) integer_data = [int(P*x) for x in data] data_bound = T*max(map(abs, integer_data)) Q = 2*data_bound + 1 categories = [0]*N + [1,2,3] raw = [d+Q*markers[c] for d,c in zip(integer_data,categories)] R = 1+2*max(map(abs,raw)) new_centers = [F(a,R) for a in raw] return dict(original_centers=t, rho=rho, N=N, K=K, weights=weights, T=T, U=U, A=A, B=B, C=C, v1=v1, v2=v2, V=V, marker_base=L, markers=markers, integer_data=integer_data, denominator_scale=P, data_bound=data_bound, Q=Q, raw=raw, R=R, categories=categories, centers=new_centers, gap=(1-rho)/F(s**(K-1)*R), gain=rho**3*F(P,R), sentinel_suffix=(N,N+1,N+2))