Repository navigation
Expand file tree
/
Copy pathsimple.py
More file actions
3637 lines (3190 loc) · 145 KB
/
Copy pathsimple.py
File metadata and controls
3637 lines (3190 loc) · 145 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
"""Public network construction, declared evolution and scoped TNFR observations.
``Network`` wraps supplied state. Its native relational methods assess organized
objects and evolve their joint form/phase law; operator studies execute requested
words under separate live-state and grammar contracts. Reports retain their
model, observation and numerical scope.
The executable introduction is ``examples/01_foundations/01_hello_world.py``.
``docs/CLI_AND_SDK.md`` routes construction, execution and observation workflows;
``docs/API_CONTRACTS.md`` owns admission and mutation boundaries.
"""
from __future__ import annotations
import math
from collections.abc import Mapping
from dataclasses import asdict, dataclass, field
from typing import Any
import networkx as nx
from .._exact_time import finite_represented_real
from ..constants import DEFAULTS
from ..constants.aliases import ALIAS_DEPI, ALIAS_DNFR, ALIAS_EPI, ALIAS_THETA, ALIAS_VF
from ..constants.canonical import HIGH_COHERENCE_THRESHOLD as COHERENCE_STRONG
from ..constants.canonical import ZHIR_THRESHOLD_XI_CANONICAL
from ..errors import TNFRValueError
from ..mathematics._neighbor_differences import mean_neighbor_difference
from ..mathematics.unified_numerical import np
from ..metrics._history import stored_sequence, stored_value
from ..metrics.coherence import compute_coherence
from ..metrics.common import (
finite_mean,
finite_mean_absolute,
is_structural_equilibrium,
structural_coherence,
validate_structural_coherence,
)
from ..metrics.sense_index import compute_Si
from ..operators.nodal_equation import (
StructuralAccelerationObservation,
observe_structural_acceleration,
)
from ..physics.mutation_trigger import (
MutationTriggerCertificate,
MutationTriggerInputError,
certify_mutation_trigger,
)
# TNFR core imports
from ..structural import create_nfr
from ..types import BEPIProtocol, require_finite_real_scalar_epi
from ..utils.io import _reject_duplicate_json_keys
from ._state import copy_graph_state, observed_mean_phase, stored_phase
from ._topology import grid_edges, nonnegative_integer, numpy_seed
from ._topology import probability as validate_probability
from ._topology import ring_edges, small_world_edges
# Canonical telemetry marks (AGENTS.md §7) -- heuristic cuts, not fitted:
# C(t) > COHERENCE_STRONG (π/(π+1) ~0.7585, selected telemetry cut)
# Si > SENSE_INDEX_EXCELLENT (~0.8) -> excellent sense index
SENSE_INDEX_EXCELLENT = 0.8
# Canonical graph-node equilibrium tolerance (EPS_DNFR_STABLE ~ 1e-3): the same
# cut the engine's stability tracker uses (metrics/coherence). The per-node
# micro-NFR equilibrium (nodal_state) and the region macro-NFR equilibrium
# (Network.nfr) share this single canonical tolerance.
_EPS_DNFR_STABLE_DEFAULT = float(DEFAULTS["EPS_DNFR_STABLE"])
def _raw_alias_value(data: dict[str, Any], aliases: tuple[str, ...]) -> Any:
"""Read the first present alias without coercing certificate inputs."""
for key in aliases:
if key in data:
return data[key]
return None
def _certificate_epi_value(value: Any) -> Any:
"""Scalarize canonical BEPI form while preserving invalid scalar inputs."""
serialized_bepi = isinstance(value, Mapping) and {
"continuous",
"discrete",
"grid",
}.issubset(value)
if isinstance(value, BEPIProtocol) or serialized_bepi:
return require_finite_real_scalar_epi(value)
return value
def _certify_sdk_mutation_trigger(
*,
node: Any | None,
current_epi: Any,
nu_f: Any,
delta_nfr: Any,
xi: Any,
epi_time_history: Any = None,
epi_history: Any = None,
legacy_epi_history: Any = None,
) -> MutationTriggerCertificate:
"""Build the pure trigger certificate and translate input errors for the SDK."""
try:
return certify_mutation_trigger(
current_epi=_certificate_epi_value(current_epi),
nu_f=nu_f,
delta_nfr=delta_nfr,
xi=xi,
epi_time_history=epi_time_history,
epi_history=epi_history,
legacy_epi_history=legacy_epi_history,
)
except MutationTriggerInputError as exc:
context: dict[str, Any] = {
"field": exc.field,
"value": repr(exc.value),
"reason": exc.reason,
}
if node is not None:
context["node"] = node
raise TNFRValueError(
"Invalid nodal Mutation-trigger input.",
context=context,
suggestion=(
"Provide finite real EPI, nu_f, DeltaNFR channels and a "
"finite nonnegative Mutation threshold."
),
) from exc
from ..operators.word_execution import ( # noqa: F401
preflight_network_mutation_sequence as _preflight_sdk_mutation_sequence,
)
from ..operators.word_execution import run_network_sequence as _run_network_sequence
# Private aliases are retained for downstream SDK compatibility; new code should
# import the neutral public functions from tnfr.operators.
def _first_interpolated_crossing(
samples: list[float], threshold: float
) -> float | None:
"""Estimate the first upward threshold crossing between sampled steps.
Returning a fractional step prevents two distinct crossings within the
same sampling interval from being reported as simultaneous. No crossing
is inferred beyond the observed trajectory.
"""
if not samples:
return None
if samples[0] >= threshold:
return 0.0
for index in range(1, len(samples)):
previous = samples[index - 1]
current = samples[index]
if previous < threshold <= current:
fraction = (threshold - previous) / (current - previous)
return float(index - 1) + fraction
return None
try:
# Availability probe for the self-optimization engine (capability flag
# only; auto_optimize uses the grammar-aware stabilizer path directly).
import tnfr.dynamics.self_optimizing_engine # noqa: F401
_HAS_OPTIMIZATION = True
except ImportError:
_HAS_OPTIMIZATION = False
# Structural Field Tetrad (CANONICAL)
try:
from ..physics.fields import (
compute_complex_geometric_field_arrays,
compute_dnfr_flux,
compute_emergent_fields,
compute_phase_current,
compute_phase_curvature,
compute_phase_gradient,
compute_structural_potential,
compute_tensor_invariants,
compute_unified_telemetry,
estimate_coherence_length,
)
_HAS_FIELDS = True
except ImportError:
_HAS_FIELDS = False
# Finite structural-balance diagnostics (historically Noether-like)
try:
from ..physics.conservation import (
ConservationTracker,
compute_energy_functional,
compute_lyapunov_derivative,
compute_noether_charge,
)
_HAS_CONSERVATION = True
except ImportError:
_HAS_CONSERVATION = False
# Auxiliary ambient symplectic model initialized from extracted graph fields
try:
from ..physics.symplectic_substrate import (
background_potential,
extract_phase_space_point,
substrate_hamiltonian,
verify_canonical_structure,
)
_HAS_SUBSTRATE = True
except ImportError:
_HAS_SUBSTRATE = False
# Structural Integrity Monitor
try:
from ..physics.integrity import MonitorMode, StructuralIntegrityMonitor
_HAS_INTEGRITY = True
except ImportError:
_HAS_INTEGRITY = False
# Grammar-aware dynamics
try:
from ..operators.grammar_dynamics import filter_candidates
_HAS_GRAMMAR_DYNAMICS = True
except ImportError:
_HAS_GRAMMAR_DYNAMICS = False
# Deprecated external factorization bridge (no archived-source discovery)
try:
from ..factorization import factorize as legacy_factorize
_HAS_FACTORIZATION = True
except Exception:
_HAS_FACTORIZATION = False
# Static arithmetic primality bridge (optional dependency path)
try:
from ..primality import analyze as canonical_primality_analyze
_HAS_PRIMALITY = True
except Exception:
_HAS_PRIMALITY = False
def _available_readout_scalar(value: Any, name: str) -> float | None:
"""Normalize diagnostic evidence without converting absence to zero."""
try:
return finite_represented_real(value, name)[0]
except (TypeError, ValueError):
return None
def _diagnostic_verdict(value: Any, name: str) -> bool | None:
"""Preserve unavailable verdicts without applying Python truthiness."""
if value is None:
return None
if not isinstance(value, (bool, np.bool_)):
raise TypeError(f"{name} must be a boolean or None")
return bool(value)
@dataclass
class TetradSnapshot:
"""Structural Field Tetrad snapshot — four canonical fields.
Captures the complete four-field diagnostic read-out
(Phi_s, |grad_phi|, K_phi, xi_C) at a single point in time. These lossy
summaries do not reconstruct the complete TNFR graph state.
Attributes
----------
phi_s : dict[Any, float]
Structural potential per node.
grad_phi : dict[Any, float]
Phase gradient per node.
k_phi : dict[Any, float]
Phase curvature per node.
xi_c : float
Coherence length (global scalar).
j_phi : dict[Any, float]
Phase current per node.
j_dnfr : dict[Any, float]
DNFR flux per node.
"""
phi_s: dict[Any, float] = field(default_factory=dict)
grad_phi: dict[Any, float] = field(default_factory=dict)
k_phi: dict[Any, float] = field(default_factory=dict)
xi_c: float = float("nan")
j_phi: dict[Any, float] = field(default_factory=dict)
j_dnfr: dict[Any, float] = field(default_factory=dict)
def summary(self) -> str:
"""Summarize each available field on its own supplied node support."""
n = len(set(self.phi_s) | set(self.grad_phi) | set(self.k_phi))
if n == 0:
return "Tetrad: empty"
def field_mean(data, *, magnitude=False):
if not data:
return "UNAVAILABLE"
try:
reducer = finite_mean_absolute if magnitude else finite_mean
value = reducer(data.values(), name="tetrad field")
except (TypeError, ValueError):
return "UNAVAILABLE"
return f"{value:.4f}"
xi = _available_readout_scalar(self.xi_c, "xi_C")
xi_text = f"{xi:.4f}" if xi is not None and xi >= 0.0 else "UNAVAILABLE"
return (
f"Phi_s={field_mean(self.phi_s)}, |grad_phi|={field_mean(self.grad_phi)}, "
f"|K_phi|={field_mean(self.k_phi, magnitude=True)}, xi_C={xi_text} (N={n})"
)
def is_safe(self) -> dict[str, bool]:
"""Check the declared diagnostic cuts and finite correlation length.
Returns dict with keys: phi_s_safe, grad_phi_safe, k_phi_safe,
xi_c_safe, and overall. Unavailable correlation length fails this
advisory check. Overall safety also requires nonempty matching local
field support; these booleans do not authorize operator execution.
"""
from ..constants.canonical import (
GRAD_PHI_CANONICAL_THRESHOLD,
K_PHI_CANONICAL_THRESHOLD,
PHI_S_VON_KOCH_THRESHOLD,
)
def field_within(data, threshold, *, nonnegative=False):
if not data:
return False
values = [
_available_readout_scalar(value, "tetrad field")
for value in data.values()
]
return all(
value is not None
and (not nonnegative or value >= 0.0)
and abs(value) < threshold
for value in values
)
phi_s_safe = field_within(self.phi_s, PHI_S_VON_KOCH_THRESHOLD)
grad_safe = field_within(
self.grad_phi, GRAD_PHI_CANONICAL_THRESHOLD, nonnegative=True
)
k_safe = field_within(self.k_phi, K_PHI_CANONICAL_THRESHOLD)
xi = _available_readout_scalar(self.xi_c, "xi_C")
xi_safe = xi is not None and xi >= 0.0
matching_support = bool(self.phi_s) and set(self.phi_s) == set(
self.grad_phi
) == set(self.k_phi)
return {
"phi_s_safe": phi_s_safe,
"grad_phi_safe": grad_safe,
"k_phi_safe": k_safe,
"xi_c_safe": xi_safe,
"overall": matching_support
and phi_s_safe
and grad_safe
and k_safe
and xi_safe,
}
@dataclass
class ConservationReport:
"""Finite-trajectory structural conservation diagnostics.
Captures the historically named tetrad charge candidate, energy candidate,
observed finite-step energy change, and balance-quality telemetry.
"""
noether_charge: float = 0.0
energy: float = 0.0
lyapunov_stable: bool = True
lyapunov_derivative: float = 0.0
conservation_quality: float = 0.0
sample_available: bool = False
@property
def structural_charge(self) -> float:
"""Accurately named view of the historical ``noether_charge`` field."""
return self.noether_charge
@property
def candidate_energy(self) -> float:
"""Structural energy evaluated as a Lyapunov candidate."""
return self.energy
@property
def candidate_energy_nonincreasing(self) -> bool | None:
"""Finite-step energy result, or ``None`` before an interval exists."""
rate = self.candidate_energy_derivative
return None if rate is None else rate <= 0.0
@property
def candidate_energy_within_numerical_tolerance(self) -> bool | None:
"""Historical Lyapunov classification, including its tolerance."""
if self.candidate_energy_derivative is None or not isinstance(
self.lyapunov_stable, (bool, np.bool_)
):
return None
return bool(self.lyapunov_stable)
@property
def candidate_energy_derivative(self) -> float | None:
"""Sampled candidate-energy derivative, unavailable on first capture."""
if self.sample_available is not True:
return None
return _available_readout_scalar(
self.lyapunov_derivative, "candidate energy rate"
)
@property
def balance_quality(self) -> float | None:
"""Finite-step balance quality, unavailable on first capture."""
if self.sample_available is not True:
return None
quality = _available_readout_scalar(
self.conservation_quality, "balance quality"
)
return quality if quality is not None and 0.0 <= quality <= 1.0 else None
def summary(self) -> str:
"""One-line scoped balance and candidate-energy summary."""
charge = _available_readout_scalar(self.noether_charge, "structural charge")
energy = _available_readout_scalar(self.energy, "candidate energy")
charge_text = f"{charge:.4f}" if charge is not None else "UNAVAILABLE"
energy_text = (
f"{energy:.4f}" if energy is not None and energy >= 0.0 else "UNAVAILABLE"
)
prefix = f"Q_candidate={charge_text}, E_candidate={energy_text}"
if self.sample_available is not True:
return prefix + ", interval=UNSAMPLED"
exact_trend = self.candidate_energy_nonincreasing
if exact_trend is None:
trend = "UNDEFINED"
else:
trend = "NON-INCREASING" if exact_trend else "INCREASING"
rate, quality = self.candidate_energy_derivative, self.balance_quality
rate_text = f"{rate:.4f}" if rate is not None else "UNAVAILABLE"
quality_text = f"{quality:.3f}" if quality is not None else "UNAVAILABLE"
return (
prefix
+ f", candidate dE/dt={rate_text} ({trend}), balance_quality={quality_text}"
)
def _empty_balance_alert_report(diagnostic_scope: str) -> dict[str, Any]:
"""Build one consistent unsampled balance-alert result."""
return {
"sample_available": False,
"alerts_detected": False,
"alert_count": 0,
"alert_types": [],
"nodes_alerted": [],
"severity": 0.0,
# Backward-compatible grammar-shaped keys remain deliberately empty.
"violations_detected": False,
"violation_count": 0,
"violation_types": [],
"nodes_violating": [],
"diagnostic_scope": diagnostic_scope,
"grammar_validation_applicable": False,
"grammar_validated": False,
"grammar_rules_assessed": (),
}
@dataclass
class SymplecticReport:
"""Diagnostics for the auxiliary ambient symplectic substrate model.
Extracted graph fields initialize a point in the ambient phase space
``R^(4N)``. The report evaluates that model's harmonic Hamiltonian,
held-fixed configuration background, Liouville divergence, and canonical
symplectic structure. It does not derive this model from the nodal flow.
"""
phase_space_dimension: int = 0
hamiltonian: float = 0.0
background_potential: float = 0.0
liouville_divergence: float = 0.0
is_valid_manifold: bool = False
def summary(self) -> str:
"""One-line symplectic substrate summary."""
valid_str = "VALID" if self.is_valid_manifold else "INVALID"
return (
f"dim={self.phase_space_dimension}, "
f"H_sub={self.hamiltonian:.4f}, "
f"U={self.background_potential:.4f}, "
f"div(X_H)={self.liouville_divergence:.2e} ({valid_str})"
)
@dataclass
class FactorizationReport:
"""SDK report from the optional arithmetic factorization lab.
Bridges `tnfr.factorization.factorize()` with SDK-level telemetry and
an optional, explicitly heuristic comparison to a caller-supplied network.
Candidate and compatibility ``tnfr_certified_factors`` fields retain the
lab's configured acceptance policy; independently check proper divisibility.
"""
n: int
modulus: int
candidate_factors: list[int] = field(default_factory=list)
tnfr_certified_factors: list[int] = field(default_factory=list)
coherence_score: float = 0.0
arithmetic_delta_nfr: float = 0.0
arithmetic_epi: float = 0.0
arithmetic_nu_f: float = 0.0
certificate_path: str | None = None
partition_manifest_path: str | None = None
operator_strategy_plan: dict[str, Any] | None = None
spectral: dict[str, Any] = field(default_factory=dict)
telemetry: dict[str, Any] = field(default_factory=dict)
network_synergy: dict[str, Any] | None = None # legacy field name
def summary(self) -> str:
certified = len(self.tnfr_certified_factors)
return (
f"n={self.n}, candidates={len(self.candidate_factors)}, "
f"certified={certified}, coherence={self.coherence_score:.3f}"
)
def to_dict(self) -> dict[str, Any]:
"""Serialize report to plain dict for JSON/reporting pipelines."""
return {
"n": int(self.n),
"modulus": int(self.modulus),
"candidate_factors": list(self.candidate_factors),
"tnfr_certified_factors": list(self.tnfr_certified_factors),
"coherence_score": float(self.coherence_score),
"arithmetic_delta_nfr": float(self.arithmetic_delta_nfr),
"arithmetic_epi": float(self.arithmetic_epi),
"arithmetic_nu_f": float(self.arithmetic_nu_f),
"certificate_path": self.certificate_path,
"partition_manifest_path": self.partition_manifest_path,
"operator_strategy_plan": self.operator_strategy_plan,
"spectral": self.spectral,
"telemetry": self.telemetry,
"network_synergy": self.network_synergy,
}
@dataclass
class PrimalityReport:
"""SDK report for the optional arithmetic-pressure primality predicate.
Bridges `tnfr.primality.analyze()` with SDK-level telemetry and
an optional, explicitly heuristic comparison to a caller-supplied network.
"""
n: int
is_prime: bool
delta_nfr: float
tolerance: float
components: dict[str, Any] = field(default_factory=dict)
triad: dict[str, Any] = field(default_factory=dict)
network_synergy: dict[str, Any] | None = None # legacy field name
def summary(self) -> str:
status = "prime" if self.is_prime else "not-prime"
return f"n={self.n}, status={status}, delta_nfr={self.delta_nfr:.6g}"
def to_dict(self) -> dict[str, Any]:
"""Serialize report to plain dict for JSON/reporting pipelines."""
return {
"n": int(self.n),
"is_prime": bool(self.is_prime),
"delta_nfr": float(self.delta_nfr),
"tolerance": float(self.tolerance),
"components": self.components,
"triad": self.triad,
"network_synergy": self.network_synergy,
}
@dataclass
class NodalStateReport:
"""Node-level nodal dynamics snapshot based on ∂EPI/∂t = νf·ΔNFR.
``expected_depi_dt`` is the nodal-equation prediction. The retained
``near_bifurcation`` name is a legacy alias of ``predicted_crossed``; it is
not an observed Mutation gate. ``mutation_threshold_satisfied`` mirrors
only the observed strict threshold gate and does not assess U4b grammar or
operator execution readiness. ``acceleration_observation`` separately
identifies three-sample acceleration evidence. The legacy ``d2epi_dt2``
remains zero when that evidence is unavailable; use
``observed_d2epi_dt2`` to distinguish absence from a measured zero.
Logical report values retain ``None`` as unavailable; malformed truthy
values are rejected when reporting. Directly supplied local coherence is
a finite represented read-out in [0, 1], not a signed magnitude.
"""
node: Any
epi: float
nu_f: float
delta_nfr: float
coherence: float
phase: float
expected_depi_dt: float
d2epi_dt2: float
degree: int
equilibrium: bool | None
active: bool | None
near_bifurcation: bool | None
observed_depi_dt: float | None = None
predicted_crossed: bool | None = None
observed_crossed: bool | None = None
evidence_available: bool | None = False
evidence_valid: bool | None = False
source: str | None = None
time_basis: str | None = None
physical_time_resolved: bool | None = False
current_endpoint_matches_state: bool | None = None
reason: str | None = None
rate_gap: float | None = None
mutation_threshold_satisfied: bool | None = False
acceleration_observation: StructuralAccelerationObservation | None = None
@property
def acceleration_available(self) -> bool:
"""Whether three-sample acceleration evidence is available."""
return (
self.acceleration_observation is not None
and self.acceleration_observation.available
)
@property
def observed_d2epi_dt2(self) -> float | None:
"""Observed acceleration, separate from the legacy numeric fallback."""
return (
self.acceleration_observation.value if self.acceleration_available else None
)
def __post_init__(self) -> None:
"""Keep the legacy prediction alias coherent for direct construction."""
prediction = (
self.near_bifurcation
if self.predicted_crossed is None
else self.predicted_crossed
)
self.predicted_crossed = _diagnostic_verdict(prediction, "predicted_crossed")
self.near_bifurcation = self.predicted_crossed
def _coherence_value(self) -> float:
"""Admit the supplied local read-out, without replacing it by a magnitude."""
return validate_structural_coherence(self.coherence, name="local coherence")
def _verdicts(self) -> dict[str, bool | None]:
"""Read mutable report metadata strictly at each reporting boundary."""
names = (
"equilibrium",
"active",
"near_bifurcation",
"predicted_crossed",
"observed_crossed",
"evidence_available",
"evidence_valid",
"physical_time_resolved",
"current_endpoint_matches_state",
"mutation_threshold_satisfied",
)
verdicts = {
name: _diagnostic_verdict(getattr(self, name), name) for name in names
}
if verdicts["near_bifurcation"] is not verdicts["predicted_crossed"]:
raise ValueError("near_bifurcation and predicted_crossed must agree")
return verdicts
def summary(self) -> str:
verdicts = self._verdicts()
state = (
"activity unavailable"
if verdicts["active"] is None
else "active" if verdicts["active"] else "inactive"
)
eq = (
"equilibrium unavailable"
if verdicts["equilibrium"] is None
else "equilibrium" if verdicts["equilibrium"] else "driven"
)
acceleration = (
f"{self.observed_d2epi_dt2:.4g}"
if self.acceleration_available
else "unavailable"
)
return (
f"node={self.node}, {state}, {eq}, "
f"∂EPI/∂t={self.expected_depi_dt:.4g}, ∂²EPI/∂t²={acceleration}"
)
def to_dict(self) -> dict[str, Any]:
return {
"node": self.node,
"epi": float(self.epi),
"nu_f": float(self.nu_f),
"delta_nfr": float(self.delta_nfr),
"coherence": self._coherence_value(),
"phase": float(self.phase),
"expected_depi_dt": float(self.expected_depi_dt),
"d2epi_dt2": float(self.d2epi_dt2),
"acceleration_available": self.acceleration_available,
"observed_d2epi_dt2": self.observed_d2epi_dt2,
"acceleration_observation": (
self.acceleration_observation.to_dict()
if self.acceleration_observation is not None
else None
),
"degree": int(self.degree),
**self._verdicts(),
"observed_depi_dt": (
None if self.observed_depi_dt is None else float(self.observed_depi_dt)
),
"source": self.source,
"time_basis": self.time_basis,
"reason": self.reason,
"rate_gap": None if self.rate_gap is None else float(self.rate_gap),
}
@dataclass
class NodalDynamicsReport:
"""Global nodal-equation prediction report for study and diagnostics.
Its total coherence aggregates pressure and predicted EPI-rate magnitudes
before applying the nonlinear constitutive kernel. ``mean_local_coherence``
remains available as a distinct descriptive statistic. Verdict counts
separate true and unavailable observations. String-key export rejects
colliding node labels rather than silently dropping a node.
"""
nodes: dict[Any, NodalStateReport] = field(default_factory=dict)
equilibrium_tolerance: float = _EPS_DNFR_STABLE_DEFAULT
bifurcation_threshold: float = ZHIR_THRESHOLD_XI_CANONICAL
def _channel_means(self) -> tuple[float, float]:
"""Return mean pressure and predicted-rate magnitudes for this scan."""
values = self.nodes.values()
mean_pressure = finite_mean_absolute(
(state.delta_nfr for state in values), name="scan dnfr"
)
mean_rate = finite_mean_absolute(
(state.expected_depi_dt for state in self.nodes.values()),
name="scan predicted depi",
)
return mean_pressure, mean_rate
def total_coherence(self) -> float:
"""Return canonical C over this scan's predicted nodal channels."""
if not self.nodes:
return 0.0
mean_pressure, mean_rate = self._channel_means()
return float(structural_coherence(mean_pressure, mean_rate))
def mean_local_coherence(self) -> float:
"""Return the distinct mean of already-reduced local coherences."""
if not self.nodes:
return 0.0
return finite_mean(
(state._coherence_value() for state in self.nodes.values()),
name="scan local coherence",
)
def _verdict_counts(self) -> dict[str, int]:
"""Count true and unavailable metadata separately, without caching."""
verdicts = [state._verdicts() for state in self.nodes.values()]
counts = {}
for label, key in (
("active", "active"),
("equilibrium", "equilibrium"),
("bifurcation", "predicted_crossed"),
):
counts[f"{label}_count"] = sum(v[key] is True for v in verdicts)
counts[f"{label}_unavailable_count"] = sum(v[key] is None for v in verdicts)
return counts
def summary(self) -> str:
n = len(self.nodes)
if n == 0:
return "Nodal dynamics: empty"
counts = self._verdict_counts()
active = counts["active_count"]
equilibrium = counts["equilibrium_count"]
bifurcation = counts["bifurcation_count"]
unavailable = ", ".join(
f"{key}={count}"
for key, count in counts.items()
if key.endswith("_unavailable_count") and count
)
_, mean_abs_rate = self._channel_means()
coherence = self.total_coherence()
return (
f"NodalDynamics(N={n}, active={active}, equilibrium={equilibrium}, "
f"bifurcation={bifurcation}, C={coherence:.3f}, "
f"mean|∂EPI/∂t|={mean_abs_rate:.4g}"
f"{', ' + unavailable if unavailable else ''})"
)
def top_pressure_nodes(self, k: int = 5) -> list[NodalStateReport]:
"""Nodes with largest |∂EPI/∂t| (highest nodal drive)."""
ranked = sorted(
self.nodes.values(), key=lambda s: abs(s.expected_depi_dt), reverse=True
)
return ranked[: max(int(k), 0)]
def near_equilibrium_nodes(self) -> list[NodalStateReport]:
"""Nodes whose pressure and predicted rate meet the fixed-point cut."""
return [
state
for state in self.nodes.values()
if state._verdicts()["equilibrium"] is True
]
def to_dict(self) -> dict[str, Any]:
"""Export detached rows; reject node labels that collide as string keys."""
labels = [str(node) for node in self.nodes]
if len(set(labels)) != len(labels):
raise ValueError("distinct node labels collide as string report keys")
values = list(self.nodes.values())
n = len(values)
mean_abs_pressure, mean_abs_rate = self._channel_means()
max_abs_rate = max(
(abs(state.expected_depi_dt) for state in values), default=0.0
)
return {
"equilibrium_tolerance": float(self.equilibrium_tolerance),
"bifurcation_threshold": float(self.bifurcation_threshold),
"nodes": {label: report.to_dict() for label, report in zip(labels, values)},
"aggregate": {
"count": n,
**self._verdict_counts(),
"coherence": self.total_coherence(),
"mean_local_coherence": self.mean_local_coherence(),
"mean_abs_dnfr": float(mean_abs_pressure),
"mean_abs_depi_dt": float(mean_abs_rate),
"max_abs_depi_dt": float(max_abs_rate),
"depi_dt_source": "nodal_equation_prediction",
},
}
def _build_factorization_report(
raw_result: Any,
network: "Network | None" = None,
) -> FactorizationReport:
"""Adapt an external legacy lab result without certifying its arithmetic."""
candidate_factors = list(getattr(raw_result, "candidate_factors", []) or [])
certified = list(getattr(raw_result, "tnfr_certified_factors", []) or [])
coherence_score = float(getattr(raw_result, "coherence_score", 0.0) or 0.0)
delta_nfr = float(getattr(raw_result, "arithmetic_delta_nfr", 0.0) or 0.0)
arithmetic_epi = float(getattr(raw_result, "arithmetic_epi", 0.0) or 0.0)
arithmetic_nu_f = float(getattr(raw_result, "arithmetic_nu_f", 0.0) or 0.0)
n = int(getattr(raw_result, "n", 0) or 0)
modulus = int(getattr(raw_result, "modulus", 0) or 0)
telemetry = {
"phi_s": float(getattr(raw_result, "phi_s", 0.0) or 0.0),
"phase_gradient": float(getattr(raw_result, "phase_gradient", 0.0) or 0.0),
"phase_curvature": float(getattr(raw_result, "phase_curvature", 0.0) or 0.0),
"coherence_length": float(getattr(raw_result, "coherence_length", 0.0) or 0.0),
"coherence_score": coherence_score,
"delta_nfr": delta_nfr,
"epi": arithmetic_epi,
"nu_f": arithmetic_nu_f,
}
spectral = {
"laplacian_gap": float(getattr(raw_result, "laplacian_gap", 0.0) or 0.0),
"fft_backend": getattr(raw_result, "fft_backend", None),
"node_count": int(getattr(raw_result, "node_count", 0) or 0),
"edge_count": int(getattr(raw_result, "edge_count", 0) or 0),
"notes": getattr(raw_result, "notes", ""),
}
network_synergy: dict[str, Any] | None = None
if network is not None:
net_coherence = float(network.coherence())
net_si = float(network.sense_index())
coherence_alignment = max(0.0, 1.0 - abs(net_coherence - coherence_score))
nodal_drive = abs(arithmetic_nu_f * delta_nfr)
drive_score = nodal_drive / (1.0 + nodal_drive)
# Exploratory equal-weight comparison. No canonical map relates the
# caller-supplied graph to this arithmetic factorization instance.
alignment_score = (coherence_alignment + drive_score) / 2.0
size_divisible_candidates = [
int(f)
for f in candidate_factors
if f > 1 and len(network.G.nodes()) % int(f) == 0
]
network_synergy = {
"status": "heuristic_alignment",
"scope": (
"independent network supplied by caller; no canonical "
"cross-domain map"
),
"weights": {"coherence_alignment": 0.5, "drive_score": 0.5},
"network_nodes": len(network.G.nodes()),
"network_coherence": net_coherence,
"network_sense_index": net_si,
"coherence_alignment": coherence_alignment,
"nodal_drive": nodal_drive,
"drive_score": drive_score,
"alignment_score": alignment_score,
"size_divisible_candidates": sorted(set(size_divisible_candidates)),
# Backward-compatible names; neither value certifies resonance.
"synergy_index": alignment_score,
"topology_resonance_factors": sorted(set(size_divisible_candidates)),
"legacy_name_warning": (
"synergy_index/topology_resonance_factors are historical names"
),
}
return FactorizationReport(
n=n,
modulus=modulus,
candidate_factors=candidate_factors,
tnfr_certified_factors=certified,
coherence_score=coherence_score,
arithmetic_delta_nfr=delta_nfr,
arithmetic_epi=arithmetic_epi,
arithmetic_nu_f=arithmetic_nu_f,
certificate_path=getattr(raw_result, "certificate_path", None),
partition_manifest_path=getattr(raw_result, "partition_manifest_path", None),
operator_strategy_plan=getattr(raw_result, "operator_strategy_plan", None),
spectral=spectral,
telemetry=telemetry,
network_synergy=network_synergy,
)
def _build_primality_report(
n: int,
raw_result: dict[str, Any],
*,
tolerance: float,
network: "Network | None" = None,
) -> PrimalityReport:
"""Convert canonical primality output into SDK-native report."""
is_prime = bool(raw_result.get("is_prime", False))
delta_nfr = float(raw_result.get("delta_nfr", float("inf")))
components = dict(raw_result.get("components", {}) or {})
triad = dict(raw_result.get("triad", {}) or {})
network_synergy: dict[str, Any] | None = None
if network is not None:
net_coherence = float(network.coherence())
net_si = float(network.sense_index())
local_coherence = float(triad.get("local_coherence", 0.0) or 0.0)
coherence_alignment = max(0.0, 1.0 - abs(net_coherence - local_coherence))
pressure_ratio = abs(delta_nfr) / max(float(tolerance), 1e-15)
pressure_score = 1.0 / (1.0 + pressure_ratio)
# Exploratory equal-weight comparison. It deliberately excludes the
# old label-conditioned ``prime_resonance`` term, which injected the
# primality answer into its own score.
alignment_score = (coherence_alignment + pressure_score) / 2.0
network_synergy = {
"status": "heuristic_alignment",
"scope": (
"independent network supplied by caller; no canonical "
"cross-domain map"
),
"weights": {"coherence_alignment": 0.5, "pressure_score": 0.5},
"network_nodes": len(network.G.nodes()),
"network_coherence": net_coherence,
"network_sense_index": net_si,
"local_coherence": local_coherence,
"coherence_alignment": coherence_alignment,
"pressure_ratio": pressure_ratio,
"pressure_score": pressure_score,
"alignment_score": alignment_score,
"synergy_index": alignment_score,
"legacy_name_warning": "synergy_index is a historical field name",
}
return PrimalityReport(
n=int(n),
is_prime=is_prime,
delta_nfr=delta_nfr,
tolerance=float(tolerance),