"""Reproduce the v3 finite experiments. These are synthetic post-conversion electrical models, not a calibrated molecular simulator or a hardware benchmark. """ import os os.environ.setdefault('OPENBLAS_NUM_THREADS', '1') os.environ.setdefault('OMP_NUM_THREADS', '1') from pathlib import Path import argparse import json import time import numpy as np from scipy.linalg import cho_factor, cho_solve from scipy.sparse.linalg import spsolve from scipy.integrate import quad from contract_genome import capsule, compile_grid, seal_ready from contract_growth import delivery_time from contracts import laplacian, kron, conductance from gauge_contracts import (RelativeEstimator, comparison_line_graph, grid_edges, ratio_observation, exact_feasibility, robust_feasibility, uniform_reserve_yield, projective_response_error, closure_bridge_is_needed) ROOT = Path(__file__).resolve().parents[1] OUT = ROOT/'results/gauge' METHODS = ['projective', 'common_detector_gain', 'common_material_scale', 'conventional_joint', 'fixed_representative', 'insufficient_reserve', 'differential_bias', 'early_reference_release'] PARAMETERS = {'tau': .04, 'seal_log_bound': .005, 'diagnostic_log_radius': .006, 'ratio_sigma': .012, 'delta': .005, 'horizon': 128, 'increment_min': .007, 'increment_max': .012, 'reserve': 1.05, 'initial_low': .65, 'initial_high': 1.35, 'root_material_rate': 2., 'hop_time': .03, 'sample_time': .001, 'material_per_conductance': .4, 'scaffold_per_node': .1} PARAMETERS['numerical_log_budget'] = 1e-8 def prepare(n, dim): genome = json.loads((ROOT/f'genomes/gauge_{dim}d.json').read_text()) if (genome['extent'] != n or genome['dimension'] != dim or genome['functional_equivalence'] != 'positive_common_conductance_scale' or genome['external_ports'] != 4 or genome['motif'] != 'parity_conductance'): raise ValueError('The requested grid and declared function capsule disagree') expected = {'log_tolerance': PARAMETERS['tau'], 'seal_log_bound': PARAMETERS['seal_log_bound'], 'reserve_capacity': PARAMETERS['reserve'], 'ratio_log_radius': PARAMETERS['diagnostic_log_radius'], 'inspection_horizon': PARAMETERS['horizon'], 'increment_bounds': [PARAMETERS['increment_min'], PARAMETERS['increment_max']], 'witness': 'stable_uncalibrated', 'closure': 'preserve_comparisons_until_all_certified'} if any(genome[key] != value for key, value in expected.items()): raise ValueError('Update the recorded experiment parameters with the capsule') net = compile_grid(genome) count, edges = comparison_line_graph(net['edges']) estimator = RelativeEstimator(count, edges) N = len(net['coordinates']) ports = np.array([0, N-1, n-1, (n-1)*n**(dim-1)]) D0 = kron(laplacian(N, net['edges'], net['target']), ports) return net, estimator, ports, D0 def voltage_solution(net, g): N = len(net['coordinates']) L = laplacian(N, net['edges'], g) fixed = np.r_[net['left'], net['right']] free = np.setdiff1d(np.arange(N), fixed) v = np.zeros(N); v[net['left']] = 1. v[free] = spsolve(L[free][:, free], -L[free][:, fixed]@v[fixed]) return v def run_one(prepared, method, seed): net, estimator, ports, D0 = prepared par = PARAMETERS R, N = len(net['target']), len(net['coordinates']) rng = np.random.default_rng(seed) rng_noise = np.random.default_rng(seed+11000000) rng_action = np.random.default_rng(seed+22000000) rng_gain = np.random.default_rng(seed+33000000) x0 = rng.uniform(par['initial_low'], par['initial_high'], R) x = x0.copy() capacity = .4 if method == 'insufficient_reserve' else par['reserve'] physical_scale = .6 if method == 'common_material_scale' else 1. target_aug = np.r_[net['target'], 1.] samples = estimator.sample_budget(par['ratio_sigma'], par['diagnostic_log_radius']-par['numerical_log_budget'], par['horizon'], par['delta']) radius = estimator.radius(par['ratio_sigma'], samples, par['horizon'], par['delta'])+par['numerical_log_budget'] bias = np.zeros(R+1) if method == 'differential_bias': positions = net['coordinates'][net['owner'], 0] bias[:-1] = .30*(positions/positions.max()-.5) accepted = np.zeros(R, bool) added = np.zeros(R) observations = 0; ratio_samples = 0; largest_error = 0. cumulative_cycle_energy = 0.; deposition_operations = 0 maximum_numerical_bound = 0. ledger_time = 0.; messages = 0 colors = int(estimator.colors.max())+1 trace = [] # The geometry is the inherited seed-grown lattice. Initial and repair # material are paid using the same capacity reservation model as v2. initial_mass = par['scaffold_per_node']*N initial_mass += par['material_per_conductance']*float(net['target']@x0) demand = np.full(N, par['scaffold_per_node']) np.add.at(demand, net['owner'], par['material_per_conductance']*net['target']*x0) growth_time = 0. for layer in range(int(net['depth'].max())+1): service, _ = delivery_time(np.where(net['depth']==layer, demand, 0.), net['parent'], par['root_material_rate'], par['hop_time'], np.minimum(net['depth'], layer)) growth_time += max(1., service) ledger_time += growth_time def inspect(): nonlocal observations, ratio_samples, largest_error nonlocal cumulative_cycle_energy, ledger_time nonlocal maximum_numerical_bound gains = np.ones(len(estimator.edges)) if method == 'common_detector_gain': gains = np.exp(rng_gain.uniform(-.7, .7, len(gains))) noise = rng_noise.normal(0, par['ratio_sigma']/np.sqrt(samples), len(estimator.edges)) y = ratio_observation(np.r_[x, 1.], target_aug, estimator.edges, gains, noise, physical_scale=physical_scale, node_bias=bias) z = estimator.estimate(y) maximum_numerical_bound = max(maximum_numerical_bound,estimator.last_numerical_bound) if estimator.last_numerical_bound > par['numerical_log_budget']: raise FloatingPointError('The numerical inference budget is not certified') largest_error = max(largest_error, float(np.max(np.abs(z[:-1]-np.log(x))))) residual = y-estimator.B@z cumulative_cycle_energy += float(residual@residual) observations += 1; ratio_samples += samples*len(estimator.edges) ledger_time += colors*samples*par['sample_time'] return z[:-1] estimate = inspect() cert = robust_feasibility(np.exp(estimate-radius), np.exp(estimate+radius), capacity, par['tau'], par['seal_log_bound'], radius, par['increment_max']) kappa = cert.get('scale_lower', 1.) reason = cert['reason'] if method == 'fixed_representative': kappa = 1. cert['feasible'] = bool(cert.get('scale_lower', 2.) <= 1 <= cert.get('scale_upper', 0.)) if not cert['feasible']: reason = 'fixed_scale_not_reachable' steps = 0 if cert['feasible']: half_band = par['tau']-par['seal_log_bound'] threshold_low = np.log(kappa)-half_band+radius threshold_high = np.log(kappa)+half_band-radius for turn in range(par['horizon']): if turn: if method == 'early_reference_release' and turn == 3: ref_edges = np.flatnonzero( np.any(estimator.edges==estimator.reference, axis=1)) assert len(ref_edges)==1 assert closure_bridge_is_needed(estimator.nodes, estimator.edges, ref_edges[0]) reason = 'reference_access_lost' break estimate = inspect() accepted |= (estimate >= threshold_low) & (estimate <= threshold_high) if accepted.all(): reason = 'complete' break need = (~accepted) & (estimate < threshold_low) if np.any((~accepted) & (estimate > threshold_high)): reason = 'unrepairable_high_state' break delta = rng_action.uniform(par['increment_min'], par['increment_max'], R) delta[~need] = 0. if np.any(added+delta > capacity+1e-12): reason = 'reserve_exhausted' break demand = np.zeros(N) np.add.at(demand, net['owner'], par['material_per_conductance']*net['target']*delta) service, _ = delivery_time(demand, net['parent'], par['root_material_rate'], par['hop_time'], net['depth']) ledger_time += max(1., service) x += delta; added += delta steps += 1; deposition_operations += int(need.sum()) # Max/min reductions use the same service tree; their latency is # not hidden inside the following physical-time subtotal. messages += 2*(N-1) trace.append([observations, int(accepted.sum()), float(added.sum())]) complete = bool(accepted.all()) sealed = np.zeros(N, bool) closure_rounds = 0 final_x = x.copy() if complete: # The calibration backbone is retained until ALL certificates exist. # Only then may the ordinary local postorder closure proceed. for _ in range(N+1): sealed = seal_ready(np.ones(N, bool), sealed, net['children']) closure_rounds += 1 if sealed.all(): break assert sealed.all() final_x *= np.exp(rng_action.uniform(-par['seal_log_bound'], par['seal_log_bound'], R)) ledger_time += closure_rounds*par['hop_time'] final_g = physical_scale*net['target']*final_x D = kron(laplacian(N, net['edges'], final_g), ports) projective_error = projective_response_error(D, D0) local_contract_error = float(np.max(np.abs(np.log(final_x/kappa)))) v0 = voltage_solution(net, net['target']) vf = voltage_solution(net, final_g) final_G = conductance(N, net['edges'], final_g, net['left'], net['right']) target_G = conductance(N, net['edges'], net['target'], net['left'], net['right']) outcome = {'seed': int(seed), 'method': method, 'nodes': N, 'modules': R, 'dimension': net['coordinates'].shape[1], 'complete': complete, 'termination_reason': reason, 'projective_error': projective_error, 'projective_function_pass': bool(complete and projective_error<=par['tau']), 'local_certificate_valid': bool(complete and local_contract_error<=par['tau']+1e-10), 'false_local_certificate': bool(complete and local_contract_error>par['tau']+1e-10), 'local_log_error': local_contract_error, 'voltage_max_absolute_error': float(np.max(np.abs(vf-v0))), 'absolute_conductance_ratio': float(final_G/target_G), 'physical_common_scale': physical_scale, 'chosen_relative_scale': float(kappa), 'samples_per_pair': samples, 'pair_edges': len(estimator.edges), 'probe_color_slots': colors, 'rho_max': estimator.rho_max, 'diagnostic_radius': radius, 'inspections': observations, 'maximum_numerical_log_error_bound': maximum_numerical_bound, 'ratio_samples': ratio_samples, 'maximum_actual_log_estimation_error': largest_error, 'mean_cycle_residual_energy': cumulative_cycle_energy/observations, 'repair_steps': steps, 'deposition_operations': deposition_operations, 'additional_material_proxy': float(par['material_per_conductance']*net['target']@added), 'initial_material_proxy': float(initial_mass), 'reserve_capacity': float(capacity), 'max_reserve_used': float(added.max()), 'growth_time': growth_time, 'service_and_acquisition_time_subtotal': ledger_time, 'inference_latency_excluded_from_subtotal': True, 'service_reduction_messages': messages, 'closure_rounds': closure_rounds, 'guard_certificate': cert} snapshot = {'initial': x0, 'final': final_x, 'target': net['target'], 'coordinates': net['coordinates'], 'edges': net['edges'], 'trace': np.array(trace), 'voltage': vf, 'target_voltage': v0, 'comparison_edges': estimator.edges} return outcome, snapshot def phase_experiment(): rng = np.random.default_rng(39060919) low, high, tau = .65, 1.35, .04 rows = [] for size in [4, 16, 64, 256, 1024]: x = rng.uniform(low, high, (5000, size)) minimum, maximum = x.min(axis=1), x.max(axis=1) for cap in np.linspace(.4, .7, 31): good = maximum <= np.exp(2*tau)*(minimum+cap) probability = uniform_reserve_yield(size, low, high, float(cap), tau) rows.append({'modules': size, 'capacity': float(cap), 'trials': 5000, 'passes': int(good.sum()), 'exact_probability': probability}) return {'low': low, 'high': high, 'tau': tau, 'critical_capacity': float(high*np.exp(-2*tau)-low), 'rows': rows, 'sampling_note': 'Within each size, the same 5000 arrays are reused across capacities.'} def theorem_experiments(): rng = np.random.default_rng(39160919) maximum_quadrature_error = 0. for _ in range(100): R = int(rng.integers(2, 60)); low = float(rng.uniform(.1, .8)) high = low+float(rng.uniform(.2, 1.5)); tau = float(rng.uniform(.003, .12)) c = float(rng.uniform(0, high*np.exp(-2*tau)-low)) if high*np.exp(-2*tau)>low else 0. q = np.exp(2*tau); width = high-low point = high/q-c f = lambda t: R/width*(max(0., min(high, q*(t+c))-t)/width)**(R-1) integration = quad(f, low, high, points=[point] if low=3 external ports. from contracts import relative_spectrum max_composition_excess = -1e9 for _ in range(200): coords, edges = grid_edges(4, 3) target = rng.uniform(.5, 1.5, len(edges)) tau = .04; common = float(np.exp(rng.uniform(-2,2))) actual = common*target*np.exp(rng.uniform(-tau,tau,len(edges))) D0 = kron(laplacian(len(coords),edges,target),[0,3,48,63]) D = kron(laplacian(len(coords),edges,actual),[0,3,48,63]) max_composition_excess = max(max_composition_excess, projective_response_error(D,D0)-tau) return {'quadrature_trials': 100, 'max_phase_formula_error': maximum_quadrature_error, 'composition_trials': 200, 'maximum_projective_bound_excess': max_composition_excess} def calibration_experiments(): records = [] for dim, sizes in [(1,[8,16,32,64,128]),(2,[4,8,12,16]),(3,[3,4,6,8])]: for n in sizes: coords, edges = grid_edges(n,dim) est = RelativeEstimator(len(coords),edges,reference=0) R = len(coords)-1 records.append({'dimension': dim,'side':n,'nodes':len(coords), 'rho_max':est.rho_max,'radius_at_64_samples': est.radius(.012,64,128,.005), 'samples_for_radius_006':est.sample_budget(.012,.006,128,.005)}) local_checks = [] for n,dim in [(4,2),(4,3),(6,3)]: coords, edges = grid_edges(n,dim) est=RelativeEstimator(len(coords),edges,reference=0) rng=np.random.default_rng(39260919+dim*100+n) truth=rng.normal(0,.2,len(coords)); truth-=truth[0] y=est.B@truth+rng.normal(0,.002,len(edges)) exact=est.estimate(y) local,info=est.local_estimate(y,tolerance=1e-5) info.update({'side':n,'dimension':dim,'nodes':len(coords), 'actual_error':float(np.max(np.abs(local-exact)))}) local_checks.append(info) coords,edges=grid_edges(5,3); est=RelativeEstimator(len(coords),edges,reference=0) rng=np.random.default_rng(39360919) noise=rng.normal(size=(len(edges),6000)) errors=cho_solve(est.factor,est.Bg.T@noise) empirical=errors.var(axis=1,ddof=1) covariance_error=float(np.max(np.abs(empirical/est.rho-1))) truth=rng.normal(0,.2,len(coords));truth-=truth[0] invisible=.15*coords[:,0]/4 y=est.B@(truth+invisible) fitted=est.estimate(y) return {'scaling':records,'local_message_solver':local_checks, 'covariance_trials':6000,'covariance_max_relative_sampling_error':covariance_error, 'gradient_bias_example':{'cycle_residual_norm':float(np.linalg.norm(y-est.B@fitted)), 'maximum_undetected_bias':float(np.max(np.abs(fitted-truth)))}} def main(): parser=argparse.ArgumentParser() parser.add_argument('--reps',type=int,default=32) parser.add_argument('--skip-theory',action='store_true') args=parser.parse_args() OUT.mkdir(parents=True,exist_ok=True) start=time.monotonic() rows=[] for n,dim in [(8,2),(5,3)]: prepared=prepare(n,dim) for method in METHODS: for rep in range(args.reps): row,snapshot=run_one(prepared,method,39460919+1000*dim+rep) rows.append(row) if rep==0: np.savez_compressed(OUT/f'{dim}d_{method}.npz',**snapshot) recent=rows[-args.reps:] print(dim,method,sum(x['complete'] for x in recent), sum(x['projective_function_pass'] for x in recent),flush=True) summary=[] for dim in [2,3]: for method in METHODS: subset=[r for r in rows if r['dimension']==dim and r['method']==method] summary.append({'dimension':dim,'method':method,'runs':len(subset), 'completed':sum(r['complete'] for r in subset), 'functional':sum(r['projective_function_pass'] for r in subset), 'false_certificates':sum(r['false_local_certificate'] for r in subset), **{key+'_mean':float(np.mean([r[key] for r in subset])) for key in [ 'projective_error','voltage_max_absolute_error','absolute_conductance_ratio', 'additional_material_proxy','inspections','ratio_samples', 'service_and_acquisition_time_subtotal','mean_cycle_residual_energy']}}) (OUT/'runs.json').write_text(json.dumps(rows,indent=2)+'\n') (OUT/'summary.json').write_text(json.dumps(summary,indent=2)+'\n') (OUT/'parameters.json').write_text(json.dumps(PARAMETERS,indent=2)+'\n') if not args.skip_theory: for name,result in [('phase',phase_experiment()),('theorem_checks',theorem_experiments()), ('calibration',calibration_experiments())]: (OUT/(name+'.json')).write_text(json.dumps(result,indent=2)+'\n') (OUT/'execution.json').write_text(json.dumps({'wall_seconds':time.monotonic()-start, 'runs':len(rows),'no_laboratory_measurements':True},indent=2)+'\n') print('Completed',len(rows),'runs in',round(time.monotonic()-start,2),'seconds') if __name__=='__main__': main()