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,70 @@
1
+ """Off-policy value of one decision type from logged propensities: self-normalized IPW and doubly robust."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections import defaultdict
7
+
8
+ Z = 1.96
9
+ PRIOR = 2.0
10
+
11
+
12
+ def _outcome_model(rows) -> dict:
13
+ by_action, by_cell = defaultdict(list), defaultdict(list)
14
+ for r in rows:
15
+ by_action[r.choice].append(r.outcome)
16
+ by_cell[(r.context, r.choice)].append(r.outcome)
17
+ mean = sum(r.outcome for r in rows) / len(rows)
18
+ action = {a: (sum(v) + PRIOR * mean) / (len(v) + PRIOR) for a, v in by_action.items()}
19
+ return {cell: (sum(v) + PRIOR * action[cell[1]]) / (len(v) + PRIOR) for cell, v in by_cell.items()} | {
20
+ ("*", a): m for a, m in action.items()} | {("*", "*"): mean}
21
+
22
+
23
+ def _q(model, context, action) -> float:
24
+ return model.get((context, action), model.get(("*", action), model[("*", "*")]))
25
+
26
+
27
+ def _clustered(values, clusters) -> tuple:
28
+ n = len(values)
29
+ mean = sum(values) / n
30
+ totals = defaultdict(float)
31
+ for v, c in zip(values, clusters):
32
+ totals[c] += v - mean
33
+ clustered = sum(t * t for t in totals.values()) / (n * n)
34
+ independent = sum((v - mean) ** 2 for v in values) / (n * n)
35
+ return mean, math.sqrt(max(clustered, independent))
36
+
37
+
38
+ def evaluate(rows, target) -> dict:
39
+ """Value of `target(row) -> distribution` against the logging policy that produced the rows."""
40
+ if not rows:
41
+ return {"n": 0}
42
+ model = _outcome_model(rows)
43
+ weights = [target(r).get(r.choice, 0.0) / r.propensity for r in rows]
44
+ total = sum(weights)
45
+ snipw = sum(w * r.outcome for w, r in zip(weights, rows)) / total if total > 0 else float("nan")
46
+ dr_terms = []
47
+ for w, r in zip(weights, rows):
48
+ policy = target(r)
49
+ direct = sum(p * _q(model, r.context, a) for a, p in policy.items())
50
+ dr_terms.append(direct + w * (r.outcome - _q(model, r.context, r.choice)))
51
+ dr, se = _clustered(dr_terms, [r.island for r in rows])
52
+ ess = total * total / sum(w * w for w in weights) if total > 0 else 0.0
53
+ return {"n": len(rows), "ess": ess, "snipw": snipw, "dr": dr, "low": dr - Z * se, "high": dr + Z * se}
54
+
55
+
56
+ def action_effect(rows, action: str, q=None) -> dict:
57
+ """Effect of always taking `action` versus the logging policy, paired per row; `q` is an optional per-row outcome model."""
58
+ if not rows:
59
+ return {"n": 0}
60
+ model = _outcome_model(rows)
61
+ diffs = []
62
+ for r in rows:
63
+ learned = q(r, action) if q is not None else None
64
+ base = _q(model, r.context, action) if learned is None else learned
65
+ dr_action = base + ((r.outcome - base) / r.propensity if r.choice == action else 0.0)
66
+ diffs.append(dr_action - r.outcome)
67
+ effect, se = _clustered(diffs, [r.island for r in rows])
68
+ taken = sum(r.choice == action for r in rows)
69
+ return {"n": len(rows), "taken": taken, "effect": effect, "se": se,
70
+ "low": effect - Z * se, "high": effect + Z * se}
sciel/causal/ledger.py ADDED
@@ -0,0 +1,134 @@
1
+ """Journaled decisions joined to lineage outcomes: an island event by the child or its descendants within a horizon."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from dataclasses import asdict, dataclass, field
7
+
8
+ HORIZON = 20
9
+
10
+
11
+ @dataclass
12
+ class Row:
13
+ decision: str
14
+ iteration: int
15
+ island: int
16
+ context: str
17
+ distribution: dict
18
+ choice: str
19
+ propensity: float
20
+ child: str | None
21
+ outcome: float | None = None
22
+ state: str | None = None
23
+ reward: float = 0.0
24
+ scope: str = "lineage"
25
+ population: list = field(default_factory=list)
26
+ gain: float = 0.0
27
+ standing: dict = field(default_factory=dict)
28
+ shaped: float = 0.0 # learning_reward of a step that gained nothing: a world-model target, never an outcome
29
+
30
+
31
+ def context_of(decision_context: dict) -> str:
32
+ phase = decision_context.get("phase", 0)
33
+ progress = decision_context.get("progress") or 0.0
34
+ return f"phase={phase}|third={min(int(progress * 3), 2)}"
35
+
36
+
37
+ class Ledger:
38
+ def __init__(self, horizon: int = HORIZON):
39
+ self.horizon = horizon
40
+ self.rows: list[Row] = []
41
+ self.parent: dict[str, str] = {}
42
+ self.now = 0
43
+ self.path_best: dict[str, float] = {}
44
+ self.scale: float | None = None
45
+
46
+ def path_gain(self, before: float, child: str | None, score: float | None, origin: float) -> float:
47
+ """Rise of the best score above `before` (the parent's path best, or the population best for a step from
48
+ scratch), on a log scale above the starting program's score; it telescopes along every lineage, so a copy adds
49
+ nothing, siblings never take each other's credit and a restart earns only what it adds to the population.
50
+ A starting score of zero takes its scale from the first nonzero score."""
51
+ before = max(before, origin)
52
+ if child is None or score is None:
53
+ return 0.0
54
+ after = max(before, score)
55
+ self.path_best[child] = after
56
+ if self.scale is None and (origin != 0 or score != 0):
57
+ self.scale = abs(origin) if origin != 0 else abs(score)
58
+ if self.scale is None:
59
+ return 0.0
60
+ potential = lambda b: math.log1p(max(b - origin, 0.0) / self.scale)
61
+ return potential(after) - potential(before)
62
+
63
+ def path_start(self, parent: str, score: float | None) -> float | None:
64
+ """The path best of a recorded program, else the program's own score (seeds, migrants, programme steps)."""
65
+ return self.path_best.get(parent, score)
66
+
67
+ def add(self, *, iteration: int, island: int, decision_context: dict, child: str | None,
68
+ parent: str | None, event: bool, gain: float = 0.0, shaped: float = 0.0) -> None:
69
+ self.now = max(self.now, iteration)
70
+ context = context_of(decision_context)
71
+ decided = int(decision_context.get("iteration_no", iteration))
72
+ for record in decision_context.get("decisions", []):
73
+ self.rows.append(Row(decision=record["decision"], iteration=decided, island=island,
74
+ context=context, distribution=dict(record["distribution"]),
75
+ choice=str(record["choice"]), propensity=float(record["propensity"]),
76
+ child=child, outcome=None if child is not None else 0.0,
77
+ state=decision_context.get("parent_id"), reward=float(event),
78
+ population=list(decision_context.get("population", [])), gain=gain,
79
+ standing=dict(record.get("standing", {})), shaped=shaped))
80
+ if child is not None and parent is not None:
81
+ self.parent[child] = parent
82
+ if event and child is not None:
83
+ self._credit(child, iteration)
84
+ if event:
85
+ for row in self.rows:
86
+ if (row.scope == "island" and row.outcome is None and row.island == island
87
+ and iteration - row.iteration <= self.horizon):
88
+ row.outcome = 1.0
89
+ self._expire(iteration)
90
+
91
+ def add_island(self, *, iteration: int, island: int, context: str, record: dict) -> None:
92
+ """A decision whose outcome is any island event within the horizon, not a lineage event."""
93
+ self.now = max(self.now, iteration)
94
+ self.rows.append(Row(decision=record["decision"], iteration=iteration, island=island, context=context,
95
+ distribution=dict(record["distribution"]), choice=str(record["choice"]),
96
+ propensity=float(record["propensity"]), child=None, scope="island"))
97
+
98
+ def _lineage(self, program: str) -> set:
99
+ seen, node = set(), program
100
+ while node is not None and node not in seen and len(seen) <= self.horizon:
101
+ seen.add(node)
102
+ node = self.parent.get(node)
103
+ return seen
104
+
105
+ def _credit(self, child: str, iteration: int) -> None:
106
+ ancestors = self._lineage(child)
107
+ for row in self.rows:
108
+ if row.outcome is None and row.child in ancestors and iteration - row.iteration <= self.horizon:
109
+ row.outcome = 1.0
110
+
111
+ def _expire(self, iteration: int) -> None:
112
+ for row in self.rows:
113
+ if row.outcome is None and iteration - row.iteration > self.horizon:
114
+ row.outcome = 0.0
115
+
116
+ def settled(self, row: Row) -> bool:
117
+ """A row enters inference only at the end of its horizon, when its outcome is fixed for good, whatever its
118
+ scope; so rows enter in decision order and no settled factor is ever revised."""
119
+ return row.outcome is not None and self.now - row.iteration > self.horizon
120
+
121
+ def labeled(self, decision: str) -> list[Row]:
122
+ return [r for r in self.rows if r.decision == decision and r.outcome is not None]
123
+
124
+ def state(self) -> dict:
125
+ return {"horizon": self.horizon, "rows": [asdict(r) for r in self.rows],
126
+ "parent": dict(self.parent), "now": self.now, "path_best": dict(self.path_best), "scale": self.scale}
127
+
128
+ def load_state(self, data: dict) -> None:
129
+ self.horizon = int(data["horizon"])
130
+ self.rows = [Row(**r) for r in data["rows"]]
131
+ self.parent = dict(data["parent"])
132
+ self.now = int(data["now"])
133
+ self.path_best = dict(data["path_best"])
134
+ self.scale = data["scale"]
@@ -0,0 +1,102 @@
1
+ """Anytime-valid inference: DR contrasts with predictable outcome models, mixture-of-bets e-processes and e-BH.
2
+
3
+ The contrast of an action is its value minus the uniform mixture of the other actions of the same decision when every
4
+ row offers the same alternatives, and minus one reference action offered in every row when the alternatives change, so
5
+ the target does not drift when the theory tilts the logging policy or arms enter and leave. Rows enter in decision order
6
+ once their outcomes are settled, so the order never depends on an outcome, and each row's outcome model uses only
7
+ earlier rows.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from collections import defaultdict
14
+
15
+ import numpy as np
16
+
17
+ GRID = np.linspace(-1.0, 1.0, 81)
18
+ PRIOR = 2.0
19
+
20
+
21
+ def comparator(rows: list, action: str) -> tuple[bool, str | None]:
22
+ """Whether `action` has a fixed comparison target in these rows: the shared alternatives or a reference action."""
23
+ others = [frozenset(r.distribution) - {action} for r in rows if action in r.distribution]
24
+ others = [o for o in others if o]
25
+ if not others or len(set(others)) == 1:
26
+ return True, None
27
+ common = frozenset.intersection(*others)
28
+ reference = next((a for r in rows if action in r.distribution for a in r.distribution if a in common), None)
29
+ return reference is not None, reference
30
+
31
+
32
+ def contrasts(rows: list, action: str, reference: str | None = None) -> tuple[np.ndarray, np.ndarray]:
33
+ """Doubly robust pseudo-outcomes of `action` against the other actions or a reference action, with known bounds."""
34
+ sums, counts = defaultdict(float), defaultdict(int)
35
+ total, seen = 0.0, 0
36
+ psi, bound = [], []
37
+ for row in rows:
38
+ others = [reference] if reference is not None else [b for b in row.distribution if b != action]
39
+ if action not in row.distribution or not others or any(b not in row.distribution for b in others):
40
+ continue
41
+ mean = (total + PRIOR * 0.5) / (seen + PRIOR)
42
+
43
+ def q(b):
44
+ return (sums[b] + PRIOR * mean) / (counts[b] + PRIOR)
45
+
46
+ y = row.reward if row.scope == "lineage" else row.outcome
47
+ value = q(action) + (row.choice == action) * (y - q(action)) / row.distribution[action]
48
+ rest = sum(q(b) + (row.choice == b) * (y - q(b)) / row.distribution[b] for b in others) / len(others)
49
+ psi.append(value - rest)
50
+ bound.append(1.0 + 1.0 / min(row.distribution.values()))
51
+ sums[row.choice] += y
52
+ counts[row.choice] += 1
53
+ total += y
54
+ seen += 1
55
+ return np.asarray(psi, dtype=float), np.asarray(bound, dtype=float)
56
+
57
+
58
+ LAMBDAS = np.array([v for v in np.linspace(-0.9, 0.9, 19) if abs(v) > 1e-9])
59
+
60
+
61
+ def mixture(psi: np.ndarray, bound, alpha: float) -> dict:
62
+ """Equal-weight mixture of fixed bets on every grid value m: the current e-value at zero and the current
63
+ confidence set, both valid at any stopping time; the log wealth per (m, bet) lets a later run continue it."""
64
+ if len(psi) == 0:
65
+ return {"n": 0, "mean": 0.0, "se": 0.0, "low": -1.0, "high": 1.0, "e": 1.0, "empty": False,
66
+ "log_wealth": np.zeros((len(GRID), len(LAMBDAS)))}
67
+ bound = np.broadcast_to(np.asarray(bound, dtype=float), psi.shape)
68
+ x = psi[:, None, None] - GRID[None, :, None]
69
+ lam = LAMBDAS[None, None, :] / (bound[:, None, None] + np.abs(GRID)[None, :, None])
70
+ log_wealth = np.log1p(lam * x).sum(0)
71
+ return {**summary(psi, log_wealth, alpha), "log_wealth": log_wealth}
72
+
73
+
74
+ def summary(psi: np.ndarray, log_wealth: np.ndarray, alpha: float) -> dict:
75
+ capital = np.logaddexp.reduce(log_wealth, axis=1) - math.log(log_wealth.shape[1])
76
+ kept = GRID[capital < math.log(1.0 / alpha)]
77
+ zero = int(np.argmin(np.abs(GRID)))
78
+ step = GRID[1] - GRID[0]
79
+ se = float(psi.std(ddof=1) / math.sqrt(len(psi))) if len(psi) > 1 else 1.0
80
+ return {"n": len(psi), "mean": float(psi.mean()), "se": se,
81
+ "low": float(kept.min() - step) if len(kept) else 0.0,
82
+ "high": float(kept.max() + step) if len(kept) else 0.0,
83
+ "e": float(np.exp(capital[zero])), "empty": not len(kept)}
84
+
85
+
86
+ def continued(log_wealth: np.ndarray, prior: np.ndarray | None, psi: np.ndarray, alpha: float) -> dict:
87
+ """The same betting martingale carried on from an earlier run's final wealth."""
88
+ total = log_wealth if prior is None else log_wealth + prior
89
+ return {**summary(psi if len(psi) else np.zeros(1), total, alpha), "log_wealth": total}
90
+
91
+
92
+ def e_bh(evalues: dict, alpha: float, weights: dict | None = None) -> set:
93
+ """e-BH: reject the largest k with weighted e-value at least K/(alpha*k); valid under any dependence."""
94
+ keys = list(evalues)
95
+ k_total = len(keys)
96
+ weights = weights or {k: 1.0 for k in keys}
97
+ ranked = sorted(keys, key=lambda k: -weights[k] * evalues[k])
98
+ rejected = 0
99
+ for k in range(1, k_total + 1):
100
+ if weights[ranked[k - 1]] * evalues[ranked[k - 1]] >= k_total / (alpha * k):
101
+ rejected = k
102
+ return set(ranked[:rejected])
sciel/cli/__init__.py ADDED
File without changes
sciel/cli/live.py ADDED
@@ -0,0 +1,144 @@
1
+ """Run the engine in its own process and follow it in the terminal, the browser, or both.
2
+
3
+ Closing a viewer never stops the run: the engine keeps going in the background and
4
+ `sciel watch`, `sciel web` or `sciel stop` reach it again by its directory.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import re
12
+ import subprocess
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+
17
+ from rich.console import Console
18
+
19
+ MODES = ("both", "terminal", "web", "none")
20
+
21
+
22
+ def log_path(run_dir: Path) -> Path:
23
+ return run_dir.parent / (run_dir.name + ".log")
24
+
25
+
26
+ def spawn(run_dir: Path, *, fresh_config=None, tasks_root=None, recover=False) -> subprocess.Popen:
27
+ """Start the engine supervisor as a detached child that writes beside the run directory."""
28
+ command = [sys.executable, "-m", "sciel.cli.main", "_engine", str(run_dir)]
29
+ if fresh_config is not None:
30
+ command += ["--fresh-config", str(fresh_config)]
31
+ if tasks_root is not None:
32
+ command += ["--tasks-root", str(tasks_root)]
33
+ if recover:
34
+ command.append("--abandon-provider-failure")
35
+ run_dir.parent.mkdir(parents=True, exist_ok=True)
36
+ log = open(log_path(run_dir), "ab")
37
+ return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
38
+ start_new_session=True, env=os.environ.copy())
39
+
40
+
41
+ def _reason(lines) -> str | None:
42
+ """The exception line that ended the engine, without the traceback above it."""
43
+ found = [line.strip() for line in lines
44
+ if re.match(r"^[A-Za-z_][\w.]*(Error|Exception|Stopped|Interrupt|Exit)\b:?", line.strip())]
45
+ found = [re.sub(r"^SuperviseError:\s*", "", line) for line in found]
46
+ if found:
47
+ return found[-1]
48
+ rest = [line.strip() for line in lines if line.strip()]
49
+ return rest[-1] if rest else None
50
+
51
+
52
+ def _tail(path: Path, lines=12) -> str:
53
+ try:
54
+ return "\n".join(path.read_text(errors="replace").splitlines()[-lines:])
55
+ except OSError:
56
+ return ""
57
+
58
+
59
+ def follow(run_dir: Path, child, mode: str) -> int:
60
+ """Show the run in the chosen viewer; return the engine's exit code, or 0 if it is still running."""
61
+ from ..ui.web import request_pause, serve
62
+ console = Console()
63
+ web = {}
64
+
65
+ def engine():
66
+ code = child.poll() if child is not None else None
67
+ tail = _tail(log_path(run_dir), 30).splitlines() if code not in (None, 0) else []
68
+ return {"exit": code, "log": str(log_path(run_dir)), "tail": tail, "reason": _reason(tail)}
69
+
70
+ def open_web():
71
+ if "url" not in web:
72
+ web["url"], web["server"] = serve(run_dir, engine=engine)
73
+ else:
74
+ import webbrowser
75
+ webbrowser.open(web["url"])
76
+ return web["url"]
77
+
78
+ if mode in ("both", "web"):
79
+ open_web()
80
+ try:
81
+ if mode in ("both", "terminal") and sys.stdin.isatty() and sys.stdout.isatty():
82
+ from ..ui.terminal import watch
83
+ watch(run_dir, web_url=web.get("url"), open_web=open_web, pause=lambda: request_pause(run_dir),
84
+ engine=engine)
85
+ else:
86
+ console.print(f"[#8A8A8E]web[/] {web.get('url', '—')} [#8A8A8E]log[/] {log_path(run_dir)} "
87
+ "[#8A8A8E]Ctrl-C leaves the run going[/]")
88
+ while child is None or child.poll() is None:
89
+ time.sleep(1)
90
+ except KeyboardInterrupt:
91
+ pass
92
+ return _farewell(console, run_dir, child)
93
+
94
+
95
+ def _farewell(console, run_dir: Path, child) -> int:
96
+ code = child.poll() if child is not None else None
97
+ summary = _summary(run_dir)
98
+ if child is None:
99
+ try:
100
+ status = json.loads((run_dir / "runtime.json").read_text()).get("status")
101
+ except (OSError, ValueError):
102
+ status = None
103
+ if status != "running":
104
+ console.print(f"The run is {status or 'not running'}. {summary}\n {run_dir}")
105
+ return 0
106
+ if code is None:
107
+ console.print(f"The run continues in the background.\n"
108
+ f" [#64D2FF]sciel watch[/] {run_dir} follow it again\n"
109
+ f" [#64D2FF]sciel web[/] {run_dir} open the page\n"
110
+ f" [#64D2FF]sciel stop[/] {run_dir} pause after the current step")
111
+ return 0
112
+ if code == 0:
113
+ console.print(f"Run finished. {summary}\n {run_dir}")
114
+ else:
115
+ reason = _reason(_tail(log_path(run_dir), 30).splitlines())
116
+ console.print(f"[#E5484D]The engine stopped with an error.[/] {summary}\n {reason or ''}\n"
117
+ f" full log: {log_path(run_dir)}")
118
+ return code
119
+
120
+
121
+ def _summary(run_dir: Path) -> str:
122
+ from ..ui.state import RunState
123
+ try:
124
+ snap = RunState(run_dir).refresh()
125
+ except (OSError, ValueError):
126
+ return ""
127
+ run = snap["run"]
128
+ if run.get("best") is None:
129
+ return ""
130
+ seed = run.get("seed_score")
131
+ gain = f" (+{run['best'] - seed:.3f} over seed)" if seed is not None else ""
132
+ return f"Best {run['best']:.4f}{gain} after {run['B_evals']} evaluations, ${run.get('cost') or 0:.2f}."
133
+
134
+
135
+ def default_mode() -> str:
136
+ return "both" if sys.stdout.isatty() else "none"
137
+
138
+
139
+ def write_config(cfg: dict, run_dir: Path) -> Path:
140
+ """Keep the exact starting configuration beside the run, where a fresh start can read it."""
141
+ path = run_dir.parent / (run_dir.name + ".config.json")
142
+ path.parent.mkdir(parents=True, exist_ok=True)
143
+ path.write_text(json.dumps(cfg, indent=1))
144
+ return path