keepfold 0.6.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. keepfold/__init__.py +1 -0
  2. keepfold/_proc.py +102 -0
  3. keepfold/access.py +154 -0
  4. keepfold/agent_eval.py +162 -0
  5. keepfold/agent_text.py +56 -0
  6. keepfold/anki.py +285 -0
  7. keepfold/app/__init__.py +5 -0
  8. keepfold/app/actions.py +690 -0
  9. keepfold/app/desktop.py +677 -0
  10. keepfold/app/exports.py +254 -0
  11. keepfold/app/hello.py +79 -0
  12. keepfold/app/launch.py +114 -0
  13. keepfold/app/news.py +60 -0
  14. keepfold/app/server.py +3142 -0
  15. keepfold/app/status.py +811 -0
  16. keepfold/app/targets.py +1374 -0
  17. keepfold/app/winpath.py +54 -0
  18. keepfold/app/wizard.py +506 -0
  19. keepfold/ask.py +475 -0
  20. keepfold/askfile.py +322 -0
  21. keepfold/assets/LICENSE-d3.txt +13 -0
  22. keepfold/assets/agent_eval.json +235 -0
  23. keepfold/assets/app/app.css +611 -0
  24. keepfold/assets/app/app.js +2712 -0
  25. keepfold/assets/app/capture.html +16 -0
  26. keepfold/assets/app/capture.js +91 -0
  27. keepfold/assets/app/index.html +149 -0
  28. keepfold/assets/brain3d.js +3730 -0
  29. keepfold/assets/chat_eval.json +454 -0
  30. keepfold/assets/d3.v7.min.js +2 -0
  31. keepfold/assets/dashboard.css +774 -0
  32. keepfold/assets/dashboard.html.tmpl +170 -0
  33. keepfold/assets/dashboard.js +4262 -0
  34. keepfold/assets/help/GUIDE.md +544 -0
  35. keepfold/assets/help/help.md +83 -0
  36. keepfold/assets/keepfold.ico +0 -0
  37. keepfold/assets/whats_new.json +162 -0
  38. keepfold/backup.py +100 -0
  39. keepfold/brainmap.py +1382 -0
  40. keepfold/browse/__init__.py +10 -0
  41. keepfold/browse/build.py +1320 -0
  42. keepfold/browse/forget.py +510 -0
  43. keepfold/browse/legacy.py +95 -0
  44. keepfold/browse/lists.py +285 -0
  45. keepfold/browse/privacy.py +391 -0
  46. keepfold/browse/selftest.py +166 -0
  47. keepfold/browse/sites.py +1068 -0
  48. keepfold/browse/sources.py +329 -0
  49. keepfold/browse/store.py +991 -0
  50. keepfold/browse/takeout.py +312 -0
  51. keepfold/browse/titles.py +127 -0
  52. keepfold/browse/vectors.py +326 -0
  53. keepfold/browse_serve.py +332 -0
  54. keepfold/catalog.py +564 -0
  55. keepfold/chat.py +1464 -0
  56. keepfold/chat_archive.py +165 -0
  57. keepfold/chat_eval.py +583 -0
  58. keepfold/chat_facts.py +721 -0
  59. keepfold/chat_import.py +1045 -0
  60. keepfold/chat_pages.py +291 -0
  61. keepfold/chat_study.py +371 -0
  62. keepfold/chats.py +669 -0
  63. keepfold/claims.py +650 -0
  64. keepfold/cli.py +3254 -0
  65. keepfold/clients.py +96 -0
  66. keepfold/cloudllm.py +135 -0
  67. keepfold/contract.py +43 -0
  68. keepfold/corrections.py +134 -0
  69. keepfold/dashboard.py +959 -0
  70. keepfold/dates.py +202 -0
  71. keepfold/delta.py +146 -0
  72. keepfold/digest.py +72 -0
  73. keepfold/doctor.py +565 -0
  74. keepfold/duplicates.py +145 -0
  75. keepfold/egress.py +68 -0
  76. keepfold/eval_history.py +109 -0
  77. keepfold/events.py +554 -0
  78. keepfold/export_context.py +109 -0
  79. keepfold/fact_harvest.py +578 -0
  80. keepfold/forget.py +720 -0
  81. keepfold/harvest.py +334 -0
  82. keepfold/home.py +714 -0
  83. keepfold/importers.py +627 -0
  84. keepfold/index.py +733 -0
  85. keepfold/know.py +40 -0
  86. keepfold/learning_eval.py +261 -0
  87. keepfold/levels.py +595 -0
  88. keepfold/life_sources.py +747 -0
  89. keepfold/lint.py +241 -0
  90. keepfold/localllm.py +699 -0
  91. keepfold/loops.py +316 -0
  92. keepfold/mcp_server.py +4464 -0
  93. keepfold/migrate.py +552 -0
  94. keepfold/more_sources.py +709 -0
  95. keepfold/packs.py +148 -0
  96. keepfold/people.py +99 -0
  97. keepfold/planner.py +819 -0
  98. keepfold/prime.py +630 -0
  99. keepfold/prime_hook.py +265 -0
  100. keepfold/profiles.py +118 -0
  101. keepfold/quarantine.py +123 -0
  102. keepfold/recall_log.py +93 -0
  103. keepfold/redteam.py +393 -0
  104. keepfold/reflect.py +164 -0
  105. keepfold/relink.py +477 -0
  106. keepfold/render.py +406 -0
  107. keepfold/review.py +1181 -0
  108. keepfold/rollups.py +412 -0
  109. keepfold/safety_net.py +571 -0
  110. keepfold/sample.py +103 -0
  111. keepfold/sample_vault/areas/programming.algorithms.md +11 -0
  112. keepfold/sample_vault/areas/programming.basics.md +11 -0
  113. keepfold/sample_vault/concepts/big-o-notation.md +13 -0
  114. keepfold/sample_vault/concepts/functions.md +13 -0
  115. keepfold/sample_vault/concepts/loops.md +14 -0
  116. keepfold/sample_vault/concepts/recursion.md +13 -0
  117. keepfold/sample_vault/domains/programming.md +10 -0
  118. keepfold/sample_vault/journal/2026-01-12.md +9 -0
  119. keepfold/sample_vault/me/goals.md +17 -0
  120. keepfold/sample_vault/me/profile.md +19 -0
  121. keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
  122. keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
  123. keepfold/sample_vault/problems/fizzbuzz.md +12 -0
  124. keepfold/sample_vault/projects/text-adventure.md +15 -0
  125. keepfold/sample_vault/resources/python-tutorial.md +16 -0
  126. keepfold/semantic.py +1254 -0
  127. keepfold/session.py +764 -0
  128. keepfold/share.py +69 -0
  129. keepfold/sources.py +612 -0
  130. keepfold/sync_copies.py +83 -0
  131. keepfold/tags.py +230 -0
  132. keepfold/taint.py +301 -0
  133. keepfold/tonight.py +195 -0
  134. keepfold/topics.py +1072 -0
  135. keepfold/update.py +300 -0
  136. keepfold/vault.py +942 -0
  137. keepfold/vecstore.py +218 -0
  138. keepfold/voice.py +260 -0
  139. keepfold/voice_memos.py +280 -0
  140. keepfold/watch.py +303 -0
  141. keepfold/where.py +119 -0
  142. keepfold/xray.py +516 -0
  143. keepfold/zotero.py +303 -0
  144. keepfold-0.6.4.dist-info/METADATA +644 -0
  145. keepfold-0.6.4.dist-info/RECORD +148 -0
  146. keepfold-0.6.4.dist-info/WHEEL +4 -0
  147. keepfold-0.6.4.dist-info/entry_points.txt +6 -0
  148. keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/brainmap.py ADDED
@@ -0,0 +1,1382 @@
1
+ """Brain v3, the neural network look: geometry and page layout.
2
+
3
+ Python owns the geometry and the layout; `assets/brain3d.js` only draws them. One implicit
4
+ brain volume (`inside`): a smooth union of two overlapping hemispheres, a temporal lobe per
5
+ side, a tucked cerebellum and a brainstem stub, with a shallow groove on top and gentle folds,
6
+ meshed once. Lobes (the dashboard clusters) get 3-D sites by classical MDS of 1 - affinity and
7
+ round regions by a centroidal capacity-constrained power diagram over seeded samples of the
8
+ volume (volume ~ count^0.65), with an empty gap at region borders. Pages sit in their region
9
+ by a PCA + kNN relaxation of their vectors in 3-D, partly transported to fill it, the most
10
+ linked pages pulled into a nucleus at its centre; unsorted chats form a thick band under the
11
+ brain. Each lobe's hue differs by HUE_GAP from every region it touches.
12
+ Fibres are the wikilinks plus each page's 3 nearest by meaning, as quadratic Béziers bundled
13
+ toward the regions' centres. The layout persists in `.keepfold/brain-layout.json` and grows
14
+ incrementally. It only reads the vector cache: it never embeds and never downloads a model.
15
+
16
+ Builder choices (measured on the real vault, see the report of 17 Nov 2026):
17
+ - the mesh is surface nets (dual marching cubes, no case table): one vertex per crossed cell,
18
+ projected onto the surface by two Newton steps, lit by the field's gradient;
19
+ - the affinity's shared-parent term is "same lobe kind";
20
+ - MDS axes go to front-back, left-right, up-down; the coordinates are whitened and each lobe
21
+ set at its radius rank before the push apart (plain MDS crowded most lobes into the centre
22
+ and made slab-shaped regions); then damped Lloyd moves round the regions while each lobe's
23
+ two most affine lobes are pulled back toward touching it (fixed sites left 14 of 40 real
24
+ regions as slabs; plain Lloyd lost the fixture's families); the cerebellum is its own pool
25
+ when a routine lobe exists;
26
+ - the in-lobe relaxation repels by negative sampling (UMAP-style), is fitted to its region by
27
+ mean and covariance, then moved 40 % of the way to its sliced optimal transport onto the
28
+ region (closes the gaps between clumps; 40 % keeps in-lobe preservation near 0.7);
29
+ - hubs are a lobe's top 5 % or the vault's top 1 % by degree, pulled toward the centre by
30
+ up to 70 % (log degree), so a journal lobe full of daily hubs gets a nucleus too;
31
+ - a lobe's centre is the mean of its region's interior samples, its anchor the interior
32
+ sample nearest that centre, its normal the anchor's direction from the brain's centre;
33
+ - a page new since the last layout goes to the similarity-weighted mean of its 3 nearest
34
+ placed pages, so a near-duplicate lands by its twin;
35
+ - the layout's `added` holds when each page first entered it (`_now`), kept through rewrites
36
+ and relayouts; a first layout and an old layout's pages have none, so an upgrade is never a
37
+ burst of new pages; the blob's `nodes.added` carries the last ADDED_DAYS days of them for
38
+ the app's growth moment;
39
+ - touching regions are lobes whose samples share a voxel or two face-adjacent ones of a
40
+ 32-cube grid; each lobe wants the hue of its site's circular order around the vertical axis
41
+ spread evenly over the wheel; touching lobes get hues 60 degrees apart by colouring the
42
+ touching graph with six hues (DSatur, backtracking), then each moves toward its wanted hue
43
+ as far as its gaps allow; lobes that share a hex colour step 0.03 darker;
44
+ - `nodes.weight` (0-1, for the renderer's node size) is 0.6 log link degree + 0.25 log
45
+ similar-fibre degree (each scaled by the vault's maximum) + 0.15 recency of `updated`
46
+ (e-folding RECENT days before the newest page);
47
+ - a lobe that appears between relayouts is a guest in its most affine lobe's region;
48
+ - a stored page also records whether it had a vector: pages new, moved or embedded since
49
+ the last layout count toward the 20 % relayout threshold;
50
+ - the ring takes no tracts; `tracts` stay for the lobe inspector's "Strongest connections".
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import base64
56
+ import hashlib
57
+ import json
58
+ import logging
59
+ import math
60
+ from datetime import UTC, date, datetime, timedelta
61
+ from functools import lru_cache
62
+
63
+ import numpy as np
64
+
65
+ from keepfold import semantic
66
+ from keepfold.browse import lists
67
+ from keepfold.vault import VaultError
68
+
69
+ log = logging.getLogger(__name__)
70
+
71
+ VERSION = 3
72
+ REVISION = 2 # of the layout code: a bump relays every vault out once
73
+ LAYOUT = ".keepfold/brain-layout.json"
74
+ LEGEND = ("lobe = a topic from your topic tree, coloured unlike every topic it touches; "
75
+ "position = similar meaning (nearby points are related, distances "
76
+ "are approximate); volume grows slower than the page count; counts are exact in "
77
+ "text; bright fibres = your links; faint fibres = similar meaning.")
78
+
79
+ # the volume: ellipsoids as (centre, radii x, y above the centre, y below it, z)
80
+ HEMI = ((0.24, 0.0, 0.0), (0.44, 0.55, 0.40, 0.86)) # the right one; the left is its mirror
81
+ TEMPORAL = ((0.40, -0.25, 0.12), (0.22, 0.18, 0.18, 0.42)) # likewise
82
+ CEREBELLUM = ((0.0, -0.38, -0.55), (0.40, 0.17, 0.17, 0.26))
83
+ STEM = ((0.0, -0.30, -0.25), (0.0, -0.74, -0.36), 0.085) # a capsule: two ends, a radius
84
+ SMOOTH = 0.08 # polynomial smooth-min width
85
+ GROOVE = (0.04, 0.06) # depth and half-width of the longitudinal groove on top
86
+ FOLD = (0.015, 12.0) # fold amplitude and wave number
87
+ BOX = ((-0.78, -0.88, -0.98), (0.78, 0.68, 0.98)) # holds the volume with a margin
88
+ GRID = 64 # mesh cells along the longest side of BOX
89
+ SAMPLES, MARGIN = 60000, 0.02 # volume samples, each at least MARGIN inside the surface
90
+ GAP = 0.02 # pages and region samples keep this far from a region border
91
+ AREA_EXP = 0.65
92
+ SPREAD = 0.3 # minimum site spacing, a share of the sum of two region radii
93
+ LLOYD, LLOYD_STEP = 10, 0.5 # site moves toward their cell's centroid, and how far each goes
94
+ TIES, TIE_PULL, TOUCH = 2, 1.0, 0.5 # each lobe's most affine lobes, pulled back toward
95
+ # TOUCH x the sum of the two regions' radii
96
+ FILL = 0.8 # sites stay inside this share of their pool's extent
97
+ FIT = 0.9 # a lobe's layout fills this share of its region's spread
98
+ FILL_OT = 0.4 # then goes this share of the way to filling its region evenly
99
+ HUBS, VAULT_HUBS = 0.05, 0.01 # hubs: a lobe's top share of pages by degree, or the vault's
100
+ HUB_PULL = 0.7 # how far the most linked hub of a lobe is pulled toward its centre
101
+ RING_Y, RING_R, RING_W = -0.62, 0.75, 0.07 # the unsorted chats' band: height, radius, thickness
102
+ KNN, NEG, EPOCHS = 6, 5, 100 # in-lobe relaxation: attracting neighbours, repelling samples
103
+ N_NEAR, N_TRACTS, N_BEACONS, N_SIMILAR = 8, 150, 3, 3
104
+ RECENT = 30 # days: a node's weight for recency falls by e for each RECENT days older
105
+ PULL, JITTER = 0.35, 0.02 # fibre control points: toward the regions' centres, seeded jitter
106
+ HUE_GAP, HUE_MIN = 60, 3 # degrees between touching regions' hues, and (where it fits) any two
107
+ RELAYOUT_SHARE = 0.2
108
+ ADDED_DAYS = 30 # the blob carries the `added` stamps of this many days (the app's growth moment)
109
+ ROUTINES = {"journal", "you", "sessions", "placements", "browsing"} # group lobes in the cerebellum
110
+ FRONTAL = {"projects", "people"} # group lobes pinned to the frontal pole
111
+ ARCHIVE = {"chats"} # group lobes on the basal ring (plus any lobe of kind "archive")
112
+ PARTS = ("cerebrum", "cerebellum")
113
+ PARAMS_HASH = hashlib.sha256(json.dumps(
114
+ [VERSION, REVISION, HEMI, TEMPORAL, CEREBELLUM, STEM, SMOOTH, GROOVE, FOLD, BOX, SAMPLES,
115
+ MARGIN, GAP, AREA_EXP, SPREAD, LLOYD, LLOYD_STEP, TIES, TIE_PULL, TOUCH, FILL, FIT,
116
+ FILL_OT, HUBS, VAULT_HUBS, HUB_PULL, RING_Y, RING_R, RING_W, KNN, NEG, EPOCHS]
117
+ ).encode()).hexdigest()[:16]
118
+
119
+
120
+ @lru_cache(maxsize=1 << 16) # read-only arrays (frombuffer of bytes), so sharing them is safe
121
+ def _u(key: str, k: int = 4) -> np.ndarray:
122
+ """k uniforms in [0, 1) from a stable hash of `key`."""
123
+ d = hashlib.blake2b(key.encode(), digest_size=4 * k).digest()
124
+ return np.frombuffer(d, "<u4") / 2.0 ** 32
125
+
126
+
127
+ def _unit(x: np.ndarray) -> np.ndarray:
128
+ return x / np.maximum(np.linalg.norm(x, axis=-1, keepdims=True), 1e-12)
129
+
130
+
131
+ # ---- the volume ----------------------------------------------------------------------------
132
+
133
+ def _ellipsoid(p: np.ndarray, c, r) -> np.ndarray:
134
+ """About the signed distance to an ellipsoid whose lower half has its own height."""
135
+ q = p - np.asarray(c)
136
+ rad = np.empty_like(q)
137
+ rad[:, 0], rad[:, 1], rad[:, 2] = r[0], np.where(q[:, 1] >= 0, r[1], r[2]), r[3]
138
+ k0 = np.linalg.norm(q / rad, axis=1)
139
+ k1 = np.linalg.norm(q / rad ** 2, axis=1)
140
+ with np.errstate(divide="ignore", invalid="ignore"):
141
+ return np.where(k1 > 1e-9, k0 * (k0 - 1) / k1, -min(r))
142
+
143
+
144
+ def _capsule(p: np.ndarray, a, b, r: float) -> np.ndarray:
145
+ a, ba = np.asarray(a), np.subtract(b, a)
146
+ t = np.clip((p - a) @ ba / (ba @ ba), 0, 1)
147
+ return np.linalg.norm(p - a - t[:, None] * ba, axis=1) - r
148
+
149
+
150
+ @lru_cache
151
+ def _waves() -> tuple[np.ndarray, np.ndarray]:
152
+ u = np.array([_u(f"fold:{k}", 3) for k in range(6)])
153
+ z, a = 2 * u[:, 0] - 1, 2 * np.pi * u[:, 1]
154
+ r = np.sqrt(1 - z * z)
155
+ return np.stack([r * np.cos(a), r * np.sin(a), z], 1) * FOLD[1], 2 * np.pi * u[:, 2]
156
+
157
+
158
+ def _parts(p: np.ndarray) -> np.ndarray:
159
+ """Distance to each part: hemispheres (left, right), temporal lobes (left, right),
160
+ cerebellum, brainstem."""
161
+ m = np.array([-1.0, 1.0, 1.0])
162
+ (hc, hr), (tc, tr) = HEMI, TEMPORAL
163
+ return np.stack([_ellipsoid(p, np.multiply(hc, m), hr), _ellipsoid(p, hc, hr),
164
+ _ellipsoid(p, np.multiply(tc, m), tr), _ellipsoid(p, tc, tr),
165
+ _ellipsoid(p, *CEREBELLUM), _capsule(p, *STEM)], 1)
166
+
167
+
168
+ def _field(p: np.ndarray, d: np.ndarray | None = None) -> np.ndarray:
169
+ """The brain's implicit function: negative inside, about the distance to the surface."""
170
+ d = _parts(p) if d is None else d
171
+ f = d[:, 0]
172
+ for k in range(1, d.shape[1]): # polynomial smooth min
173
+ h = np.maximum(SMOOTH - np.abs(f - d[:, k]), 0) / SMOOTH
174
+ f = np.minimum(f, d[:, k]) - h * h * SMOOTH / 4
175
+ depth, width = GROOVE
176
+ f = f + depth * np.exp(-(p[:, 0] / width) ** 2) * np.clip(p[:, 1] / 0.25, 0, 1)
177
+ k, ph = _waves()
178
+ return f + FOLD[0] * np.sin(p @ k.T + ph).sum(1) / math.sqrt(3)
179
+
180
+
181
+ def inside(p) -> np.ndarray:
182
+ """Whether each point (N x 3) is inside the brain volume."""
183
+ return _field(np.atleast_2d(np.asarray(p, float))) < 0
184
+
185
+
186
+ def _grad(p: np.ndarray, h: float = 1e-4) -> np.ndarray:
187
+ return np.stack([_field(p + e) - _field(p - e) for e in np.eye(3) * h], 1) / (2 * h)
188
+
189
+
190
+ @lru_cache(maxsize=1)
191
+ def _samples() -> tuple[np.ndarray, np.ndarray, float]:
192
+ """SAMPLES seeded points at least MARGIN inside the volume (none in the brainstem), which
193
+ of them are cerebellum, and the volume each stands for."""
194
+ rng = np.random.default_rng(3)
195
+ lo, hi = np.array(BOX[0]), np.array(BOX[1])
196
+ pts, cb, drawn = [], [], 0
197
+ while sum(map(len, pts)) < SAMPLES:
198
+ p = lo + (hi - lo) * rng.random((1 << 16, 3))
199
+ d = _parts(p)
200
+ part = np.argmin(d, 1)
201
+ ok = (_field(p, d) < -MARGIN) & (part != 5)
202
+ pts.append(p[ok])
203
+ cb.append(part[ok] == 4)
204
+ drawn += len(p)
205
+ kept = sum(map(len, pts))
206
+ return (np.concatenate(pts)[:SAMPLES], np.concatenate(cb)[:SAMPLES],
207
+ float(np.prod(hi - lo)) * kept / drawn / SAMPLES)
208
+
209
+
210
+ def _pool(cb: np.ndarray, part: str, split: bool) -> np.ndarray:
211
+ """Which of the points flagged cerebellum-or-not belong to `part`'s partition: the
212
+ cerebellum is its own pool only when a lobe lives there."""
213
+ return cb == (part == "cerebellum") if split else np.full(len(cb), part == "cerebrum")
214
+
215
+
216
+ @lru_cache(maxsize=1)
217
+ def _mesh() -> tuple[np.ndarray, np.ndarray, np.ndarray]:
218
+ """Surface nets over a grid of GRID cells along BOX's longest side: one vertex per cell
219
+ the surface crosses (the mean of its edge crossings, then projected onto the surface), one
220
+ quad per crossed grid edge, counter-clockwise seen from outside; gradient normals."""
221
+ lo, hi = np.array(BOX[0]), np.array(BOX[1])
222
+ h = float((hi - lo).max()) / GRID
223
+ n = np.ceil((hi - lo) / h).astype(int) + 1
224
+ g = np.stack(np.meshgrid(*(lo[a] + h * np.arange(n[a]) for a in range(3)), indexing="ij"), -1)
225
+ f = _field(g.reshape(-1, 3)).reshape(*n)
226
+ ins = f < 0
227
+ cs = tuple(int(x) for x in n - 1)
228
+ acc, cnt, quads = np.zeros((*cs, 3)), np.zeros(cs), []
229
+ for a in range(3):
230
+ b, c = (a + 1) % 3, (a + 2) % 3
231
+ s0, s1 = [slice(None)] * 3, [slice(None)] * 3
232
+ s0[a], s1[a] = slice(0, -1), slice(1, None)
233
+ f0, f1 = f[tuple(s0)], f[tuple(s1)]
234
+ x = ins[tuple(s0)] != ins[tuple(s1)]
235
+ t = np.where(x, f0 / np.where(x, f0 - f1, 1), 0)
236
+ pt = (g[tuple(s0)] + (t * h)[..., None] * np.eye(3)[a]) * x[..., None]
237
+ for db in (0, 1): # an edge along a belongs to the 4 cells around it
238
+ for dc in (0, 1):
239
+ s = [slice(None)] * 3
240
+ s[b], s[c] = slice(db, db + cs[b]), slice(dc, dc + cs[c])
241
+ acc += pt[tuple(s)]
242
+ cnt += x[tuple(s)]
243
+ e = np.argwhere(x)
244
+ e = e[(e[:, b] >= 1) & (e[:, b] < cs[b]) & (e[:, c] >= 1) & (e[:, c] < cs[c])]
245
+ corners = []
246
+ for ob, oc in ((0, 0), (1, 0), (1, 1), (0, 1)): # counter-clockwise about +a
247
+ k = e.copy()
248
+ k[:, b] += ob - 1
249
+ k[:, c] += oc - 1
250
+ corners.append(np.ravel_multi_index(tuple(k.T), cs))
251
+ q = np.stack(corners, 1)
252
+ quads.append(np.where(ins[tuple(e.T)][:, None], q, q[:, ::-1])) # inside below: faces +a
253
+ act = cnt.ravel() > 0
254
+ vid = np.cumsum(act) - 1
255
+ v = acc.reshape(-1, 3)[act] / cnt.ravel()[act, None]
256
+ for _ in range(2): # onto the surface: Newton steps of at most half a cell
257
+ gr = _grad(v)
258
+ step = (_field(v) / np.maximum((gr * gr).sum(1), 1e-9))[:, None] * gr
259
+ v = v - step * np.minimum(1, 0.5 * h / np.maximum(np.linalg.norm(step, axis=1),
260
+ 1e-12))[:, None]
261
+ q = vid[np.concatenate(quads)]
262
+ return v, _unit(_grad(v)), np.concatenate([q[:, [0, 1, 2]], q[:, [0, 2, 3]]])
263
+
264
+
265
+ # ---- partition -----------------------------------------------------------------------------
266
+
267
+ def _assign(p: np.ndarray, s: np.ndarray, w: np.ndarray):
268
+ """Power-diagram cell of each point and its distance to the nearest border (inf with one
269
+ site); cell -1 with no site."""
270
+ n, k = len(p), len(s)
271
+ if k < 2:
272
+ return np.full(n, 0 if k else -1), np.full(n, np.inf)
273
+ cost = ((p[:, None, :] - s[None]) ** 2).sum(2) - w
274
+ r = np.arange(n)
275
+ a = np.argmin(cost, axis=1)
276
+ c1 = cost[r, a]
277
+ cost[r, a] = np.inf
278
+ a2 = np.argmin(cost, axis=1)
279
+ return a, (cost[r, a2] - c1) / (2 * np.linalg.norm(s[a] - s[a2], axis=1) + 1e-9)
280
+
281
+
282
+ def _capacity(p: np.ndarray, s: np.ndarray, target: np.ndarray, r2: np.ndarray,
283
+ wt: np.ndarray | None = None, rounds: int = 60) -> np.ndarray:
284
+ """Power weights until each site's cell holds about its target count of samples."""
285
+ wt, target = np.zeros(len(s)) if wt is None else wt, np.maximum(target, 1)
286
+ d = ((p[:, None, :] - s[None]) ** 2).sum(2)
287
+ for _ in range(rounds):
288
+ got = np.bincount(np.argmin(d - wt, axis=1), minlength=len(s))
289
+ wt = wt + 0.5 * r2 * np.clip((target - got) / target, -1, 1)
290
+ return wt
291
+
292
+
293
+ def _lloyd(q: np.ndarray, x: np.ndarray, share: np.ndarray, r: np.ndarray,
294
+ aff: np.ndarray) -> np.ndarray:
295
+ """A centroidal capacity-constrained power diagram, on every k-th sample: LLOYD rounds of
296
+ capacity weights, then each site LLOYD_STEP of the way to its cell's centroid (round cells
297
+ instead of the slabs that fixed, crowded sites cut), and each lobe and its TIES most affine
298
+ lobes pulled TIE_PULL of the way back to touching (r_i + r_j apart) when the moves part them
299
+ (plain Lloyd spread the fixture's families of related lobes apart)."""
300
+ sub = q[::max(1, len(q) // 12000)]
301
+ k = len(x)
302
+ a = aff - 2 * np.eye(k)
303
+ near = np.argsort(-a, axis=1, kind="stable")[:, :min(TIES, k - 1)]
304
+ i, j = np.repeat(np.arange(k), near.shape[1]), near.ravel()
305
+ wt = None
306
+ for _ in range(LLOYD):
307
+ wt = _capacity(sub, x, share * len(sub), r ** 2, wt, 20)
308
+ cell = np.argmin(((sub[:, None, :] - x[None]) ** 2).sum(2) - wt, axis=1)
309
+ cnt = np.bincount(cell, minlength=k)
310
+ cen = np.stack([np.bincount(cell, sub[:, c], k) for c in range(3)], 1)
311
+ x = np.where(cnt[:, None] > 0, x + LLOYD_STEP * (cen / np.maximum(cnt, 1)[:, None] - x), x)
312
+ d = x[j] - x[i]
313
+ dist = np.linalg.norm(d, axis=1)
314
+ far = np.maximum(dist - TOUCH * (r[i] + r[j]), 0)
315
+ mv = (TIE_PULL / 2 * far / np.maximum(dist, 1e-9))[:, None] * d
316
+ dx = np.zeros_like(x)
317
+ np.add.at(dx, i, mv)
318
+ np.add.at(dx, j, -mv)
319
+ x = x + dx / np.maximum(np.bincount(np.concatenate([i, j]), minlength=k), 1)[:, None]
320
+ return x
321
+
322
+
323
+ def _mds(dist: np.ndarray, dim: int = 3) -> np.ndarray:
324
+ k = len(dist)
325
+ out = np.zeros((k, dim))
326
+ if k < 2:
327
+ return out
328
+ j = np.eye(k) - 1 / k
329
+ val, vec = np.linalg.eigh(-0.5 * j @ dist ** 2 @ j)
330
+ top = np.argsort(val)[::-1][:dim]
331
+ out[:, :len(top)] = vec[:, top] * np.sqrt(np.maximum(val[top], 0))
332
+ return out
333
+
334
+
335
+ def _spread(x: np.ndarray, r: np.ndarray, pinned: list[int], c: np.ndarray,
336
+ ext: np.ndarray) -> np.ndarray:
337
+ """Push sites apart toward SPREAD x the sum of their region radii, inside FILL of the
338
+ pool's extent `ext` around its centre `c`."""
339
+ free = np.ones(len(x), bool)
340
+ free[pinned] = False
341
+ need = SPREAD * (r[:, None] + r[None])
342
+ np.fill_diagonal(need, 0)
343
+ for _ in range(60):
344
+ d = x[:, None] - x[None]
345
+ dist = np.linalg.norm(d, axis=2)
346
+ np.fill_diagonal(dist, 1)
347
+ push = np.clip(need - dist, 0, None) / dist
348
+ x = x + 0.25 * free[:, None] * (push[..., None] * d).sum(1)
349
+ e = (x - c) / ext
350
+ x = c + ext * e * np.minimum(1, FILL / np.maximum(np.linalg.norm(e, axis=1),
351
+ 1e-9))[:, None]
352
+ return x
353
+
354
+
355
+ def _sites(clusters: list[dict], base: list, ring: np.ndarray, aff: np.ndarray) -> dict:
356
+ """A full relayout of the lobes: {id: {body, site, w}} ({body: "ring"} on the ring)."""
357
+ ids, size = [c["id"] for c in clusters], [c["count"] for c in clusters]
358
+ out = {ids[k]: {"body": "ring"} for k in range(len(ids)) if ring[k]}
359
+ rest = [k for k in range(len(ids)) if not ring[k]]
360
+ groups = {"cerebrum": [k for k in rest if base[k] not in ROUTINES],
361
+ "cerebellum": [k for k in rest if base[k] in ROUTINES]}
362
+ p, cb, vol = _samples()
363
+ for part, ks in groups.items():
364
+ if not ks:
365
+ continue
366
+ q = p[_pool(cb, part, bool(groups["cerebellum"]))]
367
+ ks = sorted(ks, key=lambda k: (-size[k], ids[k]))
368
+ area = np.array([size[k] for k in ks], float) ** AREA_EXP
369
+ share = area / area.sum()
370
+ dist = 1 - aff[np.ix_(ks, ks)]
371
+ np.fill_diagonal(dist, 0)
372
+ x = _mds(dist)[:, [1, 2, 0]] # the widest spread front to back, then across, then up
373
+ x = x * np.where(x[0] < 0, -1, 1) # the biggest lobe toward the front, top and right
374
+ # whitened, then each lobe at its radius rank (uniform in the ball): MDS's few far
375
+ # lobes would otherwise crowd the rest into the centre, and its main axis into slabs
376
+ u = x - x.mean(0)
377
+ u = u / np.maximum(u.std(0), 1e-9)
378
+ rank = np.argsort(np.argsort(np.linalg.norm(u, axis=1), kind="stable"), kind="stable")
379
+ x = _unit(u) * np.cbrt((rank + 0.5) / len(x))[:, None]
380
+ x = x + (np.array([_u(f"site:{ids[k]}", 3) for k in ks]) - 0.5) * 1e-3 # exact ties
381
+ pinned = [j for j, k in enumerate(ks) if base[k] in FRONTAL]
382
+ for t, j in enumerate(pinned):
383
+ x[j] = (0.35 * (t - (len(pinned) - 1) / 2), 0.1, 0.85)
384
+ c, ext = q.mean(0), math.sqrt(5) * q.std(0) # a uniform ellipsoid's semi-axes
385
+ r = (3 * share * len(q) * vol / (4 * np.pi)) ** (1 / 3)
386
+ x = _lloyd(q, _spread(c + x * ext * FILL, r, pinned, c, ext), share, r,
387
+ aff[np.ix_(ks, ks)])
388
+ wt = _capacity(q, x, share * len(q), r ** 2)
389
+ for j, k in enumerate(ks):
390
+ out[ids[k]] = {"body": part, "site": np.round(x[j], 5).tolist(),
391
+ "w": round(float(wt[j]), 6)}
392
+ return out
393
+
394
+
395
+ def _regions(lobes: dict, lid: list[str]):
396
+ """Each pool's (samples, its sited lobe ids, sites, weights, cell of each sample, border
397
+ distance) from the stored sites, and every sample's lobe index (-1 for none)."""
398
+ p, cb, _ = _samples()
399
+ split = any(e["body"] == "cerebellum" for e in lobes.values())
400
+ li = {c: k for k, c in enumerate(lid)}
401
+ geo, lab = {}, np.full(len(p), -1)
402
+ for part in PARTS:
403
+ m = _pool(cb, part, split)
404
+ own = sorted(i for i, e in lobes.items() if e["body"] == part and "site" in e)
405
+ s = np.array([lobes[i]["site"] for i in own], float).reshape(-1, 3)
406
+ wt = np.array([lobes[i]["w"] for i in own], float)
407
+ cell, gap = _assign(p[m], s, wt)
408
+ geo[part] = (p[m], own, s, wt, cell, gap)
409
+ if own:
410
+ lab[m] = np.array([li.get(i, -1) for i in own])[cell]
411
+ return geo, lab
412
+
413
+
414
+ def _adjacent(lab: np.ndarray, nl: int) -> np.ndarray:
415
+ """Lobe pairs whose regions touch: their samples share a voxel, or two face-adjacent
416
+ voxels, of a 32-cube grid over BOX."""
417
+ p = _samples()[0]
418
+ lo, hi = np.array(BOX[0]), np.array(BOX[1])
419
+ g = np.minimum(((p - lo) / (hi - lo) * 32).astype(int), 31)
420
+ ok = lab >= 0
421
+ m = np.zeros((32, 32, 32, nl), np.float32)
422
+ m[g[ok, 0], g[ok, 1], g[ok, 2], lab[ok]] = 1
423
+ a = m.reshape(-1, nl).T @ m.reshape(-1, nl)
424
+ for ax in range(3):
425
+ x = np.moveaxis(m, ax, 0)
426
+ t = x[:-1].reshape(-1, nl).T @ x[1:].reshape(-1, nl)
427
+ a += t + t.T
428
+ np.fill_diagonal(a, 0)
429
+ return a >= 2
430
+
431
+
432
+ # ---- colour --------------------------------------------------------------------------------
433
+
434
+ @lru_cache(maxsize=1 << 12) # a recolour after a lobe reorder asks again for the same shades
435
+ def _hex(light: float, chroma: float, hue: float) -> str:
436
+ """OKLCH to an sRGB hex colour; chroma is reduced until it fits the gamut."""
437
+ a, b = chroma * math.cos(math.radians(hue)), chroma * math.sin(math.radians(hue))
438
+ for _ in range(60):
439
+ lms = (np.array([[1, 0.3963377774, 0.2158037573], [1, -0.1055613458, -0.0638541728],
440
+ [1, -0.0894841775, -1.2914855480]]) @ (light, a, b)) ** 3
441
+ rgb = np.array([[4.0767416621, -3.3077115913, 0.2309699292],
442
+ [-1.2684380046, 2.6097574011, -0.3413193965],
443
+ [-0.0041960863, -0.7034186147, 1.7076147010]]) @ lms
444
+ if rgb.min() >= 0 and rgb.max() <= 1:
445
+ break
446
+ a, b = 0.95 * a, 0.95 * b
447
+ rgb = np.clip(rgb, 0, 1)
448
+ s = np.where(rgb <= 0.0031308, 12.92 * rgb, 1.055 * rgb ** (1 / 2.4) - 0.055)
449
+ return "#" + "".join(f"{round(float(x) * 255):02x}" for x in s)
450
+
451
+
452
+ def _hd(a, b) -> np.ndarray:
453
+ d = np.abs(np.asarray(a, float) - b) % 360
454
+ return np.minimum(d, 360 - d)
455
+
456
+
457
+ _HD = _hd(np.arange(360)[:, None], np.arange(360)) # whole-degree hue distances, row by hue
458
+
459
+
460
+ def _hues(want: np.ndarray, adj: np.ndarray, order: list[int]) -> dict[int, int]:
461
+ """Whole-degree hues, HUE_GAP apart where lobes touch. First a colouring of the touching
462
+ graph with 360 / HUE_GAP evenly spaced hues (the first lobe of `order` at its `want`): DSatur
463
+ with backtracking (most distinct hues among touching lobes first, then most touching
464
+ lobes, then `order`; the hues nearest a lobe's `want` tried first). Should that fail within
465
+ its budget, a greedy pass in the same order takes the hue that falls least short, and
466
+ lobes still short pick again. Then every lobe moves toward `want` as far as its gaps
467
+ allow, HUE_MIN from all other lobes where it can. (Greedy in size order, as v3 did, left
468
+ 35 touching pairs under 60 degrees on the real vault; this leaves none.)"""
469
+ cand, m = np.arange(360), 360 // HUE_GAP
470
+ slot = (round(want[order[0]]) + HUE_GAP * np.arange(m)) % 360 if order else cand
471
+ rank = {k: t for t, k in enumerate(order)}
472
+ deg = {k: int(adj[k, order].sum()) for k in order}
473
+ hue: dict[int, int] = {}
474
+ steps = [0]
475
+
476
+ def nxt(left):
477
+ return max(left, key=lambda k: (len({hue[j] for j in hue if adj[k, j]}), deg[k],
478
+ -rank[k]))
479
+
480
+ def search(left): # shortcut: recursion depth = lobe count, fine below ~900 lobes
481
+ if not left:
482
+ return True
483
+ k = nxt(left)
484
+ used = {hue[j] for j in hue if adj[k, j]}
485
+ for h in sorted((int(h) for h in slot if h not in used),
486
+ key=lambda h: (_hd(h, want[k]), h)):
487
+ steps[0] += 1
488
+ if steps[0] > 20000:
489
+ return False
490
+ hue[k] = h
491
+ if search([j for j in left if j != k]):
492
+ return True
493
+ del hue[k]
494
+ return False
495
+
496
+ def pick(k, apart=False):
497
+ js = [j for j in hue if j != k]
498
+ d = _HD[[hue[j] for j in js]] # whole degrees, so these sums are exact in any order
499
+ every = d.min(0, initial=np.inf)
500
+ short = (np.maximum(HUE_GAP - d, 0) * adj[k, js][:, None]).sum(0)
501
+ off = _hd(cand, want[k])
502
+ ok = short == 0
503
+ if ok.any():
504
+ if apart and (ok & (every >= HUE_MIN)).any():
505
+ ok &= every >= HUE_MIN
506
+ return int(cand[ok][np.argmin(off[ok])])
507
+ return int(cand[np.lexsort((off, short))[0]])
508
+
509
+ if not search(list(order)):
510
+ hue.clear()
511
+ left = list(order)
512
+ while left:
513
+ k = nxt(left)
514
+ left.remove(k)
515
+ hue[k] = pick(k)
516
+ for _ in range(20):
517
+ bad = [k for k in order if any(adj[k, j] and _hd(hue[k], h) < HUE_GAP
518
+ for j, h in hue.items())]
519
+ for k in bad:
520
+ hue[k] = pick(k)
521
+ for _ in range(2):
522
+ for k in order:
523
+ hue[k] = pick(k, True)
524
+ return hue
525
+
526
+
527
+ # ---- vectors, affinity, in-lobe layout -----------------------------------------------------
528
+
529
+ def _stamp(path) -> tuple[int, int] | None:
530
+ try:
531
+ st = path.stat()
532
+ except OSError:
533
+ return None
534
+ return st.st_mtime_ns, st.st_size
535
+
536
+
537
+ def _vectors(root, ids: list[str], memo: dict | None = None
538
+ ) -> tuple[np.ndarray, np.ndarray, bool]:
539
+ """Unit page vectors (each page's head chunk) from the semantic cache, a has-vector mask,
540
+ and whether the cache was readable. `memo` keeps the loaded vectors while the store is
541
+ unchanged."""
542
+ n = len(ids)
543
+ try:
544
+ key = semantic.stamp(root)
545
+ hit = memo.get("vectors") if memo is not None else None
546
+ if hit is None or hit[0] != key or key is None:
547
+ vid, unit = semantic.heads(root) # FileNotFoundError when there is none
548
+ norm = np.linalg.norm(unit, axis=1)
549
+ ok = np.isfinite(norm) & (norm > 0)
550
+ unit[ok] /= norm[ok, None]
551
+ unit[~ok] = 0
552
+ hit = (key, {str(i): k for k, i in enumerate(vid)}, unit, ok)
553
+ if memo is not None:
554
+ memo["vectors"] = hit
555
+ _, row, unit, ok = hit
556
+ g = np.array([row.get(i, -1) for i in ids], dtype=np.int64)
557
+ has = g >= 0
558
+ has[has] = ok[g[has]]
559
+ out = np.zeros((n, unit.shape[1]), np.float32)
560
+ out[has] = unit[g[has]]
561
+ except Exception as e: # a disposable cache: lay the brain out by links instead
562
+ if not isinstance(e, FileNotFoundError):
563
+ log.warning("brain: vector cache unreadable, laying out by links: %s", e)
564
+ return np.zeros((n, 0), np.float32), np.zeros(n, bool), False
565
+ return out, has, True
566
+
567
+
568
+ def _knn(x: np.ndarray, k: int, block: int = 1024) -> tuple[np.ndarray, np.ndarray]:
569
+ """Each row's k nearest other rows by dot product, best first (ties by index)."""
570
+ n = len(x)
571
+ k = max(0, min(k, n - 1))
572
+ idx, sim = np.zeros((n, k), np.int64), np.zeros((n, k), np.float32)
573
+ if not k:
574
+ return idx, sim
575
+ for s in range(0, n, block):
576
+ m = x[s:s + block] @ x.T
577
+ r = np.arange(len(m))
578
+ m[r, s + r] = -np.inf
579
+ part = np.argpartition(-m, k - 1, axis=1)[:, :k]
580
+ val = np.take_along_axis(m, part, 1)
581
+ o = np.lexsort((part, -val), axis=1)
582
+ idx[s:s + block], sim[s:s + block] = (np.take_along_axis(part, o, 1),
583
+ np.take_along_axis(val, o, 1))
584
+ return idx, sim
585
+
586
+
587
+ def _near(memo: dict | None, keys: list[str], x: np.ndarray, k: int) -> np.ndarray:
588
+ """_knn's indices for rows named `keys`. With `memo`, when only a few rows came, went or
589
+ changed vector since the last call, only those and the rows that lost a neighbour are
590
+ searched again; every other row merges its old neighbours with the new rows. Ties are by
591
+ index, as in _knn; a near-tie may order differently from a full search (the dot products
592
+ come from a different matrix product, equal only to the last bit or so)."""
593
+ old = memo.get("knn") if memo is not None else None
594
+ n = len(keys)
595
+ k = max(0, min(k, n - 1))
596
+ fresh = gone = None
597
+ if old is not None and old[0] == k and old[1] == keys and np.array_equal(old[2], x):
598
+ return old[3] # nothing came, went or moved
599
+ if old is not None and old[0] == k and old[2].shape[1] == x.shape[1]:
600
+ okeys, oi = old[1], {key: i for i, key in enumerate(old[1])}
601
+ com = np.array([oi.get(key, -1) for key in keys], np.int64)
602
+ same = com >= 0
603
+ same[same] = (old[2][com[same]] == x[same]).all(1)
604
+ fresh = np.flatnonzero(~same)
605
+ kept = set(com[same].tolist())
606
+ gone = len(okeys) - len(kept)
607
+ if len(fresh) + gone > max(8, n // 50): # many changes: a full search is as cheap
608
+ fresh = None
609
+ if fresh is None:
610
+ idx, sim = _knn(x, k)
611
+ else:
612
+ idx, sim = np.zeros((n, k), np.int64), np.zeros((n, k), np.float32)
613
+ to_new = np.full(len(old[1]), -1, np.int64)
614
+ to_new[com[same]] = np.flatnonzero(same)
615
+ oidx = to_new[old[3][com[same]]] # the kept rows' old neighbours, renumbered
616
+ lost = (oidx < 0).any(1)
617
+ rows = np.flatnonzero(same)
618
+ redo = np.concatenate([fresh, rows[lost]]).astype(np.int64)
619
+ merge = rows[~lost]
620
+ if len(merge):
621
+ ci = np.concatenate([oidx[~lost], np.broadcast_to(fresh, (len(merge), len(fresh)))], 1)
622
+ cs = np.concatenate([old[4][com[merge]], x[merge] @ x[fresh].T], 1)
623
+ o = np.lexsort((ci, -cs), axis=1)[:, :k]
624
+ idx[merge], sim[merge] = np.take_along_axis(ci, o, 1), np.take_along_axis(cs, o, 1)
625
+ for r in redo: # few: one row against all
626
+ s = x @ x[r]
627
+ s[r] = -np.inf
628
+ o = np.lexsort((np.arange(n), -s))[:k]
629
+ idx[r], sim[r] = o, s[o]
630
+ if memo is not None:
631
+ memo["knn"] = (k, list(keys), x.copy(), idx, sim)
632
+ return idx
633
+
634
+
635
+ def _affinity(cent, hasc, links: np.ndarray, pl: np.ndarray, clusters: list[dict]) -> np.ndarray:
636
+ """A = 0.65 cos(centroids) + 0.25 cross-links / max + 0.10 shared parent (same lobe kind)."""
637
+ n = len(clusters)
638
+ cos = cent @ cent.T if cent.shape[1] else np.zeros((n, n))
639
+ known = np.outer(hasc, hasc)
640
+ off = known & ~np.eye(n, dtype=bool)
641
+ cos = np.where(known, cos, cos[off].mean() if off.any() else 0.0)
642
+ x = np.zeros((n, n))
643
+ if len(links):
644
+ la, lb = pl[links[:, 0]], pl[links[:, 1]]
645
+ m = la != lb
646
+ np.add.at(x, (la[m], lb[m]), 1)
647
+ x = x + x.T
648
+ x = x / x.max() if x.max(initial=0) else x
649
+ fam = [{"topic": -1, "domain": -2, "group": -3}.get(c["kind"], k)
650
+ for k, c in enumerate(clusters)] # unfiled and archive share no parent
651
+ return 0.65 * cos + 0.25 * x + 0.10 * np.equal.outer(fam, fam)
652
+
653
+
654
+ def _embed(v: np.ndarray, key: str) -> np.ndarray:
655
+ """A lobe's pages in 3-D: PCA of their vectors, then EPOCHS rounds of relaxation in which
656
+ each page is pulled toward its KNN nearest by cosine (weighted by it) and pushed from NEG
657
+ seeded random pages (UMAP-style)."""
658
+ n = len(v)
659
+ if n < 4:
660
+ return np.eye(3)[:n]
661
+ x = v - v.mean(0)
662
+ if n < x.shape[1]: # PCA scores from the smaller Gram matrix: eigh of 384 x 384 is slow
663
+ val, vec = np.linalg.eigh(x @ x.T)
664
+ y = vec[:, -3:] * np.sqrt(np.maximum(val[-3:], 0))
665
+ else:
666
+ y = x @ np.linalg.eigh(x.T @ x)[1][:, -3:]
667
+ y = (y - y.mean(0)) / (y.std() or 1) * 3
668
+ nb, sim = _knn(v, KNN)
669
+ i, j = np.repeat(np.arange(n), nb.shape[1]), nb.ravel()
670
+ w = np.maximum(sim.ravel(), 0)
671
+ w = w / (w.max() or 1)
672
+ ii = np.repeat(np.arange(n), NEG)
673
+ rng = np.random.default_rng(int.from_bytes(hashlib.blake2b(key.encode(), digest_size=8)
674
+ .digest(), "little"))
675
+ for e in range(EPOCHS):
676
+ d = y[i] - y[j]
677
+ g = np.clip((-2 * w / (1 + (d * d).sum(1)))[:, None] * d, -4, 4)
678
+ jj = rng.integers(0, n, len(ii))
679
+ dn = y[ii] - y[jj]
680
+ d2 = (dn * dn).sum(1)
681
+ gn = np.clip((2 / ((0.001 + d2) * (1 + d2)))[:, None] * dn, -4, 4) * (ii != jj)[:, None]
682
+ dy = np.stack([np.bincount(i, g[:, c], n) - np.bincount(j, g[:, c], n)
683
+ + np.bincount(ii, gn[:, c], n) for c in range(3)], 1)
684
+ y = y + (1 - e / EPOCHS) * dy / nb.shape[1]
685
+ return y
686
+
687
+
688
+ def _msqrt(c: np.ndarray, p: float) -> np.ndarray:
689
+ val, vec = np.linalg.eigh(c)
690
+ return vec @ np.diag(np.maximum(val, 1e-12) ** p) @ vec.T
691
+
692
+
693
+ def _fit(y: np.ndarray, q: np.ndarray) -> np.ndarray:
694
+ """Map a 3-D page layout into a region's samples `q` by matching FIT of their spread
695
+ (mean and covariance): affine, so neighbours stay neighbours; settle() snaps the few
696
+ pages left outside. (Filling the region by radius rank was measured on the real vault:
697
+ 0.65 of the 5 nearest kept, against 0.68 for this.)"""
698
+ mq = q.mean(0)
699
+ if len(y) < 4 or len(q) < 4:
700
+ return mq + (y - y.mean(0)) * 1e-2
701
+ yc = y - y.mean(0)
702
+ return mq + FIT * yc @ _msqrt(np.cov(yc.T), -0.5) @ _msqrt(np.cov((q - mq).T), 0.5)
703
+
704
+
705
+ def _fill(y: np.ndarray, q: np.ndarray, key: str) -> np.ndarray:
706
+ """Move a fitted layout FILL_OT of the way to its sliced optimal transport onto the
707
+ region's samples `q` (seeded rotations; each axis matched by rank to q's quantiles): the
708
+ gaps between the relaxation's clumps close and the lobe fills its round region, while
709
+ neighbours mostly stay neighbours."""
710
+ n = len(y)
711
+ if n < 4 or len(q) < 4:
712
+ return y
713
+ rng = np.random.default_rng(int.from_bytes(hashlib.blake2b(f"fill:{key}".encode(),
714
+ digest_size=8).digest(), "little"))
715
+ at = ((np.arange(n) + 0.5) / n * len(q)).astype(int)
716
+ z = y.copy()
717
+ for _ in range(40):
718
+ rot = np.linalg.qr(rng.normal(size=(3, 3)))[0]
719
+ pz, pq = z @ rot, q @ rot
720
+ o = np.argsort(pz, axis=0, kind="stable")
721
+ dz = np.empty_like(pz)
722
+ np.put_along_axis(dz, o, np.sort(pq, axis=0)[at] - np.take_along_axis(pz, o, 0), 0)
723
+ z = z + dz @ rot.T
724
+ return y + FILL_OT * (z - y)
725
+
726
+
727
+ # ---- persistence ---------------------------------------------------------------------------
728
+
729
+ def _num(x) -> bool:
730
+ return isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x)
731
+
732
+
733
+ def _read_layout(root, memo: dict | None = None) -> tuple[str, dict | None]:
734
+ """The stored layout's text, and the layout when it is valid for these parameters.
735
+ `memo` keeps the parsed layout while its file is unchanged; callers get a copy whose
736
+ `pages` and `lobes` they may change."""
737
+ key = _stamp(root / LAYOUT)
738
+ hit = memo.get("layout") if memo is not None else None
739
+ if hit is None or hit[0] != key or key is None:
740
+ hit = (key, *_parse_layout(root))
741
+ if memo is not None:
742
+ memo["layout"] = hit
743
+ text, st = hit[1], hit[2]
744
+ return text, st and {**st, "pages": dict(st["pages"]), "lobes": dict(st["lobes"])}
745
+
746
+
747
+ def _parse_layout(root) -> tuple[str, dict | None]:
748
+ try:
749
+ text = (root / LAYOUT).read_text(encoding="utf-8")
750
+ st = json.loads(text)
751
+ except (OSError, ValueError):
752
+ return "", None
753
+ ok = (isinstance(st, dict) and st.get("version") == VERSION
754
+ and st.get("params_hash") == PARAMS_HASH
755
+ and isinstance(st.get("pages"), dict) and isinstance(st.get("lobes"), dict)
756
+ and all(isinstance(v, list) and len(v) == 5 and all(map(_num, v[:3]))
757
+ and isinstance(v[3], str) and v[4] in (0, 1) for v in st["pages"].values())
758
+ and all(isinstance(e, dict) for e in st["lobes"].values()))
759
+ sited = ok and {i: e["body"] for i, e in st["lobes"].items() if e.get("body") in PARTS
760
+ and isinstance(e.get("site"), list) and len(e["site"]) == 3
761
+ and all(map(_num, e["site"])) and _num(e.get("w"))}
762
+ ok = ok and all(e.get("body") == "ring" or i in sited or (
763
+ isinstance(e.get("host"), str) and sited.get(e["host"]) == e.get("body"))
764
+ for i, e in st["lobes"].items())
765
+ return text, st if ok else None
766
+
767
+
768
+ def _now() -> str:
769
+ """An `added` stamp: UTC to the millisecond, as JavaScript's toISOString writes it."""
770
+ return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
771
+
772
+
773
+ def _recent(added: dict) -> dict:
774
+ """The `added` stamps of the last ADDED_DAYS days, for the blob."""
775
+ cut = (datetime.now(UTC) - timedelta(days=ADDED_DAYS)).strftime("%Y-%m-%dT%H:%M:%S")
776
+ return {i: v for i, v in added.items() if v >= cut}
777
+
778
+
779
+ def _day(s) -> int:
780
+ """A date string's day number; 0 when it has none."""
781
+ try:
782
+ return date.fromisoformat(str(s)[:10]).toordinal()
783
+ except ValueError:
784
+ return 0
785
+
786
+
787
+ def _b64(a, dtype: str) -> str:
788
+ return base64.b64encode(np.ascontiguousarray(a, dtype=dtype).tobytes()).decode("ascii")
789
+
790
+
791
+ def _r(v, nd=4) -> list[float]:
792
+ return [round(float(x), nd) for x in v]
793
+
794
+
795
+ @lru_cache(maxsize=1)
796
+ def _mesh_b64() -> tuple[str, str, str]:
797
+ vp, vn, tri = _mesh()
798
+ return _b64(vp, "<f4"), _b64(vn, "<f4"), _b64(tri, "<u4")
799
+
800
+
801
+ def _sited(lobes: dict, memo: dict | None = None):
802
+ """What the sites alone decide, whatever the lobes' order: `_regions` over every stored
803
+ lobe id (sorted), each pool's cell of every mesh vertex, which lobes touch, and a dict that
804
+ `_geometry` fills with each lobe's own region and centre. `memo` keeps it while the stored
805
+ lobes stay the same (a lobe's page count reorders the lobes)."""
806
+ key = json.dumps(lobes, sort_keys=True)
807
+ hit = memo.get("sited") if memo is not None else None
808
+ if hit is None or hit[0] != key:
809
+ ids = sorted(lobes)
810
+ geo, lab = _regions(lobes, ids)
811
+ vp = _mesh()[0]
812
+ split = any(e["body"] == "cerebellum" for e in lobes.values())
813
+ vcb = np.argmin(_parts(vp), 1) == 4
814
+ cells = {}
815
+ for part in PARTS:
816
+ _, own, s, wt, _, _ = geo[part]
817
+ m = _pool(vcb, part, split)
818
+ if own and m.any():
819
+ cells[part] = (m, _assign(vp[m], s, wt)[0])
820
+ touch = _adjacent(lab, len(ids)) if ids else np.zeros((0, 0), bool)
821
+ hit = (key, {i: k for k, i in enumerate(ids)}, geo, cells, touch, {})
822
+ if memo is not None:
823
+ memo["sited"] = hit
824
+ return hit[1:]
825
+
826
+
827
+ def _geometry(lobes: dict, lid: list[str], kind: list[str], memo: dict | None = None):
828
+ """What the stored lobes alone decide: each sited lobe's region (pool, cell index, the
829
+ pool's sites and weights, interior samples), the lobes' centres, anchors, normals and areas,
830
+ the mesh (each vertex takes the lobe of its region in its pool) and the lobe colours."""
831
+ nl = len(lid)
832
+ li = {c: k for k, c in enumerate(lid)}
833
+ ring = np.array([lobes[i]["body"] == "ring" for i in lid], bool)
834
+ at, geo, cells, touch, own_part = _sited(lobes, memo)
835
+
836
+ def placed(i): # a sited lobe's region, centre, anchor, normal and area, whatever the order
837
+ if i not in own_part:
838
+ e = lobes[i]
839
+ q, own, s, wt, cell, gap = geo[e["body"]]
840
+ j = own.index(e.get("host", i))
841
+ m = cell == j
842
+ inner = m & (gap >= GAP)
843
+ q = q[inner if inner.any() else m]
844
+ q = q if len(q) else s[j:j + 1]
845
+ c = np.asarray(q.mean(0), float)
846
+ a = np.asarray(q[np.argmin(((q - c) ** 2).sum(1))], float)
847
+ own_part[i] = ((e["body"], j, s, wt, q), c, a, _unit(a),
848
+ 0 if "host" in e else (cell == j).sum() / SAMPLES)
849
+ return own_part[i]
850
+
851
+ regions = {k: placed(lid[k])[0] for k in range(nl) if not ring[k]}
852
+ centre, anchor, normal, area = (np.zeros((nl, 3)), np.zeros((nl, 3)), np.zeros((nl, 3)),
853
+ np.zeros(nl))
854
+ for k in range(nl):
855
+ if ring[k]:
856
+ centre[k], anchor[k], normal[k] = (0, RING_Y, 0), (0, RING_Y, RING_R), (0, 0, 1)
857
+ continue
858
+ _, centre[k], anchor[k], normal[k], area[k] = placed(lid[k])
859
+
860
+ vl = np.full(len(_mesh()[0]), 65535)
861
+ for part, (m, cell) in cells.items():
862
+ vl[m] = np.array([li.get(i, 65535) for i in geo[part][1]])[cell]
863
+ pos, nrm, idx = _mesh_b64()
864
+ mesh = [{"name": "brain", "pos": pos, "nrm": nrm, "idx": idx, "lobe": _b64(vl, "<u2")}]
865
+
866
+ # colours: hue from the site's direction around the vertical axis, apart where regions touch
867
+ perm = [at[i] for i in lid] # touching is pairwise: the stored lobes' matrix, in lid order
868
+ adj = touch[np.ix_(perm, perm)] if nl else np.zeros((0, 0), bool)
869
+ for k in range(nl): # a guest touches its host and the host's neighbours
870
+ h = li.get(lobes[lid[k]].get("host"))
871
+ if h is not None:
872
+ adj[k] |= adj[h]
873
+ adj[:, k] |= adj[:, h]
874
+ adj[k, h] = adj[h, k] = True
875
+ adj[k, k] = False
876
+ tinted = [k for k in range(nl) if not ring[k] and kind[k] in ("topic", "domain", "group")]
877
+ angle, mid = {}, {}
878
+ for k in tinted:
879
+ e = lobes[lid[k]]
880
+ if e["body"] not in mid:
881
+ mid[e["body"]] = geo[e["body"]][0].mean(0)
882
+ site, c = np.array(lobes[e.get("host", lid[k])]["site"]), mid[e["body"]]
883
+ angle[k] = (math.degrees(math.atan2(site[2] - c[2], site[0] - c[0]))
884
+ + (1e-3 if "host" in e else 0)) % 360
885
+ # spread over the whole wheel in the same circular order, the biggest lobe at its angle
886
+ order = sorted(tinted, key=lambda k: (angle[k], k))
887
+ want = np.zeros(nl)
888
+ for t, k in enumerate(order):
889
+ want[k] = (angle[tinted[0]] + 360 * (t - order.index(tinted[0])) / len(order)) % 360
890
+ hue = _hues(want, adj, tinted)
891
+ color: list[str] = []
892
+ for k in range(nl):
893
+ light, chroma = ((0.74, 0.07 if kind[k] == "group" else 0.19) if k in hue
894
+ else (0.55 if ring[k] else 0.70, 0))
895
+ c = _hex(light, chroma, hue.get(k, 0))
896
+ while c in color: # a hue shared by lobes that do not touch: a shade darker
897
+ light -= 0.03
898
+ c = _hex(light, chroma, hue.get(k, 0))
899
+ color.append(c)
900
+ return regions, centre, anchor, normal, area, mesh, color
901
+
902
+
903
+ # ---- the blob ------------------------------------------------------------------------------
904
+
905
+ def build(vault, pages: list[dict], clusters: list[dict], relayout: bool = False,
906
+ auto_relayout: bool = True, memo: dict | None = None) -> dict:
907
+ """The dashboard's `brain` key for build_data's pages and
908
+ lobes; reads and, when it changed, rewrites `.keepfold/brain-layout.json`.
909
+ `auto_relayout=False` (the app's live home) never lays the brain out again by itself,
910
+ however much changed: placed pages keep their place and new ones join their neighbours;
911
+ `relayout` still does. `memo` is a dict the caller keeps between builds: the same inputs
912
+ then give the same blob object, and the vector cache, the parsed layout, the lobe geometry
913
+ and the nearest-page search are reused while their inputs stay the same."""
914
+ root, n, nl = vault.root, len(pages), len(clusters)
915
+ inputs = None
916
+ if memo is not None and not relayout:
917
+ inputs = (auto_relayout, json.dumps(clusters, sort_keys=True),
918
+ [(p["id"], p["cluster"], p["updated"], p["links"]) for p in pages],
919
+ semantic.stamp(root), _stamp(root / LAYOUT))
920
+ if memo.get("inputs") == inputs:
921
+ return memo["out"]
922
+ ids = [p["id"] for p in pages]
923
+ at = {i: k for k, i in enumerate(ids)}
924
+ lid = [c["id"] for c in clusters]
925
+ li = {c: k for k, c in enumerate(lid)}
926
+ pl = np.array([li[p["cluster"]] for p in pages], dtype=np.int64)
927
+ vec, has, vec_ok = _vectors(root, ids, memo)
928
+ ea = np.array([(a, at[x]) for a, p in enumerate(pages) for x in p["links"] if x in at],
929
+ dtype=np.int64).reshape(-1, 2)
930
+ links = np.unique(np.sort(ea[ea[:, 0] != ea[:, 1]], axis=1), axis=0).reshape(-1, 2)
931
+ deg = np.bincount(links.ravel(), minlength=n)
932
+ nbrs: list[list[int]] = [[] for _ in range(n)]
933
+ for a, b in links.tolist():
934
+ nbrs[a].append(b)
935
+ nbrs[b].append(a)
936
+ base = [c["id"].removesuffix("-group") if c["kind"] == "group" else None for c in clusters]
937
+ ring = np.array([c["kind"] == "archive" or b in ARCHIVE for c, b in zip(clusters, base,
938
+ strict=True)], bool)
939
+ hr = np.flatnonzero(has)
940
+ hr = hr[np.argsort(pl[hr], kind="stable")]
941
+ # a lobe's sum depends only on its pages' vectors in page order: `memo` keeps it by lobe id
942
+ stamp = vec_ok and memo["vectors"][0] if memo is not None else None
943
+ was, sums = (memo.get("cent", {}) if memo is not None else {}), {}
944
+ cent = np.zeros((nl, vec.shape[1]), np.float32)
945
+ lk, cut = np.unique(pl[hr], return_index=True)
946
+ ends = [*cut.tolist(), len(hr)]
947
+ for j, k in enumerate(lk.tolist()): # in page order, bit for bit as np.add.at summed
948
+ rows = hr[ends[j]:ends[j + 1]]
949
+ key = (stamp, [ids[r] for r in rows])
950
+ got = was.get(lid[k])
951
+ if got is None or got[0] != key:
952
+ got = (key, np.cumsum(vec[rows], axis=0)[-1])
953
+ sums[lid[k]] = got
954
+ cent[k] = got[1]
955
+ if memo is not None:
956
+ memo["cent"] = sums
957
+ hasc = np.linalg.norm(cent, axis=1) > 0
958
+ cent = _unit(cent) * hasc[:, None]
959
+ aff = _affinity(cent, hasc, links, pl, clusters)
960
+
961
+ old_text, st = _read_layout(root, memo)
962
+ # when each page first entered the layout: none for an old layout's pages or a first layout
963
+ had = set(st["pages"]) if st is not None else None
964
+ was_added = st.get("added") if st is not None else None
965
+ if not isinstance(was_added, dict):
966
+ was_added = {}
967
+ was_added = {i: v for i, v in was_added.items() if isinstance(v, str)}
968
+ plid = [lid[k] for k in pl.tolist()] # each page's lobe id
969
+ hasl = has.tolist()
970
+ changed = n if st is None else sum(
971
+ 1 for k, i in enumerate(ids) if (s := st["pages"].get(i)) is None
972
+ or s[3] != plid[k] or (hasl[k] and not s[4]))
973
+ full = relayout or st is None or (auto_relayout and changed > RELAYOUT_SHARE * n)
974
+ if full:
975
+ st = {"version": VERSION, "params_hash": PARAMS_HASH, "pages": {},
976
+ "lobes": _sites(clusters, base, ring, aff)}
977
+ else:
978
+ st["pages"] = {i: s for k, i in enumerate(ids)
979
+ if (s := st["pages"].get(i)) and s[3] == plid[k]}
980
+ lobes = st["lobes"]
981
+ for k in range(nl): # a lobe new since the last layout: a guest in its most affine region
982
+ if lid[k] in lobes:
983
+ continue
984
+ owners = [h for h in range(nl) if "site" in lobes.get(lid[h], {})]
985
+ sited = sorted(i for i, e in lobes.items() if "site" in e)
986
+ if ring[k] or not sited:
987
+ lobes[lid[k]] = {"body": "ring"}
988
+ else:
989
+ host = lid[max(owners, key=lambda h: (aff[k, h], -h))] if owners else sited[0]
990
+ lobes[lid[k]] = {"body": lobes[host]["body"], "host": host}
991
+ ring_k = ring # the lobe's kind; where it sits is the stored body
992
+ ring = np.array([lobes[i]["body"] == "ring" for i in lid], bool)
993
+ kind = [c["kind"] for c in clusters]
994
+ gkey = json.dumps([lobes, lid, kind], sort_keys=True)
995
+ hit = memo.get("geometry") if memo is not None else None
996
+ if hit is None or hit[0] != gkey:
997
+ hit = (gkey, _geometry(lobes, lid, kind, memo))
998
+ if memo is not None:
999
+ memo["geometry"] = hit
1000
+ regions, centre, anchor, normal, area, mesh, color = hit[1]
1001
+ vol = _samples()[2]
1002
+
1003
+ # place every page that has no stored position
1004
+ pos = np.full((n, 3), np.nan)
1005
+ if st["pages"]:
1006
+ pos[[at[i] for i in st["pages"]]] = [s[:3] for s in st["pages"].values()]
1007
+
1008
+ def jitter(rows, tag, size):
1009
+ return (np.array([_u(f"{tag}:{ids[r]}", 3) for r in rows]).reshape(-1, 3) - 0.5) * size
1010
+
1011
+ def settle(k, pts, rows):
1012
+ """Into lobe k's region: points outside it, near a border or near the surface snap
1013
+ to its nearest interior sample."""
1014
+ _, j, s, wt, q = regions[k]
1015
+ pts = np.array(pts, float)
1016
+ cell, gap = _assign(pts, s, wt)
1017
+ bad = np.flatnonzero((cell != j) | (gap < GAP / 2) | (_field(pts) > -MARGIN / 2))
1018
+ if len(bad):
1019
+ near = np.argmin((q * q).sum(1)[None] - 2 * pts[bad] @ q.T, axis=1)
1020
+ pts[bad] = q[near] + jitter([rows[i] for i in bad], "snap", 0.6 * GAP)
1021
+ pos[rows] = np.round(pts, 5)
1022
+
1023
+ def spacing(k):
1024
+ return (max(area[k] * SAMPLES * vol, 1e-6) / max(clusters[k]["count"], 1)) ** (1 / 3)
1025
+
1026
+ cand = ([k for k in range(nl) if not ring[k] and hasc[k]
1027
+ and clusters[k]["kind"] in ("topic", "domain")]
1028
+ or [k for k in range(nl) if not ring[k] and hasc[k]])
1029
+
1030
+ def beacons(r):
1031
+ if not has[r] or not cand:
1032
+ return []
1033
+ sims = cent[cand] @ vec[r]
1034
+ return [cand[t] for t in sorted(range(len(cand)), key=lambda t: (-sims[t], t))[:N_BEACONS]]
1035
+
1036
+ big = max(float(np.quantile(deg, 1 - VAULT_HUBS)), 1) if n else 1 # the vault's top hubs
1037
+ later = []
1038
+ for k in range(nl):
1039
+ rows = np.flatnonzero((pl == k) & np.isnan(pos[:, 0])).tolist()
1040
+ if not rows:
1041
+ continue
1042
+ if ring[k]:
1043
+ for r in rows:
1044
+ u = _u(f"ring:{ids[r]}", 4)
1045
+ bl = beacons(r)
1046
+ if bl:
1047
+ wgt = np.exp(20 * (cent[bl] @ vec[r] - 1))
1048
+ a = math.atan2(float(wgt @ anchor[bl, 0]), float(wgt @ anchor[bl, 2]))
1049
+ else:
1050
+ a = 2 * math.pi * u[3]
1051
+ a += (u[0] - 0.5) * 0.3
1052
+ rho, phi = RING_W * math.sqrt(u[1]), 2 * math.pi * u[2] # in the band's section
1053
+ rr, y = RING_R + rho * math.cos(phi), RING_Y + rho * math.sin(phi)
1054
+ while _field(np.array([[rr * math.sin(a), y, rr * math.cos(a)]]))[0] < MARGIN:
1055
+ y -= MARGIN # clear of the cerebellum
1056
+ pos[r] = np.round((rr * math.sin(a), y, rr * math.cos(a)), 5)
1057
+ continue
1058
+ emb = [r for r in rows if has[r]]
1059
+ later += [r for r in rows if not has[r]]
1060
+ own_placed = ((pl == k) & has & ~np.isnan(pos[:, 0])).any()
1061
+ if emb and "host" not in lobes[lid[k]] and not own_placed:
1062
+ q = regions[k][4] # a fresh region: the lobe's map, filling it
1063
+ y = _fill(_fit(_embed(vec[emb], lid[k]), q), q, lid[k])
1064
+ rank = sorted(range(len(emb)), key=lambda t: (-deg[emb[t]], ids[emb[t]]))
1065
+ hubs = [t for i, t in enumerate(rank) if deg[emb[t]] > 0
1066
+ and (i < math.ceil(HUBS * len(emb)) or deg[emb[t]] >= big)]
1067
+ if hubs: # the nucleus: the more links, the nearer the centre
1068
+ d = np.log1p(deg[[emb[t] for t in hubs]])
1069
+ y[hubs] += (HUB_PULL * d / d.max())[:, None] * (centre[k] - y[hubs])
1070
+ settle(k, y, emb)
1071
+ continue
1072
+ host = li.get(lobes[lid[k]].get("host"), k)
1073
+ for r in emb: # next to its 3 nearest placed neighbours by vector, inside its lobe
1074
+ pool = np.flatnonzero((pl == k) & has & ~np.isnan(pos[:, 0]))
1075
+ if not len(pool):
1076
+ pool = np.flatnonzero((pl == host) & has & ~np.isnan(pos[:, 0]))
1077
+ if not len(pool):
1078
+ later.append(r)
1079
+ continue
1080
+ sims = vec[pool] @ vec[r]
1081
+ best = sorted(range(len(pool)), key=lambda t: (-sims[t], t))[:3]
1082
+ wgt = np.exp(50 * (sims[best] - sims[best[0]])) # the closest in meaning weighs most
1083
+ pt = wgt @ pos[[pool[t] for t in best]] / wgt.sum()
1084
+ settle(k, pt[None] + jitter([r], "new", 0.3 * spacing(k)), [r])
1085
+ for r in sorted(later, key=lambda r: (-deg[r], ids[r])): # by links, else a seeded spot
1086
+ k = pl[r]
1087
+ placed = [x for x in nbrs[r] if not np.isnan(pos[x, 0])]
1088
+ if placed:
1089
+ pt = pos[placed].mean(0) + jitter([r], "link", 0.5 * spacing(k))[0]
1090
+ else:
1091
+ q = regions[k][4]
1092
+ pt = q[int(_u(f"seed:{ids[r]}", 1)[0] * len(q))] + jitter([r], "seed", 0.5 * GAP)[0]
1093
+ settle(k, pt[None], [r])
1094
+
1095
+ for k, i in enumerate(ids):
1096
+ if i not in st["pages"]:
1097
+ st["pages"][i] = [*(float(x) for x in pos[k]), lid[pl[k]], int(has[k])]
1098
+ now = _now() if had is not None and any(i not in had for i in ids) else None
1099
+ st["added"] = {i: v for i in ids if (v := was_added.get(i) or (
1100
+ now if had is not None and i not in had else None))}
1101
+ text = json.dumps(st, sort_keys=True, separators=(",", ":"))
1102
+ if text != old_text:
1103
+ try:
1104
+ vault.write_text(root / LAYOUT, text)
1105
+ if memo is not None: # what was just written is what the next build reads
1106
+ memo["layout"] = (_stamp(root / LAYOUT), text, st)
1107
+ except (VaultError, OSError) as e: # a view cache: the next build lays it out again
1108
+ log.warning("brain layout not saved: %s", e)
1109
+
1110
+ # depth inside the surface as placed; 0 on the ring
1111
+ dep = np.zeros(n)
1112
+ keepfold = ~ring[pl] if n else np.zeros(0, bool)
1113
+ if keepfold.any():
1114
+ dep[keepfold] = np.maximum(-_field(pos[keepfold]), 0)
1115
+
1116
+ wide = n >= 65535
1117
+ none = 0xFFFFFFFF if wide else 65535
1118
+ near = np.full((n, N_NEAR), none, np.int64)
1119
+ emb = np.flatnonzero(has)
1120
+ nb = _near(memo, [ids[r] for r in emb], vec[emb], N_NEAR)
1121
+ near[emb, :nb.shape[1]] = emb[nb]
1122
+
1123
+ # fibres: every link, then each embedded page's nearest by meaning that is not a link
1124
+ sb = near[emb, :N_SIMILAR]
1125
+ sa, sb = np.repeat(emb, sb.shape[1]), sb.ravel()
1126
+ sa, sb = sa[sb != none], sb[sb != none]
1127
+ pair = np.minimum(sa, sb) * max(n, 1) + np.maximum(sa, sb)
1128
+ pair[np.isin(pair, links[:, 0] * max(n, 1) + links[:, 1])] = -1
1129
+ first = np.sort(np.unique(pair, return_index=True)[1]) # a pair's first sighting only
1130
+ first = first[pair[first] >= 0]
1131
+ sa, sb = sa[first], sb[first]
1132
+ fa = np.concatenate([links[:, 0], sa]).astype(np.int64)
1133
+ fb = np.concatenate([links[:, 1], sb]).astype(np.int64)
1134
+ home = np.where(ring[pl][:, None], pos, centre[pl]) if n else pos # ring ends: no pull
1135
+ mid = (pos[fa] + pos[fb]) / 2
1136
+ seed = np.array([_u(f"fibre:{i}", 6) for i in ids]).reshape(-1, 6) # a pair's: both ends'
1137
+ ctrl = (mid + PULL * ((home[fa] + home[fb]) / 2 - mid)
1138
+ + ((seed[fa, :3] + seed[fb, 3:]) % 1 - 0.5) * 2 * JITTER)
1139
+ fibres = {"a": _b64(fa, "<u4"), "b": _b64(fb, "<u4"), "c": _b64(ctrl, "<f4"),
1140
+ "k": _b64([0] * len(links) + [1] * len(sa), "u1")}
1141
+
1142
+ # node weight for the renderer's size: links, similar-meaning fibres, recency of `updated`
1143
+ sdeg = np.bincount(np.concatenate([sa, sb]).astype(np.int64), minlength=n)
1144
+ day = np.array([_day(p.get("updated")) for p in pages], float)
1145
+ recent = np.exp((day - day.max()) / RECENT) if n else day
1146
+ weight = (0.6 * np.log1p(deg) / max(math.log1p(deg.max(initial=0)), 1e-9)
1147
+ + 0.25 * np.log1p(sdeg) / max(math.log1p(sdeg.max(initial=0)), 1e-9)
1148
+ + 0.15 * recent)
1149
+
1150
+ cross: dict = {}
1151
+ for la, lb in np.sort(pl[links], axis=1).tolist():
1152
+ if la != lb and not ring[la] and not ring[lb]:
1153
+ cross[la, lb] = cross.get((la, lb), 0) + 1
1154
+ tracts = []
1155
+ for (a, b), cnt in sorted(cross.items(), key=lambda t: (-t[1], t[0]))[:N_TRACTS]:
1156
+ if cnt < 2:
1157
+ break
1158
+ p1, p2 = (anchor[a] + (anchor[b] - anchor[a]) * t for t in (1 / 3, 2 / 3))
1159
+ tracts.append({"a": a, "b": b, "n": cnt, "p": [
1160
+ _r(anchor[a]), _r(0.55 * p1), _r(0.55 * p2), _r(anchor[b])]}) # 45 % toward the centre
1161
+
1162
+ out = {
1163
+ "version": VERSION,
1164
+ "legend": LEGEND,
1165
+ "nodes": {"ids": ids, "xyz": _b64(pos, "<f4"), "lobe": _b64(pl, "<u2"),
1166
+ "depth": _b64(dep, "<f4"), "embedded": _b64(has, "u1"),
1167
+ "weight": _b64(np.clip(weight, 0, 1), "<f4"),
1168
+ "added": _recent(st["added"])},
1169
+ "lobes": [{"id": c["id"], "title": c["title"], "kind": c["kind"], "count": c["count"],
1170
+ "anchor": _r(anchor[k]), "normal": _r(normal[k]), "centre": _r(centre[k]),
1171
+ "color": color[k], "archive": bool(ring_k[k]),
1172
+ "area": round(float(area[k]), 4)} for k, c in enumerate(clusters)],
1173
+ "mesh": mesh,
1174
+ "fibres": fibres,
1175
+ "tracts": tracts,
1176
+ "near": {"ids": _b64(near, "<u4" if wide else "<u2")},
1177
+ "beacons": {str(r): bl for r in np.flatnonzero(ring[pl]).tolist() if (bl := beacons(r))},
1178
+ "stats": {"embedded": int(has.sum()), "unembedded": int(n - has.sum()),
1179
+ "relayout": bool(full), "vectors": vec_ok},
1180
+ }
1181
+ if inputs is not None: # the layout as it is now on disk: this build may have written it
1182
+ memo["inputs"], memo["out"] = (*inputs[:4], _stamp(root / LAYOUT)), out
1183
+ return out
1184
+
1185
+
1186
+ # ---- the brain stem: the owner's websites (the app's live home only) ----------------------
1187
+
1188
+ STEM_COL, STEM_R = ((0.0, -0.92, -0.36), (0.0, -1.66, -0.36)), 0.05 # the sites' column below
1189
+ # the shell (top: first seen, bottom: newest) and their farthest distance from its axis
1190
+ STEM_TUBE = ((0.0, -0.70, -0.36), (0.0, -1.74, -0.36), 0.085, 0.06) # the faint tube drawn
1191
+ # round them: from inside the stem capsule down past the column's end; top and bottom radii
1192
+ STEM_LINKS, HUB_SITES = 3, 10 # fibres per site at most; sites tied to one topic hub page at most
1193
+ _CATS = (*lists.SITE_CATEGORIES, *lists.CATEGORIES)
1194
+
1195
+
1196
+ @lru_cache(maxsize=64)
1197
+ def site_color(category: str | None) -> str:
1198
+ """A site category's colour: a golden-angle hue by its place in the category lists, so
1199
+ neighbouring categories differ; "other" and unknown ones are grey."""
1200
+ if category not in _CATS or category == "other":
1201
+ return _hex(0.70, 0, 0)
1202
+ return _hex(0.74, 0.15, (_CATS.index(category) * 137.508 + 20) % 360)
1203
+
1204
+
1205
+ def stem_order(rows: list[dict], placed: dict) -> None:
1206
+ """Give each site of `rows` ({site, first}) missing from `placed` its share (0-1) of the
1207
+ stem's axis, ordered by first seen: with nothing placed, its rank among `rows`; after
1208
+ that, interpolated between the placed sites by its first visit, so nothing placed moves
1209
+ (a site newer than all sits at the newest end). `placed`: {site: (first, share)}."""
1210
+ new = [r for r in rows if r["site"] not in placed]
1211
+ if not new:
1212
+ return
1213
+ if not placed:
1214
+ order = sorted(new, key=lambda r: (r["first"] or 0, r["site"]))
1215
+ placed.update({r["site"]: (r["first"] or 0, (k + 0.5) / len(order))
1216
+ for k, r in enumerate(order)})
1217
+ return
1218
+ have = sorted(placed.values())
1219
+ xs, ts = np.array([f for f, _ in have], float), np.array([t for _, t in have])
1220
+ for r in new:
1221
+ placed[r["site"]] = (r["first"] or 0, float(np.interp(r["first"] or 0, xs, ts)))
1222
+
1223
+
1224
+ def stem_xyz(sites: list[str], share: list[float]) -> np.ndarray:
1225
+ """Each site's point in the stem's column (STEM_COL) below the shell: down the axis by
1226
+ its share, round it at a seeded angle and radius (even over the cross-section)."""
1227
+ a, b = np.array(STEM_COL[0]), np.array(STEM_COL[1])
1228
+ ax = _unit(b - a)
1229
+ e1 = _unit(np.cross(ax, (1.0, 0.0, 0.0)))
1230
+ e2 = np.cross(ax, e1)
1231
+ u = np.array([_u(f"stem:{s}", 3) for s in sites]).reshape(-1, 3)
1232
+ s = np.clip(np.asarray(share, float) + (u[:, 2] - 0.5) * 0.01, 0, 1)
1233
+ axis = a + s[:, None] * (b - a)
1234
+ ang, rad = 2 * np.pi * u[:, 1], STEM_R * np.sqrt(u[:, 0])
1235
+ return axis + rad[:, None] * (np.cos(ang)[:, None] * e1 + np.sin(ang)[:, None] * e2)
1236
+
1237
+
1238
+ @lru_cache(maxsize=1)
1239
+ def stem_tube() -> dict:
1240
+ """The mesh body (`build`'s mesh format, named "stem", no lobe) of the tube round the
1241
+ stem's column: a tapered cylinder (STEM_TUBE) with a rounded bottom and an open top
1242
+ inside the stem capsule."""
1243
+ a, b, r0, r1 = np.array(STEM_TUBE[0]), np.array(STEM_TUBE[1]), *STEM_TUBE[2:]
1244
+ around, length = 24, float(np.linalg.norm(b - a))
1245
+ prof = [(t * length, r0 + (r1 - r0) * t) for t in np.linspace(0, 1, 14)] # (depth, radius)
1246
+ prof += [(length + r1 * math.sin(q), r1 * math.cos(q)) for q in np.linspace(0.3, 1.35, 5)]
1247
+ ax = _unit(b - a)
1248
+ e1 = _unit(np.cross(ax, (1.0, 0.0, 0.0)))
1249
+ e2 = np.cross(ax, e1)
1250
+ ang = 2 * np.pi * np.arange(around) / around
1251
+ rim = np.cos(ang)[:, None] * e1 + np.sin(ang)[:, None] * e2 # unit, round the axis
1252
+ pos, nrm = [], []
1253
+ for k, (d, r) in enumerate(prof):
1254
+ d0, ra = prof[max(k - 1, 0)]
1255
+ d1, rb = prof[min(k + 1, len(prof) - 1)]
1256
+ tn = np.array([d1 - d0, ra - rb]) # the profile's outward normal: (out, along)
1257
+ tn /= np.linalg.norm(tn)
1258
+ pos.append(a + ax * d + rim * r)
1259
+ nrm.append(rim * tn[0] + ax * tn[1])
1260
+ pos.append((a + ax * (length + r1))[None])
1261
+ nrm.append(ax[None])
1262
+ idx = []
1263
+ for k in range(len(prof) - 1):
1264
+ for j in range(around):
1265
+ p, q = k * around + j, k * around + (j + 1) % around
1266
+ idx += [p, q + around, q, p, p + around, q + around]
1267
+ pole, base = len(prof) * around, (len(prof) - 1) * around
1268
+ for j in range(around):
1269
+ idx += [base + j, pole, base + (j + 1) % around]
1270
+ vp = np.concatenate(pos)
1271
+ return {"name": "stem", "pos": _b64(vp, "<f4"), "nrm": _b64(np.concatenate(nrm), "<f4"),
1272
+ "idx": _b64(np.array(idx), "<u4"), "lobe": _b64(np.full(len(vp), 65535), "<u2")}
1273
+
1274
+
1275
+ def _stem_links(sites: list[dict], hub_at: dict[str, int], first: int) -> list[tuple[int, int]]:
1276
+ """The stem's fibres as node pairs (sites are `first` + their index): first each site up
1277
+ to its biggest topic hub's page (a hub takes its HUB_SITES most visited sites), then
1278
+ between similar sites: the related ones the store keeps, then the neighbours in
1279
+ first-seen order that share its biggest hub, then its category. Most visited sites
1280
+ choose first; no site gets more than STEM_LINKS."""
1281
+ n = len(sites)
1282
+ deg, pairs, out, per_hub = [0] * n, set(), [], {}
1283
+ order = sorted(range(n), key=lambda k: (-sites[k]["visits"], sites[k]["site"]))
1284
+ for k in order:
1285
+ hub = next((h for h, _ in sites[k]["hubs"] if h in hub_at), None)
1286
+ if hub is not None and per_hub.get(hub, 0) < HUB_SITES:
1287
+ per_hub[hub] = per_hub.get(hub, 0) + 1
1288
+ deg[k] += 1
1289
+ out.append((first + k, hub_at[hub]))
1290
+ at = {r["site"]: k for k, r in enumerate(sites)}
1291
+ cand: list[list[int]] = [[at[s] for s in r["related"] if s in at] for r in sites]
1292
+ for key in (lambda r: r["hubs"][0][0] if r["hubs"] else None, lambda r: r["category"]):
1293
+ groups: dict = {}
1294
+ for k, r in enumerate(sites): # node order is first-seen order
1295
+ if (g := key(r)) is not None:
1296
+ groups.setdefault(g, []).append(k)
1297
+ for ks in groups.values():
1298
+ for t, k in enumerate(ks):
1299
+ cand[k] += ks[max(t - 1, 0):t] + ks[t + 1:t + 2]
1300
+ for k in order:
1301
+ for j in cand[k]:
1302
+ if deg[k] >= STEM_LINKS:
1303
+ break
1304
+ p = (min(j, k), max(j, k))
1305
+ if j == k or deg[j] >= STEM_LINKS or p in pairs:
1306
+ continue
1307
+ pairs.add(p)
1308
+ deg[k] += 1
1309
+ deg[j] += 1
1310
+ out.append((first + p[0], first + p[1]))
1311
+ return out
1312
+
1313
+
1314
+ def with_stem(brain: dict, sites: list[dict], placed: dict, total: int) -> dict:
1315
+ """`brain` (a `build` blob) with the websites as a stem below the lobes: one node per site
1316
+ (`site:<site>`) after the pages, outside every lobe (lobe 65535), weighted by visits; their
1317
+ fibres (`_stem_links`, as similar-meaning fibres); and `stem` {first, total, shown, sites:
1318
+ [[site, category, visits, first day, last day, private]], colors: {category: hex}}.
1319
+ The mesh gains the faint tube round them (`stem_tube`).
1320
+ `sites`: site_rows records in node order, each with `first_day`, `last_day` and
1321
+ `private`; `placed` holds their axis shares (`stem_order`). The blob's other parts are
1322
+ shared, not copied."""
1323
+ nd = brain["nodes"]
1324
+ n0, m = len(nd["ids"]), len(sites)
1325
+ n = n0 + m
1326
+
1327
+ def col(k, t, w=1):
1328
+ return np.frombuffer(base64.b64decode(nd[k]), t).reshape(-1, w)
1329
+
1330
+ xyz = stem_xyz([r["site"] for r in sites], [placed[r["site"]][1] for r in sites])
1331
+ visits = np.maximum(np.array([r["visits"] or 0 for r in sites], float), 0)
1332
+ weight = np.log1p(visits) / max(math.log1p(visits.max(initial=0)), 1e-9)
1333
+ nodes = {"ids": [*nd["ids"], *(f"site:{r['site']}" for r in sites)],
1334
+ "xyz": _b64(np.concatenate([col("xyz", "<f4", 3), xyz]), "<f4"),
1335
+ "lobe": _b64(np.concatenate([col("lobe", "<u2")[:, 0], np.full(m, 65535)]), "<u2"),
1336
+ "depth": _b64(np.concatenate([col("depth", "<f4")[:, 0],
1337
+ np.maximum(-_field(xyz), 0) if m else []]), "<f4"),
1338
+ "embedded": _b64(np.concatenate([col("embedded", "u1")[:, 0], np.zeros(m)]), "u1"),
1339
+ "weight": _b64(np.concatenate([col("weight", "<f4")[:, 0], weight]), "<f4"),
1340
+ "added": nd.get("added", {})} # pages only: a site is never a growth
1341
+ old_none, none = (0xFFFFFFFF if n0 >= 65535 else 65535), (0xFFFFFFFF if n >= 65535 else 65535)
1342
+ near = np.frombuffer(base64.b64decode(brain["near"]["ids"]),
1343
+ "<u4" if n0 >= 65535 else "<u2").astype(np.int64).reshape(-1, N_NEAR)
1344
+ near = np.where(near == old_none, none, near)
1345
+ near = np.concatenate([near, np.full((m, N_NEAR), none, np.int64)])
1346
+ fb = brain["fibres"]
1347
+ links = np.array(_stem_links(sites, {i: k for k, i in enumerate(nd["ids"])}, n0),
1348
+ np.int64).reshape(-1, 2)
1349
+ allp = np.concatenate([col("xyz", "<f4", 3), xyz])
1350
+ fibres = {"a": _b64(np.concatenate([np.frombuffer(base64.b64decode(fb["a"]), "<u4"),
1351
+ links[:, 0]]), "<u4"),
1352
+ "b": _b64(np.concatenate([np.frombuffer(base64.b64decode(fb["b"]), "<u4"),
1353
+ links[:, 1]]), "<u4"),
1354
+ "c": _b64(np.concatenate([np.frombuffer(base64.b64decode(fb["c"]), "<f4"),
1355
+ ((allp[links[:, 0]] + allp[links[:, 1]]) / 2).ravel()]),
1356
+ "<f4"),
1357
+ "k": _b64(np.concatenate([np.frombuffer(base64.b64decode(fb["k"]), "u1"),
1358
+ np.ones(len(links))]), "u1")}
1359
+ return {**brain, "nodes": nodes, "near": {"ids": _b64(near, "<u4" if n >= 65535 else "<u2")},
1360
+ "fibres": fibres, "mesh": [*brain["mesh"], stem_tube()], "stem": {
1361
+ "first": n0, "total": total, "shown": m,
1362
+ "sites": [[r["site"], r["category"] or "other", r["visits"], r["first_day"],
1363
+ r["last_day"], int(r["private"])] for r in sites],
1364
+ "colors": {c: site_color(c) for c in sorted({r["category"] or "other"
1365
+ for r in sites})}}}
1366
+
1367
+
1368
+ def preservation(xyz: np.ndarray, vec: np.ndarray, has: np.ndarray, lobe: np.ndarray,
1369
+ skip=(), sample: int = 50, k3: int = 5, kv: int = 20) -> float:
1370
+ """The in-lobe check: for `sample` pages (seeded), the share of their k3 nearest same-lobe
1371
+ points in 3D that are among their kv nearest same-lobe pages by vector."""
1372
+ rows = [r for r in range(len(xyz)) if has[r] and lobe[r] not in skip
1373
+ and (has & (lobe == lobe[r])).sum() > kv]
1374
+ rows = sorted(rows, key=lambda r: _u(f"sample:{r}", 1)[0])[:sample]
1375
+ got = []
1376
+ for r in rows:
1377
+ m = np.flatnonzero(has & (lobe == lobe[r]))
1378
+ m = m[m != r]
1379
+ a = m[np.argsort(np.linalg.norm(xyz[m] - xyz[r], axis=1), kind="stable")[:k3]]
1380
+ b = m[np.argsort(-(vec[m] @ vec[r]), kind="stable")[:kv]]
1381
+ got.append(len(set(a) & set(b)) / k3)
1382
+ return float(np.mean(got)) if got else 1.0