File size: 6,014 Bytes
672a39e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/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()