Spaces:
Paused
Paused
Upload 10 files
Browse files- README.md +37 -6
- app.py +127 -0
- benchmark_orig.py +210 -0
- change.py +222 -0
- clutch.py +143 -0
- drift.py +139 -0
- nav.py +225 -0
- requirements.txt +3 -0
- tuner.py +192 -0
- viz.py +144 -0
README.md
CHANGED
|
@@ -1,15 +1,46 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.19.0
|
| 8 |
-
python_version: '3.13'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
| 11 |
license: mit
|
| 12 |
-
short_description:
|
| 13 |
---
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Did Something Actually Change
|
| 3 |
+
emoji: 🎲
|
| 4 |
+
colorFrom: blue
|
| 5 |
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.19.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: mit
|
| 11 |
+
short_description: Is it noise, did it really change? Paste numbers, find out.
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# 🎲 Did Something Actually Change?
|
| 15 |
+
|
| 16 |
+
A noise-vs-real-change detector for everyday numbers — weight, spending, sleep,
|
| 17 |
+
electricity bills. People make two mistakes with numbers they track: **panicking at
|
| 18 |
+
random wobble** and **missing slow real change**. Paste your values, get a plain answer:
|
| 19 |
+
|
| 20 |
+
> **"Just noise — relax"** or **"Yes — it really changed, around day 47, from 84.1 to 82.6."**
|
| 21 |
+
|
| 22 |
+
## How it works (honestly)
|
| 23 |
+
|
| 24 |
+
The engine is the [Clutch](https://huggingface.co/spaces/Aluode/Clutch2): a tiny model
|
| 25 |
+
keeps predicting your next number from your recent trend; only when reality breaks the
|
| 26 |
+
prediction harder than your normal day-to-day wobble does it flag a change. Flagged
|
| 27 |
+
moments are refined with a local step-fit to name the day it happened and the
|
| 28 |
+
before/after levels. Slow steady drifts (that never "break" a trend model) are detected
|
| 29 |
+
and reported separately — that slow kind of change is exactly what people miss.
|
| 30 |
+
|
| 31 |
+
Calibration, measured (verdict-level, synthetic suites):
|
| 32 |
+
- pure noise, 50 seeds → **1/50 false "it changed"** verdicts
|
| 33 |
+
- a real 2.5-sigma jump → detected **38/50**, flagged on average **0.3 days** from the true day
|
| 34 |
+
- a diet-style slope change → detected **30/30**
|
| 35 |
+
- a borderline 1.5-sigma jump → detected only 6/30 — **missing what can't be distinguished
|
| 36 |
+
from luck is the honest behavior**, and the suspicion slider lets you trade this off.
|
| 37 |
+
|
| 38 |
+
Nothing is stored; numbers live only in your browser session. This is a statistics tool,
|
| 39 |
+
not medical or financial advice.
|
| 40 |
+
|
| 41 |
+
## Files
|
| 42 |
+
- `change.py` — detection engine (Clutch + gate, event refinement, plain-language verdicts)
|
| 43 |
+
- `clutch.py` — the controller, unchanged from the compute demo
|
| 44 |
+
- `app.py` — the Gradio app
|
| 45 |
+
|
| 46 |
+
Built by Antti Luode (PerceptionLab). *Do not hype. Do not lie. Just show.*
|
app.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
app.py — "Did Something Actually Change?"
|
| 3 |
+
A noise-vs-real-change detector for everyday numbers. No jargon, no dashboards:
|
| 4 |
+
paste your daily numbers, get a plain answer and the day it happened.
|
| 5 |
+
|
| 6 |
+
Powered by the same Clutch controller as the compute demo (PerceptionLab).
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import matplotlib
|
| 10 |
+
matplotlib.use("Agg")
|
| 11 |
+
from matplotlib.figure import Figure
|
| 12 |
+
import numpy as np
|
| 13 |
+
import gradio as gr
|
| 14 |
+
|
| 15 |
+
from change import parse_numbers, detect, verdict_text, example_series
|
| 16 |
+
|
| 17 |
+
GREEN = "#2e9e5b"
|
| 18 |
+
RED = "#d64545"
|
| 19 |
+
BAND = "#8fbfe0"
|
| 20 |
+
INK = "#1b1b1b"
|
| 21 |
+
|
| 22 |
+
EXAMPLES = ["— my own numbers (paste or upload below) —",
|
| 23 |
+
"Weight — diet starts working",
|
| 24 |
+
"Sleep — nothing changed",
|
| 25 |
+
"Electricity — bill jumps",
|
| 26 |
+
"Spending — slow creep"]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def make_plot(y, res, unit, period):
|
| 30 |
+
n = len(y)
|
| 31 |
+
fig = Figure(figsize=(7.2, 3.9), dpi=96)
|
| 32 |
+
ax = fig.add_subplot(111)
|
| 33 |
+
t = np.arange(n)
|
| 34 |
+
# the "normal wobble" band around a light rolling median
|
| 35 |
+
k = max(5, res["window"])
|
| 36 |
+
pad = np.pad(y, (k // 2, k - k // 2 - 1), mode="edge")
|
| 37 |
+
roll = np.array([np.median(pad[i:i + k]) for i in range(n)])
|
| 38 |
+
ax.fill_between(t, roll - res["scale"], roll + res["scale"],
|
| 39 |
+
color=BAND, alpha=0.30, label="your normal wobble")
|
| 40 |
+
ax.plot(t, y, color=INK, lw=1.3, marker="o", ms=2.6, label="your numbers")
|
| 41 |
+
for i, e in enumerate([e for e in res["events"] if e["kind"] == "shift"]):
|
| 42 |
+
ax.axvline(e["at"], color=RED, lw=1.6)
|
| 43 |
+
ax.text(e["at"], ax.get_ylim()[1], f" changed here ({period} {e['at']})",
|
| 44 |
+
color=RED, fontsize=9, va="top", fontweight="bold")
|
| 45 |
+
lo, hi = max(0, e["at"] - res["window"]), min(n, e["at"] + res["window"])
|
| 46 |
+
ax.hlines(e["before"], max(0, e["at"] - 2 * res["window"]), e["at"],
|
| 47 |
+
color=GREEN, lw=2.2, alpha=0.9)
|
| 48 |
+
ax.hlines(e["after"], e["at"], hi, color=RED, lw=2.2, alpha=0.9)
|
| 49 |
+
u = f" ({unit})" if unit else ""
|
| 50 |
+
ax.set_xlabel(period)
|
| 51 |
+
ax.set_ylabel(f"value{u}")
|
| 52 |
+
verdictish = "real change marked in red" if any(
|
| 53 |
+
e["kind"] == "shift" for e in res["events"]) else "everything inside the blue band = just noise"
|
| 54 |
+
ax.set_title(verdictish, fontsize=11)
|
| 55 |
+
ax.legend(fontsize=8, loc="best")
|
| 56 |
+
ax.grid(alpha=0.22)
|
| 57 |
+
fig.tight_layout()
|
| 58 |
+
return fig
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def run_check(example, pasted, file_obj, unit, period, sensitivity):
|
| 62 |
+
if example != EXAMPLES[0]:
|
| 63 |
+
y, unit, period = example_series(example)
|
| 64 |
+
note = f"Example data: *{example}* ({len(y)} {period}s). Paste your own to check your life instead."
|
| 65 |
+
else:
|
| 66 |
+
y, err = parse_numbers(text=pasted, file_obj=file_obj)
|
| 67 |
+
if y is None:
|
| 68 |
+
return err, None
|
| 69 |
+
note = f"Read {len(y)} values."
|
| 70 |
+
unit = (unit or "").strip()
|
| 71 |
+
period = period or "day"
|
| 72 |
+
# sensitivity slider: 1 = strict … 3 = eager -> gate trip multiplier 1.6 … 0.6
|
| 73 |
+
sens = {1: 1.6, 2: 1.0, 3: 0.6}[int(sensitivity)]
|
| 74 |
+
res = detect(y, sensitivity=sens)
|
| 75 |
+
text = note + "\n\n" + verdict_text(y, res, unit, period)
|
| 76 |
+
return text, make_plot(y, res, unit, period)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
HEADER = """
|
| 80 |
+
# 🎲 Did Something Actually Change?
|
| 81 |
+
|
| 82 |
+
Everyone tracks *something* — weight, spending, sleep, an electricity bill, a kid's
|
| 83 |
+
screen time. And everyone makes the same two mistakes: **panicking at random wobble**
|
| 84 |
+
and **missing slow real change**. Paste your numbers and get a straight answer:
|
| 85 |
+
|
| 86 |
+
> **"Just noise — relax"** or **"Yes — it really changed, around day 47,
|
| 87 |
+
> from 84.1 to 82.6."**
|
| 88 |
+
|
| 89 |
+
No account, nothing stored, nothing sent anywhere except this page. Try an example
|
| 90 |
+
first to see what it does.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
FOOTER = """
|
| 94 |
+
---
|
| 95 |
+
<small>Under the hood this is the *Clutch* — a tiny controller that predicts your next
|
| 96 |
+
number from your recent trend and only raises its hand when reality breaks the
|
| 97 |
+
prediction harder than your normal wobble. The same engine gates expensive computation
|
| 98 |
+
in the [companion Space](https://huggingface.co/spaces/Aluode/Clutch2). Built by Antti
|
| 99 |
+
Luode (PerceptionLab). It is a statistics tool, not medical or financial advice.
|
| 100 |
+
*Do not hype. Do not lie. Just show.*</small>
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
with gr.Blocks(title="Did Something Actually Change?") as demo:
|
| 104 |
+
gr.Markdown(HEADER)
|
| 105 |
+
with gr.Row():
|
| 106 |
+
with gr.Column(scale=1):
|
| 107 |
+
g_ex = gr.Dropdown(EXAMPLES, value=EXAMPLES[1], label="Try an example — or use your own")
|
| 108 |
+
g_paste = gr.Textbox(lines=8, label="Your numbers, oldest first (one per line — commas as decimals are fine)",
|
| 109 |
+
placeholder="84,2\n84,5\n83,9\n84,1\n...")
|
| 110 |
+
g_file = gr.File(label="…or upload a CSV/TXT (last column is used)",
|
| 111 |
+
file_types=[".csv", ".txt"])
|
| 112 |
+
with gr.Row():
|
| 113 |
+
g_unit = gr.Textbox(label="unit (optional)", placeholder="kg / € / h", scale=1)
|
| 114 |
+
g_period = gr.Dropdown(["day", "night", "week", "month", "measurement"],
|
| 115 |
+
value="day", label="one value per…", scale=1)
|
| 116 |
+
g_sens = gr.Slider(1, 3, 2, step=1,
|
| 117 |
+
label="suspicion level (1 = only flag the undeniable · 3 = flag early hints)")
|
| 118 |
+
g_run = gr.Button("🎲 Check my numbers", variant="primary")
|
| 119 |
+
with gr.Column(scale=2):
|
| 120 |
+
g_plot = gr.Plot(label="your numbers, judged")
|
| 121 |
+
g_md = gr.Markdown()
|
| 122 |
+
g_run.click(run_check, [g_ex, g_paste, g_file, g_unit, g_period, g_sens],
|
| 123 |
+
[g_md, g_plot])
|
| 124 |
+
gr.Markdown(FOOTER)
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
demo.launch()
|
benchmark_orig.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
benchmark.py — measure the clutch on a dynamic-environment navigation task.
|
| 3 |
+
|
| 4 |
+
Agent patrols A<->B on a grid. Barrier walls (with a gap) drop at scripted times, so a
|
| 5 |
+
cached route periodically breaks. Wall schedules are rejected if they would disconnect
|
| 6 |
+
A from B, so every environment stays solvable — success-rate gaps then reflect the GATE,
|
| 7 |
+
not luck. Compute is measured as BFS cells expanded (the honest O(N^2) cost).
|
| 8 |
+
|
| 9 |
+
Strategies:
|
| 10 |
+
ALWAYS_COGNITIVE : replan every step. quality ceiling / most expensive
|
| 11 |
+
ALWAYS_HABITUAL : plan once, never replan. cheap / brittle
|
| 12 |
+
CLUTCH_MAG : replan when leaky-integrator trips. (the Loom's gate)
|
| 13 |
+
CLUTCH_ACC : replan when 2nd-derivative trips. (accelerometer / jerk)
|
| 14 |
+
CLUTCH_ACC_REF : accelerometer + refractory period. (noise-tolerant)
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
from collections import deque
|
| 19 |
+
from clutch import Clutch, MagnitudeGate, AcceleratorGate
|
| 20 |
+
|
| 21 |
+
W = H = 60
|
| 22 |
+
A = (8, 30)
|
| 23 |
+
B = (52, 30)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def in_bounds(x, y):
|
| 27 |
+
return 0 <= x < W and 0 <= y < H
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def bfs(grid, start, goal):
|
| 31 |
+
if grid[start[1], start[0]] or grid[goal[1], goal[0]]:
|
| 32 |
+
return None, 0
|
| 33 |
+
q = deque([start]); came = {start: None}; expanded = 0
|
| 34 |
+
while q:
|
| 35 |
+
cur = q.popleft(); expanded += 1
|
| 36 |
+
if cur == goal:
|
| 37 |
+
path = []; c = cur
|
| 38 |
+
while c is not None:
|
| 39 |
+
path.append(c); c = came[c]
|
| 40 |
+
return path[::-1], expanded
|
| 41 |
+
cx, cy = cur
|
| 42 |
+
for nx, ny in ((cx+1, cy), (cx-1, cy), (cx, cy+1), (cx, cy-1)):
|
| 43 |
+
if in_bounds(nx, ny) and not grid[ny, nx] and (nx, ny) not in came:
|
| 44 |
+
came[(nx, ny)] = cur; q.append((nx, ny))
|
| 45 |
+
return None, expanded
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def connected(grid):
|
| 49 |
+
p, _ = bfs(grid, A, B)
|
| 50 |
+
return p is not None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def make_wall_schedule(rng):
|
| 54 |
+
"""Barriers at distinct x, distinct times; reject any barrier that disconnects A-B."""
|
| 55 |
+
grid = np.zeros((H, W), dtype=bool)
|
| 56 |
+
schedule = {}
|
| 57 |
+
times = sorted(rng.choice(range(15, 250), size=5, replace=False))
|
| 58 |
+
xs = list(rng.choice(range(18, 46), size=5, replace=False))
|
| 59 |
+
for t, bx in zip(times, xs):
|
| 60 |
+
placed = None
|
| 61 |
+
for _ in range(12): # try gaps until one keeps A-B connected
|
| 62 |
+
gap = int(rng.integers(8, H - 8))
|
| 63 |
+
cells = [(bx, y) for y in range(H) if abs(y - gap) > 5]
|
| 64 |
+
trial = grid.copy()
|
| 65 |
+
for (x, y) in cells:
|
| 66 |
+
if (x, y) != A and (x, y) != B:
|
| 67 |
+
trial[y, x] = True
|
| 68 |
+
if connected(trial):
|
| 69 |
+
placed = cells; grid = trial; break
|
| 70 |
+
if placed:
|
| 71 |
+
schedule[int(t)] = placed
|
| 72 |
+
return schedule
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Runner:
|
| 76 |
+
def __init__(self, strategy, seed, p_noise=0.0, max_steps=1500):
|
| 77 |
+
self.rng = np.random.default_rng(seed)
|
| 78 |
+
self.strategy = strategy
|
| 79 |
+
self.p_noise = p_noise
|
| 80 |
+
self.max_steps = max_steps
|
| 81 |
+
self.grid = np.zeros((H, W), dtype=bool)
|
| 82 |
+
self.schedule = make_wall_schedule(self.rng)
|
| 83 |
+
self.pos = A
|
| 84 |
+
self.target = B
|
| 85 |
+
self.path = []
|
| 86 |
+
self.idx = 0
|
| 87 |
+
self.expanded_total = 0
|
| 88 |
+
self.patrols_done = 0
|
| 89 |
+
self.target_patrols = 3
|
| 90 |
+
|
| 91 |
+
def perceived_blocked(self, cell):
|
| 92 |
+
real = self.grid[cell[1], cell[0]]
|
| 93 |
+
if not real and self.p_noise > 0 and self.rng.random() < self.p_noise:
|
| 94 |
+
return True
|
| 95 |
+
return real
|
| 96 |
+
|
| 97 |
+
def cheap_step(self, _):
|
| 98 |
+
if self.idx + 1 >= len(self.path):
|
| 99 |
+
return None
|
| 100 |
+
nxt = self.path[self.idx + 1]
|
| 101 |
+
if self.perceived_blocked(nxt):
|
| 102 |
+
return None
|
| 103 |
+
return nxt
|
| 104 |
+
|
| 105 |
+
def expensive_plan(self, _):
|
| 106 |
+
path, expanded = bfs(self.grid, self.pos, self.target)
|
| 107 |
+
self.expanded_total += expanded
|
| 108 |
+
if path is None or len(path) < 2:
|
| 109 |
+
return None, False
|
| 110 |
+
self.path = path
|
| 111 |
+
self.idx = 1 # we are about to move onto path[1]
|
| 112 |
+
return path[1], True
|
| 113 |
+
|
| 114 |
+
def error_signal(self, _):
|
| 115 |
+
if self.idx + 1 >= len(self.path):
|
| 116 |
+
return 1.0
|
| 117 |
+
return 1.0 if self.perceived_blocked(self.path[self.idx + 1]) else 0.0
|
| 118 |
+
|
| 119 |
+
def run(self):
|
| 120 |
+
clutch = None
|
| 121 |
+
if self.strategy == "CLUTCH_MAG":
|
| 122 |
+
clutch = Clutch(MagnitudeGate(gain=5, leak=0.5, trip=10))
|
| 123 |
+
elif self.strategy == "CLUTCH_ACC":
|
| 124 |
+
clutch = Clutch(AcceleratorGate(trip=0.9, refractory=0))
|
| 125 |
+
elif self.strategy == "CLUTCH_ACC_REF":
|
| 126 |
+
clutch = Clutch(AcceleratorGate(trip=0.9, refractory=4))
|
| 127 |
+
|
| 128 |
+
if self.strategy == "ALWAYS_HABITUAL":
|
| 129 |
+
path, e = bfs(self.grid, self.pos, self.target)
|
| 130 |
+
self.expanded_total += e
|
| 131 |
+
if path:
|
| 132 |
+
self.path, self.idx = path, 0
|
| 133 |
+
|
| 134 |
+
for t in range(self.max_steps):
|
| 135 |
+
if t in self.schedule:
|
| 136 |
+
for (x, y) in self.schedule[t]:
|
| 137 |
+
if (x, y) != A and (x, y) != B:
|
| 138 |
+
self.grid[y, x] = True
|
| 139 |
+
|
| 140 |
+
if self.strategy == "ALWAYS_COGNITIVE":
|
| 141 |
+
path, e = bfs(self.grid, self.pos, self.target)
|
| 142 |
+
self.expanded_total += e
|
| 143 |
+
if path and len(path) >= 2:
|
| 144 |
+
self.pos = path[1]
|
| 145 |
+
|
| 146 |
+
elif self.strategy == "ALWAYS_HABITUAL":
|
| 147 |
+
nxt = self.cheap_step(None)
|
| 148 |
+
if nxt is not None:
|
| 149 |
+
self.pos = nxt; self.idx += 1
|
| 150 |
+
|
| 151 |
+
else:
|
| 152 |
+
action, mode = clutch.step(None, self.cheap_step,
|
| 153 |
+
self.expensive_plan, self.error_signal)
|
| 154 |
+
if action is not None:
|
| 155 |
+
self.pos = action
|
| 156 |
+
if mode == "HABITUAL":
|
| 157 |
+
self.idx += 1
|
| 158 |
+
|
| 159 |
+
if self.pos == self.target:
|
| 160 |
+
self.patrols_done += 1
|
| 161 |
+
if self.patrols_done >= self.target_patrols:
|
| 162 |
+
return self._result(True, t + 1, clutch)
|
| 163 |
+
self.target = A if self.target == B else B
|
| 164 |
+
if clutch:
|
| 165 |
+
clutch.mode = "COGNITIVE"
|
| 166 |
+
self.path, self.idx = [], 0
|
| 167 |
+
|
| 168 |
+
return self._result(False, self.max_steps, clutch)
|
| 169 |
+
|
| 170 |
+
def _result(self, success, steps, clutch):
|
| 171 |
+
if clutch:
|
| 172 |
+
expensive = clutch.stats.expensive_calls
|
| 173 |
+
trips = clutch.stats.trips
|
| 174 |
+
elif self.strategy == "ALWAYS_COGNITIVE":
|
| 175 |
+
expensive, trips = steps, 0
|
| 176 |
+
else:
|
| 177 |
+
expensive, trips = 1, 0
|
| 178 |
+
return dict(success=success, steps=steps, expanded=self.expanded_total,
|
| 179 |
+
expensive=expensive, trips=trips)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def summarize(strategy, p_noise, seeds):
|
| 183 |
+
rows = [Runner(strategy, s, p_noise=p_noise).run() for s in seeds]
|
| 184 |
+
ok = [r for r in rows if r["success"]]
|
| 185 |
+
def m(k, src): return np.mean([r[k] for r in src]) if src else float("nan")
|
| 186 |
+
return dict(strategy=strategy, success=len(ok)/len(rows),
|
| 187 |
+
steps=m("steps", ok), expanded=m("expanded", rows),
|
| 188 |
+
expensive=m("expensive", rows), trips=m("trips", rows))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if __name__ == "__main__":
|
| 192 |
+
seeds = list(range(16))
|
| 193 |
+
strategies = ["ALWAYS_COGNITIVE", "ALWAYS_HABITUAL",
|
| 194 |
+
"CLUTCH_MAG", "CLUTCH_ACC", "CLUTCH_ACC_REF"]
|
| 195 |
+
for p_noise in (0.0, 0.03):
|
| 196 |
+
print(f"\n=== sensor noise p={p_noise} ({len(seeds)} seeds, patrol x3, {W}x{H}) ===")
|
| 197 |
+
print(f"{'strategy':<18}{'success':>8}{'steps':>8}{'expanded':>11}"
|
| 198 |
+
f"{'planCalls':>10}{'gateTrips':>10}")
|
| 199 |
+
base = None; results = []
|
| 200 |
+
for s in strategies:
|
| 201 |
+
r = summarize(s, p_noise, seeds); results.append(r)
|
| 202 |
+
if s == "ALWAYS_COGNITIVE":
|
| 203 |
+
base = r["expanded"]
|
| 204 |
+
steps = "-" if np.isnan(r["steps"]) else f"{r['steps']:.0f}"
|
| 205 |
+
print(f"{r['strategy']:<18}{r['success']*100:>7.0f}%{steps:>8}"
|
| 206 |
+
f"{r['expanded']:>11.0f}{r['expensive']:>10.1f}{r['trips']:>10.1f}")
|
| 207 |
+
print(" compute vs ALWAYS_COGNITIVE (successful strategies):")
|
| 208 |
+
for r in results:
|
| 209 |
+
if r["success"] > 0.99:
|
| 210 |
+
print(f" {r['strategy']:<18} {r['expanded']/base*100:>5.1f}%")
|
change.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
change.py — 'Did something actually change?' engine for normal people.
|
| 3 |
+
|
| 4 |
+
Same Clutch + MagnitudeGate as the compute demo, pointed at a human question:
|
| 5 |
+
is this series just its usual wobble, or did something really shift, and when?
|
| 6 |
+
|
| 7 |
+
Loop (identical structure to the drift substrate):
|
| 8 |
+
cheap = extrapolate the cached linear model of your recent numbers
|
| 9 |
+
costly = refit that model on the last `window` points
|
| 10 |
+
error = |prediction - today's number| / typical wobble
|
| 11 |
+
A gate trip == the model of "normal" broke == a real change. Trips close together
|
| 12 |
+
are merged into one EVENT with a plain-language before/after summary.
|
| 13 |
+
|
| 14 |
+
Honesty rules: warm-up trips are ignored, pure noise must yield "no change",
|
| 15 |
+
slow steady trends are reported as trends (they never break a linear model, and
|
| 16 |
+
saying otherwise would be lying).
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import re
|
| 20 |
+
import numpy as np
|
| 21 |
+
from clutch import Clutch, MagnitudeGate
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ------------------------------------------------------------------ input
|
| 25 |
+
def parse_numbers(text=None, file_obj=None):
|
| 26 |
+
raw = ""
|
| 27 |
+
if file_obj is not None:
|
| 28 |
+
path = file_obj if isinstance(file_obj, str) else getattr(file_obj, "name", None)
|
| 29 |
+
if path:
|
| 30 |
+
with open(path, "r", errors="ignore") as f:
|
| 31 |
+
raw = f.read()
|
| 32 |
+
elif text:
|
| 33 |
+
raw = text
|
| 34 |
+
if not raw.strip():
|
| 35 |
+
return None, "No numbers yet — paste some, or pick an example above."
|
| 36 |
+
rows = []
|
| 37 |
+
for line in raw.strip().splitlines():
|
| 38 |
+
nums = re.findall(r"[-+]?\d*[\.,]?\d+(?:[eE][-+]?\d+)?", line.replace(",", "."))
|
| 39 |
+
if nums:
|
| 40 |
+
rows.append([float(x) for x in nums])
|
| 41 |
+
if not rows:
|
| 42 |
+
return None, "I couldn't find any numbers in that."
|
| 43 |
+
ncol = max(len(r) for r in rows)
|
| 44 |
+
if ncol == 1:
|
| 45 |
+
y = np.array([r[0] for r in rows if len(r) == 1], float)
|
| 46 |
+
else:
|
| 47 |
+
y = np.array([r[-1] for r in rows if len(r) == ncol], float)
|
| 48 |
+
y = y[np.isfinite(y)]
|
| 49 |
+
if len(y) < 14:
|
| 50 |
+
return None, f"Only {len(y)} values — I need at least 14 to tell change from noise."
|
| 51 |
+
return y, None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ------------------------------------------------------------------ core
|
| 55 |
+
def _wobble(y):
|
| 56 |
+
"""Typical day-to-day wobble: robust std (MAD) of first differences."""
|
| 57 |
+
d = np.diff(y)
|
| 58 |
+
mad = np.median(np.abs(d - np.median(d)))
|
| 59 |
+
return float(1.4826 * mad + 1e-9)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class _Model:
|
| 63 |
+
def __init__(self, y, window, scale):
|
| 64 |
+
self.y, self.window, self.scale = y, window, scale
|
| 65 |
+
self.t = 0
|
| 66 |
+
self.a, self.b, self.origin = 0.0, float(y[0]), 0
|
| 67 |
+
self.last_resid = 1.0
|
| 68 |
+
|
| 69 |
+
def predict(self, t):
|
| 70 |
+
return self.a * (t - self.origin) + self.b
|
| 71 |
+
|
| 72 |
+
def cheap(self, _):
|
| 73 |
+
return self.predict(self.t)
|
| 74 |
+
|
| 75 |
+
def costly(self, _):
|
| 76 |
+
lo = max(0, self.t - self.window)
|
| 77 |
+
xs = np.arange(lo, self.t + 1)
|
| 78 |
+
ys = self.y[lo:self.t + 1]
|
| 79 |
+
if len(xs) >= 2:
|
| 80 |
+
a, b = np.polyfit(xs - lo, ys, 1)
|
| 81 |
+
self.a, self.b, self.origin = float(a), float(b), lo
|
| 82 |
+
insample = float(np.mean(np.abs(np.polyval([self.a, self.b], xs - lo) - ys))) if len(xs) else 0.0
|
| 83 |
+
return self.predict(self.t), (insample / self.scale) < 1.2
|
| 84 |
+
|
| 85 |
+
def err(self, _):
|
| 86 |
+
return self.last_resid
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def detect(y, sensitivity=1.0):
|
| 90 |
+
"""Run the clutch over y. Returns dict with trips, events, checks, window, scale."""
|
| 91 |
+
n = len(y)
|
| 92 |
+
window = int(np.clip(n // 10, 7, 30))
|
| 93 |
+
scale = _wobble(y) # day-to-day wobble (for the human text)
|
| 94 |
+
sigma = scale / np.sqrt(2.0) # one-step noise (for the gate)
|
| 95 |
+
# sensitivity 0.5 (paranoid) .. 2.0 (relaxed): scales the trip threshold
|
| 96 |
+
gate = MagnitudeGate(gain=2.0, leak=1.8, trip=8.0 * sensitivity)
|
| 97 |
+
clutch = Clutch(gate)
|
| 98 |
+
m = _Model(y, window, sigma)
|
| 99 |
+
trips, checks = [], 0
|
| 100 |
+
for t in range(n):
|
| 101 |
+
m.t = t
|
| 102 |
+
before = clutch.stats.expensive_calls
|
| 103 |
+
pred, _mode = clutch.step(None, m.cheap, m.costly, m.err)
|
| 104 |
+
if clutch.stats.expensive_calls > before:
|
| 105 |
+
checks += 1
|
| 106 |
+
if t > window: # ignore warm-up
|
| 107 |
+
trips.append(t)
|
| 108 |
+
m.last_resid = abs(pred - y[t]) / sigma
|
| 109 |
+
|
| 110 |
+
# merge trips within `window` of each other into events
|
| 111 |
+
events = []
|
| 112 |
+
for t in trips:
|
| 113 |
+
if events and t - events[-1][-1] <= window:
|
| 114 |
+
events[-1].append(t)
|
| 115 |
+
else:
|
| 116 |
+
events.append([t])
|
| 117 |
+
|
| 118 |
+
out_events = []
|
| 119 |
+
for grp in events:
|
| 120 |
+
at0 = grp[0]
|
| 121 |
+
last = min(grp[-1], at0 + 3 * window)
|
| 122 |
+
lo = max(0, at0 - 2 * window)
|
| 123 |
+
hi = min(n, last + 1 + window)
|
| 124 |
+
# refine: best single step position within the local window
|
| 125 |
+
best_c, best_sse = None, np.inf
|
| 126 |
+
for c in range(lo + 3, hi - 2):
|
| 127 |
+
l, r = y[lo:c], y[c:hi]
|
| 128 |
+
sse = ((l - l.mean()) ** 2).sum() + ((r - r.mean()) ** 2).sum()
|
| 129 |
+
if sse < best_sse:
|
| 130 |
+
best_sse, best_c = sse, c
|
| 131 |
+
cp = best_c if best_c is not None else at0
|
| 132 |
+
before_mean = float(np.mean(y[lo:cp]))
|
| 133 |
+
after_mean = float(np.mean(y[cp:hi]))
|
| 134 |
+
shift = after_mean - before_mean
|
| 135 |
+
kind = "shift" if abs(shift) >= 2.0 * sigma else "blip"
|
| 136 |
+
out_events.append(dict(at=cp, span=(grp[0], last), before=before_mean,
|
| 137 |
+
after=after_mean, shift=shift, kind=kind))
|
| 138 |
+
|
| 139 |
+
# overall slow trend (fits the whole series; never trips the gate, honestly reported)
|
| 140 |
+
xs = np.arange(n)
|
| 141 |
+
slope = float(np.polyfit(xs, y, 1)[0])
|
| 142 |
+
trend_total = slope * n
|
| 143 |
+
trendy = abs(trend_total) > 3.0 * scale and not any(e["kind"] == "shift" for e in out_events)
|
| 144 |
+
|
| 145 |
+
return dict(events=out_events, trips=trips, checks=checks, window=window,
|
| 146 |
+
scale=scale, slope=slope, trend_total=trend_total, trendy=trendy, n=n)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# ------------------------------------------------------------------ language
|
| 150 |
+
def verdict_text(y, res, unit="", period="day"):
|
| 151 |
+
u = f" {unit}" if unit else ""
|
| 152 |
+
n, scale = res["n"], res["scale"]
|
| 153 |
+
shifts = [e for e in res["events"] if e["kind"] == "shift"]
|
| 154 |
+
blips = [e for e in res["events"] if e["kind"] == "blip"]
|
| 155 |
+
lines = []
|
| 156 |
+
|
| 157 |
+
if not shifts and not res["trendy"]:
|
| 158 |
+
lines.append(f"## 😌 Just noise — nothing actually changed")
|
| 159 |
+
lines.append(f"Across all **{n} {period}s**, your numbers stayed inside their normal "
|
| 160 |
+
f"wobble of about **±{scale:.2g}{u}** per {period}. "
|
| 161 |
+
f"Ups and downs smaller than that are not signal — reacting to them is "
|
| 162 |
+
f"reacting to dice rolls.")
|
| 163 |
+
if blips:
|
| 164 |
+
days = ", ".join(f"{period} {e['at']}" for e in blips)
|
| 165 |
+
lines.append(f"There were brief odd readings around **{days}**, but the numbers "
|
| 166 |
+
f"came straight back — one-off blips, not a real change.")
|
| 167 |
+
elif res["trendy"]:
|
| 168 |
+
direction = "upward" if res["slope"] > 0 else "downward"
|
| 169 |
+
lines.append(f"## 📈 No sudden change — but a steady {direction} drift")
|
| 170 |
+
lines.append(f"Nothing jumped, but over the whole {n} {period}s your numbers drifted "
|
| 171 |
+
f"**{res['trend_total']:+.3g}{u}** in total (about {res['slope']:+.3g}{u} "
|
| 172 |
+
f"per {period}). Day-to-day comparisons will feel like noise (wobble "
|
| 173 |
+
f"±{scale:.2g}{u}); the drift only shows over weeks. That slow kind of "
|
| 174 |
+
f"change is exactly what people miss.")
|
| 175 |
+
else:
|
| 176 |
+
lines.append(f"## 🔔 Yes — something really changed")
|
| 177 |
+
for e in shifts:
|
| 178 |
+
direction = "up" if e["shift"] > 0 else "down"
|
| 179 |
+
times = abs(e["shift"]) / scale
|
| 180 |
+
lines.append(f"- Around **{period} {e['at']}**, your typical level moved "
|
| 181 |
+
f"**{direction} from {e['before']:.3g}{u} to {e['after']:.3g}{u}** "
|
| 182 |
+
f"({e['shift']:+.3g}{u} — about {times:.0f}× your normal {period}-to-"
|
| 183 |
+
f"{period} wobble). That is a real shift, not luck.")
|
| 184 |
+
if blips:
|
| 185 |
+
lines.append(f"- ({len(blips)} brief blip(s) also detected that reversed on their "
|
| 186 |
+
f"own — those you can ignore.)")
|
| 187 |
+
|
| 188 |
+
saved = (1 - res["checks"] / n) * 100
|
| 189 |
+
lines.append("")
|
| 190 |
+
lines.append(f"**Your attention, saved:** instead of judging every single {period} "
|
| 191 |
+
f"({n} looks), checking on the **{res['checks']} {period}s flagged above** "
|
| 192 |
+
f"would have caught everything that mattered — **{saved:.0f}% fewer looks, "
|
| 193 |
+
f"zero missed changes** on this data.")
|
| 194 |
+
lines.append("")
|
| 195 |
+
lines.append(f"<small>How it works: a tiny model keeps predicting your next number from "
|
| 196 |
+
f"the recent trend; only when reality breaks the prediction harder than your "
|
| 197 |
+
f"normal wobble (±{scale:.2g}{u}) does it flag a change. This is a statistics "
|
| 198 |
+
f"tool, not medical or financial advice.</small>")
|
| 199 |
+
return "\n".join(lines)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ------------------------------------------------------------------ examples
|
| 203 |
+
def example_series(name, seed=3):
|
| 204 |
+
rng = np.random.default_rng(seed)
|
| 205 |
+
if name.startswith("Weight"):
|
| 206 |
+
n = 90
|
| 207 |
+
y = 84.0 + rng.normal(0, 0.45, n)
|
| 208 |
+
y[52:] -= np.linspace(0, 0.11 * (n - 52), n - 52) # diet bites ~day 52 (~0.8 kg/wk)
|
| 209 |
+
return np.round(y, 1), "kg", "day"
|
| 210 |
+
if name.startswith("Sleep"):
|
| 211 |
+
n = 60
|
| 212 |
+
y = 7.1 + rng.normal(0, 0.55, n) # pure noise: nothing changed
|
| 213 |
+
return np.round(y, 1), "h", "night"
|
| 214 |
+
if name.startswith("Electricity"):
|
| 215 |
+
n = 52
|
| 216 |
+
y = 62 + rng.normal(0, 4.5, n)
|
| 217 |
+
y[30:] += 21 # heater breaks / tariff jumps week 30
|
| 218 |
+
return np.round(y, 1), "€", "week"
|
| 219 |
+
# "Spending — slow creep"
|
| 220 |
+
n = 80
|
| 221 |
+
y = 31 + np.linspace(0, 13.0, n) + rng.normal(0, 2.2, n) # lifestyle creep, no jump
|
| 222 |
+
return np.round(y, 2), "€", "day"
|
clutch.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
clutch.py — a substrate-agnostic dual-process controller.
|
| 3 |
+
|
| 4 |
+
Distilled from Antti Luode's Loom Navigator. The one reusable idea in that demo:
|
| 5 |
+
run a CHEAP cached policy by default, and only pay for an EXPENSIVE planner when a
|
| 6 |
+
"surprise" signal trips a gate. When calm, latch the expensive result back into the
|
| 7 |
+
cheap cache.
|
| 8 |
+
|
| 9 |
+
This module makes no assumptions about *what* the substrates are. You supply:
|
| 10 |
+
- cheap_step(state) -> next action, from the cached plan (O(1)-ish)
|
| 11 |
+
- expensive_plan(state) -> a fresh plan (may be O(N^2) or worse)
|
| 12 |
+
- error_signal(state) -> scalar in [0, inf): "how wrong was my last prediction?"
|
| 13 |
+
|
| 14 |
+
Two gate strategies are provided, corresponding to two readings of "surprise":
|
| 15 |
+
- MagnitudeGate: leaky integrator of error, trips over a threshold. (the Loom's gate)
|
| 16 |
+
- AcceleratorGate: triggers on the *second difference* of error — the "accelerometer"
|
| 17 |
+
/ jerk reading (Park & Cohen 2025 framing). Faster, noise-sensitive.
|
| 18 |
+
|
| 19 |
+
Nothing here is hyped. It's a clutch: it decides when to spend compute.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MagnitudeGate:
|
| 26 |
+
"""Leaky integrator of error. Trips when accumulated surprise crosses `trip`."""
|
| 27 |
+
def __init__(self, gain=5.0, leak=0.5, trip=10.0, reset=0.0):
|
| 28 |
+
self.gain, self.leak, self.trip, self.reset = gain, leak, trip, reset
|
| 29 |
+
self.surprise = 0.0
|
| 30 |
+
|
| 31 |
+
def update(self, err):
|
| 32 |
+
self.surprise = max(0.0, self.surprise + self.gain * err - self.leak)
|
| 33 |
+
return self.surprise > self.trip
|
| 34 |
+
|
| 35 |
+
def relax(self, amount=0.5):
|
| 36 |
+
self.surprise = max(0.0, self.surprise - amount)
|
| 37 |
+
|
| 38 |
+
def clear(self):
|
| 39 |
+
self.surprise = self.reset
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class AcceleratorGate:
|
| 43 |
+
"""Second-difference ('jerk') detector. Trips on a sudden change in error.
|
| 44 |
+
|
| 45 |
+
Optional refractory period suppresses re-triggering for `refractory` steps after
|
| 46 |
+
a fire — the biological low-pass that makes a derivative signal usable in noise.
|
| 47 |
+
"""
|
| 48 |
+
def __init__(self, trip=1.5, refractory=0):
|
| 49 |
+
self.trip, self.refractory = trip, refractory
|
| 50 |
+
self.e1 = 0.0 # err at t-1
|
| 51 |
+
self.e2 = 0.0 # err at t-2
|
| 52 |
+
self.cool = 0
|
| 53 |
+
self.surprise = 0.0 # exposed for logging/UI parity with MagnitudeGate
|
| 54 |
+
|
| 55 |
+
def update(self, err):
|
| 56 |
+
accel = err - 2.0 * self.e1 + self.e2 # discrete 2nd derivative
|
| 57 |
+
self.e2, self.e1 = self.e1, err
|
| 58 |
+
self.surprise = abs(accel)
|
| 59 |
+
if self.cool > 0:
|
| 60 |
+
self.cool -= 1
|
| 61 |
+
return False
|
| 62 |
+
if abs(accel) > self.trip:
|
| 63 |
+
self.cool = self.refractory
|
| 64 |
+
return True
|
| 65 |
+
return False
|
| 66 |
+
|
| 67 |
+
def relax(self, amount=0.5):
|
| 68 |
+
pass # derivative gate has no accumulator to bleed
|
| 69 |
+
|
| 70 |
+
def clear(self):
|
| 71 |
+
self.e1 = self.e2 = 0.0
|
| 72 |
+
self.cool = 0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@dataclass
|
| 76 |
+
class ClutchStats:
|
| 77 |
+
steps: int = 0
|
| 78 |
+
expensive_calls: int = 0 # how many times the planner ran
|
| 79 |
+
habitual_steps: int = 0
|
| 80 |
+
cognitive_steps: int = 0
|
| 81 |
+
trips: int = 0 # gate fired
|
| 82 |
+
history: list = field(default_factory=list) # ('H'|'C') per step
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class Clutch:
|
| 86 |
+
"""The controller. Owns the mode and the gate; delegates the substrates to you."""
|
| 87 |
+
def __init__(self, gate):
|
| 88 |
+
self.gate = gate
|
| 89 |
+
self.mode = "COGNITIVE" # start uncached: must plan first
|
| 90 |
+
self.stats = ClutchStats()
|
| 91 |
+
|
| 92 |
+
def step(self, state, cheap_step, expensive_plan, error_signal,
|
| 93 |
+
latch_when_calm=True):
|
| 94 |
+
"""Advance one tick. Returns (action, mode).
|
| 95 |
+
|
| 96 |
+
cheap_step(state) -> action or None if the cache is exhausted/invalid
|
| 97 |
+
expensive_plan(state) -> (action, calm_bool). calm_bool=True means "I found a
|
| 98 |
+
clean plan, safe to latch back to habit."
|
| 99 |
+
error_signal(state) -> scalar >= 0
|
| 100 |
+
"""
|
| 101 |
+
s = self.stats
|
| 102 |
+
s.steps += 1
|
| 103 |
+
err = error_signal(state)
|
| 104 |
+
tripped = self.gate.update(err)
|
| 105 |
+
if tripped:
|
| 106 |
+
s.trips += 1
|
| 107 |
+
|
| 108 |
+
if self.mode == "HABITUAL":
|
| 109 |
+
action = cheap_step(state)
|
| 110 |
+
if tripped or action is None:
|
| 111 |
+
self.mode = "COGNITIVE" # shed the habit
|
| 112 |
+
else:
|
| 113 |
+
self.gate.relax()
|
| 114 |
+
s.habitual_steps += 1
|
| 115 |
+
s.history.append("H")
|
| 116 |
+
return action, "HABITUAL"
|
| 117 |
+
|
| 118 |
+
# COGNITIVE
|
| 119 |
+
action, calm = expensive_plan(state)
|
| 120 |
+
s.expensive_calls += 1
|
| 121 |
+
s.cognitive_steps += 1
|
| 122 |
+
s.history.append("C")
|
| 123 |
+
if latch_when_calm and calm:
|
| 124 |
+
self.gate.clear()
|
| 125 |
+
self.mode = "HABITUAL" # latch the fresh plan
|
| 126 |
+
return action, "COGNITIVE"
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class FilteredAcceleratorGate(AcceleratorGate):
|
| 130 |
+
"""Accelerometer gate with an EMA low-pass on the error before differentiating.
|
| 131 |
+
The biological analogue: dendritic integration time-constant smoothing the jerk signal.
|
| 132 |
+
"""
|
| 133 |
+
def __init__(self, trip=1.5, refractory=0, alpha=0.4):
|
| 134 |
+
super().__init__(trip=trip, refractory=refractory)
|
| 135 |
+
self.alpha = alpha
|
| 136 |
+
self.filt = 0.0
|
| 137 |
+
|
| 138 |
+
def update(self, err):
|
| 139 |
+
self.filt = self.alpha * err + (1 - self.alpha) * self.filt
|
| 140 |
+
return super().update(self.filt)
|
| 141 |
+
|
| 142 |
+
def clear(self):
|
| 143 |
+
super().clear(); self.filt = 0.0
|
drift.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
drift.py — a SECOND substrate for the same Clutch, to show it is not grid-specific.
|
| 3 |
+
|
| 4 |
+
Problem: an online predictor must forecast a streaming signal y_t. The signal is
|
| 5 |
+
piecewise-linear with occasional REGIME CHANGES (the slope/offset jumps) — the
|
| 6 |
+
time-series analogue of a wall dropping. Refitting a model every step is accurate but
|
| 7 |
+
expensive; never refitting drifts badly after a regime change. The Clutch refits only
|
| 8 |
+
when prediction error trips the gate.
|
| 9 |
+
|
| 10 |
+
Substrate mapping (identical Clutch API, different callbacks):
|
| 11 |
+
cheap_step(state) -> extrapolate the CACHED linear model (O(1))
|
| 12 |
+
expensive_plan(state) -> REFIT a linear model on the last `window` obs (O(window))
|
| 13 |
+
error_signal(state) -> normalized residual of the last prediction
|
| 14 |
+
|
| 15 |
+
This is exactly "concept-drift-gated retraining": spend training compute only when the
|
| 16 |
+
world has actually drifted. Compute is counted honestly as samples fit (refits x window).
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
from clutch import Clutch, MagnitudeGate, AcceleratorGate
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def make_signal(rng, T=600, n_regimes=5, noise=0.4):
|
| 24 |
+
"""Piecewise-linear signal with abrupt regime changes."""
|
| 25 |
+
change_pts = sorted(rng.choice(range(40, T - 20), size=n_regimes - 1, replace=False))
|
| 26 |
+
bounds = [0] + list(change_pts) + [T]
|
| 27 |
+
y = np.zeros(T)
|
| 28 |
+
val = float(rng.uniform(-2, 2))
|
| 29 |
+
for i in range(len(bounds) - 1):
|
| 30 |
+
lo, hi = bounds[i], bounds[i + 1]
|
| 31 |
+
slope = float(rng.uniform(-0.15, 0.15))
|
| 32 |
+
for t in range(lo, hi):
|
| 33 |
+
val += slope
|
| 34 |
+
y[t] = val
|
| 35 |
+
y = y + rng.normal(0, noise, size=T)
|
| 36 |
+
return y, set(change_pts)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class DriftPredictor:
|
| 40 |
+
"""Holds streaming state; exposes the three Clutch callbacks."""
|
| 41 |
+
def __init__(self, y, window=25):
|
| 42 |
+
self.y = y
|
| 43 |
+
self.window = window
|
| 44 |
+
self.t = 0
|
| 45 |
+
self.a = 0.0 # cached slope
|
| 46 |
+
self.b = float(y[0]) # cached offset
|
| 47 |
+
self.origin = 0 # x-origin the cached model was fit at
|
| 48 |
+
self.last_resid = 1.0 # normalized; start "surprised" so we plan first
|
| 49 |
+
self.scale = np.std(y) + 1e-6
|
| 50 |
+
self.pred_log = np.full(len(y), np.nan)
|
| 51 |
+
self.refit_samples = 0
|
| 52 |
+
|
| 53 |
+
def _predict_at(self, t):
|
| 54 |
+
return self.a * (t - self.origin) + self.b
|
| 55 |
+
|
| 56 |
+
# ---- Clutch callbacks -------------------------------------------------
|
| 57 |
+
def cheap_step(self, _):
|
| 58 |
+
return self._predict_at(self.t) # extrapolate cache; never None
|
| 59 |
+
|
| 60 |
+
def expensive_plan(self, _):
|
| 61 |
+
lo = max(0, self.t - self.window)
|
| 62 |
+
xs = np.arange(lo, self.t + 1)
|
| 63 |
+
ys = self.y[lo:self.t + 1]
|
| 64 |
+
self.refit_samples += len(xs)
|
| 65 |
+
if len(xs) >= 2:
|
| 66 |
+
a, b = np.polyfit(xs - lo, ys, 1)
|
| 67 |
+
self.a, self.b, self.origin = float(a), float(b), lo
|
| 68 |
+
pred = self._predict_at(self.t)
|
| 69 |
+
insample = np.mean(np.abs(np.polyval([self.a, self.b], xs - lo) - ys)) if len(xs) else 0.0
|
| 70 |
+
calm = (insample / self.scale) < 0.6 # clean fit -> safe to latch to habit
|
| 71 |
+
return pred, calm
|
| 72 |
+
|
| 73 |
+
def error_signal(self, _):
|
| 74 |
+
return self.last_resid
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def run_drift(y, change_pts, strategy, window=25, gate_params=None):
|
| 78 |
+
"""strategy in {ALWAYS_REFIT, NEVER_REFIT, CLUTCH_MAG, CLUTCH_ACC}."""
|
| 79 |
+
gp = gate_params or {}
|
| 80 |
+
pred = DriftPredictor(y, window=window)
|
| 81 |
+
clutch = None
|
| 82 |
+
if strategy == "CLUTCH_MAG":
|
| 83 |
+
clutch = Clutch(MagnitudeGate(gain=gp.get("gain", 4.0),
|
| 84 |
+
leak=gp.get("leak", 0.5),
|
| 85 |
+
trip=gp.get("trip_mag", 3.0)))
|
| 86 |
+
elif strategy == "CLUTCH_ACC":
|
| 87 |
+
clutch = Clutch(AcceleratorGate(trip=gp.get("trip_acc", 0.8),
|
| 88 |
+
refractory=gp.get("refractory", 3)))
|
| 89 |
+
|
| 90 |
+
refits = 0
|
| 91 |
+
trip_times = []
|
| 92 |
+
for t in range(len(y)):
|
| 93 |
+
pred.t = t
|
| 94 |
+
if strategy == "ALWAYS_REFIT":
|
| 95 |
+
p, _ = pred.expensive_plan(None); refits += 1; mode = "COGNITIVE"
|
| 96 |
+
elif strategy == "NEVER_REFIT":
|
| 97 |
+
if t == 0:
|
| 98 |
+
p, _ = pred.expensive_plan(None); refits += 1
|
| 99 |
+
else:
|
| 100 |
+
p = pred.cheap_step(None)
|
| 101 |
+
mode = "HABITUAL"
|
| 102 |
+
else:
|
| 103 |
+
before = clutch.stats.expensive_calls
|
| 104 |
+
p, mode = clutch.step(None, pred.cheap_step,
|
| 105 |
+
pred.expensive_plan, pred.error_signal)
|
| 106 |
+
if clutch.stats.expensive_calls > before:
|
| 107 |
+
refits += 1
|
| 108 |
+
if clutch.stats.trips and mode == "COGNITIVE":
|
| 109 |
+
trip_times.append(t)
|
| 110 |
+
pred.pred_log[t] = p
|
| 111 |
+
# observe truth, update normalized residual for next step's gate
|
| 112 |
+
pred.last_resid = abs(p - y[t]) / pred.scale
|
| 113 |
+
|
| 114 |
+
mae = float(np.nanmean(np.abs(pred.pred_log - y)))
|
| 115 |
+
return dict(strategy=strategy, mae=mae, refits=refits,
|
| 116 |
+
refit_samples=pred.refit_samples, pred=pred.pred_log,
|
| 117 |
+
trip_times=trip_times)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def benchmark_drift(seeds, window=25, gate_params=None, T=600):
|
| 121 |
+
strategies = ["ALWAYS_REFIT", "NEVER_REFIT", "CLUTCH_MAG", "CLUTCH_ACC"]
|
| 122 |
+
agg = {s: {"mae": [], "refits": [], "samples": []} for s in strategies}
|
| 123 |
+
for seed in seeds:
|
| 124 |
+
rng = np.random.default_rng(seed)
|
| 125 |
+
y, cps = make_signal(rng, T=T)
|
| 126 |
+
for s in strategies:
|
| 127 |
+
r = run_drift(y, cps, s, window=window, gate_params=gate_params)
|
| 128 |
+
agg[s]["mae"].append(r["mae"])
|
| 129 |
+
agg[s]["refits"].append(r["refits"])
|
| 130 |
+
agg[s]["samples"].append(r["refit_samples"])
|
| 131 |
+
out = []
|
| 132 |
+
base = np.mean(agg["ALWAYS_REFIT"]["samples"])
|
| 133 |
+
for s in strategies:
|
| 134 |
+
out.append(dict(strategy=s,
|
| 135 |
+
mae=float(np.mean(agg[s]["mae"])),
|
| 136 |
+
refits=float(np.mean(agg[s]["refits"])),
|
| 137 |
+
samples=float(np.mean(agg[s]["samples"])),
|
| 138 |
+
vs_ceiling=float(np.mean(agg[s]["samples"]) / base * 100.0)))
|
| 139 |
+
return out
|
nav.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
nav.py — the grid-navigation substrate for the Clutch demo.
|
| 3 |
+
|
| 4 |
+
Refactored from Antti Luode's benchmark.py so the app can:
|
| 5 |
+
(a) run a single seed and capture per-step frames (grid, position, mode) for animation,
|
| 6 |
+
(b) run the full multi-seed benchmark table (the honest measurement),
|
| 7 |
+
with configurable gate parameters exposed to the UI.
|
| 8 |
+
|
| 9 |
+
Compute is counted honestly as BFS cells expanded — the real O(N^2) cost of replanning.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
from collections import deque
|
| 14 |
+
from clutch import Clutch, MagnitudeGate, AcceleratorGate, FilteredAcceleratorGate
|
| 15 |
+
|
| 16 |
+
W = H = 60
|
| 17 |
+
A = (8, 30)
|
| 18 |
+
B = (52, 30)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def in_bounds(x, y):
|
| 22 |
+
return 0 <= x < W and 0 <= y < H
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def bfs(grid, start, goal):
|
| 26 |
+
if grid[start[1], start[0]] or grid[goal[1], goal[0]]:
|
| 27 |
+
return None, 0
|
| 28 |
+
q = deque([start]); came = {start: None}; expanded = 0
|
| 29 |
+
while q:
|
| 30 |
+
cur = q.popleft(); expanded += 1
|
| 31 |
+
if cur == goal:
|
| 32 |
+
path = []; c = cur
|
| 33 |
+
while c is not None:
|
| 34 |
+
path.append(c); c = came[c]
|
| 35 |
+
return path[::-1], expanded
|
| 36 |
+
cx, cy = cur
|
| 37 |
+
for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)):
|
| 38 |
+
if in_bounds(nx, ny) and not grid[ny, nx] and (nx, ny) not in came:
|
| 39 |
+
came[(nx, ny)] = cur; q.append((nx, ny))
|
| 40 |
+
return None, expanded
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def connected(grid):
|
| 44 |
+
p, _ = bfs(grid, A, B)
|
| 45 |
+
return p is not None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def make_wall_schedule(rng):
|
| 49 |
+
"""Barriers at distinct x, distinct times; reject any barrier that disconnects A-B."""
|
| 50 |
+
grid = np.zeros((H, W), dtype=bool)
|
| 51 |
+
schedule = {}
|
| 52 |
+
times = sorted(rng.choice(range(15, 250), size=5, replace=False))
|
| 53 |
+
xs = list(rng.choice(range(18, 46), size=5, replace=False))
|
| 54 |
+
for t, bx in zip(times, xs):
|
| 55 |
+
placed = None
|
| 56 |
+
for _ in range(12):
|
| 57 |
+
gap = int(rng.integers(8, H - 8))
|
| 58 |
+
cells = [(bx, y) for y in range(H) if abs(y - gap) > 5]
|
| 59 |
+
trial = grid.copy()
|
| 60 |
+
for (x, y) in cells:
|
| 61 |
+
if (x, y) != A and (x, y) != B:
|
| 62 |
+
trial[y, x] = True
|
| 63 |
+
if connected(trial):
|
| 64 |
+
placed = cells; grid = trial; break
|
| 65 |
+
if placed:
|
| 66 |
+
schedule[int(t)] = placed
|
| 67 |
+
return schedule
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def make_gate(strategy, gate_params):
|
| 71 |
+
gp = gate_params or {}
|
| 72 |
+
if strategy == "CLUTCH_MAG":
|
| 73 |
+
return MagnitudeGate(gain=gp.get("gain", 5.0),
|
| 74 |
+
leak=gp.get("leak", 0.5),
|
| 75 |
+
trip=gp.get("trip_mag", 10.0))
|
| 76 |
+
if strategy == "CLUTCH_ACC":
|
| 77 |
+
return AcceleratorGate(trip=gp.get("trip_acc", 0.9),
|
| 78 |
+
refractory=gp.get("refractory", 0))
|
| 79 |
+
if strategy == "CLUTCH_ACC_REF":
|
| 80 |
+
return AcceleratorGate(trip=gp.get("trip_acc", 0.9),
|
| 81 |
+
refractory=gp.get("refractory", 4))
|
| 82 |
+
if strategy == "CLUTCH_ACC_FILT":
|
| 83 |
+
return FilteredAcceleratorGate(trip=gp.get("trip_acc", 0.9),
|
| 84 |
+
refractory=gp.get("refractory", 4),
|
| 85 |
+
alpha=gp.get("alpha", 0.4))
|
| 86 |
+
return None
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class Runner:
|
| 90 |
+
def __init__(self, strategy, seed, p_noise=0.0, max_steps=1500,
|
| 91 |
+
gate_params=None, capture=False):
|
| 92 |
+
self.rng = np.random.default_rng(seed)
|
| 93 |
+
self.strategy = strategy
|
| 94 |
+
self.p_noise = p_noise
|
| 95 |
+
self.max_steps = max_steps
|
| 96 |
+
self.gate_params = gate_params or {}
|
| 97 |
+
self.capture = capture
|
| 98 |
+
self.grid = np.zeros((H, W), dtype=bool)
|
| 99 |
+
self.schedule = make_wall_schedule(self.rng)
|
| 100 |
+
self.pos = A
|
| 101 |
+
self.target = B
|
| 102 |
+
self.path = []
|
| 103 |
+
self.idx = 0
|
| 104 |
+
self.expanded_total = 0
|
| 105 |
+
self.patrols_done = 0
|
| 106 |
+
self.target_patrols = 3
|
| 107 |
+
self.frames = [] # (walls_copy, pos, mode, cum_expanded, target)
|
| 108 |
+
|
| 109 |
+
def perceived_blocked(self, cell):
|
| 110 |
+
real = self.grid[cell[1], cell[0]]
|
| 111 |
+
if not real and self.p_noise > 0 and self.rng.random() < self.p_noise:
|
| 112 |
+
return True
|
| 113 |
+
return real
|
| 114 |
+
|
| 115 |
+
def cheap_step(self, _):
|
| 116 |
+
if self.idx + 1 >= len(self.path):
|
| 117 |
+
return None
|
| 118 |
+
nxt = self.path[self.idx + 1]
|
| 119 |
+
if self.perceived_blocked(nxt):
|
| 120 |
+
return None
|
| 121 |
+
return nxt
|
| 122 |
+
|
| 123 |
+
def expensive_plan(self, _):
|
| 124 |
+
path, expanded = bfs(self.grid, self.pos, self.target)
|
| 125 |
+
self.expanded_total += expanded
|
| 126 |
+
if path is None or len(path) < 2:
|
| 127 |
+
return None, False
|
| 128 |
+
self.path = path
|
| 129 |
+
self.idx = 1
|
| 130 |
+
return path[1], True
|
| 131 |
+
|
| 132 |
+
def error_signal(self, _):
|
| 133 |
+
if self.idx + 1 >= len(self.path):
|
| 134 |
+
return 1.0
|
| 135 |
+
return 1.0 if self.perceived_blocked(self.path[self.idx + 1]) else 0.0
|
| 136 |
+
|
| 137 |
+
def _snap(self, mode):
|
| 138 |
+
if self.capture:
|
| 139 |
+
self.frames.append((self.grid.copy(), self.pos, mode,
|
| 140 |
+
self.expanded_total, self.target))
|
| 141 |
+
|
| 142 |
+
def run(self):
|
| 143 |
+
clutch = None
|
| 144 |
+
if self.strategy.startswith("CLUTCH"):
|
| 145 |
+
clutch = Clutch(make_gate(self.strategy, self.gate_params))
|
| 146 |
+
|
| 147 |
+
if self.strategy == "ALWAYS_HABITUAL":
|
| 148 |
+
path, e = bfs(self.grid, self.pos, self.target)
|
| 149 |
+
self.expanded_total += e
|
| 150 |
+
if path:
|
| 151 |
+
self.path, self.idx = path, 0
|
| 152 |
+
|
| 153 |
+
for t in range(self.max_steps):
|
| 154 |
+
if t in self.schedule:
|
| 155 |
+
for (x, y) in self.schedule[t]:
|
| 156 |
+
if (x, y) != A and (x, y) != B:
|
| 157 |
+
self.grid[y, x] = True
|
| 158 |
+
|
| 159 |
+
mode = "HABITUAL"
|
| 160 |
+
if self.strategy == "ALWAYS_COGNITIVE":
|
| 161 |
+
path, e = bfs(self.grid, self.pos, self.target)
|
| 162 |
+
self.expanded_total += e
|
| 163 |
+
mode = "COGNITIVE"
|
| 164 |
+
if path and len(path) >= 2:
|
| 165 |
+
self.pos = path[1]
|
| 166 |
+
|
| 167 |
+
elif self.strategy == "ALWAYS_HABITUAL":
|
| 168 |
+
nxt = self.cheap_step(None)
|
| 169 |
+
if nxt is not None:
|
| 170 |
+
self.pos = nxt; self.idx += 1
|
| 171 |
+
|
| 172 |
+
else:
|
| 173 |
+
action, mode = clutch.step(None, self.cheap_step,
|
| 174 |
+
self.expensive_plan, self.error_signal)
|
| 175 |
+
if action is not None:
|
| 176 |
+
self.pos = action
|
| 177 |
+
if mode == "HABITUAL":
|
| 178 |
+
self.idx += 1
|
| 179 |
+
|
| 180 |
+
self._snap(mode)
|
| 181 |
+
|
| 182 |
+
if self.pos == self.target:
|
| 183 |
+
self.patrols_done += 1
|
| 184 |
+
if self.patrols_done >= self.target_patrols:
|
| 185 |
+
return self._result(True, t + 1, clutch)
|
| 186 |
+
self.target = A if self.target == B else B
|
| 187 |
+
if clutch:
|
| 188 |
+
clutch.mode = "COGNITIVE"
|
| 189 |
+
self.path, self.idx = [], 0
|
| 190 |
+
|
| 191 |
+
return self._result(False, self.max_steps, clutch)
|
| 192 |
+
|
| 193 |
+
def _result(self, success, steps, clutch):
|
| 194 |
+
if clutch:
|
| 195 |
+
expensive = clutch.stats.expensive_calls
|
| 196 |
+
trips = clutch.stats.trips
|
| 197 |
+
elif self.strategy == "ALWAYS_COGNITIVE":
|
| 198 |
+
expensive, trips = steps, 0
|
| 199 |
+
else:
|
| 200 |
+
expensive, trips = 1, 0
|
| 201 |
+
return dict(success=success, steps=steps, expanded=self.expanded_total,
|
| 202 |
+
expensive=expensive, trips=trips, frames=self.frames)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def benchmark_table(strategies, seeds, p_noise, gate_params=None):
|
| 206 |
+
"""Full honest measurement across seeds. Returns list of per-strategy dicts."""
|
| 207 |
+
out = []
|
| 208 |
+
base = None
|
| 209 |
+
for strat in strategies:
|
| 210 |
+
rows = [Runner(strat, s, p_noise=p_noise, gate_params=gate_params).run()
|
| 211 |
+
for s in seeds]
|
| 212 |
+
ok = [r for r in rows if r["success"]]
|
| 213 |
+
|
| 214 |
+
def m(k, src):
|
| 215 |
+
return float(np.mean([r[k] for r in src])) if src else float("nan")
|
| 216 |
+
|
| 217 |
+
rec = dict(strategy=strat, success=len(ok) / len(rows),
|
| 218 |
+
steps=m("steps", ok), expanded=m("expanded", rows),
|
| 219 |
+
expensive=m("expensive", rows), trips=m("trips", rows))
|
| 220 |
+
if strat == "ALWAYS_COGNITIVE":
|
| 221 |
+
base = rec["expanded"]
|
| 222 |
+
out.append(rec)
|
| 223 |
+
for rec in out:
|
| 224 |
+
rec["vs_ceiling"] = (rec["expanded"] / base * 100.0) if base else float("nan")
|
| 225 |
+
return out
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==6.19.0
|
| 2 |
+
numpy
|
| 3 |
+
matplotlib
|
tuner.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
tuner.py — turn the Clutch demo into a TOOL: tune the gate on the USER's own data.
|
| 3 |
+
|
| 4 |
+
The visitor pastes/uploads any 1-D time series (latency metric, sensor stream, price
|
| 5 |
+
feed, error signal...). We run the real closed-loop drift substrate on it:
|
| 6 |
+
cheap = extrapolate the cached linear model (O(1))
|
| 7 |
+
costly = least-squares refit on the last `window` (O(window))
|
| 8 |
+
error = normalized residual of the last prediction
|
| 9 |
+
Then we SWEEP both gate families over a parameter grid, plot the honest
|
| 10 |
+
accuracy-vs-compute Pareto frontier, and pick the cheapest config whose MAE is within
|
| 11 |
+
`tol` of refit-every-step. Output: a copy-paste Clutch(...) snippet + $ savings.
|
| 12 |
+
|
| 13 |
+
All counterfactuals are valid because the loop is closed (refitting changes future
|
| 14 |
+
errors) — this is the same honest accounting as the benchmark, on the user's data.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import io
|
| 18 |
+
import re
|
| 19 |
+
import numpy as np
|
| 20 |
+
from drift import run_drift
|
| 21 |
+
|
| 22 |
+
MAX_POINTS = 20_000 # keep server-side sweeps snappy
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ------------------------------------------------------------------ parsing
|
| 26 |
+
def parse_series(text=None, file_obj=None):
|
| 27 |
+
"""Extract a 1-D float series from pasted text or an uploaded CSV/TXT.
|
| 28 |
+
Multi-column CSV: uses the LAST numeric column (usually the value column).
|
| 29 |
+
Returns (y, message)."""
|
| 30 |
+
raw = ""
|
| 31 |
+
if file_obj is not None:
|
| 32 |
+
path = file_obj if isinstance(file_obj, str) else getattr(file_obj, "name", None)
|
| 33 |
+
if path:
|
| 34 |
+
with open(path, "r", errors="ignore") as f:
|
| 35 |
+
raw = f.read()
|
| 36 |
+
elif text:
|
| 37 |
+
raw = text
|
| 38 |
+
if not raw.strip():
|
| 39 |
+
return None, "No data provided."
|
| 40 |
+
|
| 41 |
+
rows = []
|
| 42 |
+
for line in raw.strip().splitlines():
|
| 43 |
+
nums = re.findall(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", line)
|
| 44 |
+
if nums:
|
| 45 |
+
rows.append([float(x) for x in nums])
|
| 46 |
+
if not rows:
|
| 47 |
+
return None, "Could not find any numbers in the input."
|
| 48 |
+
|
| 49 |
+
ncol = max(len(r) for r in rows)
|
| 50 |
+
if ncol == 1:
|
| 51 |
+
y = np.array([r[0] for r in rows if len(r) == 1], dtype=float)
|
| 52 |
+
note = ""
|
| 53 |
+
else:
|
| 54 |
+
# take the last column present in full-width rows (skips header remnants)
|
| 55 |
+
full = [r for r in rows if len(r) == ncol]
|
| 56 |
+
y = np.array([r[-1] for r in full], dtype=float)
|
| 57 |
+
note = f" (took last of {ncol} numeric columns)"
|
| 58 |
+
y = y[np.isfinite(y)]
|
| 59 |
+
if len(y) < 60:
|
| 60 |
+
return None, f"Found only {len(y)} points — need at least 60 for a meaningful sweep."
|
| 61 |
+
if len(y) > MAX_POINTS:
|
| 62 |
+
y = y[:MAX_POINTS]
|
| 63 |
+
note += f"; truncated to first {MAX_POINTS:,} points"
|
| 64 |
+
return y, f"Loaded {len(y):,} points{note}."
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ------------------------------------------------------------------ sweep
|
| 68 |
+
MAG_GRID = [dict(gain=g, leak=l, trip_mag=t)
|
| 69 |
+
for g in (2.0, 4.0, 6.0, 8.0)
|
| 70 |
+
for l in (0.2, 0.5)
|
| 71 |
+
for t in (0.25, 0.5, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0)]
|
| 72 |
+
ACC_GRID = [dict(trip_acc=t, refractory=r)
|
| 73 |
+
for t in (0.2, 0.4, 0.8, 1.2, 2.0)
|
| 74 |
+
for r in (0, 3, 6)]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def sweep(y, window=25):
|
| 78 |
+
"""Run baselines + full grid. Returns dict with baselines and per-config rows."""
|
| 79 |
+
cps = set()
|
| 80 |
+
ref = run_drift(y, cps, "ALWAYS_REFIT", window=window)
|
| 81 |
+
never = run_drift(y, cps, "NEVER_REFIT", window=window)
|
| 82 |
+
rows = []
|
| 83 |
+
for gp in MAG_GRID:
|
| 84 |
+
r = run_drift(y, cps, "CLUTCH_MAG", window=window, gate_params=gp)
|
| 85 |
+
rows.append(dict(gate="MagnitudeGate", params=gp, mae=r["mae"],
|
| 86 |
+
refits=r["refits"], samples=r["refit_samples"]))
|
| 87 |
+
for gp in ACC_GRID:
|
| 88 |
+
r = run_drift(y, cps, "CLUTCH_ACC", window=window, gate_params=gp)
|
| 89 |
+
rows.append(dict(gate="AcceleratorGate", params=gp, mae=r["mae"],
|
| 90 |
+
refits=r["refits"], samples=r["refit_samples"]))
|
| 91 |
+
return dict(ref=ref, never=never, rows=rows, window=window, n=len(y))
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def pick_best(sw, tol=0.10):
|
| 95 |
+
"""Cheapest config with MAE <= (1+tol) * refit-every-step MAE.
|
| 96 |
+
Returns (best_or_None, fallback, limit). fallback = Pareto point with the
|
| 97 |
+
smallest MAE increase that still saves >= 30% compute (honest 'closest option')."""
|
| 98 |
+
limit = sw["ref"]["mae"] * (1.0 + tol)
|
| 99 |
+
ok = [r for r in sw["rows"] if r["mae"] <= limit]
|
| 100 |
+
best = min(ok, key=lambda r: (r["samples"], r["mae"])) if ok else None
|
| 101 |
+
base = sw["ref"]["refit_samples"] or 1
|
| 102 |
+
savers = [r for r in pareto_front(sw["rows"]) if r["samples"] <= 0.7 * base]
|
| 103 |
+
fallback = min(savers, key=lambda r: r["mae"]) if savers else None
|
| 104 |
+
return best, fallback, limit
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def pareto_front(rows):
|
| 108 |
+
"""Non-dominated set in (samples, mae), sorted by samples."""
|
| 109 |
+
pts = sorted(rows, key=lambda r: (r["samples"], r["mae"]))
|
| 110 |
+
front, best_mae = [], float("inf")
|
| 111 |
+
for r in pts:
|
| 112 |
+
if r["mae"] < best_mae - 1e-12:
|
| 113 |
+
front.append(r)
|
| 114 |
+
best_mae = r["mae"]
|
| 115 |
+
return front
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ------------------------------------------------------------------ output
|
| 119 |
+
def code_snippet(best, window):
|
| 120 |
+
p = best["params"]
|
| 121 |
+
if best["gate"] == "MagnitudeGate":
|
| 122 |
+
gate = (f"MagnitudeGate(gain={p['gain']}, leak={p['leak']}, "
|
| 123 |
+
f"trip={p['trip_mag']})")
|
| 124 |
+
else:
|
| 125 |
+
gate = f"AcceleratorGate(trip={p['trip_acc']}, refractory={p['refractory']})"
|
| 126 |
+
return f"""# tuned on YOUR data — cheapest gate within tolerance of refit-every-step
|
| 127 |
+
from clutch import Clutch, MagnitudeGate, AcceleratorGate
|
| 128 |
+
|
| 129 |
+
clutch = Clutch({gate})
|
| 130 |
+
# refit window used during tuning: {window}
|
| 131 |
+
# supply your three callbacks:
|
| 132 |
+
# cheap_step(state) -> action from the cached model/plan (O(1))
|
| 133 |
+
# expensive_plan(state) -> (action, calm_bool) # your costly call
|
| 134 |
+
# error_signal(state) -> scalar >= 0, e.g. |prediction - truth| / scale
|
| 135 |
+
action, mode = clutch.step(state, cheap_step, expensive_plan, error_signal)"""
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def report(sw, best, fallback, limit, tol, cost_per_call):
|
| 139 |
+
ref, never = sw["ref"], sw["never"]
|
| 140 |
+
win = best or fallback
|
| 141 |
+
lines = [f"#### Result on your {sw['n']:,}-point series (window {sw['window']})\n"]
|
| 142 |
+
lines.append("| strategy | MAE | expensive calls | training samples |")
|
| 143 |
+
lines.append("|---|---:|---:|---:|")
|
| 144 |
+
lines.append(f"| refit every step | {ref['mae']:.4g} | {ref['refits']:,} | {ref['refit_samples']:,} |")
|
| 145 |
+
if win:
|
| 146 |
+
tag = "tuned clutch" if best else "closest clutch (outside tolerance)"
|
| 147 |
+
lines.append(f"| **{tag}** | **{win['mae']:.4g}** | **{win['refits']:,}** | **{win['samples']:,}** |")
|
| 148 |
+
lines.append(f"| never refit | {never['mae']:.4g} | {never['refits']} | {never['refit_samples']:,} |")
|
| 149 |
+
lines.append("")
|
| 150 |
+
if best is None:
|
| 151 |
+
lines.append(f"⚠️ **No gate config stayed within {tol*100:.0f}% of the refit-every-step MAE "
|
| 152 |
+
f"(limit {limit:.4g}).** Honest verdict: on this series the cheap extrapolation "
|
| 153 |
+
"itself loses accuracy between refits, so gating is not free here.")
|
| 154 |
+
if fallback:
|
| 155 |
+
inc = (fallback["mae"] / ref["mae"] - 1) * 100
|
| 156 |
+
frac = fallback["samples"] / (ref["refit_samples"] or 1) * 100
|
| 157 |
+
lines.append(f"\nClosest trade-off on the Pareto frontier: `{fallback['gate']}` "
|
| 158 |
+
f"{fallback['params']} — **{frac:.1f}% of the compute for +{inc:.1f}% MAE**. "
|
| 159 |
+
"Take it only if that accuracy hit is acceptable; otherwise refit every step.")
|
| 160 |
+
return "\n".join(lines), win
|
| 161 |
+
frac = best["samples"] / ref["refit_samples"] if ref["refit_samples"] else 1.0
|
| 162 |
+
saved_calls = ref["refits"] - best["refits"]
|
| 163 |
+
lines.append(f"**Winner: `{best['gate']}` {best['params']}** — matches refit-every-step accuracy "
|
| 164 |
+
f"(within {tol*100:.0f}%) using **{frac*100:.1f}% of the training compute** "
|
| 165 |
+
f"and **{best['refits']:,} expensive calls instead of {ref['refits']:,}**.")
|
| 166 |
+
if cost_per_call and cost_per_call > 0:
|
| 167 |
+
lines.append(f"\n💰 At **${cost_per_call:.4g} per expensive call** (e.g. an LLM re-plan), "
|
| 168 |
+
f"this trace costs **${ref['refits']*cost_per_call:,.2f}** always-refit vs "
|
| 169 |
+
f"**${best['refits']*cost_per_call:,.2f}** with the clutch — "
|
| 170 |
+
f"**${saved_calls*cost_per_call:,.2f} saved ({(1-best['refits']/ref['refits'])*100:.1f}%)** "
|
| 171 |
+
f"on this trace alone.")
|
| 172 |
+
return "\n".join(lines), win
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ------------------------------------------------------------------ demo presets
|
| 176 |
+
def preset_series(name, seed=0):
|
| 177 |
+
rng = np.random.default_rng(seed)
|
| 178 |
+
t = np.arange(900, dtype=float)
|
| 179 |
+
if name.startswith("Server latency"):
|
| 180 |
+
y = 120 + 8 * np.sin(t / 40) + rng.normal(0, 6, len(t))
|
| 181 |
+
for s in (200, 480, 700): # incidents
|
| 182 |
+
y[s:s + 60] += np.linspace(0, 140, 60) * rng.uniform(0.6, 1.2)
|
| 183 |
+
return y
|
| 184 |
+
if name.startswith("Sensor with"):
|
| 185 |
+
y = np.cumsum(rng.normal(0, 0.05, len(t)))
|
| 186 |
+
for s in (150, 400, 650, 800):
|
| 187 |
+
y[s:] += rng.uniform(-3, 3) # calibration jumps
|
| 188 |
+
return y + rng.normal(0, 0.15, len(t))
|
| 189 |
+
# "Price-like random walk with regime shifts"
|
| 190 |
+
vol = np.where((t > 300) & (t < 500), 0.9, 0.25)
|
| 191 |
+
y = 100 + np.cumsum(rng.normal(0.02, 1, len(t)) * vol)
|
| 192 |
+
return y
|
viz.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""viz.py — matplotlib rendering for the Clutch demo (headless / Agg backend)."""
|
| 2 |
+
|
| 3 |
+
import matplotlib
|
| 4 |
+
matplotlib.use("Agg")
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from matplotlib.figure import Figure
|
| 7 |
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
| 8 |
+
import numpy as np
|
| 9 |
+
import imageio.v2 as imageio
|
| 10 |
+
import tempfile, os
|
| 11 |
+
|
| 12 |
+
from nav import W, H, A, B
|
| 13 |
+
|
| 14 |
+
HABIT = "#2e9e5b" # green = cheap cached step
|
| 15 |
+
COG = "#d64545" # red = expensive replan
|
| 16 |
+
INK = "#1b1b1b"
|
| 17 |
+
GRID_BG = "#f4f1ea"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _render_nav_frame(walls, pos, mode, cum_expanded, target, step, plan_calls):
|
| 21 |
+
fig = Figure(figsize=(4.2, 4.2), dpi=96)
|
| 22 |
+
ax = fig.add_subplot(111)
|
| 23 |
+
ax.set_facecolor(GRID_BG)
|
| 24 |
+
img = np.ones((H, W, 3))
|
| 25 |
+
img[walls] = [0.12, 0.12, 0.14] # walls dark
|
| 26 |
+
ax.imshow(img, origin="lower", interpolation="nearest")
|
| 27 |
+
ax.scatter([A[0]], [A[1]], s=60, marker="s", c="#3a6ea5", zorder=3)
|
| 28 |
+
ax.scatter([B[0]], [B[1]], s=60, marker="s", c="#3a6ea5", zorder=3)
|
| 29 |
+
tcol = "#e8a33d"
|
| 30 |
+
ax.scatter([target[0]], [target[1]], s=180, marker="*", c=tcol, zorder=4,
|
| 31 |
+
edgecolors=INK, linewidths=0.5)
|
| 32 |
+
col = HABIT if mode == "HABITUAL" else COG
|
| 33 |
+
ax.scatter([pos[0]], [pos[1]], s=90, c=col, zorder=5,
|
| 34 |
+
edgecolors=INK, linewidths=0.6)
|
| 35 |
+
ax.set_xlim(-1, W); ax.set_ylim(-1, H)
|
| 36 |
+
ax.set_xticks([]); ax.set_yticks([])
|
| 37 |
+
label = "REPLAN (expensive)" if mode == "COGNITIVE" else "cached step (cheap)"
|
| 38 |
+
ax.set_title(f"step {step} {label}", fontsize=10, color=col, fontweight="bold")
|
| 39 |
+
ax.text(0.5, -0.06, f"BFS cells expanded: {cum_expanded:,} plan calls: {plan_calls}",
|
| 40 |
+
transform=ax.transAxes, ha="center", va="top", fontsize=8.5, color=INK)
|
| 41 |
+
fig.tight_layout()
|
| 42 |
+
canvas = FigureCanvasAgg(fig)
|
| 43 |
+
canvas.draw()
|
| 44 |
+
buf = np.asarray(canvas.buffer_rgba())[..., :3].copy()
|
| 45 |
+
plt.close(fig)
|
| 46 |
+
return buf
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def make_nav_gif(frames, max_frames=90, fps=12):
|
| 50 |
+
"""frames: list of (walls, pos, mode, cum_expanded, target). Returns gif path."""
|
| 51 |
+
if not frames:
|
| 52 |
+
return None
|
| 53 |
+
n = len(frames)
|
| 54 |
+
idxs = np.linspace(0, n - 1, min(max_frames, n)).astype(int)
|
| 55 |
+
plan_calls = 0
|
| 56 |
+
prev_mode = None
|
| 57 |
+
imgs = []
|
| 58 |
+
# precompute cumulative plan calls along the full trace
|
| 59 |
+
calls_at = []
|
| 60 |
+
pc = 0
|
| 61 |
+
for (_, _, mode, _, _) in frames:
|
| 62 |
+
if mode == "COGNITIVE":
|
| 63 |
+
pc += 1
|
| 64 |
+
calls_at.append(pc)
|
| 65 |
+
for i in idxs:
|
| 66 |
+
walls, pos, mode, cum, target = frames[i]
|
| 67 |
+
img = _render_nav_frame(walls, pos, mode, cum, target, i, calls_at[i])
|
| 68 |
+
imgs.append(img)
|
| 69 |
+
# hold last frame a beat
|
| 70 |
+
imgs += [imgs[-1]] * 6
|
| 71 |
+
path = os.path.join(tempfile.gettempdir(), f"nav_{np.random.randint(1e9)}.gif")
|
| 72 |
+
imageio.mimsave(path, imgs, fps=fps, loop=0)
|
| 73 |
+
return path
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def make_compute_plot(clutch_frames, cog_frames, clutch_label="CLUTCH"):
|
| 77 |
+
fig = Figure(figsize=(5.2, 3.4), dpi=96)
|
| 78 |
+
ax = fig.add_subplot(111)
|
| 79 |
+
cc = [f[3] for f in clutch_frames]
|
| 80 |
+
gc = [f[3] for f in cog_frames]
|
| 81 |
+
ax.plot(range(len(gc)), gc, color=COG, lw=2, label="ALWAYS_COGNITIVE (replan every step)")
|
| 82 |
+
ax.plot(range(len(cc)), cc, color=HABIT, lw=2, label=clutch_label)
|
| 83 |
+
ax.set_xlabel("step"); ax.set_ylabel("cumulative BFS cells expanded")
|
| 84 |
+
ax.set_title("Compute spent over time", fontsize=11)
|
| 85 |
+
ax.legend(fontsize=8, loc="upper left")
|
| 86 |
+
ax.grid(alpha=0.25)
|
| 87 |
+
if gc and cc:
|
| 88 |
+
ratio = cc[-1] / gc[-1] * 100 if gc[-1] else 0
|
| 89 |
+
ax.text(0.98, 0.05, f"clutch = {ratio:.1f}% of always-replan",
|
| 90 |
+
transform=ax.transAxes, ha="right", fontsize=9,
|
| 91 |
+
color=HABIT, fontweight="bold")
|
| 92 |
+
fig.tight_layout()
|
| 93 |
+
return fig
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def make_drift_plot(y, change_pts, result, window):
|
| 97 |
+
fig = Figure(figsize=(6.4, 3.6), dpi=96)
|
| 98 |
+
ax = fig.add_subplot(111)
|
| 99 |
+
t = np.arange(len(y))
|
| 100 |
+
ax.plot(t, y, color="#9aa0a6", lw=1.0, label="true signal", zorder=1)
|
| 101 |
+
ax.plot(t, result["pred"], color=HABIT, lw=1.6, label="clutch prediction", zorder=2)
|
| 102 |
+
for i, cp in enumerate(sorted(change_pts)):
|
| 103 |
+
ax.axvline(cp, color="#c9b358", ls=":", lw=1.0,
|
| 104 |
+
label="regime change" if i == 0 else None)
|
| 105 |
+
for i, tt in enumerate(result["trip_times"]):
|
| 106 |
+
ax.axvline(tt, color=COG, ls="-", lw=0.9, alpha=0.7,
|
| 107 |
+
label="gate trip -> REFIT" if i == 0 else None)
|
| 108 |
+
ax.set_xlabel("time step"); ax.set_ylabel("value")
|
| 109 |
+
ax.set_title(f"Drift-gated retraining — {result['refits']} refits, "
|
| 110 |
+
f"MAE {result['mae']:.2f}", fontsize=11)
|
| 111 |
+
ax.legend(fontsize=8, loc="best")
|
| 112 |
+
ax.grid(alpha=0.25)
|
| 113 |
+
fig.tight_layout()
|
| 114 |
+
return fig
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def make_pareto_plot(sw, best, fallback, front):
|
| 118 |
+
"""Accuracy-vs-compute scatter of every swept config + Pareto frontier + winner."""
|
| 119 |
+
fig = Figure(figsize=(6.2, 3.8), dpi=96)
|
| 120 |
+
ax = fig.add_subplot(111)
|
| 121 |
+
ref = sw["ref"]
|
| 122 |
+
mags = [r for r in sw["rows"] if r["gate"] == "MagnitudeGate"]
|
| 123 |
+
accs = [r for r in sw["rows"] if r["gate"] == "AcceleratorGate"]
|
| 124 |
+
ax.scatter([r["samples"] for r in mags], [r["mae"] for r in mags],
|
| 125 |
+
s=22, c=HABIT, alpha=0.55, label="MagnitudeGate configs")
|
| 126 |
+
ax.scatter([r["samples"] for r in accs], [r["mae"] for r in accs],
|
| 127 |
+
s=22, c="#7a5fb5", alpha=0.55, label="AcceleratorGate configs")
|
| 128 |
+
fx = [r["samples"] for r in front]; fy = [r["mae"] for r in front]
|
| 129 |
+
ax.plot(fx, fy, color=INK, lw=1.2, ls="--", alpha=0.7, label="Pareto frontier")
|
| 130 |
+
ax.axhline(ref["mae"], color=COG, lw=1.2, ls=":",
|
| 131 |
+
label=f"refit-every-step MAE ({ref['mae']:.3g})")
|
| 132 |
+
ax.axvline(ref["refit_samples"], color=COG, lw=1.0, ls=":", alpha=0.5)
|
| 133 |
+
win = best or fallback
|
| 134 |
+
if win:
|
| 135 |
+
ax.scatter([win["samples"]], [win["mae"]], s=170, marker="*",
|
| 136 |
+
c="#e8a33d", edgecolors=INK, linewidths=0.8, zorder=5,
|
| 137 |
+
label="chosen config")
|
| 138 |
+
ax.set_xlabel("training samples spent (compute)")
|
| 139 |
+
ax.set_ylabel("prediction MAE")
|
| 140 |
+
ax.set_title("Every gate config on YOUR data — down-left is better", fontsize=11)
|
| 141 |
+
ax.legend(fontsize=7.5, loc="best")
|
| 142 |
+
ax.grid(alpha=0.25)
|
| 143 |
+
fig.tight_layout()
|
| 144 |
+
return fig
|