dsh-biocore 0.1.2 → 0.1.4

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 (210) hide show
  1. package/lib/index.js +170 -27
  2. package/package.json +1 -1
  3. package/python/biocore_runtime/pipeline.py +42 -0
  4. package/python/biocore_runtime/rerank.py +201 -0
  5. package/python/mindbase/__init__.py +18 -0
  6. package/python/mindbase/__main__.py +3 -0
  7. package/python/mindbase/actions.py +56 -0
  8. package/python/mindbase/active_inference.py +54 -0
  9. package/python/mindbase/addressing.py +69 -0
  10. package/python/mindbase/affect.py +86 -0
  11. package/python/mindbase/affective.py +111 -0
  12. package/python/mindbase/allostasis.py +28 -0
  13. package/python/mindbase/appraisal.py +101 -0
  14. package/python/mindbase/attachment.py +49 -0
  15. package/python/mindbase/attention.py +30 -0
  16. package/python/mindbase/autonomy.py +81 -0
  17. package/python/mindbase/autonomy_bench.py +251 -0
  18. package/python/mindbase/autonomy_evolve.py +342 -0
  19. package/python/mindbase/autonomy_loop.py +65 -0
  20. package/python/mindbase/autonomy_meta.py +91 -0
  21. package/python/mindbase/base_only.py +28 -0
  22. package/python/mindbase/benchmark.py +61 -0
  23. package/python/mindbase/bio_adaptation.py +274 -0
  24. package/python/mindbase/bio_noise.py +39 -0
  25. package/python/mindbase/bio_semantic.py +138 -0
  26. package/python/mindbase/bm25.py +46 -0
  27. package/python/mindbase/bootstrap.py +256 -0
  28. package/python/mindbase/bootstrap_real.py +231 -0
  29. package/python/mindbase/brain.py +178 -0
  30. package/python/mindbase/care.py +78 -0
  31. package/python/mindbase/chaos_search.py +79 -0
  32. package/python/mindbase/character_profile.py +33 -0
  33. package/python/mindbase/circadian.py +38 -0
  34. package/python/mindbase/circuit.py +235 -0
  35. package/python/mindbase/clock.py +53 -0
  36. package/python/mindbase/companion_runtime.py +366 -0
  37. package/python/mindbase/companion_train.py +126 -0
  38. package/python/mindbase/config.py +66 -0
  39. package/python/mindbase/connection_state.py +76 -0
  40. package/python/mindbase/connectome_prior.py +35 -0
  41. package/python/mindbase/connectome_world.py +158 -0
  42. package/python/mindbase/constructs.py +88 -0
  43. package/python/mindbase/context_builder.py +58 -0
  44. package/python/mindbase/critical.py +36 -0
  45. package/python/mindbase/criticality.py +123 -0
  46. package/python/mindbase/defaults.py +27 -0
  47. package/python/mindbase/demo.py +163 -0
  48. package/python/mindbase/diary.py +116 -0
  49. package/python/mindbase/diary_service.py +40 -0
  50. package/python/mindbase/digital_prior.py +37 -0
  51. package/python/mindbase/diversity.py +110 -0
  52. package/python/mindbase/drives.py +106 -0
  53. package/python/mindbase/embedding.py +132 -0
  54. package/python/mindbase/embedding_memory.py +74 -0
  55. package/python/mindbase/embodiment.py +83 -0
  56. package/python/mindbase/emotion_calibration.py +39 -0
  57. package/python/mindbase/emotion_calibrator.py +50 -0
  58. package/python/mindbase/emotion_core.py +113 -0
  59. package/python/mindbase/emotion_dynamics.py +104 -0
  60. package/python/mindbase/emotion_intent.py +164 -0
  61. package/python/mindbase/emotion_layer.py +200 -0
  62. package/python/mindbase/emotion_schema.py +92 -0
  63. package/python/mindbase/engine.py +781 -0
  64. package/python/mindbase/episode_log.py +90 -0
  65. package/python/mindbase/evaluation.py +493 -0
  66. package/python/mindbase/event_appraisal.py +84 -0
  67. package/python/mindbase/evolution.py +77 -0
  68. package/python/mindbase/evolve_offline.py +232 -0
  69. package/python/mindbase/experiments.py +358 -0
  70. package/python/mindbase/expression.py +54 -0
  71. package/python/mindbase/external_brain.py +157 -0
  72. package/python/mindbase/fly_mb.py +159 -0
  73. package/python/mindbase/fly_tasks.py +45 -0
  74. package/python/mindbase/forage.py +179 -0
  75. package/python/mindbase/goal_generator.py +98 -0
  76. package/python/mindbase/goals.py +153 -0
  77. package/python/mindbase/grid_world.py +123 -0
  78. package/python/mindbase/group_autonomy.py +92 -0
  79. package/python/mindbase/group_context.py +67 -0
  80. package/python/mindbase/homeostatic.py +71 -0
  81. package/python/mindbase/homeostatic_action.py +38 -0
  82. package/python/mindbase/human_standard.py +53 -0
  83. package/python/mindbase/identity_suite.py +50 -0
  84. package/python/mindbase/image_context.py +27 -0
  85. package/python/mindbase/impression.py +119 -0
  86. package/python/mindbase/initiative_quota.py +145 -0
  87. package/python/mindbase/insight.py +51 -0
  88. package/python/mindbase/intelligence_search.py +108 -0
  89. package/python/mindbase/intention.py +76 -0
  90. package/python/mindbase/interaction_log.py +30 -0
  91. package/python/mindbase/interoception.py +67 -0
  92. package/python/mindbase/invariants.py +53 -0
  93. package/python/mindbase/iteration.py +29 -0
  94. package/python/mindbase/layered_memory.py +170 -0
  95. package/python/mindbase/layers/__init__.py +18 -0
  96. package/python/mindbase/layers/l0_substrate.py +39 -0
  97. package/python/mindbase/layers/l1_homeostasis.py +6 -0
  98. package/python/mindbase/layers/l2_affect.py +6 -0
  99. package/python/mindbase/layers/l3_attention.py +6 -0
  100. package/python/mindbase/layers/l4_learning.py +17 -0
  101. package/python/mindbase/layers/l5_self_social.py +35 -0
  102. package/python/mindbase/layers/l6_expression.py +23 -0
  103. package/python/mindbase/layers/l7_evaluation.py +45 -0
  104. package/python/mindbase/learner.py +196 -0
  105. package/python/mindbase/lexicon.py +33 -0
  106. package/python/mindbase/life_state.py +169 -0
  107. package/python/mindbase/lifecycle.py +87 -0
  108. package/python/mindbase/liquid_readout.py +48 -0
  109. package/python/mindbase/llm_adapter.py +233 -0
  110. package/python/mindbase/llm_cache.py +77 -0
  111. package/python/mindbase/llm_gate.py +85 -0
  112. package/python/mindbase/llm_openai.py +130 -0
  113. package/python/mindbase/llm_setup.py +99 -0
  114. package/python/mindbase/longrun.py +83 -0
  115. package/python/mindbase/longterm_memory.py +606 -0
  116. package/python/mindbase/mb/__init__.py +14 -0
  117. package/python/mindbase/mb/apl.py +22 -0
  118. package/python/mindbase/mb/dan.py +14 -0
  119. package/python/mindbase/mb/habituation.py +27 -0
  120. package/python/mindbase/mb/kc.py +28 -0
  121. package/python/mindbase/mb/mbon.py +23 -0
  122. package/python/mindbase/mb/mushroom_body.py +116 -0
  123. package/python/mindbase/memory.py +201 -0
  124. package/python/mindbase/memory_framework.py +158 -0
  125. package/python/mindbase/memory_retriever.py +110 -0
  126. package/python/mindbase/memory_summarizer.py +177 -0
  127. package/python/mindbase/memory_task.py +32 -0
  128. package/python/mindbase/memory_trace.py +46 -0
  129. package/python/mindbase/meta.py +32 -0
  130. package/python/mindbase/motivation.py +31 -0
  131. package/python/mindbase/multi_session.py +19 -0
  132. package/python/mindbase/narrative.py +87 -0
  133. package/python/mindbase/needs.py +77 -0
  134. package/python/mindbase/neural.py +45 -0
  135. package/python/mindbase/neuron_models.py +134 -0
  136. package/python/mindbase/noise.py +309 -0
  137. package/python/mindbase/one_on_one.py +60 -0
  138. package/python/mindbase/online_iteration.py +63 -0
  139. package/python/mindbase/ostracism.py +35 -0
  140. package/python/mindbase/parallel_eval.py +60 -0
  141. package/python/mindbase/parallel_qd.py +64 -0
  142. package/python/mindbase/persona.py +221 -0
  143. package/python/mindbase/persona_ab.py +64 -0
  144. package/python/mindbase/persona_bridge.py +129 -0
  145. package/python/mindbase/persona_compile.py +34 -0
  146. package/python/mindbase/persona_dsh.py +120 -0
  147. package/python/mindbase/persona_learner.py +157 -0
  148. package/python/mindbase/physiology.py +197 -0
  149. package/python/mindbase/population_lifecycle.py +83 -0
  150. package/python/mindbase/preferences.py +50 -0
  151. package/python/mindbase/proactive_agent.py +274 -0
  152. package/python/mindbase/proactive_gate.py +53 -0
  153. package/python/mindbase/proactive_group.py +119 -0
  154. package/python/mindbase/proactive_policy.py +422 -0
  155. package/python/mindbase/proactive_profile.py +196 -0
  156. package/python/mindbase/proactive_timing.py +28 -0
  157. package/python/mindbase/pyramid_stages.py +61 -0
  158. package/python/mindbase/quantum.py +132 -0
  159. package/python/mindbase/quantum_chaos.py +98 -0
  160. package/python/mindbase/reflection.py +68 -0
  161. package/python/mindbase/regulation_posture.py +50 -0
  162. package/python/mindbase/relationship_session.py +431 -0
  163. package/python/mindbase/relationship_suite.py +45 -0
  164. package/python/mindbase/relationships.py +70 -0
  165. package/python/mindbase/replay.py +22 -0
  166. package/python/mindbase/reply_diversity.py +53 -0
  167. package/python/mindbase/reply_gate.py +52 -0
  168. package/python/mindbase/rerank.py +41 -0
  169. package/python/mindbase/rerank_local.py +46 -0
  170. package/python/mindbase/ripple.py +187 -0
  171. package/python/mindbase/robust_search.py +68 -0
  172. package/python/mindbase/runtime.py +113 -0
  173. package/python/mindbase/scoped_identity.py +116 -0
  174. package/python/mindbase/self_insight.py +51 -0
  175. package/python/mindbase/self_model.py +116 -0
  176. package/python/mindbase/selftest.py +118 -0
  177. package/python/mindbase/semantic_memory.py +108 -0
  178. package/python/mindbase/session_store.py +175 -0
  179. package/python/mindbase/session_window.py +31 -0
  180. package/python/mindbase/shadow_eval.py +42 -0
  181. package/python/mindbase/sim_env.py +86 -0
  182. package/python/mindbase/social.py +138 -0
  183. package/python/mindbase/social_constraint.py +141 -0
  184. package/python/mindbase/social_feedback.py +95 -0
  185. package/python/mindbase/social_norm.py +225 -0
  186. package/python/mindbase/spiking_reservoir.py +204 -0
  187. package/python/mindbase/spontaneity.py +40 -0
  188. package/python/mindbase/story_loop.py +203 -0
  189. package/python/mindbase/survival_gauntlet.py +128 -0
  190. package/python/mindbase/symbolic.py +170 -0
  191. package/python/mindbase/teacher.py +244 -0
  192. package/python/mindbase/theory.py +42 -0
  193. package/python/mindbase/theory_of_mind.py +98 -0
  194. package/python/mindbase/translation_layer.py +80 -0
  195. package/python/mindbase/turn_eval.py +52 -0
  196. package/python/mindbase/types.py +78 -0
  197. package/python/mindbase/uncertainty_field.py +61 -0
  198. package/python/mindbase/user_loop.py +45 -0
  199. package/python/mindbase/user_profile.py +73 -0
  200. package/python/mindbase/value_model.py +64 -0
  201. package/python/mindbase/values.py +102 -0
  202. package/python/mindbase/vector_store.py +78 -0
  203. package/python/mindbase/viability.py +41 -0
  204. package/python/mindbase/virtual_body.py +90 -0
  205. package/python/mindbase/will.py +60 -0
  206. package/python/mindbase/working_memory.py +32 -0
  207. package/python/mindbase/workspace.py +55 -0
  208. package/ui/panel.css +16 -5
  209. package/ui/panel.html +25 -1
  210. package/ui/panel.js +57 -15
@@ -0,0 +1,178 @@
1
+ """Functional brain modules: amygdala, hippocampus, PFC, thalamus, insula,
2
+ striatum, dopamine and a small default-mode/self-referential loop.
3
+
4
+ Not a neural simulation. Numeric modules with explicit loops and behavior hooks.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+
10
+
11
+ def _clip(x, lo=0.0, hi=1.0):
12
+ try:
13
+ return max(lo, min(hi, float(x)))
14
+ except Exception:
15
+ return lo
16
+
17
+
18
+ @dataclass
19
+ class Amygdala:
20
+ threat: float = 0.0
21
+ sensitization: float = 0.0
22
+
23
+ def stimulate(self, valence: float, arousal: float, social_negative: bool,
24
+ repetition: float = 0.0) -> float:
25
+ neg = max(0.0, -float(valence))
26
+ raw = 0.45 * neg + 0.25 * _clip(arousal) + (0.20 if social_negative else 0.0)
27
+ raw += 0.10 * _clip(repetition) + 0.15 * self.sensitization
28
+ self.threat = _clip(0.55 * self.threat + 0.65 * raw)
29
+ self.sensitization = _clip(self.sensitization + 0.02 * self.threat - 0.005)
30
+ return self.threat
31
+
32
+ def decay(self, dt_min: float = 1.0) -> None:
33
+ dt = max(0.0, float(dt_min))
34
+ self.threat = _clip(self.threat * (1.0 - min(0.5, 0.01 * dt)))
35
+ self.sensitization = _clip(self.sensitization - 0.001 * dt)
36
+
37
+
38
+ @dataclass
39
+ class Hippocampus:
40
+ safety: float = 0.5
41
+ last_context: float = 0.0
42
+
43
+ def bind(self, valence: float, threat: float, trust: float = 0.5) -> float:
44
+ ctx = 0.5 + 0.5 * max(-1.0, min(1.0, float(valence))) * _clip(trust)
45
+ self.last_context = ctx
46
+ self.safety = _clip(0.85 * self.safety + 0.15 * (0.6 * ctx + 0.4 * (1.0 - threat)))
47
+ return self.safety
48
+
49
+
50
+ @dataclass
51
+ class Prefrontal:
52
+ inhibition: float = 0.5
53
+ working_memory: list = field(default_factory=list)
54
+
55
+ def regulate(self, threat: float, safety: float, load: float = 0.0) -> float:
56
+ self.inhibition = _clip(0.35 + 0.35 * _clip(safety) + 0.20 * (1.0 - _clip(load)))
57
+ regulated = _clip(threat * (1.0 - 0.65 * self.inhibition))
58
+ self.working_memory = (self.working_memory + [round(threat, 3)])[-6:]
59
+ return regulated
60
+
61
+
62
+ @dataclass
63
+ class Thalamus:
64
+ focus: float = 0.5
65
+
66
+ def relay(self, valence: float, arousal: float, social_negative: bool,
67
+ stress: float = 0.0) -> float:
68
+ salience = 0.25 + 0.35 * abs(float(valence)) + 0.20 * _clip(arousal)
69
+ salience += 0.15 if social_negative else 0.0
70
+ salience *= (1.0 - 0.25 * _clip(stress))
71
+ self.focus = _clip(salience)
72
+ return self.focus
73
+
74
+
75
+ @dataclass
76
+ class Insula:
77
+ intero_load: float = 0.2
78
+ sensation: float = 0.5
79
+
80
+ def read(self, body: dict | None, stress: float = 0.0) -> float:
81
+ b = body or {}
82
+ tired = float(b.get("fatigue", 0.0) or 0.0)
83
+ hypo = 1.0 - float(b.get("hydration", 0.6) or 0.6)
84
+ cold = abs(float(b.get("warmth", 0.68) or 0.68) - 0.68)
85
+ pain = float(b.get("pain", 0.0) or 0.0)
86
+ self.intero_load = _clip(0.20 * tired + 0.20 * hypo + 0.15 * cold +
87
+ 0.25 * pain + 0.20 * _clip(stress))
88
+ self.sensation = _clip(0.5 + 0.5 * (self.intero_load - 0.2))
89
+ return self.intero_load
90
+
91
+
92
+ @dataclass
93
+ class Striatum:
94
+ values: dict = field(default_factory=lambda: {
95
+ "speak": 0.55, "withdraw": 0.30, "self_care": 0.45, "wait": 0.30})
96
+ dopamine: float = 0.5
97
+ last_action: str = "speak"
98
+
99
+ def choose(self, threat: float, safety: float, energy: float,
100
+ intero_load: float = 0.0) -> str:
101
+ utils = {
102
+ "speak": 0.55 + 0.20 * (1.0 - threat) + 0.15 * safety,
103
+ "withdraw": 0.25 + 0.45 * threat + 0.10 * (1.0 - safety),
104
+ "self_care": 0.25 + 0.50 * intero_load + 0.15 * (1.0 - energy),
105
+ "wait": 0.25 + 0.20 * threat + 0.15 * (1.0 - energy),
106
+ }
107
+ action = max(utils, key=lambda k: utils[k] + 0.25 * self.values.get(k, 0.0))
108
+ self.last_action = action
109
+ return action
110
+
111
+ def reward(self, reward: float) -> float:
112
+ baseline = 0.5
113
+ rpe = _clip(float(reward) - baseline, -1.0, 1.0)
114
+ self.dopamine = _clip(self.dopamine + 0.15 * rpe)
115
+ self.values[self.last_action] = _clip(self.values.get(self.last_action, 0.5) + 0.10 * rpe)
116
+ return round(self.dopamine, 4)
117
+
118
+
119
+ @dataclass
120
+ class DefaultMode:
121
+ self_focus: float = 0.3
122
+ narrative: float = 0.3
123
+
124
+ def tick(self, connection: float = 0.0, stress: float = 0.0,
125
+ idle_min: float = 1.0) -> float:
126
+ idle = _clip(max(0.0, float(idle_min)) / 30.0)
127
+ self.self_focus = _clip(0.25 + 0.35 * _clip(connection) +
128
+ 0.20 * _clip(stress) + 0.20 * idle)
129
+ self.narrative = _clip(0.5 * self.self_focus + 0.5 * (1.0 - _clip(connection)))
130
+ return self.self_focus
131
+
132
+
133
+ @dataclass
134
+ class BrainLoop:
135
+ amygdala: Amygdala = field(default_factory=Amygdala)
136
+ hippocampus: Hippocampus = field(default_factory=Hippocampus)
137
+ pfc: Prefrontal = field(default_factory=Prefrontal)
138
+ thalamus: Thalamus = field(default_factory=Thalamus)
139
+ insula: Insula = field(default_factory=Insula)
140
+ striatum: Striatum = field(default_factory=Striatum)
141
+ dmn: DefaultMode = field(default_factory=DefaultMode)
142
+ last: dict = field(default_factory=dict)
143
+
144
+ def tick(self, valence: float, arousal: float, social_negative: bool = False,
145
+ repetition: float = 0.0, trust: float = 0.5,
146
+ load: float = 0.0, dt_min: float = 1.0,
147
+ body: dict | None = None, energy: float = 0.7,
148
+ connection: float = 0.0) -> dict:
149
+ self.amygdala.decay(dt_min)
150
+ focus = self.thalamus.relay(valence, arousal, social_negative, load)
151
+ raw = self.amygdala.stimulate(valence, arousal, social_negative, repetition)
152
+ safety = self.hippocampus.bind(valence, raw, trust)
153
+ intero = self.insula.read(body, load)
154
+ regulated = self.pfc.regulate(raw, safety, max(load, intero))
155
+ action = self.striatum.choose(regulated, safety, energy, intero)
156
+ self.dmn.tick(connection, load, dt_min)
157
+ self.last = {
158
+ "threat_raw": round(raw, 4), "threat": round(regulated, 4),
159
+ "safety": round(safety, 4), "inhibition": round(self.pfc.inhibition, 4),
160
+ "focus": round(focus, 4), "intero_load": round(intero, 4),
161
+ "action": action, "dopamine": round(self.striatum.dopamine, 4),
162
+ "self_focus": round(self.dmn.self_focus, 4),
163
+ }
164
+ return self.last
165
+
166
+ def reward(self, reward: float) -> float:
167
+ return self.striatum.reward(reward)
168
+
169
+ def context(self) -> str:
170
+ if not self.last:
171
+ return ""
172
+ return ("杏仁核威胁=%.2f 海马安全=%.2f 前额叶抑制=%.2f 丘脑显著性=%.2f "
173
+ "岛叶内感=%.2f 纹状体动作=%s 多巴胺=%.2f 自我聚焦=%.2f;"
174
+ "威胁要经过安全记忆和抑制,不要直接反应。"
175
+ % (self.last.get("threat_raw", 0.0), self.last.get("safety", 0.5),
176
+ self.last.get("inhibition", 0.5), self.last.get("focus", 0.5),
177
+ self.last.get("intero_load", 0.0), self.last.get("action", "speak"),
178
+ self.last.get("dopamine", 0.5), self.last.get("self_focus", 0.0)))
@@ -0,0 +1,78 @@
1
+ """Care requests: the body asks for help, but can always self-care."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from dataclasses import dataclass, field
6
+ from typing import Dict, Optional
7
+
8
+
9
+ @dataclass
10
+ class CareTracker:
11
+ pending: Optional[Dict[str, object]] = None
12
+ offered: int = 0
13
+ accepted: int = 0
14
+ ignored: int = 0
15
+ rejected: int = 0
16
+ last_offer: float = -1e9
17
+ cooldown_s: float = 1800.0
18
+ expiry_s: float = 600.0
19
+
20
+ def need(self, body) -> Optional[str]:
21
+ if body.hydration < 0.35:
22
+ return "drink"
23
+ if body.energy < 0.28:
24
+ return "eat"
25
+ if body.fatigue > 0.86:
26
+ return "rest"
27
+ return None
28
+
29
+ def offer(self, kind: str, now: Optional[float] = None) -> Dict[str, object]:
30
+ now = float(time.time() if now is None else now)
31
+ self.pending = {"kind": str(kind), "at": now, "expires": now + self.expiry_s}
32
+ self.last_offer = now
33
+ self.offered += 1
34
+ return dict(self.pending)
35
+
36
+ def can_offer(self, body, now: Optional[float] = None) -> Optional[str]:
37
+ now = float(time.time() if now is None else now)
38
+ if self.pending is not None:
39
+ return None
40
+ if now - self.last_offer < self.cooldown_s:
41
+ return None
42
+ return self.need(body)
43
+
44
+ def respond(self, text: str, body, now: Optional[float] = None) -> Optional[Dict[str, object]]:
45
+ if self.pending is None:
46
+ return None
47
+ now = float(time.time() if now is None else now)
48
+ t = str(text or "")
49
+ reject = any(w in t for w in ("不用", "不要", "不了", "别", "自己来", "不用了"))
50
+ accept = any(w in t for w in ("好", "给你", "喝吧", "吃吧", "去吧", "可以", "行", "谢谢", "嗯"))
51
+ kind = str(self.pending.get("kind") or "rest")
52
+ if reject:
53
+ self.rejected += 1
54
+ self.pending = None
55
+ body.act(kind)
56
+ return {"result": "rejected", "kind": kind, "self_care": True}
57
+ if accept:
58
+ self.accepted += 1
59
+ self.pending = None
60
+ body.act(kind)
61
+ return {"result": "accepted", "kind": kind, "self_care": False}
62
+ return None
63
+
64
+ def tick(self, body, now: Optional[float] = None) -> Optional[Dict[str, object]]:
65
+ if self.pending is None:
66
+ return None
67
+ now = float(time.time() if now is None else now)
68
+ if now < float(self.pending.get("expires", now)):
69
+ return None
70
+ kind = str(self.pending.get("kind") or "rest")
71
+ self.pending = None
72
+ self.ignored += 1
73
+ body.act(kind)
74
+ return {"result": "ignored", "kind": kind, "self_care": True}
75
+
76
+ def stats(self) -> Dict[str, object]:
77
+ return {"pending": self.pending, "offered": self.offered, "accepted": self.accepted,
78
+ "ignored": self.ignored, "rejected": self.rejected}
@@ -0,0 +1,79 @@
1
+ """Generic uncertainty/chaos search.
2
+
3
+ This is deliberately not tied to the bot: any genome, objective, mutation,
4
+ crossover and behaviour descriptor can be plugged in. A two-level density
5
+ matrix supplies an uncertainty signal that modulates mutation scale and
6
+ selection; a QD archive keeps diverse solutions.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import random
12
+ from typing import Any, Callable, Dict, List, Tuple
13
+
14
+ from .quantum import QuantumUncertainty
15
+
16
+
17
+ class ChaosSearch:
18
+ def __init__(self, objective: Callable[[Any], float],
19
+ mutate: Callable[..., Any],
20
+ descriptor: Callable[[Any], Tuple],
21
+ initials: List[Any],
22
+ rng: random.Random | None = None,
23
+ quantum_weight: float = 0.5,
24
+ quantum_gamma: float = 0.05,
25
+ quantum_dephase: float = 0.10,
26
+ mutation_scale: float = 0.20):
27
+ self.objective = objective
28
+ self.mutate = mutate
29
+ self.descriptor = descriptor
30
+ self.initials = list(initials)
31
+ self.rng = rng or random.Random(1)
32
+ self.quantum_weight = float(quantum_weight)
33
+ self.quantum_gamma = float(quantum_gamma)
34
+ self.quantum_dephase = float(quantum_dephase)
35
+ self.mutation_scale = float(mutation_scale)
36
+ self.q = QuantumUncertainty()
37
+ self.archive: Dict[Tuple, Dict[str, Any]] = {}
38
+ self.history: List[Dict[str, Any]] = []
39
+
40
+ def _uncertainty_scale(self) -> float:
41
+ self.q.step(1.0, gamma=self.quantum_gamma, dephase=self.quantum_dephase)
42
+ return 1.0 + self.quantum_weight * self.q.entropy()
43
+
44
+ def run(self, generations: int = 10, population: int = 8) -> Dict[str, Any]:
45
+ # seed archive
46
+ for g in self.initials:
47
+ self._consider(g)
48
+ for gen in range(max(1, int(generations))):
49
+ scale = self._uncertainty_scale()
50
+ elites = list(self.archive.values())
51
+ candidates = []
52
+ if elites:
53
+ for e in elites[:max(1, population // 2)]:
54
+ candidates.append(self.mutate(e["genome"], self.rng,
55
+ self.mutation_scale * scale))
56
+ while len(candidates) < max(1, population):
57
+ base = self.rng.choice(elites)["genome"] if elites else self.rng.choice(self.initials)
58
+ candidates.append(self.mutate(base, self.rng,
59
+ self.mutation_scale * scale * 1.5))
60
+ for g in candidates:
61
+ self._consider(g)
62
+ best = max(self.archive.values(), key=lambda e: e["score"])
63
+ self.history.append({"generation": gen + 1, "archive": len(self.archive),
64
+ "best": round(float(best["score"]), 5),
65
+ "uncertainty_scale": round(scale, 4)})
66
+ # feedback nudges the quantum state toward success
67
+ self.q.nudge("speak", float(best["score"]))
68
+ best = max(self.archive.values(), key=lambda e: e["score"])
69
+ return {"best": best, "archive_size": len(self.archive),
70
+ "history": self.history, "uncertainty": self.q.metrics()}
71
+
72
+ def _consider(self, genome: Any) -> None:
73
+ try:
74
+ score = float(self.objective(genome))
75
+ except Exception:
76
+ return
77
+ key = tuple(self.descriptor(genome))
78
+ if key not in self.archive or score > self.archive[key]["score"]:
79
+ self.archive[key] = {"genome": genome, "score": score, "descriptor": key}
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Dict
6
+
7
+ BOUNDS = {
8
+ "O": (0.0, 1.0), "C": (0.0, 1.0), "E": (0.0, 1.0), "A": (0.0, 1.0), "N": (0.0, 1.0),
9
+ "baseline_v": (0.0, 1.0), "baseline_a": (0.0, 1.0),
10
+ "stress_reactivity": (0.0, 1.0), "recovery_rate": (0.0, 1.0),
11
+ "social_baseline": (0.0, 1.0), "energy_baseline": (0.0, 1.0),
12
+ "curiosity_baseline": (0.0, 1.0), "safety_baseline": (0.0, 1.0),
13
+ "da_baseline": (0.0, 1.0), "oa_baseline": (0.0, 1.0), "ht_baseline": (0.0, 1.0),
14
+ "autonomy_gain": (0.0, 1.5), "learning_rate": (0.01, 0.12),
15
+ }
16
+
17
+
18
+ def merge(base: Dict[str, float], delta: Dict[str, float]) -> Dict[str, float]:
19
+ out = {}
20
+ for key, value in base.items():
21
+ d = float(delta.get(key, 0.0) or 0.0)
22
+ v = float(value) + d
23
+ lo, hi = BOUNDS.get(key, (-1e9, 1e9))
24
+ out[key] = round(max(lo, min(hi, v)), 4)
25
+ return out
26
+
27
+
28
+ def load_character(root: Path) -> Dict[str, float]:
29
+ base = json.loads((root / "base.json").read_text(encoding="utf-8"))
30
+ delta = json.loads((root / "delta.json").read_text(encoding="utf-8"))
31
+ effective = merge(base, delta)
32
+ (root / "effective.json").write_text(json.dumps(effective, ensure_ascii=False, indent=2), encoding="utf-8")
33
+ return effective
@@ -0,0 +1,38 @@
1
+ """Numeric circadian rhythm (local wall clock)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import time
6
+ from dataclasses import dataclass
7
+
8
+
9
+ def _clip(x, lo=0.0, hi=1.0):
10
+ return max(lo, min(hi, float(x)))
11
+
12
+
13
+ @dataclass
14
+ class Circadian:
15
+ night_start: float = 23.0
16
+ wake_hour: float = 7.0
17
+
18
+ def hour(self, now: float = 0.0) -> float:
19
+ return (time.localtime(float(now or time.time())).tm_hour +
20
+ time.localtime(float(now or time.time())).tm_min / 60.0)
21
+
22
+ def is_awake(self, now: float = 0.0) -> bool:
23
+ h = self.hour(now)
24
+ if self.night_start >= self.wake_hour:
25
+ return not (h >= self.night_start or h < self.wake_hour)
26
+ return self.wake_hour <= h < self.night_start
27
+
28
+ def alertness(self, now: float = 0.0) -> float:
29
+ h = self.hour(now)
30
+ # peak around 10:00 and 16:00, trough 03:00-05:00
31
+ x = 2.0 * math.pi * (h - 10.0) / 24.0
32
+ day = 0.5 + 0.5 * math.cos(x)
33
+ if 3.0 <= h <= 5.0:
34
+ day *= 0.35
35
+ return round(_clip(day), 4)
36
+
37
+ def sleep_bias(self, now: float = 0.0) -> float:
38
+ return round(_clip(1.0 - self.alertness(now)), 4)
@@ -0,0 +1,235 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict
4
+ import random
5
+ import numpy as np
6
+ from .fly_mb import FlyMushroomBody
7
+
8
+
9
+ class Circuit:
10
+ """Coarse mushroom-body populations and sparse activity (FlyWire-style scale)."""
11
+
12
+ FLYWIRE_TOTAL = 139255
13
+ FLYWIRE = {"KC": 2000, "DAN": 200, "MBON": 100, "APL": 1}
14
+ MB_SUBREGIONS = {"gamma": 0.40, "alpha": 0.30, "beta": 0.30}
15
+ SUBREGION_RATES = {"gamma": 1.00, "alpha": 0.80, "beta": 0.70}
16
+ SUBREGION_MEMORY = {"gamma": "short", "alpha": "long", "beta": "long"}
17
+ SUBREGION_TAU_DAYS = {"gamma": 1.0, "alpha": 30.0, "beta": 20.0}
18
+
19
+ POPULATIONS = {
20
+ "sensory": 3000,
21
+ "KC": 2000,
22
+ "DAN": 200,
23
+ "MBON": 100,
24
+ "APL": 1,
25
+ }
26
+
27
+ def __init__(self):
28
+ self.activity = {k: 0.0 for k in self.POPULATIONS}
29
+ self.dan_reward = 0.0
30
+ self.dan_punishment = 0.0
31
+ self.mbon_approach = 0.0
32
+ self.mbon_avoid = 0.0
33
+ self.lesions = set()
34
+ self.lesion_timers = {}
35
+ self.lesion_strength = {}
36
+ self.lesion_rate = {}
37
+ self.recovery_speed = 1.0
38
+ self.recovery_lr = 0.01
39
+ self.connection_gain = {"KC": 1.0, "DAN": 1.0, "MBON": 1.0}
40
+ self.connection_lr = 0.005
41
+ self.sparsity = 0.05
42
+ self.fly_mb = None
43
+ self.pending_features = None
44
+ self.second_order_events = 0
45
+ self.second_order_gain = 0.0
46
+ self.chronic_scar = 0.0
47
+ self.scar_floor = 0.05
48
+
49
+ def update(self, salience: float, sparse: float | None = None, reward: float = 0.0, punishment: float = 0.0) -> Dict[str, float]:
50
+ for region, left in list(self.lesion_timers.items()):
51
+ self.lesion_strength[region] = max(0.0, self.lesion_strength.get(region, 0.0) - self.lesion_rate.get(region, 0.0))
52
+ if left <= 1 or self.lesion_strength[region] <= 1e-9:
53
+ self.recover(region)
54
+ else:
55
+ self.lesion_timers[region] = left - 1
56
+ sparse = self.sparsity if sparse is None else float(sparse)
57
+ s = max(0.0, min(1.0, float(salience)))
58
+ self.dan_reward = max(0.0, min(1.0, float(reward)))
59
+ self.dan_punishment = max(0.0, min(1.0, float(punishment)))
60
+ features = np.array([s, self.dan_reward, self.dan_punishment, 1.0,
61
+ s * (1.0 - self.dan_reward), s * (1.0 - self.dan_punishment),
62
+ self.chronic_scar, 0.5], dtype=float)
63
+ if self.fly_mb is None:
64
+ self.fly_mb = FlyMushroomBody(seed=1, sparsity=self.sparsity)
65
+ if self.fly_mb is None:
66
+ self.fly_mb = FlyMushroomBody(seed=1, sparsity=self.sparsity)
67
+ dan_lesion = float(self.lesion_strength.get("DAN", 0.0))
68
+ dan_factor = max(0.0, 1.0 - dan_lesion)
69
+ if (self.dan_reward > 0.0 or self.dan_punishment > 0.0) and self.pending_features is not None:
70
+ before = float(self.fly_mb.mbon_approach)
71
+ self.fly_mb.second_order_pair(self.pending_features, features,
72
+ reward=min(1.0, max(self.dan_reward, self.dan_punishment) * dan_factor * 1.5), repeats=3)
73
+ self.second_order_gain = round(float(self.fly_mb.mbon_approach) - before, 4)
74
+ self.second_order_events += 1
75
+ self.pending_features = None
76
+ elif self.dan_reward <= 0.0 and self.dan_punishment <= 0.0:
77
+ self.pending_features = features.copy()
78
+ mb = self.fly_mb.step(features, reward=self.dan_reward * dan_factor, punishment=self.dan_punishment * dan_factor)
79
+ self.sparsity = float(self.fly_mb.sparsity)
80
+ self.activity["sensory"] = s
81
+ self.activity["KC"] = round(float(mb["kc_sparse"]), 4)
82
+ self.activity["DAN"] = max(self.dan_reward, self.dan_punishment)
83
+ self.mbon_approach = max(0.0, float(mb["mbon_approach"]))
84
+ self.mbon_avoid = max(0.0, float(mb["mbon_avoid"]))
85
+ self.activity["MBON"] = min(1.0, max(self.mbon_approach, self.mbon_avoid))
86
+ self.activity["APL"] = float(mb["apl"])
87
+ return dict(self.activity)
88
+
89
+ def memory_retention(self, subregion: str, days: float) -> float:
90
+ import math
91
+ tau = max(1e-6, self.SUBREGION_TAU_DAYS.get(subregion, 1.0))
92
+ return round(math.exp(-max(0.0, float(days)) / tau), 4)
93
+
94
+ def chronic_stress(self, amount: float = 0.01) -> None:
95
+ sev = min(0.80, self.lesion_strength.get("DAN", 0.0) + max(0.0, float(amount)))
96
+ self.lesions.add("DAN")
97
+ self.lesion_strength["DAN"] = sev
98
+ self.chronic_scar = min(0.50, self.chronic_scar + 0.001 * max(0.0, float(amount)) * 20.0)
99
+ for k in self.connection_gain:
100
+ self.connection_gain[k] = max(0.50, self.connection_gain[k] - 0.20 * max(0.0, float(amount)))
101
+
102
+ def sleep_recovery(self, duration: float) -> Dict[str, float]:
103
+ factor = min(1.0, max(0.0, float(duration)) / (8.0 * 3600.0))
104
+ for region in list(self.lesion_strength):
105
+ self.lesion_strength[region] = max(0.0, self.lesion_strength[region] - 0.5 * factor)
106
+ if self.lesion_strength[region] <= 1e-9:
107
+ self.recover(region)
108
+ for k in self.connection_gain:
109
+ self.connection_gain[k] += (1.0 - self.connection_gain[k]) * 0.20 * factor
110
+ self.sparsity += (0.05 - self.sparsity) * 0.20 * factor
111
+ if self.fly_mb is not None:
112
+ self.fly_mb.sparsity = self.sparsity
113
+ self.chronic_scar *= max(0.0, 1.0 - 0.02 * factor)
114
+ return {"factor": round(factor, 3), "lesions": sorted(self.lesions), "scar": round(self.chronic_scar, 4)}
115
+
116
+ def learn_connection(self, rpe: float) -> None:
117
+ for k in self.connection_gain:
118
+ self.connection_gain[k] = max(0.50, min(1.50, self.connection_gain[k] + self.connection_lr * float(rpe)))
119
+
120
+ def learn_recovery(self, rpe: float) -> None:
121
+ self.recovery_speed = max(0.2, min(3.0, self.recovery_speed + self.recovery_lr * float(rpe)))
122
+
123
+ def lesion(self, region: str, ticks: int | None = None, severity: float = 1.0) -> None:
124
+ region = str(region)
125
+ self.lesions.add(region)
126
+ self.lesion_strength[region] = max(0.0, min(1.0, float(severity)))
127
+ if ticks is not None:
128
+ self.lesion_timers[region] = int(ticks)
129
+ self.lesion_rate[region] = self.lesion_strength[region] / max(1, int(ticks)) * self.recovery_speed
130
+
131
+ def recover(self, region: str) -> None:
132
+ region = str(region)
133
+ self.lesions.discard(region)
134
+ self.lesion_timers.pop(region, None)
135
+ self.lesion_strength.pop(region, None)
136
+ self.lesion_rate.pop(region, None)
137
+
138
+ def learning_gain(self) -> float:
139
+ g = sum(self.MB_SUBREGIONS[k] * self.SUBREGION_RATES[k] for k in self.MB_SUBREGIONS)
140
+ fly = getattr(self, "fly_mb", None)
141
+ if fly is not None:
142
+ default_sum = sum({"gamma": 1.0, "alpha": 0.8, "beta": 0.7}.values())
143
+ g *= sum(float(v) for v in fly.subregion_gain.values()) / default_sum
144
+ g *= sum(self.connection_gain.values()) / len(self.connection_gain)
145
+ g *= 1.0 - self.chronic_scar
146
+ dan = self.lesion_strength.get("DAN", 0.0)
147
+ g *= 1.0 - 0.5 * dan
148
+ return g
149
+
150
+ def valence(self) -> float:
151
+ # MBON output is approach; DAN is modulation/punishment
152
+ mbon = self.lesion_strength.get("MBON", 0.0)
153
+ dan = self.lesion_strength.get("DAN", 0.0)
154
+ approach = float(self.mbon_approach) * (1.0 - mbon) * self.connection_gain["MBON"]
155
+ avoid = float(self.mbon_avoid) * (1.0 - mbon) * self.connection_gain["MBON"]
156
+ reward = self.dan_reward * (1.0 - dan) * self.connection_gain["DAN"]
157
+ punish = self.dan_punishment * (1.0 - dan) * self.connection_gain["DAN"]
158
+ return approach + 0.5 * reward - avoid - 0.5 * punish
159
+
160
+ def behavior_bias(self) -> str:
161
+ if self.chronic_scar >= 0.25:
162
+ return "avoid"
163
+ v = self.valence()
164
+ if v > 0.15: return "approach"
165
+ if v < -0.10: return "avoid"
166
+ return "neutral"
167
+
168
+ def spontaneous_signal(self, social_need: float = 0.0, unfinished: float = 0.0, attachment: float = 0.0) -> float:
169
+ """Low-level noise + social deficit; used to trigger voluntary speech, not timed proactive."""
170
+ kc = float(self.activity.get("KC", 0.0))
171
+ apl = float(self.activity.get("APL", 0.0))
172
+ noise = abs(random.gauss(0.0, 1.0))
173
+ drive = (0.08 + 0.55 * min(1.0, noise / 2.5) + 0.15 * max(0.0, 1.0 - apl) + 0.10 * min(1.0, kc * 8.0)
174
+ + 0.30 * max(0.0, min(1.0, float(social_need)))
175
+ + 0.20 * max(0.0, min(1.0, float(unfinished)))
176
+ + 0.15 * max(0.0, min(1.0, float(attachment))))
177
+ self.last_spontaneous = round(float(min(1.0, drive)), 4)
178
+ return self.last_spontaneous
179
+
180
+ def metabolic_cost(self) -> float:
181
+ # population activity weighted by size, normalized
182
+ units = sum(self.activity[k] * self.POPULATIONS[k] for k in self.POPULATIONS)
183
+ return min(1.0, units / 5000.0)
184
+
185
+ def enforce_capacity(self, limit: float = 0.90) -> Dict[str, object]:
186
+ rep = self.capacity_report()
187
+ if rep["utilization"] <= limit:
188
+ if rep["utilization"] < 0.35:
189
+ self.sparsity = max(0.02, self.sparsity * 0.99)
190
+ if self.fly_mb is not None:
191
+ self.fly_mb.sparsity = self.sparsity
192
+ return {"overloaded": False, "scale": 1.0}
193
+ scale = limit / max(1e-9, rep["utilization"])
194
+ self.sparsity = min(0.20, self.sparsity * 1.20)
195
+ if self.fly_mb is not None:
196
+ self.fly_mb.sparsity = self.sparsity
197
+ for k in self.activity:
198
+ self.activity[k] *= scale
199
+ self.overloaded = True
200
+ return {"overloaded": True, "scale": round(scale, 4)}
201
+
202
+ def action_activity(self, salience: float) -> float:
203
+ util = float(self.capacity_report()["utilization"])
204
+ return round(max(0.0, float(salience)) * (1.0 + util), 4)
205
+
206
+ def write_gain(self) -> float:
207
+ util = float(self.capacity_report()["utilization"])
208
+ return round(max(0.40, 1.0 - 0.60 * max(0.0, util - 0.50)), 4)
209
+
210
+ def capacity_report(self) -> Dict[str, object]:
211
+ total = sum(self.POPULATIONS.values())
212
+ active = sum(self.activity[k] * self.POPULATIONS[k] for k in self.POPULATIONS)
213
+ return {
214
+ "total_capacity": total,
215
+ "active_units": round(active, 1),
216
+ "utilization": round(active / max(1, total), 4),
217
+ "limit": 0.90,
218
+ "within_limit": (active / max(1, total)) <= 0.90,
219
+ "sparsity": round(self.sparsity, 4),
220
+ }
221
+
222
+ def structure_report(self) -> Dict[str, object]:
223
+ mb = sum(self.POPULATIONS[k] for k in ("KC", "DAN", "MBON", "APL"))
224
+ return {
225
+ "total": self.FLYWIRE_TOTAL,
226
+ "mb_neurons": mb,
227
+ "mb_fraction": round(mb / self.FLYWIRE_TOTAL, 5),
228
+ "reference": dict(self.FLYWIRE),
229
+ "subregions": {k: round(v * self.POPULATIONS["KC"], 1) for k, v in self.MB_SUBREGIONS.items()},
230
+ "memory_types": dict(self.SUBREGION_MEMORY),
231
+ }
232
+
233
+ def snapshot(self) -> Dict[str, object]:
234
+ active = {k: round(self.activity[k] * self.POPULATIONS[k], 1) for k in self.POPULATIONS}
235
+ return {"populations": dict(self.POPULATIONS), "activity": {k: round(v, 3) for k, v in self.activity.items()}, "active_units": active, "dan_reward": round(self.dan_reward, 3), "dan_punishment": round(self.dan_punishment, 3), "mbon_approach": round(self.mbon_approach, 3), "mbon_avoid": round(self.mbon_avoid, 3), "lesions": sorted(self.lesions), "recovery_speed": round(self.recovery_speed, 3), "connection_gain": {k: round(v, 3) for k, v in self.connection_gain.items()}}