-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathallcode.txt
More file actions
6778 lines (5827 loc) · 276 KB
/
Copy pathallcode.txt
File metadata and controls
6778 lines (5827 loc) · 276 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
# ADCD — All Core Source Code (2026-08-13 18:19:11)
TABLE OF CONTENTS:
- src/adcd/anomaly_scenarios.py
- src/adcd/arc_scorer.py
- src/adcd/asymptotic_dictionary_proposer_v3.py
- src/adcd/bayesian_ranker.py
- src/adcd/budget_sweep.py
- src/adcd/coarse_evaluator.py
- src/adcd/constants.py
- src/adcd/context.py
- src/adcd/dimensional_checker.py
- src/adcd/grammar_proposer_v3.py
- src/adcd/identifiability.py
- src/adcd/jax_optimizer.py
- src/adcd/jax_precision_config.py
- src/adcd/metrics.py
- src/adcd/mode_detection.py
- src/adcd/pipeline.py
- src/adcd/quickfit.py
- src/adcd/real_data_loader.py
- src/adcd/real_scenarios.py
- src/adcd/residual_features.py
- src/adcd/run_adcd_v3_validation_blind.py
- src/adcd/__init__.py
- eval/audit_logger.py
- eval/compute_metrics.py
- eval/contamination_check.py
- paper/generate_final_3_figures.py
- run_outputs/adcd_v3_taxonomy_validation_report.json
- paper/neurips_paper.tex
================================================================
FILE: src/adcd/anomaly_scenarios.py
================================================================
import numpy as np
import sympy as sp
from dataclasses import dataclass
from typing import Dict, List, Tuple
from adcd.constants import G as G_CODATA, K_B as K_B_CODATA
@dataclass
class AnomalyScenario:
name: str
tier: str # "textbook" | "cross_domain" | "synthetic"
domain: str # e.g., "gravity", "thermodynamics"
# The known classical law
classical_expr: str # e.g., "0.5 * m * v**2"
classical_variables: List[str] # e.g., ["m", "v"]
classical_constants: Dict[str, float] # e.g., {"c": 3e8}
# The hidden correction (ground truth, hidden from the pipeline)
correction_type: str # "multiplicative" or "additive"
correction_expr: str # e.g., "theta_0 * (v / c)**2"
correction_constants: Dict[str, float] # e.g., {"theta_0": 0.75}
anomaly_regime: str # e.g., "high speeds v approaching c"
variables_with_units: Dict[str, str]
classical_limit_variable: str # e.g., "v"
classical_limit_direction: str # e.g., "0" (Δ -> 0 as v -> 0)
# Structural classification (for evaluation)
correction_class: str # "exponential" | "power_law" | "rational" | "trigonometric" | "polynomial" | "logarithmic"
def generate_data(self, n_points: int = 200, noise_level: float = 0.0, seed: int = 42, domain_max: float = None) -> Tuple[Dict[str, np.ndarray], np.ndarray, np.ndarray, np.ndarray]:
"""
Generates variables X, classical prediction y_classical,
noisy observation y_obs, and the corresponding residual.
"""
rng = np.random.RandomState(seed)
X = {}
# 1. Generate domain-specific variables in the anomaly-sensitive regime
if self.name == "Relativistic KE" or self.name.startswith("Subtle Misspecification"):
c = self.classical_constants["c"]
v_max = domain_max * c if domain_max is not None else 0.85 * c
X["m"] = rng.uniform(0.5, 10.0, size=n_points)
X["v"] = rng.uniform(0.1 * c, v_max, size=n_points)
elif self.name == "Time Dilation":
c = self.classical_constants.get("c", 1.0)
v_max = domain_max * c if domain_max is not None else 0.99 * c
X["t_0"] = rng.uniform(1.0, 10.0, size=n_points)
X["v"] = rng.uniform(0.1 * c, v_max, size=n_points)
elif self.name == "Entropy Expansion":
V_i = rng.uniform(1.0, 10.0, size=n_points)
u_max = domain_max if domain_max is not None else 100.0
dV = rng.uniform(0.1, u_max, size=n_points) * V_i
S_i = np.full_like(V_i, 15.0)
X["V_i"] = V_i
X["dV"] = dV
X["S_i"] = S_i
elif self.name == "Yukawa Gravity":
X["m"] = rng.uniform(1.0, 10.0, size=n_points)
X["M"] = rng.uniform(10.0, 100.0, size=n_points)
X["r"] = rng.uniform(0.5, 5.0, size=n_points)
elif self.name == "Anharmonic Spring":
X["k"] = rng.uniform(5.0, 50.0, size=n_points)
X["x"] = rng.uniform(0.1, 3.0, size=n_points)
elif self.name == "Screened Coulomb":
r_max = domain_max if domain_max is not None else 4.0
X["q1"] = rng.uniform(1e-6, 1e-5, size=n_points)
X["q2"] = rng.uniform(1e-6, 1e-5, size=n_points)
X["r"] = rng.uniform(0.2, r_max, size=n_points)
elif self.name == "Net Radiation":
X["A"] = rng.uniform(0.1, 2.0, size=n_points)
X["T"] = rng.uniform(250.0, 800.0, size=n_points)
elif "Nonlinear Drag" in self.name:
X["b"] = rng.uniform(0.5, 5.0, size=n_points)
X["v"] = rng.uniform(0.1, 5.0, size=n_points)
elif self.name == "Mystery-A":
X["m"] = rng.uniform(1.0, 10.0, size=n_points)
X["M"] = rng.uniform(10.0, 100.0, size=n_points)
X["r"] = rng.uniform(0.5, 5.0, size=n_points)
elif self.name == "Mystery-B":
X["m"] = rng.uniform(0.5, 5.0, size=n_points)
X["v"] = rng.uniform(0.1, 10.0, size=n_points)
elif self.name == "Mystery-C":
X["k"] = rng.uniform(10.0, 100.0, size=n_points)
X["x"] = rng.uniform(0.1, 5.0, size=n_points)
elif self.name == "Blind-1: Van der Waals":
X["n"] = rng.uniform(1.0, 5.0, size=n_points)
X["T"] = rng.uniform(250.0, 450.0, size=n_points)
X["V"] = rng.uniform(1.0, 5.0, size=n_points)
elif self.name == "Blind-2: Stokes-Einstein":
X["T"] = rng.uniform(270.0, 350.0, size=n_points)
X["r"] = rng.uniform(1.0, 5.0, size=n_points)
elif self.name == "Blind-3: Wien Displacement" or self.name == "Blind-8: Composite Blackbody":
X["T"] = rng.uniform(1000.0, 6000.0, size=n_points)
f_max = domain_max * 1e15 if domain_max is not None else 1e14
X["f"] = rng.uniform(1e12, f_max, size=n_points)
elif self.name == "Blind-4: Relativistic Pendulum":
c = self.classical_constants["c"]
v_max = domain_max * c if domain_max is not None else 0.85 * c
X["m"] = rng.uniform(0.5, 10.0, size=n_points)
X["v"] = rng.uniform(0.1 * c, v_max, size=n_points)
elif self.name == "Blind-5: Clausius-Mossotti Field" or self.name == "Blind-7: Casimir Vacuum":
X["m"] = rng.uniform(1.0, 10.0, size=n_points)
X["M"] = rng.uniform(10.0, 100.0, size=n_points)
X["r"] = rng.uniform(0.5, 5.0, size=n_points)
elif self.name == "Blind-6: Magnus Wind-Tunnel" or self.name == "Blind-9: Composite Relativistic Drag":
X["b"] = rng.uniform(0.5, 5.0, size=n_points)
X["v"] = rng.uniform(0.1, 5.0, size=n_points)
elif self.name == "MV-1: Yukawa Mass-Ratio":
X["m"] = rng.uniform(1.0, 10.0, size=n_points)
X["M"] = rng.uniform(10.0, 100.0, size=n_points)
X["r"] = rng.uniform(0.5, 5.0, size=n_points)
elif self.name == "MV-2: Plasma Correction":
X["n"] = rng.uniform(1e18, 1e21, size=n_points)
X["T"] = rng.uniform(500.0, 5000.0, size=n_points)
elif self.name == "MV-3: Turbulent Drag 2D":
X["v"] = rng.uniform(0.1, 10.0, size=n_points)
X["rho"] = rng.uniform(0.5, 5.0, size=n_points)
elif self.name == "MV-4: Van der Waals 2D":
X["n"] = rng.uniform(0.5, 5.0, size=n_points)
X["V"] = rng.uniform(1.0, 10.0, size=n_points)
elif self.name == "Misspecification 1: Wrong Baseline Form":
X["m"] = rng.uniform(1.0, 10.0, size=n_points)
X["v"] = rng.uniform(0.1, 5.0, size=n_points)
elif self.name == "Misspecification 2: Missing Variable":
X["m"] = rng.uniform(1.0, 10.0, size=n_points)
X["g"] = np.full(n_points, 9.81)
# We generate 'v' here internally to create the ground truth,
# even though the user (classical_variables) didn't specify it.
# We must explicitly add it to local_corr_dict later.
self._hidden_v = rng.uniform(0.1, 5.0, size=n_points)
elif self.name == "Misspecification 3: Spurious Variable":
X["k"] = rng.uniform(5.0, 50.0, size=n_points)
X["x"] = rng.uniform(0.1, 3.0, size=n_points)
X["T"] = rng.uniform(250.0, 400.0, size=n_points) # Irrelevant variable
else:
# Fallback random generator for arbitrary names
for var in self.classical_variables:
X[var] = rng.uniform(1.0, 10.0, size=n_points)
# 2. Evaluate classical law
local_dict = {**X, **self.classical_constants}
y_classical = eval(self.classical_expr, {"np": np, "sp": sp}, local_dict)
if np.isscalar(y_classical):
y_classical = np.full(n_points, y_classical)
# 3. Evaluate ground-truth correction
local_corr_dict = {**X, **self.classical_constants, **self.correction_constants}
# Inject hidden variables for missing variable case
if self.name == "Misspecification 2: Missing Variable":
local_corr_dict["v"] = self._hidden_v
# Safely evaluate ground truth correction
# Replace theta_X names with their actual values in the expression
expr_str = self.correction_expr
for k, v in self.correction_constants.items():
expr_str = expr_str.replace(k, str(v))
# Map exp, sin, cos, tanh to numpy counterparts
eval_env = {
"np": np,
"sp": sp,
"exp": np.exp,
"sin": np.sin,
"cos": np.cos,
"tanh": np.tanh,
"log": np.log,
"sqrt": np.sqrt
}
delta_true = eval(expr_str, eval_env, local_corr_dict)
# 4. Compute y_true
if self.correction_type == "multiplicative":
y_true = y_classical * (1.0 + delta_true)
else: # additive
y_true = y_classical + delta_true
# 5. Add observational Gaussian noise
if noise_level > 0.0:
# Multiplicative noise relative to y_true
noise = rng.normal(0, noise_level, size=n_points)
y_obs = y_true * (1.0 + noise)
else:
y_obs = y_true.copy()
# 6. Compute residual
if self.correction_type == "multiplicative":
residual = y_obs / y_classical - 1.0
else:
residual = y_obs - y_classical
return X, y_obs, y_classical, residual
def get_all_scenarios() -> List[AnomalyScenario]:
"""Returns standard scenarios plus multivariable Phase 2 scenarios."""
return [
AnomalyScenario(
name="Entropy Expansion",
tier="textbook",
domain="boltzmann_thermodynamics",
classical_expr="S_i",
classical_variables=["V_i", "dV"],
classical_constants={"nR": 8.314, "S_i": 15.0},
correction_type="multiplicative",
correction_expr="(nR/S_i) * log(1.0 + dV/V_i)",
correction_constants={},
anomaly_regime="large volume expansion",
variables_with_units={"V_i": "m^3", "dV": "m^3"},
classical_limit_variable="dV",
classical_limit_direction="-> 0",
correction_class="logarithmic"
),
# =========================================================================
# TIER 2: Multivariable & Phase 2 Scenarios
# =========================================================================
AnomalyScenario(
name="Time Dilation",
tier="textbook",
domain="lorentz_special_relativity",
classical_expr="t_0",
classical_variables=["t_0", "v"],
classical_constants={"c": 1.0},
correction_type="multiplicative",
correction_expr="1.0 / sqrt(1.0 - (v / c)**2) - 1.0",
correction_constants={},
anomaly_regime="high speeds v approaching c",
variables_with_units={"t_0": "s", "v": "m/s", "c": "m/s"},
classical_limit_variable="v",
classical_limit_direction="0",
correction_class="rational"
),
AnomalyScenario(
name="Relativistic KE",
tier="textbook",
domain="relativistic",
classical_expr="0.5 * m * v**2",
classical_variables=["m", "v"],
classical_constants={"c": 3.0e8},
correction_type="multiplicative",
correction_expr="theta_0 * (v / c)**2",
correction_constants={"theta_0": 0.75},
anomaly_regime="high speeds v approaching c",
variables_with_units={"m": "kg", "v": "m/s", "c": "m/s"},
classical_limit_variable="v",
classical_limit_direction="0",
correction_class="polynomial"
),
AnomalyScenario(
name="Yukawa Gravity",
tier="textbook",
domain="gravitation",
classical_expr="G * m * M / r**2",
classical_variables=["m", "M", "r"],
classical_constants={"G": G_CODATA},
correction_type="multiplicative",
correction_expr="theta_0 * exp(-r / theta_1)",
correction_constants={"theta_0": 0.15, "theta_1": 2.5},
anomaly_regime="short distances r < 5.0",
variables_with_units={"m": "kg", "M": "kg", "r": "m", "G": "N*m^2/kg^2"},
classical_limit_variable="r",
classical_limit_direction="oo",
correction_class="exponential"
),
AnomalyScenario(
name="Anharmonic Spring",
tier="textbook",
domain="mechanics",
classical_expr="0.5 * k * x**2",
classical_variables=["k", "x"],
classical_constants={},
correction_type="additive",
correction_expr="theta_0 * x**4",
correction_constants={"theta_0": 0.15},
anomaly_regime="large amplitude displacements x > 1.5",
variables_with_units={"k": "N/m", "x": "m"},
classical_limit_variable="x",
classical_limit_direction="0",
correction_class="polynomial"
),
# =========================================================================
# TIER 2: Cross-Domain (known physics, unusual pairing)
# =========================================================================
AnomalyScenario(
name="Screened Coulomb",
tier="cross_domain",
domain="yukawa_debye_screening",
classical_expr="k_e * q1 * q2 / r**2",
classical_variables=["q1", "q2", "r"],
classical_constants={"k_e": 8.9876e9},
correction_type="multiplicative",
correction_expr="exp(-r / theta_0) - 1.0",
correction_constants={"theta_0": 1.5},
anomaly_regime="shielded plasma environments, large distances r > 1.0",
variables_with_units={"q1": "C", "q2": "C", "r": "m", "k_e": "N*m^2/C^2"},
classical_limit_variable="r",
classical_limit_direction="0",
correction_class="exponential"
),
AnomalyScenario(
name="Net Radiation",
tier="cross_domain",
domain="thermodynamics",
classical_expr="sigma * A * T**4",
classical_variables=["A", "T"],
classical_constants={"sigma": 5.6704e-8},
correction_type="multiplicative",
correction_expr="- (theta_0 / T)**4",
# We treat T_env = 293.15 K as theta_0 parameter
correction_constants={"theta_0": 293.15},
anomaly_regime="cool temperatures close to ambient temperature T < 500 K",
variables_with_units={"A": "m^2", "T": "K", "sigma": "W/(m^2*K^4)"},
classical_limit_variable="T",
classical_limit_direction="oo",
correction_class="power_law"
),
AnomalyScenario(
name="Nonlinear Drag",
tier="cross_domain",
domain="fluid dynamics",
classical_expr="b * v",
classical_variables=["b", "v"],
classical_constants={},
correction_type="additive",
# F_drag = b*v + theta_0 * v**2
# residual = F_drag - b*v = theta_0 * v**2
# Enforces addition of quadratic drag at higher Reynolds numbers
correction_expr="theta_0 * v**2",
correction_constants={"theta_0": 0.25},
anomaly_regime="high speed turbulent flows v > 2.0",
variables_with_units={"b": "kg/s", "v": "m/s"},
classical_limit_variable="v",
classical_limit_direction="0",
correction_class="polynomial"
),
# =========================================================================
# =========================================================================
AnomalyScenario(
name="Mystery-A",
tier="synthetic",
domain="gravitation",
classical_expr="G * m * M / r**2",
classical_variables=["m", "M", "r"],
classical_constants={"G": G_CODATA},
correction_type="multiplicative",
correction_expr="-tanh(theta_0 / r)**2",
correction_constants={"theta_0": 1.2},
anomaly_regime="sub-wavelength strong gravitational fields, small r < 3.0",
variables_with_units={"m": "kg", "M": "kg", "r": "m", "G": "N*m^2/kg^2"},
classical_limit_variable="r",
classical_limit_direction="oo",
correction_class="trigonometric"
),
AnomalyScenario(
name="Mystery-B",
tier="synthetic",
domain="mechanics",
classical_expr="0.5 * m * v**2",
classical_variables=["m", "v"],
classical_constants={},
correction_type="multiplicative",
# sinc correction function: sinc(v/v_0) - 1
correction_expr="sin(v / theta_0) / (v / theta_0) - 1.0",
correction_constants={"theta_0": 4.5},
anomaly_regime="velocity fluctuations under quantum boundary, v > 1.0",
variables_with_units={"m": "kg", "v": "m/s"},
classical_limit_variable="v",
classical_limit_direction="0",
correction_class="trigonometric"
),
AnomalyScenario(
name="Mystery-C",
tier="synthetic",
domain="mechanics",
classical_expr="k * x",
classical_variables=["k", "x"],
classical_constants={},
correction_type="multiplicative",
correction_expr="log(1.0 + x / theta_0) / (x / theta_0) - 1.0",
correction_constants={"theta_0": 2.0},
anomaly_regime="nonlinear polymer stretching, x > 0.5",
variables_with_units={"k": "N/m", "x": "m"},
classical_limit_variable="x",
classical_limit_direction="0",
correction_class="logarithmic"
),
# ── BLIND TEST SCENARIOS ──────────────────────────────────────────────
# Ground truth DISEMBUNYIKAN dari pipeline. Kita hanya tahu correction_class.
# Ini untuk membuktikan generalisasi di luar benchmark yang dibuat sendiri.
AnomalyScenario(
name="Blind-1: Van der Waals",
tier="blind",
domain="thermodynamics",
# Classical: Ideal gas law: P = nRT/V
# Anomaly: Van der Waals correction factor (a/V^2 pressure term)
classical_expr="n * R * T / V",
classical_variables=["n", "T", "V"],
classical_constants={"R": 8.314},
correction_type="multiplicative",
# Correction: (1 - a*n^2/V^2) factor, simplified as additive delta
correction_expr="theta_0 * n**2 / V**2",
correction_constants={"theta_0": 0.364}, # 'a' for CO2 in Pa·m^6/mol^2
anomaly_regime="high pressure / low volume gas, V < 5L",
variables_with_units={"n": "mol", "T": "K", "V": "m^3"},
classical_limit_variable="V",
classical_limit_direction="oo", # correction -> 0 as V -> infinity (ideal gas limit)
correction_class="power_law"
),
AnomalyScenario(
name="Blind-2: Stokes-Einstein",
tier="blind",
domain="biophysics",
# Classical: Einstein diffusion D = kT/(6*pi*eta*r)
# Anomaly: Shape correction factor for non-spherical particles
classical_expr="k_B * T / (6 * pi * eta * r)",
classical_variables=["T", "r"],
classical_constants={"k_B": K_B_CODATA, "pi": 3.14159, "eta": 1e-3},
correction_type="multiplicative",
# Oblate spheroid correction: (3/8)*sqrt(pi)*r^0.5 - 1 (simplified)
correction_expr="theta_0 * (r / theta_1)**0.5",
correction_constants={"theta_0": 0.15, "theta_1": 1.0},
anomaly_regime="non-spherical macromolecules, r > 5nm",
variables_with_units={"T": "K", "r": "m"},
classical_limit_variable="r",
classical_limit_direction="0",
correction_class="power_law"
),
AnomalyScenario(
name="Blind-3: Wien Displacement",
tier="blind",
domain="quantum_optics",
# Classical: Rayleigh-Jeans law: I = 2*k*T*f^2/c^2 (low freq)
# Anomaly: Planck quantum correction
classical_expr="2 * k_B * T * f**2 / c**2",
classical_variables=["T", "f"],
classical_constants={"k_B": K_B_CODATA, "c": 3e8},
correction_type="multiplicative",
# Quantum correction: (hf/kT)/(exp(hf/kT) - 1) relative to kT/hf limit
# Simplified as: exp(-theta_0 * f / T) correction
correction_expr="exp(-theta_0 * f / T) / (1 - exp(-theta_0 * f / T)) * (theta_0 * f / T)",
correction_constants={"theta_0": 4.799e-11}, # h/k_B
anomaly_regime="high frequency UV/visible regime, f > 1e13 Hz",
variables_with_units={"T": "K", "f": "Hz"},
classical_limit_variable="f",
classical_limit_direction="0",
correction_class="exponential"
),
AnomalyScenario(
name="Blind-4: Relativistic Pendulum",
tier="blind",
domain="relativistic",
classical_expr="0.5 * m * v**2",
classical_variables=["m", "v"],
classical_constants={"c": 3.0e8},
correction_type="multiplicative",
correction_expr="2.0 * (c/v)**2 * (1.0 / sqrt(1.0 - (v/c)**2) - 1.0) - 1.0",
correction_constants={},
anomaly_regime="high speeds approaching c",
variables_with_units={"m": "kg", "v": "m/s", "c": "m/s"},
classical_limit_variable="v",
classical_limit_direction="0",
correction_class="rational"
),
AnomalyScenario(
name="Blind-5: Clausius-Mossotti Field",
tier="blind",
domain="gravitation",
classical_expr="G * m * M / r**2",
classical_variables=["m", "M", "r"],
classical_constants={"G": G_CODATA},
correction_type="multiplicative",
correction_expr="theta_0 * (r / theta_1) / (1.0 + r / theta_1)",
correction_constants={"theta_0": 0.25, "theta_1": 2.0},
anomaly_regime="short distance gravitational field scaling",
variables_with_units={"m": "kg", "M": "kg", "r": "m", "G": "N*m^2/kg^2"},
classical_limit_variable="r",
classical_limit_direction="0",
correction_class="rational"
),
AnomalyScenario(
name="Blind-6: Magnus Wind-Tunnel",
tier="blind",
domain="fluid dynamics",
classical_expr="b * v",
classical_variables=["b", "v"],
classical_constants={},
correction_type="multiplicative",
correction_expr="theta_0 * (v / theta_1)**1.5",
correction_constants={"theta_0": 0.4, "theta_1": 1.0},
anomaly_regime="turbulent high speed airflow scaling",
variables_with_units={"b": "kg/s", "v": "m/s"},
classical_limit_variable="v",
classical_limit_direction="0",
correction_class="power_law"
),
AnomalyScenario(
name="Blind-7: Casimir Vacuum",
tier="blind",
domain="gravitation",
classical_expr="G * m * M / r**2",
classical_variables=["m", "M", "r"],
classical_constants={"G": G_CODATA},
correction_type="additive",
correction_expr="-theta_0 / r**4",
correction_constants={"theta_0": 0.05},
anomaly_regime="sub-micron distance vacuum force correction",
variables_with_units={"m": "kg", "M": "kg", "r": "m", "G": "N*m^2/kg^2"},
classical_limit_variable="r",
classical_limit_direction="oo",
correction_class="power_law"
),
AnomalyScenario(
name="Blind-8: Composite Blackbody",
tier="blind",
domain="quantum_optics",
classical_expr="2 * k_B * T * f**2 / c**2",
classical_variables=["T", "f"],
classical_constants={"k_B": K_B_CODATA, "c": 3e8},
correction_type="multiplicative",
# Composite product of polynomial and exponential
correction_expr="(theta_0 * f / T) * exp(-theta_0 * f / T)",
correction_constants={"theta_0": 4.799e-11},
anomaly_regime="high frequency radiation limit",
variables_with_units={"T": "K", "f": "Hz"},
classical_limit_variable="f",
classical_limit_direction="0",
correction_class="exponential"
),
AnomalyScenario(
name="Blind-9: Composite Relativistic Drag",
tier="blind",
domain="fluid dynamics",
classical_expr="b * v",
classical_variables=["b", "v"],
classical_constants={"c": 3e8},
correction_type="multiplicative",
# Composite product of polynomial and exponential
correction_expr="(v / c)**2 * exp(-v / c)",
correction_constants={},
anomaly_regime="relativistic drag limits",
variables_with_units={"b": "kg/s", "v": "m/s", "c": "m/s"},
classical_limit_variable="v",
classical_limit_direction="0",
correction_class="exponential"
),
] + get_mv_scenarios()
def get_mv_scenarios() -> List[AnomalyScenario]:
"""Four validated multivariable correction scenarios (Phase 2)."""
return [
AnomalyScenario(
name="MV-1: Yukawa Mass-Ratio",
tier="multivariable",
domain="gravitation",
classical_expr="G * m * M / r**2",
classical_variables=["m", "M", "r"],
classical_constants={"G": G_CODATA, "r_0": 2.5},
correction_type="multiplicative",
correction_expr="theta_0 * (m / M) * exp(-r / r_0)",
correction_constants={"theta_0": 0.50},
anomaly_regime="mass-ratio screening with exponential radial decay",
variables_with_units={"m": "kg", "M": "kg", "r": "m", "G": "N*m^2/kg^2"},
classical_limit_variable="r,m",
classical_limit_direction="oo,0",
correction_class="exponential",
),
AnomalyScenario(
name="MV-2: Plasma Correction",
tier="multivariable",
domain="plasma physics",
classical_expr="n * k_B * T",
classical_variables=["n", "T"],
classical_constants={"k_B": K_B_CODATA, "n_ref": 1e20, "T_ref": 1000.0},
correction_type="multiplicative",
correction_expr="theta_0 * (n / n_ref) * (T_ref / T)**0.5",
correction_constants={"theta_0": 0.3},
anomaly_regime="low density and high temperature plasma limits",
variables_with_units={"n": "1/m^3", "T": "K"},
classical_limit_variable="n,T",
classical_limit_direction="0,oo",
correction_class="power_law",
),
AnomalyScenario(
name="MV-3: Turbulent Drag 2D",
tier="multivariable",
domain="fluid dynamics",
classical_expr="b * v",
classical_variables=["v", "rho"],
classical_constants={"b": 1.0, "v_ref": 10.0, "rho_ref": 1.0},
correction_type="additive",
correction_expr="theta_0 * (v / v_ref)**2 * (rho / rho_ref)",
correction_constants={"theta_0": 0.5},
anomaly_regime="turbulent drag at low speed and density",
variables_with_units={"v": "m/s", "rho": "kg/m^3"},
classical_limit_variable="v,rho",
classical_limit_direction="0,0",
correction_class="power_law",
),
AnomalyScenario(
name="MV-4: Van der Waals 2D",
tier="multivariable",
domain="thermodynamics",
classical_expr="n * k_B * T / V",
classical_variables=["n", "V"],
classical_constants={
"k_B": K_B_CODATA,
"T": 300.0,
"n_ref": 1.0,
"V_ref": 1.0,
},
correction_type="additive",
correction_expr="theta_0 * (n / n_ref)**2 / (V / V_ref)**2",
correction_constants={"theta_0": 0.1},
anomaly_regime="van der Waals molecular interaction correction",
variables_with_units={"n": "mol", "V": "m^3"},
classical_limit_variable="n,V",
classical_limit_direction="0,oo",
correction_class="power_law",
),
]
def get_mv_scenario(name: str) -> AnomalyScenario:
"""Return a multivariable scenario by full or partial name."""
for scenario in get_mv_scenarios():
if scenario.name == name or scenario.name.startswith(name):
return scenario
raise KeyError(f"Unknown multivariable scenario: {name}")
================================================================
FILE: src/adcd/arc_scorer.py
================================================================
import logging
from dataclasses import dataclass
from typing import List, Union, Any, Dict, Sequence
import numpy as np
import sympy as sp
# Structured Logging Configuration
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ARCScorer")
@dataclass
class AsymptoticRegime:
"""
Formal representation of asymptotic physical boundary conditions (Regime Bounds).
R_k = (variable, limit_target, ground_truth_expression, importance_weight)
"""
variable: Union[str, sp.Symbol]
limit_target: Any # Can be numeric (0, 1) or sp.oo / -sp.oo
ground_truth_expr: Union[str, sp.Expr]
weight: float = 1.0
def __post_init__(self):
# Automatically convert strings to SymPy symbolic objects if needed
if isinstance(self.variable, str):
self.variable = sp.Symbol(self.variable)
if isinstance(self.ground_truth_expr, str):
self.ground_truth_expr = sp.sympify(self.ground_truth_expr)
def calculate_similarity(expr1: sp.Expr, expr2: sp.Expr) -> float:
"""
Evaluates the structural mathematical similarity between two algebraic expressions
using a Three-Tier verification architecture (Symbolic -> Divergence -> Numerical).
"""
# --- TIER 1: EXACT SYMBOLIC VERIFICATION ---
try:
diff = sp.simplify(expr1 - expr2)
if diff == 0:
return 1.0
except Exception as e:
logger.debug(f"Tier 1 simplification split failed: {e}")
# --- TIER 3: DIVERGENCE DETECTION (HARD FAILURE GATE) ---
# If one expression diverges to infinity/undefined while the other is constant
inf_tokens = [sp.oo, -sp.oo, sp.zoo]
is_inf1 = expr1 in inf_tokens or getattr(expr1, "is_infinite", False)
is_inf2 = expr2 in inf_tokens or getattr(expr2, "is_infinite", False)
if is_inf1 != is_inf2:
return 0.0
if is_inf1 and is_inf2:
return 1.0 if expr1 == expr2 else 0.0
# --- TIER 2: NUMERICAL PROXIMITY EVALUATION (FALLBACK STRATEGY) ---
# If algebraic simplification fails due to non-elementary transcendental functions,
# sample 100 random points across the remaining physical constants (e.g., m, c, G, M).
free_symbols = expr1.free_symbols.union(expr2.free_symbols)
if not free_symbols:
try:
val1 = float(expr1.evalf())
val2 = float(expr2.evalf())
if np.isnan(val1) or np.isnan(val2):
return 0.0
if abs(val1 - val2) < 1e-4:
return 1.0
denom = max(abs(val2), 1e-3)
rel_error = abs(val1 - val2) / denom
return float(np.exp(-rel_error))
except Exception:
return 0.0
# Consistent random number generator (seeded for testing stability)
rng = np.random.default_rng(42)
symbols_list = list(free_symbols)
errors = []
for _ in range(100):
# Assign reasonable random positive physical values [0.5, 2.0] for remaining parameters
sample_vals = rng.uniform(0.5, 2.0, size=len(symbols_list))
subs_dict = dict(zip(symbols_list, sample_vals))
try:
val1 = float(expr1.subs(subs_dict).evalf())
val2 = float(expr2.subs(subs_dict).evalf())
if np.isinf(val1) or np.isinf(val2) or np.isnan(val1) or np.isnan(val2):
return 0.0
rel_error = abs(val1 - val2) / (abs(val2) + 1e-9)
errors.append(rel_error)
except Exception:
return 0.0
if not errors:
return 0.0
mean_relative_error = np.mean(errors)
return float(np.exp(-mean_relative_error))
def _parse_limit_tokens(
limit_variables: Union[str, Sequence[str]],
limit_directions: Union[str, Sequence[str]],
) -> tuple[List[str], List[str]]:
"""Parse comma-separated or sequence limit specs into aligned variable/direction lists."""
if isinstance(limit_variables, str):
vars_list = [v.strip() for v in limit_variables.split(",") if v.strip()]
else:
vars_list = [str(v).strip() for v in limit_variables]
if isinstance(limit_directions, str):
dirs_list = [d.strip() for d in limit_directions.split(",") if d.strip()]
else:
dirs_list = [str(d).strip() for d in limit_directions]
if not vars_list:
raise ValueError("At least one limit variable is required.")
if not dirs_list:
dirs_list = ["0"]
if len(dirs_list) < len(vars_list):
dirs_list.extend([dirs_list[-1]] * (len(vars_list) - len(dirs_list)))
elif len(dirs_list) > len(vars_list):
dirs_list = dirs_list[: len(vars_list)]
return vars_list, dirs_list
def build_arc_regimes(
limit_variables: Union[str, Sequence[str]],
limit_directions: Union[str, Sequence[str]] = "0",
ground_truth_expr: Union[str, sp.Expr] = "0",
weight: float = 1.0,
) -> List[AsymptoticRegime]:
"""
Build ARC asymptotic regimes for one or more limit variables.
Supports multi-variable corrections Δ(x₁, x₂, …) by specifying comma-separated
limits, e.g. limit_variables="x,y" and limit_directions="0,oo".
"""
vars_list, dirs_list = _parse_limit_tokens(limit_variables, limit_directions)
regimes: List[AsymptoticRegime] = []
for var, direction in zip(vars_list, dirs_list):
limit_target = sp.oo if direction == "oo" else 0
regimes.append(
AsymptoticRegime(
variable=sp.Symbol(var),
limit_target=limit_target,
ground_truth_expr=ground_truth_expr,
weight=weight,
)
)
return regimes
def _resolve_limit_unsafe(candidate: sp.Expr, variable: sp.Symbol, limit_target: Any):
"""Compute lim_{variable -> limit_target}(candidate), robust to undetermined-sign parameters
and featuring a Laurent series fallback for singular/divergent expressions.
"""
# 1. Evaluate limit assuming free parameters are substituted with 1.0 FIRST.
# This prevents sympy's Gruntz limit algorithm from hanging infinitely on undetermined symbols.
theta_syms = [s for s in candidate.free_symbols if str(s).startswith("theta_")]
if theta_syms:
try:
unit_map = {s: 1.0 for s in theta_syms}
unit_candidate = candidate.subs(unit_map)
res_unit = sp.limit(unit_candidate, variable, limit_target, dir='+')
if res_unit is not None and res_unit not in (sp.oo, -sp.oo, sp.zoo):
if isinstance(res_unit, sp.Order) or (hasattr(res_unit, "has") and res_unit.has(sp.Order)):
return sp.Integer(0)
return res_unit
except Exception:
pass
# 2. Try standard limit fallback
try:
res = sp.limit(candidate, variable, limit_target, dir='+')
if res is not None and res not in (sp.oo, -sp.oo, sp.zoo):
return res
except Exception:
res = None
# 3. Laurent Series Fallback (G3-L)
try:
eps = sp.symbols('_arc_eps', positive=True)
# Shift target to approach 0+
if limit_target == sp.oo:
shifted = candidate.subs(variable, 1/eps)
elif limit_target == -sp.oo:
shifted = candidate.subs(variable, -1/eps)
else:
shifted = candidate.subs(variable, limit_target - eps)
# Declare theta positive for series expansion to avoid sign branch errors
if theta_syms:
positive_map = {s: sp.Symbol(str(s), positive=True) for s in theta_syms}
shifted = shifted.subs(positive_map)
series_expr = sp.series(shifted, eps, 0, 2)
leading = series_expr.as_leading_term(eps)
# Check pole order (observability/logging)
denom_leading = sp.denom(leading)
if eps in denom_leading.free_symbols:
pole_order = sp.degree(denom_leading, eps)
logger.debug(f"Laurent fallback active: detected divergent pole of order {pole_order} for {candidate}")
# Evaluate limit of leading term as eps -> 0+
resolved_val = sp.limit(leading, eps, 0, dir='+')
if resolved_val is not None and resolved_val not in (sp.oo, -sp.oo, sp.zoo):
if isinstance(resolved_val, sp.Order) or (hasattr(resolved_val, "has") and resolved_val.has(sp.Order)):
return sp.Integer(0)
return resolved_val
except Exception as e:
logger.debug(f"Laurent series fallback failed: {e}")
# 4. High-Precision Numerical Fallback (for complex transcendental functions like atan/tanh/erf)
try:
theta_map = {s: 1.0 for s in candidate.free_symbols if str(s).startswith("theta_")}
eval_expr = candidate.subs(theta_map)
if limit_target == sp.oo:
val_near = float(eval_expr.subs(variable, 1e6).evalf())
elif limit_target == -sp.oo:
val_near = float(eval_expr.subs(variable, -1e6).evalf())
else:
val_near = float(eval_expr.subs(variable, float(limit_target) + 1e-6).evalf())
if np.isfinite(val_near):
return sp.Float(round(val_near, 6))
except Exception:
pass
return res
import threading
def _resolve_limit(candidate: sp.Expr, variable: sp.Symbol, limit_target: Any, timeout: float = 2.0):
"""
Wraps _resolve_limit_unsafe with threading.
Prevents blocking the main pipeline if SymPy's Gruntz algorithm hits an infinite loop.
Uses daemon threads so abandoned threads won't block program exit.
"""
result = [None]
def worker():
try:
res = _resolve_limit_unsafe(candidate, variable, limit_target)
result[0] = res
except Exception:
pass
t = threading.Thread(target=worker, daemon=True)
t.start()
t.join(timeout=timeout)
if t.is_alive():
logger.debug(f"Timeout ({timeout}s) - limit computation abandoned for: {candidate}")
return None
return result[0]
class ARCScorer:
"""
Core engine for Stage 1 Gatekeeper to compute feasibility weights
"""
def __init__(self, regimes: List[AsymptoticRegime]):
if not regimes:
raise ValueError("Regimes boundary list cannot be empty.")
self.regimes = regimes
self.total_weight = sum(r.weight for r in regimes)
def score(self, candidate_expr: Union[str, sp.Expr], constants: Dict[str, float] = None) -> float:
"""
Computes the final ARC Score for a candidate expression.
Utilizes pure mathematical limit evaluation without basic string matching.
"""
try:
candidate = sp.sympify(candidate_expr)
if constants:
subs_dict = {sp.Symbol(k): v for k, v in constants.items() if sp.Symbol(k) in candidate.free_symbols}
if subs_dict:
candidate = candidate.subs(subs_dict)
except Exception as e:
logger.error(f"Failed to process candidate expression syntax: {e}")
return 0.0
weighted_similarity_sum = 0.0
for r in self.regimes:
evaluated_limit = _resolve_limit(candidate, r.variable, r.limit_target)
if evaluated_limit is None:
# Critical mathematical failures (e.g., PoleError) are immediately penalized with 0
logger.warning(f"Limit computation failure for variable {r.variable}")
continue