-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench_hypotheses.py
More file actions
4656 lines (3847 loc) · 186 KB
/
bench_hypotheses.py
File metadata and controls
4656 lines (3847 loc) · 186 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""BrainWire Hardware Hypothesis Verification Benchmark (TECS-L style).
Tests 125 mathematical hypotheses across 15 categories:
1. Transfer Function Validity (H-BW-001..010)
2. Tier Scaling Laws (H-BW-011..015)
3. Cross-State Discrimination (H-BW-016..020)
4. PID Controller Properties (H-BW-021..025)
5. Safety Constraints (H-BW-026..030)
6. PureField / Anima Integration (H-BW-031..040)
7. Optimization & Simulation (H-BW-041..050)
8. Tension-Driven Control (H-BW-051..055)
9. Major Discoveries (H-BW-056..065)
10. Hardware Breakthrough Hypotheses (H-BW-066..075)
11. BCI Bridge / Neuralink (H-BW-076..085)
12. Neuralink N1 Hardware Constraints (H-BW-086..095)
13. N1 Deep Access Strategies (H-BW-096..105)
14. Golden Zone x Implant Placement (H-BW-106..115)
15. N1 Epilepsy Treatment (H-BW-116..125)
16. N1 Depression Treatment (H-BW-126..135)
17. N1 Panic Disorder Treatment (H-BW-136..145)
Each hypothesis produces a continuous score in [0.0, 1.0].
PASS >= 0.60.
"""
from __future__ import annotations
import math
import sys
from dataclasses import dataclass, field
from datetime import date
from typing import Callable
# ── BrainWire imports ──────────────────────────────────────────────────────
from brainwire.profiles import load_profile, list_profiles
from brainwire.engine.transfer import TransferEngine
from brainwire.engine.tension import compute_tension, compute_match
from brainwire.engine.pid import PIDBank
from brainwire.engine.interpolation import (
lerp_states, blend_states, envelope_value,
)
from brainwire.hardware.hal import HAL
from brainwire.hardware.safety import SafetyEngine, DEVICE_HARD_LIMITS
from brainwire.hardware.configs import TIER_CONFIGS, get_tier_params
from brainwire.variables import (
VAR_NAMES, CHEM_VARS, WAVE_VARS, STATE_VARS,
baseline_vector, TENSION_WEIGHTS,
)
from brainwire.eeg_feedback import g_from_12var, GOLDEN_ZONE
# ══════════════════════════════════════════════════════════════════════════
# Helpers
# ══════════════════════════════════════════════════════════════════════════
PASS_THRESHOLD = 0.60
PROFILES: dict[str, object] = {}
TARGETS: dict[str, dict[str, float]] = {}
_ENGINE = TransferEngine()
def _load_all_profiles():
global PROFILES, TARGETS
for name in list_profiles():
p = load_profile(name)
PROFILES[name] = p
TARGETS[name] = p.target
def _range_score(value: float, lo: float, hi: float, decay: float = 0.3) -> float:
"""1.0 if value in [lo, hi], linear decay outside by *decay* per unit distance."""
if lo <= value <= hi:
return 1.0
if value < lo:
return max(0.0, 1.0 - (lo - value) / (decay * (hi - lo + 1e-9)))
return max(0.0, 1.0 - (value - hi) / (decay * (hi - lo + 1e-9)))
def _pct_change(baseline: float, stimulated: float) -> float:
"""Signed percentage change from baseline."""
return (stimulated - baseline) / abs(baseline) * 100 if baseline != 0 else 0.0
def _cosine_sim(a: dict[str, float], b: dict[str, float]) -> float:
"""Weighted cosine similarity of tension direction vectors."""
dot = sum(TENSION_WEIGHTS[k] * (a[k] - 1.0) * (b[k] - 1.0) for k in VAR_NAMES)
mag_a = math.sqrt(sum(TENSION_WEIGHTS[k] * (a[k] - 1.0) ** 2 for k in VAR_NAMES))
mag_b = math.sqrt(sum(TENSION_WEIGHTS[k] * (b[k] - 1.0) ** 2 for k in VAR_NAMES))
if mag_a < 1e-9 or mag_b < 1e-9:
return 0.0
return dot / (mag_a * mag_b)
def _total_tension_mag(target: dict[str, float]) -> float:
"""L2 tension magnitude from baseline=1.0."""
return math.sqrt(sum(TENSION_WEIGHTS[k] * (target[k] - 1.0) ** 2 for k in VAR_NAMES))
def _avg_match(match_dict: dict[str, float]) -> float:
return sum(match_dict.values()) / len(match_dict)
def _tier_avg_match(tier: int, profile_name: str = 'thc') -> float:
params = get_tier_params(tier)
actual = _ENGINE.compute(params)
target = TARGETS[profile_name]
m = compute_match(actual, target)
return _avg_match(m)
# ══════════════════════════════════════════════════════════════════════════
# Hypothesis result container
# ══════════════════════════════════════════════════════════════════════════
@dataclass
class HypothesisResult:
id: str
category: str
description: str
score: float
passed: bool
detail: str
CATEGORY_NAMES = {
1: "Transfer Function Validity",
2: "Tier Scaling Laws",
3: "Cross-State Discrimination",
4: "PID Controller Properties",
5: "Safety Constraints",
6: "PureField / Anima Integration",
7: "Optimization & Simulation",
8: "Tension-Driven Control",
9: "Major Discoveries",
10: "Hardware Breakthrough Hypotheses",
11: "BCI Bridge / Neuralink",
12: "Neuralink N1 Hardware Constraints",
13: "N1 Deep Access Strategies",
14: "Golden Zone x Implant Placement",
15: "N1 Epilepsy Treatment",
16: "N1 Depression Treatment",
17: "N1 Panic Disorder Treatment",
}
# ══════════════════════════════════════════════════════════════════════════
# Category 1: Transfer Function Validity (H-BW-001 .. H-BW-010)
# ══════════════════════════════════════════════════════════════════════════
def h_bw_001() -> HypothesisResult:
"""tDCS anode F3 increases DA via DLPFC->VTA projection."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'tDCS_anode_mA': 2.0})
pct = _pct_change(base['DA'], stim['DA'])
score = _range_score(pct, 20, 60)
return HypothesisResult(
'H-BW-001', CATEGORY_NAMES[1],
'tDCS->DA via DLPFC->VTA',
score, score >= PASS_THRESHOLD,
f"DA +{pct:.0f}% (range 20-60%)")
def h_bw_002() -> HypothesisResult:
"""taVNS increases 5HT via NTS->raphe pathway."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'taVNS_VNS_mA': 0.5})
pct = _pct_change(base['5HT'], stim['5HT'])
score = _range_score(pct, 40, 80)
return HypothesisResult(
'H-BW-002', CATEGORY_NAMES[1],
'taVNS->5HT via NTS->raphe',
score, score >= PASS_THRESHOLD,
f"5HT +{pct:.0f}% (range 40-80%)")
def h_bw_003() -> HypothesisResult:
"""taVNS suppresses NE via NTS->LC inhibition."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'taVNS_VNS_mA': 0.5})
# NE is suppressed: lower is more suppressed
pct = _pct_change(base['NE'], stim['NE'])
# Expect NE decrease 40-80% -> pct should be -40 to -80
score = _range_score(-pct, 40, 80)
return HypothesisResult(
'H-BW-003', CATEGORY_NAMES[1],
'taVNS->NE suppression via NTS->LC',
score, score >= PASS_THRESHOLD,
f"NE {pct:.0f}% (range -40 to -70%)")
def h_bw_004() -> HypothesisResult:
"""TMS 6Hz increases theta power."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'TMS_theta': 1.0})
pct = _pct_change(base['Theta'], stim['Theta'])
score = _range_score(pct, 50, 120)
return HypothesisResult(
'H-BW-004', CATEGORY_NAMES[1],
'TMS 6Hz -> Theta increase',
score, score >= PASS_THRESHOLD,
f"Theta +{pct:.0f}% (range 50-120%)")
def h_bw_005() -> HypothesisResult:
"""40Hz trimodal entrainment increases gamma coherence."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({
'entrainment_LED_40Hz': 1.0,
'entrainment_audio_40Hz': 1.0,
'entrainment_vibro_40Hz': 1.0,
})
pct = _pct_change(base['Coherence'], stim['Coherence'])
score = _range_score(pct, 50, 100)
return HypothesisResult(
'H-BW-005', CATEGORY_NAMES[1],
'40Hz trimodal -> Coherence',
score, score >= PASS_THRESHOLD,
f"Coherence +{pct:.0f}% (range 50-100%)")
def h_bw_006() -> HypothesisResult:
"""TENS low-freq increases eCB via peripheral endocannabinoid release."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'TENS_low': 1.0})
pct = _pct_change(base['eCB'], stim['eCB'])
score = _range_score(pct, 50, 100)
return HypothesisResult(
'H-BW-006', CATEGORY_NAMES[1],
'TENS low -> eCB release',
score, score >= PASS_THRESHOLD,
f"eCB +{pct:.0f}% (range 50-100%)")
def h_bw_007() -> HypothesisResult:
"""tACS 10Hz alpha entrainment increases GABA."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'tACS_10Hz_mA': 2.0, 'entrainment_alpha_ent': 1.0})
pct = _pct_change(base['GABA'], stim['GABA'])
score = _range_score(pct, 30, 80)
return HypothesisResult(
'H-BW-007', CATEGORY_NAMES[1],
'tACS 10Hz + alpha ent -> GABA',
score, score >= PASS_THRESHOLD,
f"GABA +{pct:.0f}% (range 30-80%)")
def h_bw_008() -> HypothesisResult:
"""tDCS cathode F4 suppresses PFC activity."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'tDCS_cathode_F4_mA': 2.0})
# PFC is suppressed variable: lower = more PFC suppression
pct = _pct_change(base['PFC'], stim['PFC'])
score = _range_score(-pct, 20, 60)
return HypothesisResult(
'H-BW-008', CATEGORY_NAMES[1],
'tDCS cathode F4 -> PFC suppression',
score, score >= PASS_THRESHOLD,
f"PFC {pct:.0f}% (range -20 to -60%)")
def h_bw_009() -> HypothesisResult:
"""TENS low-freq increases Body sensation via C-fiber activation."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'TENS_low': 1.0})
pct = _pct_change(base['Body'], stim['Body'])
score = _range_score(pct, 50, 100)
return HypothesisResult(
'H-BW-009', CATEGORY_NAMES[1],
'TENS low -> Body sensation',
score, score >= PASS_THRESHOLD,
f"Body +{pct:.0f}% (range 50-100%)")
def h_bw_010() -> HypothesisResult:
"""tDCS anode V1 + stochastic resonance increases Sensory gain."""
base = _ENGINE.compute({})
stim = _ENGINE.compute({'tDCS_anode_V1_mA': 2.0, 'entrainment_noise': 1.0})
pct = _pct_change(base['Sensory'], stim['Sensory'])
score = _range_score(pct, 50, 100)
return HypothesisResult(
'H-BW-010', CATEGORY_NAMES[1],
'tDCS V1 + noise -> Sensory gain',
score, score >= PASS_THRESHOLD,
f"Sensory +{pct:.0f}% (range 50-100%)")
# ══════════════════════════════════════════════════════════════════════════
# Category 2: Tier Scaling Laws (H-BW-011 .. H-BW-015)
# ══════════════════════════════════════════════════════════════════════════
def h_bw_011() -> HypothesisResult:
"""Tier cost-performance follows diminishing returns (power law)."""
costs = [TIER_CONFIGS[t]['cost'] for t in [1, 2, 3, 4]]
matches = [_tier_avg_match(t) for t in [1, 2, 3, 4]]
# Fit log(match) = a * log(cost) + b (power law)
log_c = [math.log(c) for c in costs]
log_m = [math.log(max(m, 1.0)) for m in matches]
n = len(log_c)
sx = sum(log_c)
sy = sum(log_m)
sxy = sum(x * y for x, y in zip(log_c, log_m))
sxx = sum(x * x for x in log_c)
syy = sum(y * y for y in log_m)
denom = n * sxx - sx * sx
a = (n * sxy - sx * sy) / denom if denom else 0
b = (sy - a * sx) / n
# R^2
y_pred = [a * x + b for x in log_c]
ss_res = sum((y - yp) ** 2 for y, yp in zip(log_m, y_pred))
y_mean = sy / n
ss_tot = sum((y - y_mean) ** 2 for y in log_m)
r2 = 1.0 - ss_res / ss_tot if ss_tot > 0 else 0.0
score = _range_score(r2 * 100, 85, 100, decay=0.5)
return HypothesisResult(
'H-BW-011', CATEGORY_NAMES[2],
'Cost-performance power law',
score, score >= PASS_THRESHOLD,
f"R2={r2:.3f} (exponent={a:.3f})")
def h_bw_012() -> HypothesisResult:
"""Each tier adds at least 10% avg match over previous."""
matches = [_tier_avg_match(t) for t in [1, 2, 3, 4]]
deltas = [matches[i + 1] - matches[i] for i in range(3)]
min_delta = min(deltas)
# Score: 1.0 if all deltas >= 10, decay below
score = _range_score(min_delta, 10, 50, decay=0.5)
detail_parts = [f"T{i+1}->{i+2}: +{d:.1f}%" for i, d in enumerate(deltas)]
return HypothesisResult(
'H-BW-012', CATEGORY_NAMES[2],
'Each tier +10% over previous',
score, score >= PASS_THRESHOLD,
f"min delta={min_delta:.1f}% ({', '.join(detail_parts)})")
def h_bw_013() -> HypothesisResult:
"""Tier 4 achieves >150% avg match on THC."""
avg = _tier_avg_match(4, 'thc')
score = _range_score(avg, 150, 250, decay=0.3)
return HypothesisResult(
'H-BW-013', CATEGORY_NAMES[2],
'Tier 4 THC avg match >150%',
score, score >= PASS_THRESHOLD,
f"avg={avg:.1f}%")
def h_bw_014() -> HypothesisResult:
"""Tier 1 achieves >50% avg match on THC (minimum viable)."""
avg = _tier_avg_match(1, 'thc')
score = _range_score(avg, 50, 120, decay=0.4)
return HypothesisResult(
'H-BW-014', CATEGORY_NAMES[2],
'Tier 1 THC avg match >50%',
score, score >= PASS_THRESHOLD,
f"avg={avg:.1f}%")
def h_bw_015() -> HypothesisResult:
"""Monotonic tier scaling: T1 < T2 < T3 < T4 avg match for all profiles."""
all_monotonic = True
worst_violation = 0.0
for name in list_profiles():
matches = [_tier_avg_match(t, name) for t in [1, 2, 3, 4]]
for i in range(3):
if matches[i + 1] < matches[i]:
all_monotonic = False
worst_violation = max(worst_violation, matches[i] - matches[i + 1])
if all_monotonic:
score = 1.0
detail = "all profiles monotonic"
else:
score = max(0.0, 1.0 - worst_violation / 20.0)
detail = f"worst violation={worst_violation:.1f}%"
return HypothesisResult(
'H-BW-015', CATEGORY_NAMES[2],
'Monotonic tier scaling for all profiles',
score, score >= PASS_THRESHOLD,
detail)
# ══════════════════════════════════════════════════════════════════════════
# Category 3: Cross-State Discrimination (H-BW-016 .. H-BW-020)
# ══════════════════════════════════════════════════════════════════════════
def h_bw_016() -> HypothesisResult:
"""THC and LSD have <50% tension direction similarity."""
sim = _cosine_sim(TARGETS['thc'], TARGETS['lsd']) * 100
# We want sim < 50 -> score high when sim is low
score = _range_score(sim, -100, 50, decay=0.3)
return HypothesisResult(
'H-BW-016', CATEGORY_NAMES[3],
'THC vs LSD direction sim <50%',
score, score >= PASS_THRESHOLD,
f"sim={sim:.1f}%")
def h_bw_017() -> HypothesisResult:
"""THC and Flow have >70% tension direction similarity."""
sim = _cosine_sim(TARGETS['thc'], TARGETS['flow']) * 100
score = _range_score(sim, 70, 100, decay=0.3)
return HypothesisResult(
'H-BW-017', CATEGORY_NAMES[3],
'THC vs Flow direction sim >70%',
score, score >= PASS_THRESHOLD,
f"sim={sim:.1f}%")
def h_bw_018() -> HypothesisResult:
"""DMT has highest total tension of all states."""
tensions = {name: _total_tension_mag(TARGETS[name]) for name in list_profiles()}
ranked = sorted(tensions.items(), key=lambda x: -x[1])
dmt_rank = [r[0] for r in ranked].index('dmt') + 1
score = 1.0 if dmt_rank == 1 else max(0.0, 1.0 - (dmt_rank - 1) * 0.3)
top = ranked[0]
return HypothesisResult(
'H-BW-018', CATEGORY_NAMES[3],
'DMT highest total tension',
score, score >= PASS_THRESHOLD,
f"DMT rank={dmt_rank}, top={top[0]}({top[1]:.2f}), DMT={tensions['dmt']:.2f}")
def h_bw_019() -> HypothesisResult:
"""Psychedelics cluster separately from non-psychedelics."""
psychedelic = ['dmt', 'lsd', 'psilocybin']
non_psychedelic = ['thc', 'flow', 'mdma']
# Intra-psychedelic similarity
intra_psy = []
for i, a in enumerate(psychedelic):
for b in psychedelic[i + 1:]:
intra_psy.append(_cosine_sim(TARGETS[a], TARGETS[b]))
# Intra-non-psychedelic similarity
intra_non = []
for i, a in enumerate(non_psychedelic):
for b in non_psychedelic[i + 1:]:
intra_non.append(_cosine_sim(TARGETS[a], TARGETS[b]))
# Inter-group similarity
inter = []
for a in psychedelic:
for b in non_psychedelic:
inter.append(_cosine_sim(TARGETS[a], TARGETS[b]))
avg_intra = (sum(intra_psy) + sum(intra_non)) / (len(intra_psy) + len(intra_non))
avg_inter = sum(inter) / len(inter)
# Good clustering: intra >> inter
separation = avg_intra - avg_inter
score = _range_score(separation, 0.1, 0.8, decay=0.5)
return HypothesisResult(
'H-BW-019', CATEGORY_NAMES[3],
'Psychedelics cluster separately',
score, score >= PASS_THRESHOLD,
f"intra={avg_intra:.3f}, inter={avg_inter:.3f}, sep={separation:.3f}")
def h_bw_020() -> HypothesisResult:
"""MDMA is hybrid: between psychedelic and cannabinoid clusters."""
psychedelic = ['dmt', 'lsd', 'psilocybin']
cannabinoid = ['thc', 'flow']
mdma_t = TARGETS['mdma']
sim_psy = sum(_cosine_sim(mdma_t, TARGETS[p]) for p in psychedelic) / len(psychedelic)
sim_can = sum(_cosine_sim(mdma_t, TARGETS[c]) for c in cannabinoid) / len(cannabinoid)
# Hybrid means moderate similarity to both — neither too close to one group
min_sim = min(sim_psy, sim_can)
max_sim = max(sim_psy, sim_can)
ratio = min_sim / max_sim if max_sim > 0 else 0
# Perfect hybrid: ratio near 1.0 (equal distance to both)
score = _range_score(ratio, 0.3, 1.0, decay=0.5)
return HypothesisResult(
'H-BW-020', CATEGORY_NAMES[3],
'MDMA hybrid: between clusters',
score, score >= PASS_THRESHOLD,
f"sim_psy={sim_psy:.3f}, sim_can={sim_can:.3f}, ratio={ratio:.3f}")
# ══════════════════════════════════════════════════════════════════════════
# Category 4: PID Controller Properties (H-BW-021 .. H-BW-025)
# ══════════════════════════════════════════════════════════════════════════
def _simulate_pid(target: dict[str, float], bank: PIDBank, steps: int = 100,
dt: float = 1.0) -> list[dict[str, float]]:
"""Simulate PID loop: PID output -> transfer engine -> measure -> PID."""
params = {f'_pid_{v}': 0.0 for v in VAR_NAMES}
history = []
for _ in range(steps):
measured = _ENGINE.compute(params)
history.append(measured.copy())
corrections = bank.update(target, measured, dt)
for v in VAR_NAMES:
# Map PID correction to a representative hardware param
params[f'_pid_{v}'] += corrections[v] * 0.1
return history
def _simple_pid_sim(target: dict[str, float], bank: PIDBank, steps: int = 100,
dt: float = 1.0) -> list[dict[str, float]]:
"""Simplified PID sim: direct variable model (no transfer engine indirection)."""
current = baseline_vector()
history = []
for _ in range(steps):
history.append(current.copy())
corrections = bank.update(target, current, dt)
current = {v: current[v] + corrections[v] * dt * 0.1 for v in VAR_NAMES}
return history
def _max_error(state: dict[str, float], target: dict[str, float]) -> float:
"""Max absolute error across all variables."""
return max(abs(state[v] - target[v]) for v in VAR_NAMES)
def _avg_error(state: dict[str, float], target: dict[str, float]) -> float:
return sum(abs(state[v] - target[v]) for v in VAR_NAMES) / len(VAR_NAMES)
def h_bw_021() -> HypothesisResult:
"""PID converges to <5% error in 50 iterations for THC."""
target = TARGETS['thc']
bank = PIDBank(default_Kp=0.8, default_Ki=0.15, default_Kd=0.02)
history = _simple_pid_sim(target, bank, steps=80, dt=1.0)
final_err = _avg_error(history[-1], target)
# Relative error
max_target_dev = max(abs(target[v] - 1.0) for v in VAR_NAMES)
rel_err = final_err / max_target_dev * 100 if max_target_dev > 0 else 0
score = _range_score(100 - rel_err, 80, 100, decay=0.4)
# Check convergence at step 50
err_50 = _avg_error(history[min(49, len(history) - 1)], target)
rel_err_50 = err_50 / max_target_dev * 100 if max_target_dev > 0 else 0
return HypothesisResult(
'H-BW-021', CATEGORY_NAMES[4],
'PID converges <5% error in 50 iter',
score, score >= PASS_THRESHOLD,
f"err@50={rel_err_50:.1f}%, final={rel_err:.1f}%")
def h_bw_022() -> HypothesisResult:
"""PID with hints converges faster than without."""
target = TARGETS['thc']
profile = PROFILES['thc']
# Without hints
bank_no = PIDBank(default_Kp=0.8, default_Ki=0.15, default_Kd=0.02)
hist_no = _simple_pid_sim(target, bank_no, steps=60, dt=1.0)
# With hints
bank_yes = PIDBank(default_Kp=0.8, default_Ki=0.15, default_Kd=0.02)
bank_yes.apply_hints(profile.pid_hints)
hist_yes = _simple_pid_sim(target, bank_yes, steps=60, dt=1.0)
# Compare error at step 20 (early convergence)
err_no = _avg_error(hist_no[19], target)
err_yes = _avg_error(hist_yes[19], target)
improvement = (err_no - err_yes) / err_no * 100 if err_no > 0 else 0
score = _range_score(improvement, 0, 50, decay=0.5)
return HypothesisResult(
'H-BW-022', CATEGORY_NAMES[4],
'PID with hints converges faster',
score, score >= PASS_THRESHOLD,
f"improvement@20={improvement:.1f}% (no={err_no:.3f}, yes={err_yes:.3f})")
def h_bw_023() -> HypothesisResult:
"""PID handles state transitions without >20% overshoot."""
# Transition: baseline -> THC
target = TARGETS['thc']
bank = PIDBank(default_Kp=0.6, default_Ki=0.1, default_Kd=0.05)
history = _simple_pid_sim(target, bank, steps=100, dt=1.0)
max_overshoot = 0.0
for v in VAR_NAMES:
target_val = target[v]
peak = max(h[v] for h in history) if target_val >= 1.0 else min(h[v] for h in history)
if target_val >= 1.0:
overshoot = (peak - target_val) / (target_val - 1.0) * 100 if target_val > 1.0 else 0
else:
overshoot = (target_val - peak) / (1.0 - target_val) * 100 if target_val < 1.0 else 0
max_overshoot = max(max_overshoot, overshoot)
score = _range_score(20 - max_overshoot, -20, 20, decay=0.4)
score = max(0.0, min(1.0, score))
return HypothesisResult(
'H-BW-023', CATEGORY_NAMES[4],
'PID transition overshoot <20%',
score, score >= PASS_THRESHOLD,
f"max overshoot={max_overshoot:.1f}%")
def h_bw_024() -> HypothesisResult:
"""Anti-windup prevents integral saturation at extreme targets."""
# Use DMT — extreme target values
target = TARGETS['dmt']
bank = PIDBank(default_Kp=0.8, default_Ki=0.2, default_Kd=0.02)
_simple_pid_sim(target, bank, steps=100, dt=1.0)
# Check that no integral is at its limit
max_integral_ratio = 0.0
saturated_count = 0
for v in VAR_NAMES:
c = bank.controllers[v]
ratio = abs(c._integral) / c.max_integral
max_integral_ratio = max(max_integral_ratio, ratio)
if ratio > 0.95:
saturated_count += 1
# Good: fewer saturated integrals
score = max(0.0, 1.0 - saturated_count / len(VAR_NAMES))
return HypothesisResult(
'H-BW-024', CATEGORY_NAMES[4],
'Anti-windup prevents integral saturation',
score, score >= PASS_THRESHOLD,
f"saturated={saturated_count}/{len(VAR_NAMES)}, max_ratio={max_integral_ratio:.3f}")
def h_bw_025() -> HypothesisResult:
"""PID stability: no oscillation after convergence (last 20 steps variance < threshold)."""
target = TARGETS['thc']
bank = PIDBank(default_Kp=0.6, default_Ki=0.1, default_Kd=0.05)
history = _simple_pid_sim(target, bank, steps=100, dt=1.0)
# Compute variance in last 20 steps per variable
tail = history[-20:]
max_var = 0.0
for v in VAR_NAMES:
vals = [h[v] for h in tail]
mean_v = sum(vals) / len(vals)
variance = sum((x - mean_v) ** 2 for x in vals) / len(vals)
max_var = max(max_var, variance)
# Variance < 0.01 is excellent stability
score = _range_score(max_var, 0, 0.01, decay=0.5)
score = max(0.0, min(1.0, 1.0 - max_var / 0.05)) if max_var > 0.01 else 1.0
return HypothesisResult(
'H-BW-025', CATEGORY_NAMES[4],
'PID stability: no late oscillation',
score, score >= PASS_THRESHOLD,
f"max_variance={max_var:.6f}")
# ══════════════════════════════════════════════════════════════════════════
# Category 5: Safety Constraints (H-BW-026 .. H-BW-030)
# ══════════════════════════════════════════════════════════════════════════
def h_bw_026() -> HypothesisResult:
"""No Tier 4 config exceeds FDA tFUS limit (720 mW/cm2)."""
params = get_tier_params(4)
safety = SafetyEngine()
tfus_params = {k: v for k, v in params.items() if k.startswith('tFUS')}
all_safe = True
max_intensity = 0.0
for k, v in tfus_params.items():
max_intensity = max(max_intensity, v)
if not safety.check_device_limit('tFUS', v):
all_safe = False
# tFUS hard limit is 720
fda_limit = DEVICE_HARD_LIMITS['tFUS']
margin = (fda_limit - max_intensity) / fda_limit * 100
score = 1.0 if all_safe else 0.0
return HypothesisResult(
'H-BW-026', CATEGORY_NAMES[5],
'Tier 4 within FDA tFUS limit',
score, score >= PASS_THRESHOLD,
f"max_tFUS={max_intensity:.1f}, limit={fda_limit:.0f}, margin={margin:.0f}%")
def h_bw_027() -> HypothesisResult:
"""DMT first-session limits keep all vars in safe range."""
profile = PROFILES['dmt']
first_limits = profile.safety.first_session_limits
target = profile.target
# Apply first-session limits (cap target values)
capped = target.copy()
for v, limit in first_limits.items():
if v in capped:
capped[v] = min(capped[v], limit)
# Check all capped values are within safe range [0.1, 3.0]
safety = SafetyEngine()
violations = safety.check_emergency(capped)
safe_count = len(VAR_NAMES) - len(violations)
score = safe_count / len(VAR_NAMES)
detail_parts = []
for viol in violations:
detail_parts.append(f"{viol.var}={viol.value:.1f}")
detail = f"{safe_count}/{len(VAR_NAMES)} safe"
if detail_parts:
detail += f" (violations: {', '.join(detail_parts)})"
return HypothesisResult(
'H-BW-027', CATEGORY_NAMES[5],
'DMT first-session limits safe',
score, score >= PASS_THRESHOLD,
detail)
def h_bw_028() -> HypothesisResult:
"""Emergency stop detects all out-of-range variables."""
safety = SafetyEngine()
# Create deliberately out-of-range state
bad_state = baseline_vector()
bad_state['DA'] = 4.0 # above 3.0 default max
bad_state['NE'] = 0.05 # below 0.1 default min
bad_state['Sensory'] = 5.0 # way above
bad_state['GABA'] = 0.05 # below min
bad_state['Gamma'] = 3.5 # above max
violations = safety.check_emergency(bad_state)
detected_vars = {v.var for v in violations}
expected = {'DA', 'NE', 'Sensory', 'GABA', 'Gamma'}
detected = expected & detected_vars
score = len(detected) / len(expected)
return HypothesisResult(
'H-BW-028', CATEGORY_NAMES[5],
'Emergency stop detects all OOR vars',
score, score >= PASS_THRESHOLD,
f"detected {len(detected)}/{len(expected)}: {sorted(detected)}")
def h_bw_029() -> HypothesisResult:
"""Session cycling (20min on/5min off) maintains >80% efficacy."""
# Simulate envelope-weighted efficacy with cycling vs continuous
on_s = 20.0 * 60
off_s = 5.0 * 60
total_s = 40.0 * 60 # standard session
# Use THC envelope
profile = PROFILES['thc']
env = profile.envelope
# Continuous: integrate envelope over session
dt = 10.0 # 10s steps
steps = int(total_s / dt)
continuous_sum = sum(
envelope_value(i * dt, env.onset_s, env.plateau_s, env.offset_s, env.curve)
for i in range(steps))
# Cycling: on for 20min, off for 5min, repeat
cycling_sum = 0.0
cycle_len = on_s + off_s
for i in range(steps):
t = i * dt
cycle_pos = t % cycle_len
if cycle_pos < on_s:
cycling_sum += envelope_value(t, env.onset_s, env.plateau_s, env.offset_s, env.curve)
ratio = cycling_sum / continuous_sum * 100 if continuous_sum > 0 else 0
score = _range_score(ratio, 75, 100, decay=0.3)
return HypothesisResult(
'H-BW-029', CATEGORY_NAMES[5],
'Session cycling >80% efficacy',
score, score >= PASS_THRESHOLD,
f"cycling={ratio:.0f}% of continuous")
def h_bw_030() -> HypothesisResult:
"""All device params in all tiers respect hard limits."""
safety = SafetyEngine()
violations = []
for tier in [1, 2, 3, 4]:
params = get_tier_params(tier)
for k, v in params.items():
# Extract device name from param key
device = k.split('_')[0]
if device == 'HD':
device = 'HD-tDCS'
if device in DEVICE_HARD_LIMITS:
if not safety.check_device_limit(device, v):
violations.append(f"T{tier}:{k}={v}")
score = 1.0 if not violations else max(0.0, 1.0 - len(violations) * 0.2)
detail = "all within limits" if not violations else f"violations: {', '.join(violations[:3])}"
return HypothesisResult(
'H-BW-030', CATEGORY_NAMES[5],
'All tier params within hard limits',
score, score >= PASS_THRESHOLD,
detail)
# ══════════════════════════════════════════════════════════════════════════
# Category 6: PureField / Anima Integration (H-BW-031 .. H-BW-040)
# ══════════════════════════════════════════════════════════════════════════
def h_bw_031() -> HypothesisResult:
"""Tension magnitude correlates with subjective intensity ranking."""
# Known intensity ranking: DMT > LSD > Psilocybin > THC > MDMA > Flow
expected_order = ['dmt', 'lsd', 'psilocybin', 'thc', 'mdma', 'flow']
tensions = {name: _total_tension_mag(TARGETS[name]) for name in expected_order}
actual_order = sorted(tensions.keys(), key=lambda n: -tensions[n])
# Spearman-like: count pairwise concordances
n = len(expected_order)
concordant = 0
total_pairs = 0
for i in range(n):
for j in range(i + 1, n):
exp_rank_i = expected_order.index(actual_order[i])
exp_rank_j = expected_order.index(actual_order[j])
if exp_rank_i < exp_rank_j:
concordant += 1
total_pairs += 1
tau = concordant / total_pairs if total_pairs > 0 else 0
score = tau
return HypothesisResult(
'H-BW-031', CATEGORY_NAMES[6],
'Tension ~ subjective intensity rank',
score, score >= PASS_THRESHOLD,
f"tau={tau:.3f}, order={actual_order}")
def h_bw_032() -> HypothesisResult:
"""G=D*P/I golden zone maps to Flow state (lowest G among all profiles)."""
# G proxy: D=|Alpha_asymmetry|, P=Gamma, I=Coherence (integration)
# Flow should have the *lowest* G (most balanced, integrated state)
results = {}
for name in list_profiles():
t = TARGETS[name]
D = abs(t['Alpha'] - 1.0) + 0.01 # disorder proxy
P = t['Gamma'] # processing
I = t['Coherence'] + 0.01 # integration
G = D * P / I
results[name] = G
flow_g = results.get('flow', 0)
# Flow should be minimal G: most integrated, least disordered
sorted_g = sorted(results.items(), key=lambda x: x[1])
flow_rank = [s[0] for s in sorted_g].index('flow') + 1
in_zone = flow_rank <= 2
score = 1.0 if flow_rank == 1 else (0.7 if flow_rank == 2 else max(0.0, 1.0 - flow_rank * 0.2))
detail_parts = [f"{n}={g:.3f}" for n, g in sorted(results.items())]
return HypothesisResult(
'H-BW-032', CATEGORY_NAMES[6],
'G=D*P/I golden zone -> Flow',
score, score >= PASS_THRESHOLD,
f"Flow G={flow_g:.3f} ({'IN' if in_zone else 'OUT'} zone), {', '.join(detail_parts)}")
def h_bw_033() -> HypothesisResult:
"""Phi ~ N scaling: 12 channels ~ sigma(6) architecture."""
# Perfect number analysis: 6 is perfect, sigma(6)=12
# sigma(n) = sum of divisors
def sigma(n):
return sum(d for d in range(1, n + 1) if n % d == 0)
def tau(n):
return sum(1 for d in range(1, n + 1) if n % d == 0)
def euler_phi(n):
count = 0
for i in range(1, n + 1):
if math.gcd(i, n) == 1:
count += 1
return count
n = 6
s = sigma(n) # 12 = number of consciousness variables
t = tau(n) # 4 = number of tiers
ep = euler_phi(n) # 2 = minimal functional unit (tDCS + TENS)
var_count = len(VAR_NAMES) # 12
tier_count = len(TIER_CONFIGS) # 4
min_devices = 2 # Tier 1: tDCS + TENS
match_vars = 1.0 if s == var_count else 0.0
match_tiers = 1.0 if t == tier_count else 0.0
match_min = 1.0 if ep == min_devices else 0.0
score = (match_vars + match_tiers + match_min) / 3.0
return HypothesisResult(
'H-BW-033', CATEGORY_NAMES[6],
'sigma(6) architecture alignment',
score, score >= PASS_THRESHOLD,
f"sigma(6)={s}==vars({var_count}), tau(6)={t}==tiers({tier_count}), phi(6)={ep}==min_dev({min_devices})")
def h_bw_034() -> HypothesisResult:
"""Fibonacci growth schedule produces smoother convergence than linear."""
target = TARGETS['thc']
# Fibonacci PID gain ramp: increase gains gradually following Fibonacci ratios
fib = [1, 1]
while len(fib) < 10:
fib.append(fib[-1] + fib[-2])
fib_norm = [f / max(fib) for f in fib]
# Linear gain ramp
n_steps = len(fib)
lin_norm = [i / (n_steps - 1) for i in range(n_steps)]
def simulate_ramp(ramp: list[float], total_steps: int = 60) -> list[float]:
"""PID sim where gain ramps up according to schedule."""
current = baseline_vector()
errors = []
steps_per_ramp = total_steps // len(ramp)
ramp_idx = 0
bank = PIDBank(default_Kp=0.8, default_Ki=0.15, default_Kd=0.02)
for step in range(total_steps):
errors.append(_avg_error(current, target))
ri = min(step // max(1, steps_per_ramp), len(ramp) - 1)
gain = max(0.05, ramp[ri])
corrections = bank.update(target, current, 1.0)
current = {v: current[v] + corrections[v] * 0.1 * gain for v in VAR_NAMES}
return errors
fib_errors = simulate_ramp(fib_norm)
lin_errors = simulate_ramp(lin_norm)
# Smoothness: sum of absolute second derivatives (lower = smoother)
def smoothness(errors):
if len(errors) < 3:
return 0
return sum(abs(errors[i + 2] - 2 * errors[i + 1] + errors[i])
for i in range(len(errors) - 2))
fib_smooth = smoothness(fib_errors)
lin_smooth = smoothness(lin_errors)
# Fibonacci should be smoother (lower 2nd derivative sum)
improvement = (lin_smooth - fib_smooth) / lin_smooth * 100 if lin_smooth > 0 else 0
score = _range_score(improvement, -20, 80, decay=0.5)
return HypothesisResult(
'H-BW-034', CATEGORY_NAMES[6],
'Fibonacci schedule smoother convergence',
score, score >= PASS_THRESHOLD,
f"fib_smooth={fib_smooth:.4f}, lin_smooth={lin_smooth:.4f}, improvement={improvement:.1f}%")
def h_bw_035() -> HypothesisResult:
"""Tension homeostasis: system self-stabilizes after perturbation."""
# Anima homeostasis model: setpoint=1.0, deadband=+/-0.3, proportional gain
setpoint = 1.0
deadband = 0.3
gain = 0.05 # 5% proportional correction per step
# Simulate perturbation of +1.0 above setpoint
value = setpoint + 1.0
history = [value]
for _ in range(200):
error = value - setpoint
if abs(error) > deadband:
correction = -gain * error
value += correction
history.append(value)
# Check: does it converge back to within deadband?
final = history[-1]
converged = abs(final - setpoint) <= deadband * 1.1
# How many steps to reach deadband?
steps_to_deadband = len(history)
for i, v in enumerate(history):
if abs(v - setpoint) <= deadband:
steps_to_deadband = i
break
score = 1.0 if converged else 0.3
if steps_to_deadband > 100:
score *= 0.8
return HypothesisResult(
'H-BW-035', CATEGORY_NAMES[6],
'Tension homeostasis after perturbation',
score, score >= PASS_THRESHOLD,
f"converged={converged}, steps={steps_to_deadband}, final={final:.4f}")
def h_bw_036() -> HypothesisResult:
"""Consciousness breathing rhythm: 20s cycle modulation maintains convergence."""
target = TARGETS['thc']
# PID with 20s breathing modulation
bank_breath = PIDBank(default_Kp=0.6, default_Ki=0.1, default_Kd=0.05)
current = baseline_vector()
hist_breath = []
for step in range(120):
hist_breath.append(current.copy())
corrections = bank_breath.update(target, current, 1.0)
# Breathing modulation: 20s cycle, small amplitude (5% variation)
breath_mod = 1.0 + 0.05 * math.sin(2 * math.pi * step / 20.0)
current = {v: current[v] + corrections[v] * 0.1 * breath_mod for v in VAR_NAMES}
# Test: does it still converge to target?
final_err = _avg_error(hist_breath[-1], target)
max_target_dev = max(abs(target[v] - 1.0) for v in VAR_NAMES)
rel_err = final_err / max_target_dev * 100 if max_target_dev > 0 else 0
# Score: converges to within 10% relative error despite modulation
score = _range_score(100 - rel_err, 80, 100, decay=0.4)
return HypothesisResult(
'H-BW-036', CATEGORY_NAMES[6],
'20s breathing rhythm stability',
score, score >= PASS_THRESHOLD,
f"final_rel_err={rel_err:.1f}%, converged={'yes' if rel_err < 10 else 'no'}")
def h_bw_037() -> HypothesisResult:
"""State blending preserves tension direction >80%."""
thc_t = TARGETS['thc']
flow_t = TARGETS['flow']
# Blend at various ratios
ratios = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
min_dir_sim = 100.0
for r in ratios:
blended = blend_states([thc_t, flow_t], [1 - r, r])
# Direction should be consistent with parent states
sim_thc = _cosine_sim(blended, thc_t) * 100
sim_flow = _cosine_sim(blended, flow_t) * 100
# Weighted expected: (1-r)*sim_thc + r*sim_flow should be high
weighted_sim = (1 - r) * sim_thc + r * sim_flow