sciel 0.23.2__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 (305) hide show
  1. sciel/__init__.py +1 -0
  2. sciel/campaign/__init__.py +0 -0
  3. sciel/campaign/budget.py +467 -0
  4. sciel/campaign/identity.py +97 -0
  5. sciel/campaign/memory.py +298 -0
  6. sciel/campaign/no_regression.py +118 -0
  7. sciel/candidate_modules/__init__.py +239 -0
  8. sciel/causal/__init__.py +4 -0
  9. sciel/causal/estimators.py +70 -0
  10. sciel/causal/ledger.py +134 -0
  11. sciel/causal/sequential.py +102 -0
  12. sciel/cli/__init__.py +0 -0
  13. sciel/cli/live.py +144 -0
  14. sciel/cli/main.py +335 -0
  15. sciel/cli/profile.py +65 -0
  16. sciel/cli/start.py +189 -0
  17. sciel/cli/supervise.py +202 -0
  18. sciel/components/__init__.py +0 -0
  19. sciel/components/bets/__init__.py +0 -0
  20. sciel/components/code_novelty.py +105 -0
  21. sciel/components/containers.py +374 -0
  22. sciel/components/policy/__init__.py +0 -0
  23. sciel/components/policy/base.py +52 -0
  24. sciel/components/policy/code_embed.py +472 -0
  25. sciel/components/policy/controller.py +166 -0
  26. sciel/components/policy/mode_bandit.py +93 -0
  27. sciel/components/policy/mode_features.py +30 -0
  28. sciel/components/policy/mode_policy_mlp.py +102 -0
  29. sciel/components/policy/pop_features.py +29 -0
  30. sciel/components/policy/preset_weights.py +127 -0
  31. sciel/components/policy/three_head.py +167 -0
  32. sciel/components/policy/tilt.py +40 -0
  33. sciel/components/selection/__init__.py +0 -0
  34. sciel/components/selection/kernels.py +206 -0
  35. sciel/components/selection/novelty_chain.py +82 -0
  36. sciel/config.py +155 -0
  37. sciel/config_validation.py +180 -0
  38. sciel/culture/__init__.py +3 -0
  39. sciel/culture/methods.py +52 -0
  40. sciel/culture/repertoire.py +90 -0
  41. sciel/demo/__init__.py +5 -0
  42. sciel/demo/circles.py +54 -0
  43. sciel/diagnostics/__init__.py +1 -0
  44. sciel/diagnostics/methods_observer.py +427 -0
  45. sciel/diagnostics/paired_eval.py +244 -0
  46. sciel/engine/__init__.py +0 -0
  47. sciel/engine/admission.py +358 -0
  48. sciel/engine/assay.py +81 -0
  49. sciel/engine/bootstrap.py +270 -0
  50. sciel/engine/capacity.py +425 -0
  51. sciel/engine/checkpoint.py +133 -0
  52. sciel/engine/checkpoint_identity.py +230 -0
  53. sciel/engine/checkpoint_restore.py +248 -0
  54. sciel/engine/container_db.py +212 -0
  55. sciel/engine/cooperative_io.py +420 -0
  56. sciel/engine/db.py +259 -0
  57. sciel/engine/decisions.py +85 -0
  58. sciel/engine/determinism.py +24 -0
  59. sciel/engine/evaluation.py +199 -0
  60. sciel/engine/evaluation_timing.py +114 -0
  61. sciel/engine/evaluator_fifo.py +209 -0
  62. sciel/engine/eviction_planner.py +22 -0
  63. sciel/engine/factory.py +104 -0
  64. sciel/engine/incubator.py +201 -0
  65. sciel/engine/initialization.py +354 -0
  66. sciel/engine/journal_anchor.py +26 -0
  67. sciel/engine/knockout.py +91 -0
  68. sciel/engine/lifecycle.py +251 -0
  69. sciel/engine/llm/__init__.py +0 -0
  70. sciel/engine/llm/anthropic_api.py +78 -0
  71. sciel/engine/llm/claude_code.py +149 -0
  72. sciel/engine/llm/client.py +443 -0
  73. sciel/engine/llm/codex.py +368 -0
  74. sciel/engine/llm/codex_protocol.py +252 -0
  75. sciel/engine/llm/errors.py +132 -0
  76. sciel/engine/llm/mock.py +109 -0
  77. sciel/engine/llm/trace.py +133 -0
  78. sciel/engine/loop.py +98 -0
  79. sciel/engine/loop_contracts.py +105 -0
  80. sciel/engine/novelty.py +376 -0
  81. sciel/engine/observed_changes.py +404 -0
  82. sciel/engine/observed_schema.py +189 -0
  83. sciel/engine/operators.py +107 -0
  84. sciel/engine/output_measurements.py +44 -0
  85. sciel/engine/output_novelty.py +256 -0
  86. sciel/engine/parallel.py +472 -0
  87. sciel/engine/parallel_calls.py +330 -0
  88. sciel/engine/parallel_control.py +51 -0
  89. sciel/engine/parallel_recovery.py +363 -0
  90. sciel/engine/parallel_schedule.py +215 -0
  91. sciel/engine/parallel_store.py +433 -0
  92. sciel/engine/population_view.py +113 -0
  93. sciel/engine/portfolio_allocation.py +74 -0
  94. sciel/engine/probe.py +75 -0
  95. sciel/engine/prompt/__init__.py +0 -0
  96. sciel/engine/prompt/budget.py +20 -0
  97. sciel/engine/prompt/build.py +202 -0
  98. sciel/engine/prompt/parse.py +54 -0
  99. sciel/engine/prompt/patch.py +101 -0
  100. sciel/engine/prompt/sources.py +10 -0
  101. sciel/engine/prompt/templates/cross.txt +26 -0
  102. sciel/engine/prompt/templates/diff.txt +24 -0
  103. sciel/engine/prompt/templates/error_repair.txt +23 -0
  104. sciel/engine/prompt/templates/fix.txt +8 -0
  105. sciel/engine/prompt/templates/full_rewrite.txt +24 -0
  106. sciel/engine/prompt/templates/idea.txt +27 -0
  107. sciel/engine/provider_abandonment.py +15 -0
  108. sciel/engine/recovery.py +85 -0
  109. sciel/engine/repeat_execution.py +177 -0
  110. sciel/engine/repeat_journal.py +91 -0
  111. sciel/engine/repeat_learning.py +20 -0
  112. sciel/engine/repeat_planning.py +128 -0
  113. sciel/engine/repeat_policy.py +131 -0
  114. sciel/engine/repeat_promotion.py +147 -0
  115. sciel/engine/repeat_state.py +253 -0
  116. sciel/engine/repeat_support.py +175 -0
  117. sciel/engine/research_artifacts.py +323 -0
  118. sciel/engine/research_candidate.py +84 -0
  119. sciel/engine/research_cells_context.py +168 -0
  120. sciel/engine/research_culture.py +119 -0
  121. sciel/engine/research_queue.py +129 -0
  122. sciel/engine/research_search_evidence.py +160 -0
  123. sciel/engine/research_targets.py +204 -0
  124. sciel/engine/research_tool_signals.py +57 -0
  125. sciel/engine/run_lock.py +37 -0
  126. sciel/engine/runtime.py +165 -0
  127. sciel/engine/schedule.py +179 -0
  128. sciel/engine/siblings.py +135 -0
  129. sciel/engine/source_identity.py +16 -0
  130. sciel/engine/step_cycle.py +217 -0
  131. sciel/engine/step_plan.py +405 -0
  132. sciel/engine/telemetry.py +168 -0
  133. sciel/engine/types.py +87 -0
  134. sciel/engine/validation.py +444 -0
  135. sciel/engine/viability.py +431 -0
  136. sciel/engine/warm_start.py +69 -0
  137. sciel/engine/worker.py +294 -0
  138. sciel/engine/worker_feedback.py +131 -0
  139. sciel/eval/__init__.py +0 -0
  140. sciel/eval/_candidate_worker.py +131 -0
  141. sciel/eval/_repeat_runner.py +229 -0
  142. sciel/eval/_runner.py +280 -0
  143. sciel/eval/_scorer_worker.py +24 -0
  144. sciel/eval/candidate_backend.py +209 -0
  145. sciel/eval/candidate_config.py +58 -0
  146. sciel/eval/candidate_evidence.py +52 -0
  147. sciel/eval/candidate_receipts.py +272 -0
  148. sciel/eval/candidate_registry.py +2 -0
  149. sciel/eval/cascade.py +55 -0
  150. sciel/eval/facade.py +153 -0
  151. sciel/eval/native_geometry.py +251 -0
  152. sciel/eval/near_output.py +147 -0
  153. sciel/eval/output_identity.py +308 -0
  154. sciel/eval/packing_geometry.py +185 -0
  155. sciel/eval/registry.py +251 -0
  156. sciel/eval/repeat_docker.py +187 -0
  157. sciel/eval/repeat_draw.py +466 -0
  158. sciel/eval/repeat_io.py +51 -0
  159. sciel/eval/sandbox.py +350 -0
  160. sciel/eval/scorer_container.py +186 -0
  161. sciel/eval/task_prompt.py +82 -0
  162. sciel/eval/trusted_scoring/__init__.py +1 -0
  163. sciel/eval/trusted_scoring/adapter.py +125 -0
  164. sciel/eval/trusted_scoring/beat.py +191 -0
  165. sciel/eval/trusted_scoring/circle.py +102 -0
  166. sciel/eval/trusted_scoring/heil.py +107 -0
  167. sciel/eval/trusted_scoring/transport.py +120 -0
  168. sciel/evidence/__init__.py +1 -0
  169. sciel/evidence/change_audit.py +243 -0
  170. sciel/evidence/eligibility.py +110 -0
  171. sciel/evidence/measurement.py +186 -0
  172. sciel/evidence/restart_optimizer_trace.py +189 -0
  173. sciel/evidence/restart_trace.py +54 -0
  174. sciel/evidence/restart_trace_recorder.py +253 -0
  175. sciel/evidence/restart_trace_source.py +31 -0
  176. sciel/evidence/restart_trace_validation.py +234 -0
  177. sciel/evidence/restart_trace_values.py +231 -0
  178. sciel/local_task.py +142 -0
  179. sciel/methods/__init__.py +11 -0
  180. sciel/methods/__main__.py +397 -0
  181. sciel/methods/_loader.py +99 -0
  182. sciel/methods/_runner.py +225 -0
  183. sciel/methods/budget.py +322 -0
  184. sciel/methods/campaign.py +372 -0
  185. sciel/methods/configuration.py +139 -0
  186. sciel/methods/coordinator.py +368 -0
  187. sciel/methods/coordinator_context.py +108 -0
  188. sciel/methods/coordinator_contracts.py +42 -0
  189. sciel/methods/coordinator_episode.py +251 -0
  190. sciel/methods/coordinator_exchange.py +156 -0
  191. sciel/methods/coordinator_execution.py +170 -0
  192. sciel/methods/coordinator_planning.py +156 -0
  193. sciel/methods/coordinator_policy.py +193 -0
  194. sciel/methods/engine_bridge.py +342 -0
  195. sciel/methods/evidence.py +384 -0
  196. sciel/methods/examples.py +255 -0
  197. sciel/methods/executor.py +519 -0
  198. sciel/methods/funding.py +119 -0
  199. sciel/methods/materialize.py +248 -0
  200. sciel/methods/models.py +242 -0
  201. sciel/methods/proposals.py +289 -0
  202. sciel/methods/provider_budget.py +71 -0
  203. sciel/methods/registry.py +500 -0
  204. sciel/methods/registry_records.py +117 -0
  205. sciel/methods/resource_values.py +129 -0
  206. sciel/methods/tasks.py +203 -0
  207. sciel/methods/technical.py +167 -0
  208. sciel/methods/transport.py +217 -0
  209. sciel/population.py +15 -0
  210. sciel/research_tools/__init__.py +2 -0
  211. sciel/research_tools/artifact_manifest.py +207 -0
  212. sciel/research_tools/artifact_reading.py +34 -0
  213. sciel/research_tools/canonical_diagnostics.py +241 -0
  214. sciel/research_tools/canonical_evidence.py +94 -0
  215. sciel/research_tools/cells.py +394 -0
  216. sciel/research_tools/comparison_assessment.py +89 -0
  217. sciel/research_tools/config.py +174 -0
  218. sciel/research_tools/continuations.py +289 -0
  219. sciel/research_tools/controller.py +236 -0
  220. sciel/research_tools/controller_jobs.py +315 -0
  221. sciel/research_tools/controller_state.py +204 -0
  222. sciel/research_tools/decision_projection.py +116 -0
  223. sciel/research_tools/episode_evidence.py +129 -0
  224. sciel/research_tools/episode_execution.py +249 -0
  225. sciel/research_tools/episode_results.py +224 -0
  226. sciel/research_tools/experiment_protocol.py +271 -0
  227. sciel/research_tools/followups.py +442 -0
  228. sciel/research_tools/job_worker.py +240 -0
  229. sciel/research_tools/jobs.py +364 -0
  230. sciel/research_tools/library.py +357 -0
  231. sciel/research_tools/lifecycle.py +377 -0
  232. sciel/research_tools/lifecycle_delivery.py +198 -0
  233. sciel/research_tools/lifecycle_evidence.py +324 -0
  234. sciel/research_tools/observation_cards.py +179 -0
  235. sciel/research_tools/planning.py +152 -0
  236. sciel/research_tools/projection_data.py +169 -0
  237. sciel/research_tools/projection_validation.py +133 -0
  238. sciel/research_tools/prompt_builder.py +393 -0
  239. sciel/research_tools/prompt_sections.py +377 -0
  240. sciel/research_tools/replay_feedback.py +153 -0
  241. sciel/research_tools/research_steps.py +222 -0
  242. sciel/research_tools/result_contract.py +73 -0
  243. sciel/research_tools/result_projection.py +319 -0
  244. sciel/research_tools/retained_observations.py +227 -0
  245. sciel/research_tools/sequential_research.py +371 -0
  246. sciel/research_tools/shared_evidence.py +408 -0
  247. sciel/research_tools/sharing.py +287 -0
  248. sciel/research_tools/stage_data.py +68 -0
  249. sciel/research_tools/tool_actions.py +241 -0
  250. sciel/research_tools/tool_artifacts.py +175 -0
  251. sciel/research_tools/tool_protocol.py +41 -0
  252. sciel/research_tools/transfer_jobs.py +190 -0
  253. sciel/reward.py +181 -0
  254. sciel/rl/__init__.py +3 -0
  255. sciel/rl/critic.py +104 -0
  256. sciel/rl/policy.py +235 -0
  257. sciel/rl/returns.py +56 -0
  258. sciel/rng.py +38 -0
  259. sciel/run_log.py +212 -0
  260. sciel/solvers/__init__.py +1 -0
  261. sciel/solvers/circle_anytime.py +257 -0
  262. sciel/solvers/circle_lp_initializer.py +132 -0
  263. sciel/solvers/circle_relocation.py +121 -0
  264. sciel/stats.py +217 -0
  265. sciel/swm/__init__.py +6 -0
  266. sciel/swm/archive.py +91 -0
  267. sciel/swm/diffusion.py +61 -0
  268. sciel/swm/embedding.py +94 -0
  269. sciel/swm/model.py +200 -0
  270. sciel/swm/niches.py +46 -0
  271. sciel/swm/sets.py +63 -0
  272. sciel/swm/tabular.py +66 -0
  273. sciel/swm/targets.py +63 -0
  274. sciel/swm/world.py +500 -0
  275. sciel/task.py +21 -0
  276. sciel/taskbuilder/__init__.py +118 -0
  277. sciel/taskbuilder/audit.py +92 -0
  278. sciel/taskbuilder/draft.py +69 -0
  279. sciel/taskbuilder/materials.py +88 -0
  280. sciel/theory/__init__.py +7 -0
  281. sciel/theory/assumptions.py +131 -0
  282. sciel/theory/claims.py +138 -0
  283. sciel/theory/experiments.py +106 -0
  284. sciel/theory/findings.py +148 -0
  285. sciel/theory/procedures.py +89 -0
  286. sciel/theory/schools.py +64 -0
  287. sciel/theory/strategies.py +85 -0
  288. sciel/theory/trials.py +107 -0
  289. sciel/tui/__init__.py +0 -0
  290. sciel/tui/board.py +52 -0
  291. sciel/ui/__init__.py +1 -0
  292. sciel/ui/activity.py +112 -0
  293. sciel/ui/engine.py +169 -0
  294. sciel/ui/render.py +165 -0
  295. sciel/ui/state.py +343 -0
  296. sciel/ui/static/engine.js +162 -0
  297. sciel/ui/static/index.html +397 -0
  298. sciel/ui/terminal.py +455 -0
  299. sciel/ui/views.py +307 -0
  300. sciel/ui/web.py +144 -0
  301. sciel-0.23.2.dist-info/METADATA +508 -0
  302. sciel-0.23.2.dist-info/RECORD +305 -0
  303. sciel-0.23.2.dist-info/WHEEL +5 -0
  304. sciel-0.23.2.dist-info/entry_points.txt +2 -0
  305. sciel-0.23.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,472 @@
1
+ """Program embedder (arch-v4 #3): behavior + code -> score-organized latent.
2
+
3
+ Shared by offline training (scripts/) and online inference (learned grid + VQ
4
+ niches). The feature vector is the evaluator's behavioral `cases` readout (AutoQD lesson:
5
+ behavior >> code text) plus token-hash and AST stats. Two heads on a shared
6
+ trunk: contrastive projection + jointly-trained score regressor (the ingredient
7
+ that organized the latent in every winning latent-search domain)."""
8
+
9
+ from __future__ import annotations
10
+
11
+ import ast
12
+ import hashlib
13
+ import math
14
+ import os
15
+ import re
16
+ from io import BytesIO
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+
21
+
22
+ def _stable_bin(token: str, mod: int) -> int:
23
+ """Deterministic token hashing (builtin hash() is per-process salted, which
24
+ would make embeddings -- and any grid descriptor built on them -- irreproducible
25
+ across runs)."""
26
+ return int.from_bytes(hashlib.blake2b(token.encode(), digest_size=8).digest(),
27
+ "little") % mod
28
+
29
+ try:
30
+ import torch
31
+ from torch import nn
32
+ _TORCH = True
33
+ except ImportError: # pragma: no cover
34
+ _TORCH = False
35
+
36
+ DIM_HASH = 256
37
+ _TOKEN_RE = re.compile(r"[A-Za-z_][A-Za-z_0-9]*")
38
+
39
+ # The v2 behavior slots, in the fixed order the shipped embedder was trained on.
40
+ # NEVER reorder or insert: the trained model's input layout depends on it.
41
+ BEHAVIOR_KEYS = ["combined_score", "sum_radii", "target_ratio", "validity",
42
+ "min_area_normalized", "value", "distance", "reliability"]
43
+
44
+ # Evaluators name some of those slots differently (function_minimization emits
45
+ # `value_score`/`distance_score`/`reliability_score`). Without this table three of
46
+ # its four readouts were silently read as 0.0 -- the behavior input collapsed to
47
+ # `combined_score` alone. Canonical name wins; aliases are tried in order.
48
+ BEHAVIOR_ALIASES = {
49
+ "value": ("value_score",),
50
+ "distance": ("distance_score", "distance_to_global"),
51
+ "reliability": ("reliability_score", "runs_successfully"),
52
+ }
53
+
54
+ # Behavior added AFTER the v2 embedder was trained. Appended at the TAIL of the
55
+ # feature vector precisely so an older model can be fed by truncation without any
56
+ # misalignment of the slots it does know (see `embed_batch`). Order is fixed for
57
+ # the same reason; append only.
58
+ #
59
+ # These are shape descriptors of the solution, not restatements of its score --
60
+ # that was the point of the change. A task emits the subset that applies to it;
61
+ # missing keys read 0.0, which is also what the pre-change journals replay as.
62
+ BEHAVIOR_EXTRA_KEYS = [
63
+ "b_dispersion", # spread of the solution's parts (radii CV, area CV, x-spread)
64
+ "b_boundary_frac", # how much of the solution sits on the domain boundary
65
+ "b_contact", # mean contact / neighbour-coupling of the parts
66
+ "b_offset", # displacement of the solution's centroid from the domain's
67
+ "b_concentration", # fraction of trials/parts in the dominant mode
68
+ "b_structure", # task-specific structural readout (rank, discreteness, ...)
69
+ ]
70
+
71
+
72
+ class VQBook:
73
+ """arch-v4 #4b: an online-growing VQ codebook over unit embeddings -- the niche
74
+ assignment of VQ-Elites, decoupled from the embedder so the codebook logic is
75
+ pure numpy and testable on its own.
76
+
77
+ A candidate whose cosine distance to every centroid exceeds `d_min` starts a new
78
+ niche (up to `k_max`); otherwise it joins the nearest. After each growth the
79
+ threshold adapts (AURORA container-size-control) to steer the codebook toward
80
+ `target_k`: over target -> raise d_min (harder to grow), under -> lower it.
81
+ Deterministic -- assignment order follows eval order, no RNG."""
82
+
83
+ def __init__(self, d_min: float = 0.35, target_k: int = 6, k_max: int = 12,
84
+ csc_rate: float = 0.08):
85
+ self.d_min = float(d_min)
86
+ self.target_k = int(target_k)
87
+ self.k_max = int(k_max)
88
+ self.csc_rate = float(csc_rate)
89
+ self.centroids: list = []
90
+
91
+ @staticmethod
92
+ def _unit(z: np.ndarray) -> np.ndarray:
93
+ z = np.asarray(z, dtype=np.float32)
94
+ return z / (float(np.linalg.norm(z)) + 1e-8)
95
+
96
+ def _nearest(self, z: np.ndarray) -> tuple:
97
+ dots = [float(z @ c) for c in self.centroids]
98
+ j = int(max(range(len(dots)), key=lambda i: dots[i]))
99
+ return j, 1.0 - dots[j] # (id, cosine distance)
100
+
101
+ def assign(self, z: np.ndarray) -> int:
102
+ """Assign and, if the candidate is far from every niche, grow the codebook.
103
+ The CSC feedback runs on EVERY call (not only on growth) so a too-high initial
104
+ threshold self-corrects downward toward `target_k` instead of stalling at K=1."""
105
+ z = self._unit(z)
106
+ if not self.centroids:
107
+ self.centroids.append(z)
108
+ self._csc()
109
+ return 0
110
+ j, dist = self._nearest(z)
111
+ nid = j
112
+ if dist > self.d_min and len(self.centroids) < self.k_max:
113
+ self.centroids.append(z)
114
+ nid = len(self.centroids) - 1
115
+ self._csc()
116
+ return nid
117
+
118
+ def assign_fixed(self, z: np.ndarray) -> int:
119
+ """Nearest niche without growing -- used to re-encode the archive on SH
120
+ milestones so cells stay consistent as the codebook shifts (AURORA re-encode)."""
121
+ z = self._unit(z)
122
+ if not self.centroids:
123
+ return 0
124
+ return self._nearest(z)[0]
125
+
126
+ def _csc(self) -> None:
127
+ k = len(self.centroids)
128
+ self.d_min *= (1.0 + self.csc_rate * (k - self.target_k))
129
+ self.d_min = min(max(self.d_min, 1e-3), 2.0)
130
+
131
+ def state(self) -> dict:
132
+ return {"d_min": self.d_min, "target_k": self.target_k, "k_max": self.k_max,
133
+ "csc_rate": self.csc_rate,
134
+ "centroids": [c.tolist() for c in self.centroids]}
135
+
136
+ def load_state(self, d: dict) -> None:
137
+ self.d_min = d["d_min"]
138
+ self.target_k = d["target_k"]
139
+ self.k_max = d["k_max"]
140
+ self.csc_rate = d["csc_rate"]
141
+ self.centroids = [np.asarray(c, dtype=np.float32) for c in d["centroids"]]
142
+
143
+
144
+ def behavior_value(cases: dict, key: str) -> float:
145
+ """One behavior slot, resolving the evaluator's own spelling via BEHAVIOR_ALIASES."""
146
+ cases = cases or {}
147
+ if key in cases:
148
+ try:
149
+ return float(cases[key])
150
+ except (TypeError, ValueError):
151
+ return 0.0
152
+ for alias in BEHAVIOR_ALIASES.get(key, ()):
153
+ if alias in cases:
154
+ try:
155
+ return float(cases[alias])
156
+ except (TypeError, ValueError):
157
+ return 0.0
158
+ return 0.0
159
+
160
+
161
+ def featurize(code: str, cases: dict) -> np.ndarray:
162
+ """[behavior(8) | token-hash(256) | AST(6) | behavior_extra(6)].
163
+
164
+ The extra behavior block is LAST so that a model trained on the shorter vector
165
+ can be fed `X[:, :in_dim]` and still receive exactly the features it was trained
166
+ on. Growing the block in the middle would silently shift every token-hash bin."""
167
+ beh = np.array([behavior_value(cases, k) for k in BEHAVIOR_KEYS],
168
+ dtype=np.float32)
169
+ tok = np.zeros(DIM_HASH, dtype=np.float32)
170
+ toks = _TOKEN_RE.findall(code or "")
171
+ for t in toks:
172
+ tok[_stable_bin(t, DIM_HASH)] += 1.0
173
+ tok /= max(len(toks), 1)
174
+ astv = np.zeros(6, dtype=np.float32)
175
+ try:
176
+ tree = ast.parse(code or "")
177
+ astv[:] = [
178
+ len(code) / 1e4,
179
+ sum(isinstance(x, ast.FunctionDef) for x in ast.walk(tree)) / 10,
180
+ sum(isinstance(x, (ast.For, ast.While)) for x in ast.walk(tree)) / 10,
181
+ sum(isinstance(x, ast.Call) for x in ast.walk(tree)) / 100,
182
+ max((len(list(ast.walk(x))) for x in tree.body), default=0) / 100,
183
+ (code or "").count("np.") / 50,
184
+ ]
185
+ except SyntaxError:
186
+ pass
187
+ extra = np.array([behavior_value(cases, k) for k in BEHAVIOR_EXTRA_KEYS],
188
+ dtype=np.float32)
189
+ return np.concatenate([beh, tok, astv, extra])
190
+
191
+
192
+ class BehaviorAxis:
193
+ """A FITTED behavior axis for the MAP-Elites grid: centre the latent, project on
194
+ one principal direction, standardize the projection, then squash.
195
+
196
+ Why fitted and not a seeded random direction. Measured over 13 673 stored
197
+ programs, the raw projection on the seeded direction had std 0.065 inside a
198
+ range of [-0.19, 0.20]; tanh is a straight line on that interval, so the
199
+ descriptor never spread beyond two of ten bins. Standardizing the projection is
200
+ what makes the squash do any work at all.
201
+
202
+ Why the SECOND principal component by default. The grid's other coordinate is
203
+ already the score, and the first principal component of this embedder's latent
204
+ correlates 0.82 with the score -- as a behavior axis it would duplicate the axis
205
+ the cell already has. The fitter therefore picks the leading component whose
206
+ score correlation is below a threshold, which on our corpus is the second.
207
+
208
+ The axis is fitted OFFLINE over pooled journals and then frozen: refitting moves
209
+ every archived program's coordinate retroactively, so the artifact carries a
210
+ version and the hash of the embedder it was fitted against, and runs are only
211
+ comparable within one (embedder, axis) pair."""
212
+
213
+ FORMAT = "behavior_axis/1"
214
+
215
+ def __init__(self, axis, mean, center=0.0, scale=1.0, *, component=1,
216
+ version="", embed_sha="", corr_score=float("nan"),
217
+ explained=float("nan"), n_fit=0, corr_worst=float("nan"),
218
+ corr_worst_task="", fit_task=""):
219
+ self.axis = np.asarray(axis, dtype=np.float32).reshape(-1)
220
+ n = float(np.linalg.norm(self.axis))
221
+ if not np.isfinite(n) or n <= 0:
222
+ raise ValueError("behavior axis must be a non-zero finite vector")
223
+ self.axis = self.axis / n
224
+ self.mean = np.asarray(mean, dtype=np.float32).reshape(-1)
225
+ if self.mean.shape != self.axis.shape:
226
+ raise ValueError(f"axis {self.axis.shape} and mean {self.mean.shape} disagree")
227
+ self.center = float(center)
228
+ self.scale = float(scale)
229
+ if not np.isfinite(self.scale) or self.scale <= 0:
230
+ raise ValueError(f"behavior axis scale must be positive, got {self.scale}")
231
+ self.component = int(component)
232
+ self.version = str(version)
233
+ self.embed_sha = str(embed_sha)
234
+ self.corr_score = float(corr_score)
235
+ self.explained = float(explained)
236
+ self.n_fit = int(n_fit)
237
+ # The pooled correlation hides per-task structure: fitted across tasks whose
238
+ # scores live on different scales, an axis can read as decorrelated overall
239
+ # while duplicating the score axis inside one task. A grid only ever sees one
240
+ # task, so the WORST per-task correlation is the number that matters.
241
+ self.corr_worst = float(corr_worst)
242
+ self.corr_worst_task = str(corr_worst_task)
243
+ self.fit_task = str(fit_task) # non-empty => fitted on one task only
244
+
245
+ @property
246
+ def dim(self) -> int:
247
+ return int(self.axis.shape[0])
248
+
249
+ def value(self, z: np.ndarray) -> float:
250
+ """Latent -> [0,1] descriptor. Standardize first, squash second."""
251
+ u = float((np.asarray(z, dtype=np.float32).reshape(-1) - self.mean) @ self.axis)
252
+ return float((np.tanh((u - self.center) / self.scale) + 1.0) / 2.0)
253
+
254
+ def save(self, path: str) -> None:
255
+ np.savez(path, fmt=np.array(self.FORMAT), axis=self.axis, mean=self.mean,
256
+ center=np.array(self.center, dtype=np.float64),
257
+ scale=np.array(self.scale, dtype=np.float64),
258
+ component=np.array(self.component), version=np.array(self.version),
259
+ embed_sha=np.array(self.embed_sha),
260
+ corr_score=np.array(self.corr_score, dtype=np.float64),
261
+ explained=np.array(self.explained, dtype=np.float64),
262
+ n_fit=np.array(self.n_fit),
263
+ corr_worst=np.array(self.corr_worst, dtype=np.float64),
264
+ corr_worst_task=np.array(self.corr_worst_task),
265
+ fit_task=np.array(self.fit_task))
266
+
267
+ @classmethod
268
+ def load(cls, path: str) -> "BehaviorAxis":
269
+ raw = Path(path).read_bytes()
270
+ with np.load(BytesIO(raw), allow_pickle=False) as d:
271
+ fmt = str(d["fmt"]) if "fmt" in d else ""
272
+ if fmt != cls.FORMAT:
273
+ raise ValueError(f"{path}: expected {cls.FORMAT}, got {fmt!r}")
274
+ axis = cls(d["axis"], d["mean"], float(d["center"]), float(d["scale"]),
275
+ component=int(d["component"]), version=str(d["version"]),
276
+ embed_sha=str(d["embed_sha"]), corr_score=float(d["corr_score"]),
277
+ explained=float(d["explained"]), n_fit=int(d["n_fit"]),
278
+ corr_worst=float(d["corr_worst"]) if "corr_worst" in d else float("nan"),
279
+ corr_worst_task=str(d["corr_worst_task"]) if "corr_worst_task" in d else "",
280
+ fit_task=str(d["fit_task"]) if "fit_task" in d else "")
281
+ axis.artifact_identity = {"format": cls.FORMAT,
282
+ "sha256": hashlib.sha256(raw).hexdigest()}
283
+ return axis
284
+
285
+
286
+ def file_sha(path: str, n: int = 12) -> str:
287
+ """Short content hash -- ties a fitted axis to the exact embedder it came from."""
288
+ h = hashlib.sha256()
289
+ with open(path, "rb") as f:
290
+ for chunk in iter(lambda: f.read(1 << 20), b""):
291
+ h.update(chunk)
292
+ return h.hexdigest()[:n]
293
+
294
+
295
+ if _TORCH:
296
+ class Embedder(nn.Module):
297
+ def __init__(self, in_dim, out_dim=64):
298
+ super().__init__()
299
+ self.in_dim = int(in_dim)
300
+ self.trunk = nn.Sequential(nn.Linear(in_dim, 128), nn.ReLU())
301
+ self.proj = nn.Linear(128, out_dim)
302
+ self.score = nn.Linear(128, 1)
303
+
304
+ def embed(self, x):
305
+ z = self.proj(self.trunk(x))
306
+ return z / (z.norm(dim=-1, keepdim=True) + 1e-8)
307
+
308
+ def predict_score(self, x):
309
+ return self.score(self.trunk(x)).squeeze(-1)
310
+
311
+ @classmethod
312
+ def load(cls, path: str) -> "Embedder":
313
+ raw = Path(path).read_bytes()
314
+ d = torch.load(BytesIO(raw), weights_only=False)
315
+ m = cls(d["in_dim"]); m.load_state_dict(d["state"]); m.eval()
316
+ m.artifact_identity = {"format": "sciel-code-embedder/1",
317
+ "sha256": hashlib.sha256(raw).hexdigest(), "in_dim": m.in_dim}
318
+ return m
319
+
320
+ def embed_batch(model: "Embedder", programs) -> np.ndarray:
321
+ """programs: iterable of (code, cases) -> (N, 64) unit embeddings.
322
+
323
+ A model trained before BEHAVIOR_EXTRA_KEYS existed declares a shorter
324
+ `in_dim`; since the extra block is at the tail, slicing gives it byte-for-byte
325
+ the features it was trained on. A model wider than the featurizer is a real
326
+ mismatch and raises rather than being zero-padded into nonsense."""
327
+ X = np.stack([featurize(c, cs) for c, cs in programs]).astype(np.float32)
328
+ want = int(getattr(model, "in_dim", X.shape[1]))
329
+ if want > X.shape[1]:
330
+ raise ValueError(
331
+ f"embedder expects {want} features, featurizer produces {X.shape[1]}; "
332
+ "the model is newer than this code")
333
+ if want < X.shape[1]:
334
+ X = X[:, :want] # older model: drop the tail block only
335
+ with torch.no_grad():
336
+ return model.embed(torch.tensor(X)).numpy()
337
+
338
+ class LearnedDescriptor:
339
+ """The MAP-Elites behavior axis: embed the program, reduce to one number in
340
+ [0,1]. Deterministic, and frozen for the whole run.
341
+
342
+ Two modes, and the run journal records which one was used, because the two
343
+ are NOT comparable -- the same program gets a different cell under each.
344
+
345
+ fitted -- a BehaviorAxis artifact: centred latent, principal direction,
346
+ standardized projection. This is the mode to run in.
347
+ legacy -- no artifact: the seeded random direction with an unstandardized
348
+ tanh, i.e. exactly what shipped before. Kept so old runs replay
349
+ and resume bit-identically, not because it works: measured over
350
+ 13 673 programs it occupies 2 of 10 bins.
351
+ """
352
+
353
+ def __init__(self, embedder: "Embedder", out_dim: int = 64, seed: int = 0,
354
+ axis: "BehaviorAxis | None" = None, axis_sha: str | None = None):
355
+ self.embedder = embedder
356
+ self.axis = axis
357
+ # The artifact's own content hash. `version` is author-supplied and a refit
358
+ # under the same name reuses it, so version alone cannot tell two axes apart.
359
+ self.axis_sha = axis_sha or ""
360
+ if axis is None:
361
+ rng = np.random.default_rng(seed)
362
+ self.w = rng.standard_normal(out_dim).astype(np.float32)
363
+ self.w /= np.linalg.norm(self.w)
364
+ else:
365
+ self.w = None
366
+
367
+ @classmethod
368
+ def load(cls, embed_path: str, seed: int = 0,
369
+ axis_path: str | None = None) -> "LearnedDescriptor":
370
+ """Load configured artifacts exactly; only explicit null selects legacy mode."""
371
+ embedder = Embedder.load(embed_path)
372
+ axis = axis_sha = None
373
+ if axis_path is not None:
374
+ axis = BehaviorAxis.load(axis_path)
375
+ axis_sha = axis.artifact_identity['sha256'][:12]
376
+ sha = embedder.artifact_identity['sha256'][:12]
377
+ if not axis.embed_sha:
378
+ raise ValueError(
379
+ f"{axis_path} records no embedder hash, so nothing ties it to "
380
+ f"{embed_path}; refit it with scripts/fit_behavior_axis.py")
381
+ if axis.embed_sha != sha:
382
+ raise ValueError(
383
+ f"{axis_path} was fitted against embedder {axis.embed_sha}, "
384
+ f"but {embed_path} hashes to {sha}; refit the axis")
385
+ # Width is checked here rather than at the first descriptor call: a
386
+ # mismatch discovered mid-run surfaces as a broadcast error inside
387
+ # db.add, tens of evaluations in.
388
+ probe = embed_batch(embedder, [("x = 1\n", {})])[0]
389
+ if axis.dim != probe.shape[0]:
390
+ raise ValueError(
391
+ f"{axis_path} is {axis.dim}-dimensional but {embed_path} "
392
+ f"produces a {probe.shape[0]}-dimensional latent; refit the axis")
393
+ return cls(embedder, seed=seed, axis=axis, axis_sha=axis_sha)
394
+
395
+ @property
396
+ def kind(self) -> str:
397
+ """Identifies the axis strongly enough to compare two runs. `version` is
398
+ author-supplied and a refit that overwrites the same file reuses it, so the
399
+ artifact's content hash is part of the name."""
400
+ if self.axis is None:
401
+ return "legacy_random_raw"
402
+ tag = self.axis.version or "unversioned"
403
+ if self.axis_sha:
404
+ tag = f"{tag}@{self.axis_sha[:8]}"
405
+ return f"pca{self.axis.component + 1}_{tag}"
406
+
407
+ @staticmethod
408
+ def _num(x):
409
+ """json.dumps writes bare NaN/Infinity, which is not valid JSON and breaks
410
+ any strict reader of the journal. Unknown metadata is None, not NaN."""
411
+ x = float(x)
412
+ return round(x, 4) if math.isfinite(x) else None
413
+
414
+ def describe(self) -> dict:
415
+ """Goes into run_start: a run must say which axis produced its cells.
416
+
417
+ `behavior_in_latent` is the honest flag. An embedder trained before
418
+ BEHAVIOR_EXTRA_KEYS existed has a narrower in_dim, so embed_batch slices
419
+ that block off and the evaluator's behaviour readout -- computed, logged,
420
+ and in case_metrics -- never reaches the latent, the axis, or the grid.
421
+ Retraining the embedder is what closes that gap; until then the flag says
422
+ so in every journal instead of leaving it to be discovered."""
423
+ want = len(BEHAVIOR_KEYS) + DIM_HASH + 6 + len(BEHAVIOR_EXTRA_KEYS)
424
+ d = {"kind": self.kind,
425
+ "behavior_in_latent": int(getattr(self.embedder, "in_dim", want)) >= want}
426
+ if self.axis is not None:
427
+ d.update(component=self.axis.component, version=self.axis.version,
428
+ embed_sha=self.axis.embed_sha, axis_sha=self.axis_sha,
429
+ n_fit=self.axis.n_fit, fit_task=self.axis.fit_task,
430
+ corr_score=self._num(self.axis.corr_score),
431
+ corr_worst=self._num(self.axis.corr_worst),
432
+ corr_worst_task=self.axis.corr_worst_task,
433
+ explained=self._num(self.axis.explained))
434
+ return d
435
+
436
+ def __call__(self, code: str, cases: dict) -> float:
437
+ z = embed_batch(self.embedder, [(code, cases)])[0]
438
+ if self.axis is not None:
439
+ return self.axis.value(z)
440
+ return float((np.tanh(z @ self.w) + 1.0) / 2.0) # [0,1]
441
+
442
+ class VQNiches:
443
+ """Adaptive codebook over program embeddings, checkpointed with the population."""
444
+
445
+ def __init__(self, embedder: "Embedder", d_min: float = 0.35,
446
+ target_k: int = 6, k_max: int = 12, csc_rate: float = 0.08):
447
+ self.embedder = embedder
448
+ self.book = VQBook(d_min=d_min, target_k=target_k, k_max=k_max,
449
+ csc_rate=csc_rate)
450
+
451
+ @classmethod
452
+ def load(cls, embed_path: str, **kw) -> "VQNiches":
453
+ return cls(Embedder.load(embed_path), **kw)
454
+
455
+ def _embed(self, code: str, cases: dict) -> np.ndarray:
456
+ return embed_batch(self.embedder, [(code, cases)])[0]
457
+
458
+ def assign(self, code: str, cases: dict) -> int:
459
+ return self.book.assign(self._embed(code, cases))
460
+
461
+ def assign_fixed(self, code: str, cases: dict) -> int:
462
+ return self.book.assign_fixed(self._embed(code, cases))
463
+
464
+ @property
465
+ def k(self) -> int:
466
+ return len(self.book.centroids)
467
+
468
+ def state(self) -> dict:
469
+ return self.book.state()
470
+
471
+ def load_state(self, d: dict) -> None:
472
+ self.book.load_state(d)
@@ -0,0 +1,166 @@
1
+ """pi controller: static mode-mix over selection modes.
2
+
3
+ pick_mode samples a selection mode from a static mixture and returns the tilt that
4
+ realizes it (base = the active kernel unchanged). Off (enabled=False) draws no RNG and
5
+ returns the base mode, so a run without policy is byte-identical. on_plateau shifts the
6
+ mixture for a hold window (step 3, gated by plateau_shift).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from .base import floor_clip, sample
12
+ from .mode_bandit import MODES, ModeBandit
13
+ from .mode_policy_mlp import ReturnConditionedModeMLP
14
+ from .tilt import Tilt, elite_target, uniform_target
15
+
16
+
17
+ # Score spread below this is not a real gradient: real scores are O(0.01-1) across
18
+ # tasks, while degenerate candidates land at ~1e-16 (machine epsilon). Without this
19
+ # floor, `max > min` treats a 1e-16 "elite" as exploitable and traps parent selection
20
+ # on a degenerate basin.
21
+ _GRAD_EPS = 1e-9
22
+
23
+
24
+ def _has_gradient(view) -> bool:
25
+ """True if the island has a score spread worth exploiting (task-agnostic:
26
+ catches an all-zero elite, an all-equal population, and an all-epsilon
27
+ 'elite' of degenerate candidates)."""
28
+ s = [view.scores[i] for i in view.ids]
29
+ return len(s) >= 1 and (max(s) - min(s)) > _GRAD_EPS
30
+
31
+ _KEYS = {"enabled", "base_mix", "plateau_mix", "mode_floor", "tilt_beta", "elite_k",
32
+ "plateau_hold", "plateau_shift", "plateau_shadow", "plateau_threshold",
33
+ "plateau_horizon", "plateau_min_n",
34
+ "mode_bandit", "mode_bandit_temp", "mode_bandit_window", "mode_bandit_prior",
35
+ "mode_source", "mode_policy_path", "mode_beta", "mode_target_rtg"}
36
+
37
+
38
+ class Controller:
39
+ def __init__(self, cfg_policy: dict, num_islands: int):
40
+ unknown = set(cfg_policy) - _KEYS
41
+ if unknown:
42
+ raise ValueError(f"unknown policy keys: {sorted(unknown)}")
43
+ self.enabled = bool(cfg_policy.get("enabled"))
44
+ self.base_mix = dict(cfg_policy.get("base_mix", {"base": 1.0}))
45
+ self.plateau_mix = dict(cfg_policy.get("plateau_mix", self.base_mix))
46
+ self.floor = cfg_policy.get("mode_floor", 1e-3)
47
+ self.beta = cfg_policy.get("tilt_beta", 0.3)
48
+ self.elite_k = cfg_policy.get("elite_k", 3)
49
+ self.hold_windows = cfg_policy.get("plateau_hold", 50)
50
+ self.plateau_shift = bool(cfg_policy.get("plateau_shift"))
51
+ for mix in (self.base_mix, self.plateau_mix):
52
+ bad = set(mix) - set(MODES)
53
+ if bad:
54
+ raise ValueError(f"unknown selection modes {sorted(bad)}; known {MODES}")
55
+ # Step 2 (online RL): a per-phase bandit that learns the non-plateau mode mix,
56
+ # warm-started from base_mix. None -> static base_mix (byte-identical when off).
57
+ self.mode_bandit = (
58
+ ModeBandit(self.base_mix,
59
+ temp=cfg_policy.get("mode_bandit_temp", 0.5),
60
+ window=cfg_policy.get("mode_bandit_window", 50),
61
+ prior_w=cfg_policy.get("mode_bandit_prior", 3.0))
62
+ if cfg_policy.get("mode_bandit") else None)
63
+ # Stage A: a frozen return-conditioned MLP as the non-plateau mode source,
64
+ # blended into base_mix as a tilt (beta). Trained offline; no in-run updates.
65
+ self.mode_source = cfg_policy.get("mode_source")
66
+ self.mode_mlp = (ReturnConditionedModeMLP.load(cfg_policy["mode_policy_path"])
67
+ if self.mode_source == "mlp" else None)
68
+ self.mode_beta = cfg_policy.get("mode_beta", 0.5)
69
+ self.target_rtg = cfg_policy.get("mode_target_rtg", 1.0)
70
+ self.plateau_until = {i: -1 for i in range(num_islands)}
71
+
72
+ def needs_tilt(self) -> bool:
73
+ """Can a non-base mode ever be drawn? The engine uses this to refuse a
74
+ selection kernel that ignores tilt.
75
+
76
+ It must ask about the FLOOR-CLIPPED mix, which is what pick_mode samples from.
77
+ Testing the raw mix said "no" for base_mix {base: 1.0}, while floor_clip still
78
+ handed every other mode `mode_floor` of the mass -- so a tilt-blind kernel was
79
+ accepted, those draws ran plain selection, and the journal recorded a mode and
80
+ a propensity that did not match the distribution actually sampled."""
81
+ if not self.enabled:
82
+ return False
83
+ if self.mode_bandit is not None or self.mode_mlp is not None:
84
+ return True # a learned source can draw exploit/explore in any phase
85
+ for mix in (self.base_mix, self.plateau_mix):
86
+ clipped = floor_clip(mix, self.floor)
87
+ if any(w > 0 for m, w in clipped.items() if m != "base"):
88
+ return True
89
+ return False
90
+
91
+ def in_plateau(self, island: int, t: int) -> bool:
92
+ return self.plateau_until.get(island, -1) > t
93
+
94
+ def pick_mode(self, island: int, t: int, rng, view=None, phase=None,
95
+ features=None, adjust=None) -> tuple:
96
+ """Returns (mode, propensity, tilt, mix) -- mix is the floor-clipped
97
+ distribution actually sampled from (for honest observability)."""
98
+ if not self.enabled:
99
+ return "base", 1.0, None, None
100
+ if self.in_plateau(island, t):
101
+ mix = self.plateau_mix
102
+ elif self.mode_mlp is not None and features is not None:
103
+ # step 3 (Stage A): return-conditioned MLP, blended into base_mix as a
104
+ # tilt of strength mode_beta (base_mix is the index prior; I-5 floor below).
105
+ mlp_mix = self.mode_mlp.dist(features, self.target_rtg)
106
+ b = self.mode_beta
107
+ mix = {m: (1 - b) * self.base_mix.get(m, 0.0) + b * mlp_mix[m]
108
+ for m in MODES}
109
+ elif self.mode_bandit is not None and phase is not None:
110
+ mix = self.mode_bandit.dist(phase) # step 2: learned mix
111
+ else:
112
+ mix = self.base_mix # step 1: static mix
113
+ mix = floor_clip(mix, self.floor)
114
+ if adjust is not None:
115
+ mix = adjust(mix)
116
+ mode = sample(mix, rng)
117
+ tilt = self._tilt_for(mode)
118
+ # Warmup gate: exploit tilts parent selection toward the island's top-k,
119
+ # but with no score gradient (a fresh island whose elite is all-zero) that
120
+ # top-k is garbage -- concentrating on it starves the island of the diverse
121
+ # sampling it needs to land its first record, and SH then cuts it. Drop the
122
+ # tilt so selection stays base-like (rho untouched -> honest propensity).
123
+ if mode == "exploit" and view is not None and not _has_gradient(view):
124
+ tilt = None
125
+ return mode, mix[mode], tilt, mix
126
+
127
+ def _tilt_for(self, mode: str):
128
+ if mode == "exploit":
129
+ k = self.elite_k
130
+ return Tilt(self.beta, lambda view: elite_target(view, k))
131
+ if mode == "explore":
132
+ return Tilt(self.beta, uniform_target)
133
+ return None
134
+
135
+ def observe(self, phase: int, mode: str, ev, on_policy: bool = True) -> None:
136
+ """Feed the mode bandit the reward from an iteration that used `mode`
137
+ (the effective mode -- a warmup-gated exploit is reported as base).
138
+
139
+ `on_policy=False` drops the sample. pick_mode short-circuits to plateau_mix
140
+ when the island is holding, so those iterations were never drawn from the
141
+ bandit's own distribution; crediting them anyway fed the non-plateau estimator
142
+ the run's systematically lowest-yield steps, under a mix that over-weights
143
+ exploit, and dragged exploit's learned value down for choices it never made."""
144
+ if self.mode_bandit is not None and on_policy:
145
+ self.mode_bandit.observe(phase, mode, ev)
146
+
147
+ def on_plateau(self, island: int, t: int, islands: int = 1) -> None:
148
+ """Hold this island in the plateau mix for `plateau_hold` of ITS OWN steps.
149
+
150
+ `t` is the global iteration counter, so a hold of 40 expressed in global steps
151
+ is ~13 steps of the island's own with three islands and ~7 with six. The hold
152
+ is documented and configured per island, so the window is scaled by how many
153
+ islands share the iteration stream."""
154
+ if self.plateau_shift:
155
+ self.plateau_until[island] = t + self.hold_windows * max(1, int(islands))
156
+
157
+ def state(self) -> dict:
158
+ d = {"plateau_until": {str(i): v for i, v in self.plateau_until.items()}}
159
+ if self.mode_bandit is not None:
160
+ d["mode_bandit"] = self.mode_bandit.state()
161
+ return d
162
+
163
+ def load_state(self, d: dict) -> None:
164
+ self.plateau_until = {int(i): v for i, v in d["plateau_until"].items()}
165
+ if self.mode_bandit is not None and "mode_bandit" in d:
166
+ self.mode_bandit.load_state(d["mode_bandit"])