"""Restricted Growth Genome IR, evaluator, and exact finite-library compiler. Coordinates below are temporary inherited counters, NOT a target-array oracle. The scalar/counter machine is abstract; no nucleotide sequence backend is claimed. """ import json import numpy as np def canonical(g): return json.dumps(g, sort_keys=True, separators=(',', ':')).encode() def evaluate(g, counters): """Evaluate a capsule at one or many inherited local counter tuples.""" q = np.asarray(counters, dtype=np.int64) op = g['op'] if op == 'material': return np.full(q.shape[:-1], g['value'], dtype=np.int8) if op == 'split': mask = q[..., g['axis']] < g['cut'] return np.where(mask, evaluate(g['left'], q), evaluate(g['right'], q)) n = g['n']; x, y = q[..., 0], q[..., 1] if op == 'paired_path': # A connected frame with two parallel tracks and asymmetric branch. t = max(1, n // 12) track = ((abs(y-n//3) < t) | (abs(y-2*n//3) < t)) ends = (x < t) | (x >= n-t) spur = (abs(x-n//2) < t) & (y >= n//3) & (y <= 2*n//3) solid = track | ends | spur # A dielectric backing occupies the remainder except an off-centre notch. notch = (x > 3*n//4) & (y > 3*n//4) return np.where(solid, 2, np.where(notch, 0, 1)).astype(np.int8) if op == 'braced_shell': z = q[..., 2]; t = max(1, n//8) wall = (x=n-t)|(y>=n-t)|(z>=n-t) brace = (abs(x-y)=n-t)&(y>n//3)&(y<2*n//3)&(z>n//3)&(z<2*n//3) solid = (wall|brace)&~window label = 1 + (((x//t) ^ (y//t) ^ (z//t)) & 1) return np.where(solid, label, 0).astype(np.int8) raise ValueError(f'Unknown op {op}') def make_target(g, dim): return evaluate(g, np.moveaxis(np.indices((g['n'],)*dim), 0, -1)) def compile_target(target, candidates=()): """Exact reconstruction with a midpoint split grammar plus supplied motifs. Finite search only: no guarantee of minimal program over all computable rules. """ target = np.asarray(target) def recurse(a, lo): if np.all(a == a.flat[0]): return {'op':'material','value':int(a.flat[0])} axis = int(np.argmax(a.shape)); mid = a.shape[axis]//2 sl0 = [slice(None)]*a.ndim; sl1 = sl0.copy() sl0[axis] = slice(0,mid); sl1[axis] = slice(mid,None) hi = list(lo); hi[axis] += mid return {'op':'split','axis':axis,'cut':lo[axis]+mid, 'left':recurse(a[tuple(sl0)],lo), 'right':recurse(a[tuple(sl1)],hi)} choices = [recurse(target,[0]*target.ndim)] coords = np.moveaxis(np.indices(target.shape),0,-1) for g in candidates: if np.array_equal(evaluate(g,coords),target): choices.append(g) g = min(choices, key=lambda x:len(canonical(x))) return g, {'program_bytes':len(canonical(g)), 'raw_uint8_bytes':target.size, 'full_ternary_array_capacity_bits':float(target.size*np.log2(3)), 'candidate_count':len(choices), 'exact':True}