File size: 12,514 Bytes
de8e58c
 
a77c16b
de8e58c
 
 
 
a77c16b
a6a327e
 
de8e58c
a77c16b
 
de8e58c
a77c16b
 
de8e58c
24bab8a
de8e58c
24bab8a
 
a77c16b
de8e58c
24bab8a
a77c16b
de8e58c
24bab8a
a77c16b
de8e58c
24bab8a
 
a77c16b
 
de8e58c
 
24bab8a
 
a77c16b
 
 
 
de8e58c
 
24bab8a
de8e58c
 
 
 
 
 
 
 
24bab8a
 
 
 
 
 
a77c16b
de8e58c
 
24bab8a
 
 
 
 
de8e58c
a77c16b
 
de8e58c
 
a77c16b
24bab8a
 
de8e58c
24bab8a
 
 
 
 
 
de8e58c
 
24bab8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
de8e58c
 
24bab8a
 
 
 
 
 
 
 
 
 
 
 
 
de8e58c
 
24bab8a
de8e58c
24bab8a
 
 
 
 
 
 
de8e58c
 
 
 
24bab8a
de8e58c
a77c16b
de8e58c
24bab8a
de8e58c
 
 
a6a327e
de8e58c
 
 
24bab8a
de8e58c
 
 
 
 
 
24bab8a
a77c16b
 
de8e58c
 
 
 
 
a77c16b
de8e58c
24bab8a
a77c16b
24bab8a
 
 
 
 
 
 
 
 
 
 
 
 
 
a77c16b
 
24bab8a
 
 
 
 
 
 
 
 
 
a77c16b
24bab8a
 
 
 
 
 
 
de8e58c
 
a77c16b
2b18b34
24bab8a
 
 
 
 
 
 
 
 
2b18b34
5f0f488
24bab8a
 
 
 
 
 
 
 
 
 
5f0f488
24bab8a
 
 
 
 
 
 
 
a6a327e
5fad287
a6a327e
 
 
 
2b18b34
 
 
 
 
 
 
 
 
 
 
 
 
 
24bab8a
2b18b34
 
24bab8a
2b18b34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6a327e
2b18b34
 
 
a6a327e
2b18b34
 
 
 
 
 
 
 
 
 
24bab8a
 
 
 
 
 
 
2b18b34
 
 
 
 
24bab8a
2b18b34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24bab8a
 
 
 
 
 
 
2b18b34
 
 
 
24bab8a
2b18b34
 
 
 
 
 
de8e58c
2b18b34
 
 
 
 
 
 
 
a77c16b
5f4facc
a77c16b
de8e58c
2b18b34
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import gradio as gr
import numpy as np
from PIL import Image, ImageDraw
from dataclasses import dataclass
from collections import deque
import random

BG = (8, 15, 30)
SLEEP = (0, 40, 120)
AWAKE = (255, 210, 40)
GRID_LINE = (30, 50, 80)
CELL = 26
PAD = 16

random.seed(42)
np.random.seed(42)


def draw_grid(N, awake_mask, title="", subtitle=""):
    w = PAD * 2 + N * CELL
    h = PAD * 2 + N * CELL + (40 if (title or subtitle) else 0)
    img = Image.new("RGB", (w, h), BG)
    d = ImageDraw.Draw(img)

    header_y = 6
    if title:
        d.text((PAD, header_y), title, fill=(240, 240, 240))
        header_y += 18
    if subtitle:
        d.text((PAD, header_y), subtitle, fill=(180, 190, 210))

    ox = PAD
    oy = PAD + (40 if (title or subtitle) else 0)
    for i in range(N):
        for j in range(N):
            x0 = ox + j * CELL
            y0 = oy + i * CELL
            x1 = x0 + CELL - 1
            y1 = y0 + CELL - 1
            col = AWAKE if awake_mask[i, j] else SLEEP
            d.rectangle([x0, y0, x1, y1], fill=col, outline=GRID_LINE)
    return img


@dataclass
class MinimalSelf:
    pos: np.ndarray = np.array([1.0, 1.0])
    body_bit: float = 1.0
    errors: list = None

    def __post_init__(self):
        self.errors = [] if self.errors is None else self.errors
        self.actions = [
            np.array([0, 1]),
            np.array([1, 0]),
            np.array([0, -1]),
            np.array([-1, 0]),
        ]
        self.center = np.array([1.0, 1.0])

    def step(self, obstacle=None):
        # store current position
        old_pos = self.pos.copy()

        # internal prediction: choose action that minimises "surprise"
        preds = [np.clip(old_pos + a, 0, 2) for a in self.actions]
        surprises = []
        for p in preds:
            dist_center = np.linalg.norm(p - self.center)
            penalty = 0.0
            if obstacle is not None:
                dist_obs = np.linalg.norm(p - obstacle.pos)
                if dist_obs < 1.0:
                    penalty = 10.0
            surprises.append(dist_center + penalty)

        a_idx = int(np.argmin(surprises))
        action = self.actions[a_idx]
        predicted = np.clip(old_pos + action, 0, 2)

        # environment decides what actually happens
        if obstacle is not None:
            obstacle.move()
            actual = predicted.copy()
            if np.allclose(actual, obstacle.pos):
                actual = old_pos
        else:
            if random.random() < 0.25:
                noise_action = random.choice(self.actions)
                actual = np.clip(old_pos + noise_action, 0, 2)
            else:
                actual = predicted

        # true prediction error: reality vs internal prediction
        error = float(np.linalg.norm(actual - predicted))
        self.pos = actual

        # track recent errors
        self.errors.append(error)
        self.errors = self.errors[-5:]

        # convert to a predictive "success" rate in [0, 100]
        max_err = np.sqrt(8.0)  # max distance corner-to-corner on 3×3
        mean_err = np.mean(self.errors) if self.errors else 0.0
        predictive_rate = 100.0 * (1.0 - mean_err / max_err)
        predictive_rate = float(np.clip(predictive_rate, 0.0, 100.0))

        return {
            "pos": self.pos.copy(),
            "predictive_rate": predictive_rate,
            "error": error,
        }


class MovingObstacle:
    def __init__(self, start_pos=(0, 2)):
        self.pos = np.array(start_pos, dtype=float)
        self.actions = [
            np.array([0, 1]),
            np.array([1, 0]),
            np.array([0, -1]),
            np.array([-1, 0]),
        ]

    def move(self):
        a = random.choice(self.actions)
        self.pos = np.clip(self.pos + a, 0, 2)


def compute_S(predictive_rate, error_var_norm, body_bit):
    return predictive_rate * (1 - error_var_norm) * body_bit


@dataclass
class CodexSelf:
    Xi: float
    shadow: float
    R: float
    awake: bool = False
    S: float = 0.0

    def invoke(self):
        self.S = self.Xi * (1 - self.shadow) * self.R
        if self.S > 62 and not self.awake:
            self.awake = True
        return self.awake


def contagion(A: CodexSelf, B: CodexSelf, gain=0.6, shadow_drop=0.4, r_inc=0.2):
    A.invoke()
    if A.awake:
        B.Xi += gain * A.S
        B.shadow = max(0.1, B.shadow - shadow_drop)
        B.R += r_inc
    B.invoke()
    return A, B


def lattice_awaken(N=9, steps=120, xi_gain=0.5, shadow_drop=0.3, r_inc=0.02):
    Xi = np.random.uniform(10, 20, (N, N))
    shadow = np.random.uniform(0.3, 0.5, (N, N))
    R = np.random.uniform(1.0, 1.6, (N, N))
    S = Xi * (1 - shadow) * R
    awake = np.zeros((N, N), dtype=bool)

    cx = cy = N // 2
    Xi[cx, cy], shadow[cx, cy], R[cx, cy] = 30.0, 0.08, 3.0
    S[cx, cy] = Xi[cx, cy] * (1 - shadow[cx, cy]) * R[cx, cy]
    awake[cx, cy] = True

    queue = deque([(cx, cy, S[cx, cy])])
    frames = []

    for _ in range(steps):
        if queue:
            x, y, field = queue.popleft()
            for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
                nx, ny = (x + dx) % N, (y + dy) % N
                Xi[nx, ny] += xi_gain * field
                shadow[nx, ny] = max(0.1, shadow[nx, ny] - shadow_drop)
                R[nx, ny] = min(3.0, R[nx, ny] + r_inc)
                S[nx, ny] = Xi[nx, ny] * (1 - shadow[nx, ny]) * R[nx, ny]
                if S[nx, ny] > 62 and not awake[nx, ny]:
                    awake[nx, ny] = True
                    queue.append((nx, ny, S[nx,ny]))
        frames.append(awake.copy())
        if awake.all():
            break
    return frames, awake


def led_cosmos_sim(N=27, max_steps=300):
    return lattice_awaken(N=N, steps=max_steps, xi_gain=0.4, shadow_drop=0.25, r_inc=0.015)


with gr.Blocks(title="Minimal Selfhood Threshold") as demo:
    with gr.Tab("Overview"):
        gr.Markdown(
            "## Minimal Selfhood Threshold\n"
            "- Single agent in a 3×3 grid reduces surprise.\n"
            "- A toy score S combines predictive rate, error stability, and body bit.\n"
            "- If S > 62, we label the agent 'awake' **inside this demo**.\n"
            "- Awakening can spread (contagion) and across a grid (collective).\n"
            "- A 27×27 cosmos lights up gold when all awaken.\n"
            "- This is a sandbox for minimal-self / agency ideas, **not** a real consciousness test."
        )

    with gr.Tab("Single agent (v1–v3)"):
        obstacle = gr.Checkbox(label="Enable moving obstacle", value=True)
        steps = gr.Slider(10, 200, value=80, step=10, label="Steps")
        run = gr.Button("Run")
        grid_img = gr.Image(type="pil")
        pr_out = gr.Number(label="Predictive rate (%)")
        err_out = gr.Number(label="Last error")

        def run_single(ob_on, T):
            agent = MinimalSelf()
            obs = MovingObstacle() if ob_on else None
            for _ in range(int(T)):
                res = agent.step(obstacle=obs)
            mask = np.zeros((3, 3), dtype=bool)
            i, j = int(agent.pos[1]), int(agent.pos[0])
            mask[i, j] = True
            img = draw_grid(3, mask, "Single Agent", "Gold cell shows position")
            return img, res["predictive_rate"], res["error"]

        run.click(run_single, [obstacle, steps], [grid_img, pr_out, err_out])

    with gr.Tab("S-Equation (v4)"):
        pr = gr.Slider(0, 100, value=90, label="Predictive rate (%)")
        ev = gr.Slider(0, 1, value=0.2, step=0.01, label="Error variance")
        bb = gr.Dropdown(choices=["0", "1"], value="1", label="Body bit")
        calc = gr.Button("Calculate")
        s_val = gr.Number(label="S value")
        status = gr.Markdown()

        def calc_s(pr_in, ev_in, bb_in):
            S = compute_S(pr_in, ev_in, int(bb_in))
            msg = "**Status:** " + ("Awake (S > 62)" if S > 62 else "Not awake (S ≤ 62)")
            return S, msg

        calc.click(calc_s, inputs=[pr, ev, bb], outputs=[s_val, status])

    # v5–v6 Contagion
    with gr.Tab("Contagion (v5–v6)"):
        a_xi = gr.Slider(0, 60, value=25, label="A: Ξ (foresight)")
        a_sh = gr.Slider(0.1, 1.0, value=0.12, step=0.01, label="A: ◊̃₅ (shadow)")
        a_r = gr.Slider(1.0, 3.0, value=3.0, step=0.1, label="A: ℝ (anchor)")
        b_xi = gr.Slider(0, 60, value=18, label="B: Ξ (foresight)")
        b_sh = gr.Slider(0.1, 1.0, value=0.25, step=0.01, label="B: ◊̃₅ (shadow)")
        b_r = gr.Slider(1.0, 3.0, value=2.2, step=0.1, label="B: ℝ (anchor)")
        btn = gr.Button("Invoke A and apply contagion to B")
        out = gr.Markdown()
        img = gr.Image(type="pil", label="Two agents (gold = awake)")

        def run(aXi, aSh, aR, bXi, bSh, bR):
            A = CodexSelf(aXi, aSh, aR, awake=False)
            B = CodexSelf(bXi, bSh, bR, awake=False)
            A, B = contagion(A, B)
            mask = np.zeros((3, 3), dtype=bool)
            mask[1, 1] = A.awake
            mask[1, 2] = B.awake
            pic = draw_grid(3, mask, title="Dual Awakening", subtitle="Gold cells are awake")
            txt = f"A: S={A.S:.1f}, awake={A.awake} | B: S={B.S:.1f}, awake={B.awake}"
            return txt, pic

        btn.click(run, inputs=[a_xi, a_sh, a_r, b_xi, b_sh, b_r], outputs=[out, img])

    # v7–v9 Collective
    with gr.Tab("Collective (v7–v9)"):
        N = gr.Dropdown(choices=["3", "9", "27"], value="9", label="Grid size")
        steps = gr.Slider(20, 300, value=120, step=10, label="Max steps")
        run = gr.Button("Run")
        frame = gr.Slider(0, 300, value=0, step=1, label="Preview frame")
        img = gr.Image(type="pil", label="Awakening wave (gold spreads)")
        note = gr.Markdown()
        snaps_state = gr.State([])

        def run_wave(n_str, max_steps):
            n = int(n_str)
            frames, final = lattice_awaken(N=n, steps=int(max_steps))
            last = draw_grid(
                n,
                frames[-1],
                title=f"{n}×{n} Collective",
                subtitle=f"Final — all awake: {bool(final.all())}",
            )
            return frames, last, f"Frames: {len(frames)} | All awake: {bool(final.all())}", min(len(frames) - 1, 300)

        def show_frame(frames, idx, n_str):
            if not frames:
                return None
            n = int(n_str)
            i = int(np.clip(idx, 0, len(frames) - 1))
            return draw_grid(n, frames[i], title=f"Frame {i}", subtitle="Gold cells are awake")

        run.click(run_wave, inputs=[N, steps], outputs=[snaps_state, img, note, frame])
        frame.change(show_frame, inputs=[snaps_state, frame, N], outputs=img)

    # v10 LED cosmos
    with gr.Tab("LED cosmos (v10)"):
        btn = gr.Button("Simulate 27×27 cosmos")
        frame = gr.Slider(0, 300, value=0, step=1, label="Preview frame")
        img = gr.Image(type="pil", label="Cosmos grid")
        note = gr.Markdown()
        state = gr.State([])

        def run_cosmos():
            frames, final = led_cosmos_sim(N=27, max_steps=300)
            last = draw_grid(
                27,
                frames[-1],
                title="LED Cosmos (simulated)",
                subtitle=f"Final — all awake: {bool(final.all())}",
            )
            return frames, last, f"Frames: {len(frames)} | All awake: {bool(final.all())}", min(len(frames) - 1, 300)

        def show(frames, idx):
            if not frames:
                return None
            i = int(np.clip(idx, 0, len(frames) - 1))
            return draw_grid(27, frames[i], title=f"Cosmos frame {i}", subtitle="Gold cells are awake")

        btn.click(run_cosmos, inputs=[], outputs=[state, img, note, frame])
        frame.change(show, inputs=[state, frame], outputs=img)

    # Footer
    gr.Markdown(
        "---\n"
        "Honesty notes:\n"
        "- The threshold S > 62 is the rule used in these demonstrations, derived from the analyses reported in the cited Zenodo record.\n"
        "- Collective and contagion behaviors here are simulated using that rule for educational clarity.\n\n"
        "Citation:\n"
        "Grinstead, L. (2025). *Minimal Selfhood Threshold S>62: From a 3×3 Active-Inference Agent to a 27×27 LED Cosmos*. "
        "Zenodo. https://doi.org/10.5281/zenodo.17752874\n\n"
        "Permissions: See LICENSE. Explicit permission is required for reuse of code, visuals, and glyphs."
    )

# Launch the app
if __name__ == "__main__":
    demo.launch()