hv-chemical-memory / example.py
zeechimp's picture
Create example.py
672a39e verified
Raw History Blame Contribute Delete
6.01 kB
#!/usr/bin/env python3
"""
example.py — Usage demonstrations for hv_chemical_memory.
NumPy only.
"""
import numpy as np
from hv_chemical_memory import (
AmberMemory, ErrorThreshold, TopologicalMemory,
SelfModifyingGenome, SubstrateOS,
SECONDS_PER_YEAR,
)
def _fmt_years(y):
if y < 1:
return f"{y * SECONDS_PER_YEAR:.2e} s"
if y < 1e3:
return f"{y:.1f} yr"
if y < 1e6:
return f"{y / 1e3:.1f} kyr"
return f"{y / 1e6:.2f} Myr"
def demo_amber():
print("=" * 72)
print("Demo 1 — Amber dielectric memory")
print("=" * 72)
print()
amber = AmberMemory()
print(f" τ ladder: {[_fmt_years(t) for t in amber.tau]}")
print(f" Effective τ: {_fmt_years(amber.effective_tau())}")
print()
print(f" {'time':>12s} {'retention':>10s} bar")
print(" " + "-" * 50)
for t in [1, 1e2, 1e3, 1e4, 1e5, 1e6]:
r = float(amber.retention(t)[0])
bar = "█" * int(r * 40)
print(f" {_fmt_years(t):>12s} {r:>10.4f} {bar}")
print()
print(f" 50% retention: {_fmt_years(amber.retention_time(0.5))}")
print(f" 10% retention: {_fmt_years(amber.retention_time(0.1))}")
print(f" 1% retention: {_fmt_years(amber.retention_time(0.01))}")
print()
def demo_genome():
print("=" * 72)
print("Demo 2 — Eigen error threshold")
print("=" * 72)
print()
et = ErrorThreshold(L=100, sigma=2.0)
print(f" L = {et.L}, σ = {et.sigma}")
print(f" μ_crit = {et.critical_mutation_rate():.5f}")
print()
print(f" {'μ':>10s} {'informational':>15s} {'retention':>12s}")
print(" " + "-" * 42)
for mu in [0.001, 0.005, 0.01, 0.02, 0.05]:
info = et.is_informational(mu)
ret = et.retention_estimate(mu)
print(f" {mu:>10.4f} {str(info):>15s} {ret:>12.4f}")
print()
print(" Scaling with σ at fixed L = 100:")
for sigma in [1.5, 2.0, 5.0, 10.0]:
et = ErrorThreshold(L=100, sigma=sigma)
print(f" σ={sigma:>4.1f} μ_crit = {et.critical_mutation_rate():.5f}")
print()
def demo_topological():
print("=" * 72)
print("Demo 3 — Topological protection via writhe")
print("=" * 72)
print()
tm = TopologicalMemory(0)
moves = ['R3', 'R2_+', 'R1_+', 'R3', 'R1_-', 'R2_-']
print(f" {'move':>8s} {'writhe':>8s} {'mod 2':>6s} {'preserved':>10s}")
print(" " + "-" * 38)
initial_mod2 = tm.mod2_invariant()
print(f" {'init':>8s} {tm.writhe:>8d} {initial_mod2:>6d} {'—':>10s}")
for m in moves:
tm.apply(m)
preserved = (tm.mod2_invariant() == initial_mod2)
print(f" {m:>8s} {tm.writhe:>8d} "
f"{tm.mod2_invariant():>6d} {str(preserved):>10s}")
print()
print(" Key: mod-2 is preserved under R2 and R3, broken by R1.")
print()
def demo_selfmod():
print("=" * 72)
print("Demo 4 — Self-modifying genome")
print("=" * 72)
print()
scenarios = [
('static', lambda i: 0.0),
('constant drift 0.05', lambda i: 0.05),
('linear drift', lambda i: 0.001 * i),
('sinusoidal', lambda i: 0.05 * np.sin(i / 50)),
]
for name, sched in scenarios:
smg = SelfModifyingGenome(mu_init=0.01, alpha=0.5, beta=0.1)
history = smg.evolve(sched, 500)
print(f" {name:<22s} "
f"μ_init={history[0]:.4f} "
f"μ_final={history[-1]:.4f} "
f"μ_mean={history.mean():.4f}")
print()
print(" Steady-state μ under constant drift = α·d/β = 0.5·0.05/0.1 = 0.25")
print()
def demo_unified():
print("=" * 72)
print("Demo 5 — Unified substrate report")
print("=" * 72)
print()
os_ = SubstrateOS()
reports = [
os_.simulate_amber(),
os_.simulate_genome(L=100, sigma=2.0, mu=0.005),
os_.simulate_topological(initial_writhe=0,
moves=('R3', 'R1_+', 'R3', 'R1_-')),
os_.simulate_selfmod(mu_init=0.01,
drift_schedule=lambda i: 0.05,
n_steps=500),
]
print(f" {'substrate':<18s} {'retention_time':>16s} notes")
print(" " + "-" * 74)
for r in reports:
if r['substrate'] == 'amber':
rt = _fmt_years(r['retention_time_years'])
note = f"τ_eff = {_fmt_years(r['effective_tau_years'])}"
elif r['substrate'] == 'genome':
rt = 'infinite' if r['is_informational'] else '0'
note = f"μ_crit = {r['mu_crit']:.5f}"
elif r['substrate'] == 'topological':
rt = 'infinite'
note = f"writhe = {r['writhe']}, mod 2 = {r['mod2']}"
elif r['substrate'] == 'self_modifying':
rt = f"{r['retention_time']:.0f} steps"
note = f"μ_final = {r['mu_final']:.4f}"
else:
rt = '—'
note = ''
print(f" {r['substrate']:<18s} {rt:>16s} {note}")
print()
def demo_custom_amber():
print("=" * 72)
print("Demo 6 — Custom τ ladder (fast-decaying amber)")
print("=" * 72)
print()
# Custom fast-decaying τ ladder
tau_ladder = np.geomspace(0.1, 100, 6)
amber = AmberMemory(tau_ladder_years=tau_ladder)
print(f" τ ladder: {[_fmt_years(t) for t in amber.tau]}")
print(f" 50% retention: {_fmt_years(amber.retention_time(0.5))}")
print(f" 10% retention: {_fmt_years(amber.retention_time(0.1))}")
print()
# Custom slow-decaying τ ladder
tau_ladder = np.geomspace(1e3, 1e7, 8)
amber = AmberMemory(tau_ladder_years=tau_ladder)
print(f" τ ladder: {[_fmt_years(t) for t in amber.tau]}")
print(f" 50% retention: {_fmt_years(amber.retention_time(0.5))}")
print(f" 10% retention: {_fmt_years(amber.retention_time(0.1))}")
print()
def main():
demo_amber()
demo_genome()
demo_topological()
demo_selfmod()
demo_unified()
demo_custom_amber()
if __name__ == "__main__":
main()