Download research/code/optimize_capacity.py from PureOne/ISORYTH-Lily-v5: direct link, hf CLI and curl.
- Browser
- Download file 5.29 kB
-
https://huggingface.co/datasets/PureOne/ISORYTH-Lily-v5/resolve/main/research/code/optimize_capacity.py
- Command line
-
hf download hf://datasets/PureOne/ISORYTH-Lily-v5/research/code/optimize_capacity.py
-
curl -L -o optimize_capacity.py https://huggingface.co/datasets/PureOne/ISORYTH-Lily-v5/resolve/main/research/code/optimize_capacity.py
5.29 kB
| #!/usr/bin/env python3 | |
| """Optional numerical candidate finder. Final certificates use exact rationals. | |
| A supporting-hyperplane outer approximation solves LPs with SciPy/HiGHS. | |
| Only zero or one >= utility moment is supported by the repair helper. | |
| The independent verifier has no SciPy or NumPy dependency. | |
| """ | |
| from __future__ import annotations | |
| import argparse,json,time | |
| from pathlib import Path | |
| from fractions import Fraction as F | |
| import numpy as np | |
| from scipy.optimize import linprog | |
| from scipy import sparse | |
| from certified_compiler import (Model,Task,Moment,repair_one_moment,scale_to_energies, | |
| pack_fraction,model_record) | |
| ROOT=Path(__file__).resolve().parents[1] | |
| P=(F(7,16),F(4,16),F(4,16),F(1,16)) | |
| TASKS=(Task('first coordinate',2,(0,1,0,1)),Task('second coordinate',2,(0,0,1,1))) | |
| def as_rational(x:float)->F: | |
| # Numerical suggestions become explicit finite rational candidate data. | |
| return F(format(float(x),'.17g')) | |
| def solve(model:Model,tolerance=2e-6,max_iterations=120): | |
| if len(model.moments)>1: | |
| raise ValueError('Numerical repair supports at most one utility constraint.') | |
| started=time.perf_counter() | |
| N=len(model.rows) | |
| caps=np.array([float(r.cap) for r in model.rows]) | |
| bs=np.array([[float(r.margins[j]) for r in model.rows] for j in range(len(model.moments))]) | |
| groups=[np.array([r.output[k] for r in model.rows],dtype=int) for k in range(len(model.tasks))] | |
| weights=[np.array([float(c) for c in cs]) for cs in model.weights] | |
| rows=[];bounds=[];cut_metadata=[] | |
| for b in bs: | |
| rows.append(-b*caps);bounds.append(0.) | |
| log=[] | |
| lp=None | |
| for iteration in range(max_iterations): | |
| A=sparse.csr_matrix(np.array(rows)) if rows else None | |
| lp=linprog(-caps,A_ub=A,b_ub=np.array(bounds) if bounds else None, | |
| bounds=(0.,1.),method='highs', | |
| options={'dual_feasibility_tolerance':1e-9,'primal_feasibility_tolerance':1e-9}) | |
| if not lp.success: | |
| raise RuntimeError('LP failed: '+lp.message) | |
| mass=-lp.fun | |
| x=caps*lp.x | |
| output=[np.bincount(g,weights=x,minlength=len(w)) for g,w in zip(groups,weights)] | |
| energies=[float(np.dot(w,y*y)) for w,y in zip(weights,output)] | |
| log.append({'iteration':iteration,'mass_upper_numerical':mass,'energies_numerical':energies,'cuts':len(cut_metadata)}) | |
| if max(energies)<=1+tolerance: | |
| break | |
| added=0 | |
| for k,(w,y,E,g) in enumerate(zip(weights,output,energies,groups)): | |
| if E>1+tolerance: | |
| u=w*y/np.sqrt(E) | |
| rows.append(u[g]*caps) | |
| bounds.append(1.) | |
| cut_metadata.append((k,u)) | |
| added+=1 | |
| if not added: break | |
| x=tuple(r.cap*min(F(1),max(F(0),as_rational(y))) for r,y in zip(model.rows,lp.x)) | |
| x=repair_one_moment(model,x) | |
| x=scale_to_energies(model,x) | |
| eta=[] | |
| if rows: | |
| multipliers=-np.array(lp.ineqlin.marginals) | |
| eta=[max(F(0),as_rational(v)) for v in multipliers[:len(model.moments)]] | |
| potentials=[[F(0) for _ in cs] for cs in model.weights] | |
| for alpha,(k,u) in zip(multipliers[len(model.moments):] if rows else [],cut_metadata): | |
| a=max(F(0),as_rational(alpha)) | |
| for j,v in enumerate(u): | |
| potentials[k][j]+=a*as_rational(v) | |
| certificate=model.certify(x,potentials,eta,bits=110) | |
| return {'model':model_record(model),'x':pack_fraction(x), | |
| 'potentials':pack_fraction(potentials),'eta':pack_fraction(eta), | |
| 'certificate':pack_fraction(certificate), | |
| 'display':{'lower':float(certificate['lower']),'upper':float(certificate['upper']), | |
| 'relative_gap':float(certificate['relative_gap']) if certificate['relative_gap'] is not None else None, | |
| 'energies':[float(v) for v in certificate['primal']['energies']], | |
| 'utility_slacks':[float(v) for v in certificate['primal']['moment_slacks']], | |
| 'type_variables':N,'word_variables':model.d**model.n, | |
| 'cuts':len(cut_metadata),'lp_iterations':len(log),'energy_stop_reached':max(energies)<=1+tolerance, | |
| 'elapsed_seconds':time.perf_counter()-started, | |
| 'retained_support_types':sum(v>0 for v in x)}, | |
| 'iterations':log, | |
| 'scope':'Floating-point LP proposes witnesses; independently recomputed rational certificates control all validity claims.'} | |
| def main(): | |
| ap=argparse.ArgumentParser() | |
| ap.add_argument('--depth',type=int,default=8) | |
| ap.add_argument('--threshold',default='1/10',help='Minimum mean frequency of symbol 3; none disables utility.') | |
| ap.add_argument('--output',default=None) | |
| a=ap.parse_args() | |
| moments=() if a.threshold=='none' else (Moment('useful symbol frequency',(F(0),F(0),F(0),F(1)),F(a.threshold)),) | |
| model=Model(P,a.depth,TASKS,moments) | |
| result=solve(model) | |
| out=Path(a.output) if a.output else ROOT/'results'/f'capacity_n{a.depth}_g{a.threshold.replace("/","_")}.json' | |
| out.parent.mkdir(parents=True,exist_ok=True) | |
| out.write_text(json.dumps(result,indent=2)+'\n') | |
| print(json.dumps({'output':str(out),**result['display']},indent=2)) | |
| if __name__=='__main__':main() | |