1 #!/usr/bin/env python3 2 """ 3 sa: simulated annealing over tabular data, one label at a time. 4 (c) 2026, Tim Menzies <timm@ieee.org>, MIT license 5 6 USAGE: python3 sa.py [--key=val ...] 7 8 OPTIONS: 9 --dir data directory = $MOOT/optimize 10 --file file(s) | all = all 11 --seed random seed = 1 12 --runs repeats = 5 13 --val random evals = 10 14 --few pool rows tried = 32 15 --temp start temp = 0.2 16 --cool cooling rate = 0.9 17 18 Design: an "eval" reads one row's y values (its label). Spend 19 --val evals on random rows. Then walk: mutate the current row by 20 extrapolating between two of the top sqrt(n) evaluated rows; 21 realize that as the nearest of --few random unevaluated rows; 22 evaluate it; move there if it is better, or if lucky at this 23 temperature. 24 25 Reports "win" after 25, 50, ... 1000 evals, one column per data 26 file: 100 = found the best row in all the data, 0 = no better 27 than the median row; mean of --runs repeats. A file with fewer 28 rows than evals just evaluates every row. Files are named 29 relative to --dir, without ".csv". 30 """ 31 import os, sys # make hair importable whether run from source or installed 32 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 33 import random 34 from math import exp, sqrt 35 from bisect import insort 36 from hair import * 37 38 rand = random.random 39 any = random.choice # shadows builtin 40 EVALS = [25, 50, 100, 200, 500, 1000] 41 42 #-- mutate ----------------------------------------------------- 43 def top(done: list) -> list: 44 return done[:int(sqrt(len(done)))] # done is sorted, best first 45 46 def mutate(tbl, done: list, row: list, p=1.0) -> list: 47 """Walk step: copy of row where each x cell, with probability 48 p, is replaced by a value extrapolated between two top rows 49 (t in -.25..1.25).""" 50 b1, b2 = any(top(done)), any(top(done)) 51 out = row[:] 52 for a in tbl.x: 53 u, v = b1[a], b2[a] 54 if rand() > p or u == v == "?": continue 55 if "?" in (u, v): out[a] = v if u == "?" else u 56 elif isa(tbl.cols[a], Sym): out[a] = u if rand() < .5 else v 57 else: out[a] = v + (rand()*1.5 - .25) * (u - v) 58 return out 59 60 #-- sa --------------------------------------------------------- 61 def near(tbl, pool: list, row: list) -> int: 62 some = random.sample(range(len(pool)), min(the.few, len(pool))) 63 return min(some, key=lambda i: distx(tbl, pool[i], row)) 64 65 def accept(y: float, ycur: float, t: float) -> bool: 66 "The whole SA kernel: better, or lucky at this temperature" 67 return y < ycur or rand() < exp(-(y - ycur)/(t + TINY)) 68 69 def sa(tbl) -> list: 70 "Return the best disty seen after each eval" 71 pool, done, best = random.sample(tbl.rows, len(tbl.rows)), [], [] 72 def evaluate(row): 73 insort(done, row, key=lambda r: disty(tbl, r)) 74 best.append(disty(tbl, done[0])) 75 return row 76 for _ in range(the.val): evaluate(pool.pop()) 77 cur, t = done[0], the.temp 78 while pool and len(best) < EVALS[-1]: 79 new = evaluate(pool.pop(near(tbl, pool, mutate(tbl, done, cur)))) 80 if accept(disty(tbl,new), disty(tbl,cur), t): cur = new 81 t *= the.cool 82 return best 83 84 #-- test ------------------------------------------------------- 85 def win(y: float, lo: float, mid: float) -> float: 86 return 100 * (1 - (y - lo) / (mid - lo + TINY)) 87 88 def wins(file: str) -> list: 89 tbl = TAB(csv(file)) 90 ys = sorted(disty(tbl,r) for r in tbl.rows) 91 random.seed(the.seed) 92 runs = [sa(tbl) for _ in range(the.runs)] 93 return [sum(win(best[min(n, len(best)) - 1], ys[0], ys[len(ys)//2]) 94 for best in runs) / the.runs for n in EVALS] 95 96 #-- main ------------------------------------------------------- 97 def main() -> None: 98 cli(the) 99 print("win after n evals: 100 = found the best row; " 100 "0 = only the median row\n") 101 table([name(f) for f in files()], EVALS, 102 [wins(f) for f in files()]) 103 104 if __name__ == "__main__": main() 105