In this section
- Wafer transform · cosmic / tools/explore/lab/wafer.py lines 1–252
- Laws — Demo Page render · cosmic / tools/explore/laws/demo/index.html lines 1–278
Wafer
A Python module in the lab folder of Cosmic that ranks spiral (`rank_spiral`), using SHA-256.
transformcosmic / tools/explore/lab/wafer.py · lines 1–252 of 252 · pattern measure (shared by 35 files)
- What it does
- It calculates its inputs. Defines 14 functions or classes, including key32, law, rank_spiral, registry_spiral, hash_key. Uses libraries hashlib, math, random, numpy.
- Downstream impact
- Used directly by 3 files: Explore — Lab (cosmic); Test Lab (cosmic); Test Visualise (cosmic). Reached from 4 other entry points, including Extras (cosmic); Ship (cosmic); Test Extras (cosmic).
- What it achieves
- It hashes key (`hash_key`) and is built from the key32 step (`key32`) and the law step (`law`). Experiment 3: Kuiper wafer layout. Positions are computed from a permanent ordinal, never stored.
- Why it matters
- Imported by Explore — Lab. Checked by 2 tests, including Test Lab.
- Application
- cosmic · tools/explore/lab · Python module
- Uses
- Explore — Lab (import), hashlib, math, random, numpy
- Used by
- imported by Explore — Lab (import), imported by Test Lab (import), imported by Test Visualise (sys.path import)
- Produces
- key32, law, rank_spiral, registry_spiral, hash_key, hex_cell, wafer_dies, shelf, force, procrustes, diameter, snapshots
- Defines here
- key32, law, rank_spiral, registry_spiral, hash_key, hex_cell, wafer_dies, shelf, force, procrustes, diameter, snapshots, measure, run
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/lab/wafer.py:1-252 · blob bb5161b54a3b8a02e7ead8afb42489f927c1161e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Experiment 3: Kuiper wafer layout. Positions are computed from a permanent ordinal, never stored.
Compares, across two estate snapshots (5% of files dropped, 5% added, seeded), the displacement of the files
present in both under six layouts: three ordinal laws, one hierarchical wafer of dies, and two state-free
baselines (a sorted shelf packing like the current map view, and a force-directed layout).
"""
import hashlib
import math
import random
import numpy as np
from common import SEED, overlay, r4
NAME = 'wafer'
RULES = ('lab-wafer-v1 (law r = sqrt(key), theta = 2 pi frac(key x 2654435769 / 2^32); hash key = first 32 bits '
'of sha256("repo/path"); dies on a hex spiral by permanent repo number, die capacity 2^ceil(log2 files); '
'snapshot B = drop 5%% + add 5%% seeded %d; force = Fruchterman-Reingold 60 iterations, Procrustes-aligned)' % SEED)
HYPOTHESIS = ('A layout computed from a permanent key (Kuiper\'s law) keeps every unchanged file exactly where it '
'was when the estate changes, while sorted packing and force layouts move most files; a die per '
'repository keeps that stability and adds locality.')
ALGORITHM = ('Six laws key -> (x, y). rank_spiral: ordinal = rank of (repo, path) in the current snapshot. '
'registry_spiral: ordinal assigned once, new files appended (Modular Star: never renumbered). '
'hash_key: the key is the file\'s own 32-bit hash, no registry needed. wafer_dies: repo die at a '
'hex-spiral cell given by its permanent repo number; inside the die the hash-key law. shelf: '
'repos in sorted rows, files row-major by path (like a packed map). force: Fruchterman-Reingold '
'from a hash-seeded start, snapshot B aligned to A by Procrustes (generous to it). Metric: mean '
'displacement of files in both snapshots, as a share of the snapshot-A diameter.')
PHI32 = 2654435769
GOLD = 2 * math.pi * PHI32 / 2 ** 32
def key32(repo, path):
return int(hashlib.sha256(('%s/%s' % (repo, path)).encode()).hexdigest()[:8], 16)
def law(k):
"""Kuiper's placement law for an integer key k (the ordinal)."""
r = math.sqrt(k)
th = 2 * math.pi * ((k * PHI32) % 2 ** 32) / 2 ** 32
return r * math.cos(th), r * math.sin(th)
def rank_spiral(keys):
s = sorted(keys)
return {k: law(i) for i, k in enumerate(s)}
def registry_spiral(keys, registry):
"""registry: dict key -> ordinal, extended in place (append-only) for unseen keys in sorted order."""
for k in sorted(set(keys) - set(registry)):
registry[k] = len(registry)
return {k: law(registry[k]) for k in keys}
def hash_key(keys):
out = {}
for k in keys:
u = key32(*k)
r = math.sqrt(u / 2 ** 32)
th = 2 * math.pi * ((u * PHI32) % 2 ** 32) / 2 ** 32
out[k] = (r * math.cos(th), r * math.sin(th))
return out
def hex_cell(i):
"""Ordinal -> hex cell centre on an outward spiral (0 at centre, ring 1 has 6 cells, ring r has 6r)."""
if i == 0:
return 0.0, 0.0
ring = 1
while 1 + 3 * ring * (ring + 1) <= i:
ring += 1
j = i - (1 + 3 * ring * (ring - 1))
side, off = divmod(j, ring)
dirs = [(1, 0), (1, -1), (0, -1), (-1, 0), (-1, 1), (0, 1)]
q, r = dirs[4][0] * ring, dirs[4][1] * ring
for s in range(side):
q += dirs[s][0] * ring
r += dirs[s][1] * ring
q += dirs[side][0] * off
r += dirs[side][1] * off
return q + r / 2.0, r * math.sqrt(3) / 2
def wafer_dies(keys, repo_registry):
for rp in sorted({k[0] for k in keys} - set(repo_registry)):
repo_registry[rp] = len(repo_registry)
count = {}
for rp, _ in keys:
count[rp] = count.get(rp, 0) + 1
cap = {rp: 2 ** math.ceil(math.log2(max(1, c))) for rp, c in count.items()}
maxcap = max(cap.values()) if cap else 1
dies = {}
for rp in count:
cx, cy = hex_cell(repo_registry[rp])
dies[rp] = (cx, cy, max(0.14, 0.49 * math.sqrt(cap[rp] / maxcap)))
out = {}
for k in keys:
cx, cy, rad = dies[k[0]]
u = key32(*k)
r = rad * math.sqrt(u / 2 ** 32)
th = 2 * math.pi * ((u * PHI32) % 2 ** 32) / 2 ** 32
out[k] = (cx + r * math.cos(th), cy + r * math.sin(th))
return out, dies
def shelf(keys):
"""Repos in sorted order, each a square block of files row-major by path, blocks packed in rows of width W."""
by = {}
for k in sorted(keys):
by.setdefault(k[0], []).append(k)
total = len(keys)
W = max(1, int(math.sqrt(total) * 1.6))
out = {}
x0 = y0 = rowh = 0
for rp in sorted(by):
fs = by[rp]
side = max(1, int(math.ceil(math.sqrt(len(fs)))))
if x0 + side > W and x0 > 0:
x0, y0, rowh = 0, y0 + rowh + 1, 0
for i, k in enumerate(fs):
out[k] = (x0 + i % side, y0 + i // side)
x0 += side + 1
rowh = max(rowh, side)
return out
def force(keys, edges, iters=60):
"""Fruchterman-Reingold in numpy, start positions from each key's hash (so unchanged files start equal)."""
keys = sorted(keys)
ix = {k: i for i, k in enumerate(keys)}
n = len(keys)
pos = np.array([[((key32(*k) & 0xffff) / 65535.0) - 0.5, ((key32(*k) >> 16) / 65535.0) - 0.5] for k in keys],
dtype=np.float32)
E = np.array([(ix[a], ix[b]) for a, b in edges if a in ix and b in ix], dtype=np.int64).reshape(-1, 2)
kk = math.sqrt(1.0 / max(1, n))
t = 0.1
chunk = 768
for it in range(iters):
disp = np.zeros_like(pos)
for s in range(0, n, chunk):
d = pos[s:s + chunk, None, :] - pos[None, :, :]
dist2 = (d * d).sum(-1) + np.float32(1e-9)
disp[s:s + chunk] += np.einsum('ijk,ij->ik', d, np.float32(kk * kk) / dist2)
if len(E):
d = pos[E[:, 0]] - pos[E[:, 1]]
dist = np.sqrt((d ** 2).sum(-1)) + 1e-9
f = (d * (dist / np.float32(kk))[:, None]).astype(np.float32)
np.add.at(disp, E[:, 0], -f)
np.add.at(disp, E[:, 1], f)
ln = np.sqrt((disp ** 2).sum(-1)) + 1e-9
pos += (disp / ln[:, None] * np.minimum(ln, np.float32(t))[:, None]).astype(np.float32)
t *= 0.95
return {k: (float(pos[i, 0]), float(pos[i, 1])) for i, k in enumerate(keys)}
def procrustes(A, B):
"""Similarity transform mapping B onto A (rows matched). Returns transformed B."""
ma, mb = A.mean(0), B.mean(0)
A0, B0 = A - ma, B - mb
U, S, Vt = np.linalg.svd(B0.T @ A0)
R = U @ Vt
s = S.sum() / max(1e-12, (B0 ** 2).sum())
return s * B0 @ R + ma
def diameter(P):
P = np.asarray(list(P))
return float(np.sqrt(((P.max(0) - P.min(0)) ** 2).sum())) if len(P) else 1.0
def snapshots(G, seed=SEED, frac=0.05):
keys = [(G.repo[i], G.path[i]) for i in range(G.n)]
rng = random.Random(seed)
drop = set(rng.sample(range(G.n), int(frac * G.n)))
keysB = [keys[i] for i in range(G.n) if i not in drop]
repos = [keys[i][0] for i in range(G.n)]
added = []
for j in range(int(frac * G.n)):
rp = repos[rng.randrange(G.n)]
added.append((rp, 'zz-new/%05d-%s.js' % (j, hashlib.sha256(str(j).encode()).hexdigest()[:6])))
keysB += added
edgesA = [(keys[a], keys[b]) for a, b in G.uedges]
edgesB = [(keys[a], keys[b]) for a, b in G.uedges if a not in drop and b not in drop]
same_repo = {}
for i in range(G.n):
if i not in drop:
same_repo.setdefault(keys[i][0], []).append(keys[i])
for k in added:
pool = same_repo.get(k[0]) or [keysB[0]]
for _ in range(2):
edgesB.append((k, pool[rng.randrange(len(pool))]))
return keys, keysB, edgesA, edgesB
def measure(layA, layB, edgesA, keys_common, align=False):
A = np.array([layA[k] for k in keys_common])
B = np.array([layB[k] for k in keys_common])
if align:
B = procrustes(A, B)
dia = diameter(layA.values())
d = np.sqrt(((A - B) ** 2).sum(1)) / dia
allk = sorted(layA)
P = np.array([layA[k] for k in allk])
ix = {k: i for i, k in enumerate(allk)}
rng = np.random.default_rng(SEED)
ra = rng.integers(0, len(allk), 20000)
rb = rng.integers(0, len(allk), 20000)
rnd = np.sqrt(((P[ra] - P[rb]) ** 2).sum(1)).mean()
ea = np.array([ix[a] for a, b in edgesA])
eb = np.array([ix[b] for a, b in edgesA])
el = np.sqrt(((P[ea] - P[eb]) ** 2).sum(1)).mean() if len(ea) else 0.0
return {'mean_displacement': r4(d.mean()), 'p95_displacement': r4(np.percentile(d, 95)),
'share_moved_over_1pct': r4((d > 0.01).mean()),
'edge_length_vs_random_pair': r4(el / rnd) if rnd > 0 else None}
def run(G):
keysA, keysB, edgesA, edgesB = snapshots(G)
common = sorted(set(keysA) & set(keysB))
reg = {}
regA = registry_spiral(keysA, reg)
regB = registry_spiral(keysB, reg)
rreg = {}
diesA, dA = wafer_dies(keysA, rreg)
diesB, _ = wafer_dies(keysB, rreg)
lay = {
'rank_spiral': (rank_spiral(keysA), rank_spiral(keysB), False),
'registry_spiral': (regA, regB, False),
'hash_key': (hash_key(keysA), hash_key(keysB), False),
'wafer_dies': (diesA, diesB, False),
'shelf': (shelf(keysA), shelf(keysB), False),
'force': (force(keysA, edgesA), force(keysB, edgesB), True),
}
res = {nm: measure(a, b, edgesA, common, align) for nm, (a, b, align) in lay.items()}
metrics = {'files_A': len(keysA), 'files_B': len(keysB), 'unchanged': len(common), 'layouts': res}
findings = ['%s: mean displacement %.4f of diameter, %.1f%% of unchanged files moved >1%%, edge/random length %.3f'
% (nm, m['mean_displacement'], 100 * m['share_moved_over_1pct'], m['edge_length_vs_random_pair'] or 0)
for nm, m in res.items()]
keys = [(G.repo[i], G.path[i]) for i in range(G.n)]
rs = lay['rank_spiral'][0]
fo = lay['force'][0]
cols = {'wx': [round(diesA[k][0], 4) for k in keys], 'wy': [round(diesA[k][1], 4) for k in keys],
'hx': [round(lay['hash_key'][0][k][0], 4) for k in keys], 'hy': [round(lay['hash_key'][0][k][1], 4) for k in keys],
'sx': [round(rs[k][0], 2) for k in keys], 'sy': [round(rs[k][1], 2) for k in keys],
'fx': [round(fo[k][0], 4) for k in keys], 'fy': [round(fo[k][1], 4) for k in keys]}
legend = {'dies': ['repo', 'repo_number', 'cx', 'cy', 'radius'],
'rows': [[rp, rreg[rp], round(dA[rp][0], 4), round(dA[rp][1], 4), round(dA[rp][2], 4)] for rp in sorted(dA)]}
ov = overlay(G, NAME, RULES, cols=cols, legend=legend,
extra={'note': 'positions are computed from the key, never stored; recompute with lab/wafer.py law()'})
return ov, metrics, findingsLaws — Demo Page
A web page in Cosmic that works with verdict cls and verdict txt, calculates planar distances, draws on a canvas and reads inputs for law s1. Published at https://ventusltd.github.io/cosmic/tools/explore/laws/demo/.
rendercosmic / tools/explore/laws/demo/index.html · lines 1–278 of 278 · Entry point · pattern explain (shared by 7 files)
- What it does
- It draws its content. Defines 17 functions or classes, including keyPos, hue, verdictCls, verdictTxt, explain. Uses libraries data.js. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "`build_graph.json` (see `GRAPH-CONTRACT.md`) feeds `visualise.py`, which writes `visual/index.html`: pipeline (Ingest / Transform / Output), estate map and topic flow, coloured by role, topic, stage or pattern, with a reachability overlay."
- Inputs & outputs
- Out: web page; canvas drawing.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/cosmic/tools/explore/laws/demo/.
- What it achieves
- It is built from the key pos helper (`keyPos`), the hue step (`hue`) and the verdict cls helper (`verdictCls`). Nine physical analogies measured on the Explore Code graph, each with a toggle that changes the drawing. It responds to change, resize and click events.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools/explore/laws/demo · page
- Uses
- data.js
- Used by
- none found
- Produces
- keyPos, hue, verdictCls, verdictTxt, explain, resize, sx, sy, rad, step, draw, rnd
- Defines here
- keyPos, hue, verdictCls, verdictTxt, explain, resize, sx, sy, rad, step, draw, rnd, induce, pick, show, li, frame
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/laws/demo/index.html:1-278 · blob c1804a2713fb26d4d450ff63412c957c937c41d4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Estate laws: the code base as physics (demo)</title>
<meta name="description" content="Nine physical analogies measured on the Explore Code graph, each with a toggle that changes the drawing. Offline, no external files.">
<style>
:root{--bg:#05070d;--fg:#e8edf5;--dim:#8a94a6;--line:#1c2433;--ok:#4ade80;--part:#facc15;--no:#f87171;--acc:#38bdf8}
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:var(--bg);color:var(--fg);font:15px/1.4 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
body{display:flex;flex-direction:column;min-height:100vh;min-height:100dvh}
header{padding:10px 14px 6px}
h1{font-size:17px;margin:0 0 2px}
header p{margin:0;color:var(--dim);font-size:13px}
#stage{position:relative;flex:1 1 auto;min-height:52vh}
canvas{position:absolute;inset:0;width:100%;height:100%;touch-action:none;display:block}
#stamp{position:absolute;right:8px;top:6px;font-size:11px;color:var(--dim);text-align:right;pointer-events:none}
#info{position:absolute;left:8px;bottom:8px;right:8px;max-width:520px;background:rgba(10,14,24,.92);border:1px solid var(--line);border-radius:10px;padding:8px 10px;font-size:13px;display:none}
#info b{display:block;font-size:14px}
#info code{font-size:11px;color:var(--dim);word-break:break-all}
#info ul{margin:4px 0 0;padding-left:18px}
#info button{position:absolute;right:6px;top:4px;background:none;border:0;color:var(--dim);font-size:18px;min-width:44px;min-height:44px;cursor:pointer}
#panel{border-top:1px solid var(--line);padding:8px 10px calc(10px + env(safe-area-inset-bottom))}
#toggles{display:flex;flex-wrap:wrap;gap:6px}
.t{display:flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:999px;padding:0 12px;min-height:44px;font-size:14px;cursor:pointer;user-select:none;background:#0b101b}
.t input{width:18px;height:18px;margin:0;accent-color:var(--acc)}
.t .v{font-size:11px;font-weight:600;border-radius:6px;padding:1px 5px}
.v.HOLDS{background:#14532d;color:var(--ok)} .v.PARTLY{background:#422006;color:var(--part)} .v.NO{background:#450a0a;color:var(--no)}
#explain{margin:8px 2px 0;font-size:13px;color:var(--dim);min-height:2.8em}
#explain b{color:var(--fg)}
#actions{display:flex;gap:6px;margin-top:6px;flex-wrap:wrap}
#actions button{min-height:44px;padding:0 14px;border-radius:8px;border:1px solid var(--line);background:#111827;color:var(--fg);font-size:14px;cursor:pointer}
@media (min-width:900px){
body{flex-direction:row;flex-wrap:wrap}
header{width:100%}
#stage{flex:1 1 60%;min-height:calc(100vh - 60px)}
#panel{flex:0 0 360px;border-top:0;border-left:1px solid var(--line);overflow:auto;max-height:calc(100vh - 60px)}
#toggles{flex-direction:column}
}
</style>
</head>
<body>
<header>
<h1>If the code base obeyed physical laws</h1>
<p>Each toggle is one law, measured on the real estate. The badge says whether it holds. Tap a file to see it; tap a file with induction on to send a pulse.</p>
</header>
<div id="stage">
<canvas id="c" aria-label="Estate laws canvas: files as bodies" role="img"></canvas>
<div id="stamp"></div>
<div id="info" role="dialog" aria-live="polite"><button id="close" aria-label="Close">×</button><div id="infob"></div></div>
</div>
<div id="panel">
<div id="toggles"></div>
<div id="explain">Turn a law on to see how it changes the drawing.</div>
<div id="actions"><button id="distil" type="button">Distil copies</button><button id="shake" type="button">Shake</button><button id="reset" type="button">Reset</button></div>
</div>
<script src="data.js"></script>
<script>
(function(){
'use strict';
var D = window.LAWS_DATA;
var cv = document.getElementById('c'), cx = cv.getContext('2d');
var ORDER = ['G1','F1','C1','S1','I1','K9','FA','K1','L11'];
var SHORT = {G1:'Gravity',F1:'Fields',C1:'Conservation',S1:'Entropy',I1:'Inertia',K9:'Kirchhoff',FA:'Induction',K1:'Keys',L11:'Light'};
var on = {G1:true,F1:false,C1:true,S1:false,I1:false,K9:false,FA:true,K1:false,L11:true};
var N = D.nodes.length, W = 0, H = 0, dpr = 1, scale = 1;
var users = [], uses = [];
for (var i = 0; i < N; i++) { users.push([]); uses.push([]); }
D.edges.forEach(function(e){ uses[e[0]].push(e[1]); users[e[1]].push(e[0]); });
// key position: Kuiper wafer law on the permanent rank k (r = sqrt(k), golden turn)
var KMAX = 0; D.nodes.forEach(function(n){ if (n.k > KMAX) KMAX = n.k; });
function keyPos(n){
var r = Math.sqrt(n.k + 0.5) / Math.sqrt(KMAX + 1);
var th = 2 * Math.PI * (((n.k * 2654435769) >>> 0) / 4294967296);
return [r * Math.cos(th), r * Math.sin(th)];
}
var P = D.nodes.map(function(n){ var k = keyPos(n); return {x:k[0], y:k[1], vx:0, vy:0, kx:k[0], ky:k[1], flash:0}; });
var hue = function(r){ return (r * 137.508) % 360; };
var distil = 0, distilTarget = 0, sel = -1, pulses = [], t0 = 0;
function verdictCls(v){ return v === 'HOLDS' ? 'HOLDS' : (v === 'PARTLY' ? 'PARTLY' : 'NO'); }
function verdictTxt(v){ return v === 'HOLDS' ? 'holds' : (v === 'PARTLY' ? 'partly' : 'does not hold'); }
var tg = document.getElementById('toggles'), ex = document.getElementById('explain');
ORDER.forEach(function(id){
var L = D.laws[id];
var lab = document.createElement('label'); lab.className = 't';
var cb = document.createElement('input'); cb.type = 'checkbox'; cb.checked = on[id]; cb.id = 'law-' + id;
cb.addEventListener('change', function(){ on[id] = cb.checked; explain(id); });
var s = document.createElement('span'); s.textContent = SHORT[id];
var v = document.createElement('span'); v.className = 'v ' + verdictCls(L.verdict); v.textContent = verdictTxt(L.verdict);
lab.appendChild(cb); lab.appendChild(s); lab.appendChild(v); tg.appendChild(lab);
});
function explain(id){
var L = D.laws[id];
ex.textContent = '';
var b = document.createElement('b'); b.textContent = L.name + ' (' + verdictTxt(L.verdict) + '): ';
ex.appendChild(b); ex.appendChild(document.createTextNode(L.law + ' Drawing: ' + D.visual[id]));
}
var st = document.getElementById('stamp');
var oldest = 0; for (var lk in D.ages) if (D.ages[lk] > oldest) oldest = D.ages[lk];
st.textContent = 'graph as of ' + D.cut + (oldest ? ' \u00b7 near-copy layer (identity) ' + Math.round(oldest) + ' min older' : '');
function resize(){
var r = cv.getBoundingClientRect(); dpr = Math.min(window.devicePixelRatio || 1, 2);
W = Math.max(1, r.width); H = Math.max(1, r.height);
cv.width = Math.round(W * dpr); cv.height = Math.round(H * dpr);
scale = Math.min(W, H) * 0.44;
}
window.addEventListener('resize', resize);
function sx(p){ return W / 2 + p.x * scale; }
function sy(p){ return H / 2 + p.y * scale; }
function rad(n){ return on.G1 ? 1.6 + 2.2 * Math.log(1 + n.m) : 2.6; }
function step(){
var i, n, p;
for (i = 0; i < N; i++) { P[i].fx = 0; P[i].fy = 0; }
if (on.G1) {
D.edges.forEach(function(e){
var a = P[e[0]], b = P[e[1]], m = D.nodes[e[1]].m;
var dx = b.x - a.x, dy = b.y - a.y, d = Math.sqrt(dx*dx + dy*dy) + 1e-6;
var k = 0.0009 * Math.log(1 + m) * (d - 0.04);
a.fx += k * dx / d; a.fy += k * dy / d;
b.fx -= 0.25 * k * dx / d; b.fy -= 0.25 * k * dy / d;
});
}
if (on.C1) {
for (i = 0; i < N; i++) { p = P[i]; p.fx += 0.012 * (p.kx - p.x); p.fy += 0.012 * (p.ky - p.y); }
} else {
for (i = 0; i < N; i++) { p = P[i]; p.fx += 0.002 * (0 - p.x); p.fy += 0.002 * (0 - p.y); }
}
// soft repulsion between near neighbours (cheap grid-free O(N^2) for N ~ 240)
for (i = 0; i < N; i++) for (var j = i + 1; j < N; j++) {
var a = P[i], b = P[j], dx = a.x - b.x, dy = a.y - b.y, d2 = dx*dx + dy*dy;
if (d2 < 0.0025 && d2 > 1e-9) { var f = 0.00004 / d2; a.fx += f*dx; a.fy += f*dy; b.fx -= f*dx; b.fy -= f*dy; }
}
for (i = 0; i < N; i++) {
n = D.nodes[i]; p = P[i];
var inv = on.I1 ? 1 / (1 + n.m) : 1;
p.vx = (p.vx + p.fx * inv) * 0.86; p.vy = (p.vy + p.fy * inv) * 0.86;
p.x += p.vx; p.y += p.vy;
}
distil += (distilTarget - distil) * 0.05;
}
function draw(ts){
var i, n, p;
cx.setTransform(dpr, 0, 0, dpr, 0, 0);
cx.fillStyle = '#05070d'; cx.fillRect(0, 0, W, H);
var oldDim = 1;
if (on.L11) { var age = 0; for (var k in D.ages) if (D.ages[k] > age) age = D.ages[k]; oldDim = Math.max(0.45, 1 - age / 240); }
// use edges
cx.lineWidth = 0.6;
cx.strokeStyle = 'rgba(120,140,170,0.22)';
cx.beginPath();
D.edges.forEach(function(e){ var a = P[e[0]], b = P[e[1]]; cx.moveTo(sx(a), sy(a)); cx.lineTo(sx(b), sy(b)); });
cx.stroke();
// field lines (named data files: writers -> readers)
if (on.F1) {
cx.setLineDash([3, 4]); cx.lineWidth = 1;
D.fields.forEach(function(f, fi){
cx.strokeStyle = 'hsla(' + ((fi * 61 + 200) % 360) + ',90%,65%,0.55)';
f.w.forEach(function(w){ f.c.forEach(function(c){
if (w === c) return;
var a = P[w], b = P[c], mx = (sx(a) + sx(b)) / 2, my = (sy(a) + sy(b)) / 2;
var nx = -(sy(b) - sy(a)) * 0.25, ny = (sx(b) - sx(a)) * 0.25;
cx.beginPath(); cx.moveTo(sx(a), sy(a)); cx.quadraticCurveTo(mx + nx, my + ny, sx(b), sy(b)); cx.stroke();
}); });
});
cx.setLineDash([]);
}
// entropy dust: near copies jitter around the file they copy
var tt = ts / 1000;
for (i = 0; i < N; i++) {
n = D.nodes[i]; p = P[i];
var x = sx(p), y = sy(p), r = rad(n);
var dust = on.S1 && n.of != null;
if (dust) {
var q = P[n.of];
x += (sx(q) - x) * distil; y += (sy(q) - y) * distil;
var j = (1 - distil) * 3;
x += Math.sin(tt * 2.1 + i) * j; y += Math.cos(tt * 1.7 + i * 1.3) * j;
}
var alpha = dust ? 0.45 * (1 - distil) + 0.05 : 1;
if (on.L11 && dust) alpha *= oldDim; // the identity layer (near copies) is older than the graph
var light = on.G1 ? 45 + Math.min(30, 6 * Math.log(1 + n.m)) : 55;
var col = 'hsla(' + hue(n.r) + ',70%,' + light + '%,' + alpha + ')';
cx.beginPath(); cx.arc(x, y, r, 0, 2 * Math.PI);
if (on.K1 && n.cand) { cx.strokeStyle = col; cx.lineWidth = 1.2; cx.stroke(); }
else { cx.fillStyle = col; cx.fill(); }
if (on.K9) {
cx.lineWidth = 2;
cx.strokeStyle = n.in ? 'rgba(56,189,248,0.9)' : 'rgba(60,70,90,0.6)';
cx.beginPath(); cx.arc(x, y, r + 2.5, Math.PI / 2, 3 * Math.PI / 2); cx.stroke();
cx.strokeStyle = n.out ? 'rgba(74,222,128,0.9)' : 'rgba(60,70,90,0.6)';
cx.beginPath(); cx.arc(x, y, r + 2.5, -Math.PI / 2, Math.PI / 2); cx.stroke();
if (n.leak) { cx.strokeStyle = 'rgba(248,113,113,' + (0.5 + 0.4 * Math.sin(tt * 4)) + ')'; cx.lineWidth = 1.5; cx.beginPath(); cx.arc(x, y, r + 6, 0, 2 * Math.PI); cx.stroke(); }
}
if (p.flash > 0) {
cx.strokeStyle = 'rgba(255,255,255,' + p.flash + ')'; cx.lineWidth = 2;
cx.beginPath(); cx.arc(x, y, r + 4 + 8 * (1 - p.flash), 0, 2 * Math.PI); cx.stroke();
p.flash = Math.max(0, p.flash - 0.02);
}
if (i === sel) { cx.strokeStyle = '#fff'; cx.lineWidth = 1.5; cx.beginPath(); cx.arc(x, y, r + 3, 0, 2 * Math.PI); cx.stroke(); }
}
// induction pulses travelling along use edges, user <- used
pulses = pulses.filter(function(q){
q.t += 0.03;
var a = P[q.from], b = P[q.to];
var x = sx(a) + (sx(b) - sx(a)) * Math.min(1, q.t), y = sy(a) + (sy(b) - sy(a)) * Math.min(1, q.t);
cx.fillStyle = 'rgba(253,224,71,0.95)'; cx.beginPath(); cx.arc(x, y, 2.4, 0, 2 * Math.PI); cx.fill();
if (q.t >= 1) {
if (q.hit) { P[q.to].flash = 1; if (q.depth < 2) induce(q.to, q.depth + 1); }
return false;
}
return true;
});
}
// deterministic per-click pseudo-random (no Math.random: same tap, same result)
var seed = 20261205;
function rnd(){ seed = (seed * 1103515245 + 12345) >>> 0; return seed / 4294967296; }
function induce(i, depth){
users[i].forEach(function(u){ pulses.push({from:i, to:u, t:0, depth:depth, hit: rnd() < D.p_induce}); });
}
function pick(px, py){
var best = -1, bd = 1e9;
for (var i = 0; i < N; i++) {
var dx = sx(P[i]) - px, dy = sy(P[i]) - py, d = dx*dx + dy*dy;
if (d < bd) { bd = d; best = i; }
}
return bd < 22 * 22 ? best : -1;
}
var info = document.getElementById('info'), infob = document.getElementById('infob');
function show(i){
sel = i;
if (i < 0) { info.style.display = 'none'; return; }
var n = D.nodes[i];
infob.textContent = '';
var b = document.createElement('b'); b.textContent = n.t || n.p; infob.appendChild(b);
var c = document.createElement('code'); c.textContent = n.key; infob.appendChild(c);
var ul = document.createElement('ul');
function li(s){ var x = document.createElement('li'); x.textContent = s; ul.appendChild(x); }
li(n.m > 0 ? 'Used by ' + n.m + ' file' + (n.m === 1 ? '' : 's') + ' (whole estate).' : 'Not used by any file in the graph.');
if (n.of != null) li('A near copy (' + Math.round(100 * n.sim) + '% of lines shared) of ' + (D.nodes[n.of].t || D.nodes[n.of].p) + '.');
if (n.leak) li('Takes something in, but no file in the graph uses its result and it records no named output: a possible dead end.');
if (n.cand) li('Described from its file name only (a candidate).');
if (on.FA && users[i].length) li('Induction pulse sent to ' + users[i].length + ' user(s) shown here; each lights with p = ' + D.p_induce + '.');
infob.appendChild(ul);
info.style.display = 'block';
}
document.getElementById('close').addEventListener('click', function(){ show(-1); });
cv.addEventListener('pointerdown', function(ev){
var r = cv.getBoundingClientRect(), i = pick(ev.clientX - r.left, ev.clientY - r.top);
show(i);
if (i >= 0 && on.FA) { P[i].flash = 1; induce(i, 0); }
});
document.getElementById('distil').addEventListener('click', function(){
if (!on.S1) { on.S1 = true; document.getElementById('law-S1').checked = true; }
distilTarget = distilTarget > 0.5 ? 0 : 1; explain('S1');
});
document.getElementById('shake').addEventListener('click', function(){
for (var i = 0; i < N; i++) { P[i].vx += (rnd() - 0.5) * 0.06; P[i].vy += (rnd() - 0.5) * 0.06; }
});
document.getElementById('reset').addEventListener('click', function(){
for (var i = 0; i < N; i++) { P[i].x = P[i].kx; P[i].y = P[i].ky; P[i].vx = P[i].vy = 0; P[i].flash = 0; }
pulses = []; distil = distilTarget = 0; seed = 20261205; show(-1);
});
resize();
for (var w = 0; w < 120; w++) step();
function frame(ts){ step(); draw(ts); requestAnimationFrame(frame); }
requestAnimationFrame(frame);
window.__lawsReady = true;
})();
</script>
</body>
</html>