Repository navigation
Expand file tree
/
Copy pathconservation.py
More file actions
1582 lines (1309 loc) · 58.4 KB
/
Copy pathconservation.py
File metadata and controls
1582 lines (1309 loc) · 58.4 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
"""TNFR structural conservation diagnostics.
The module records the balance
Δρ/Δt + div J = S, ρ = Φ_s + K_φ,
J = (J_φ, J_ΔNFR),
between two observed graph states. ``S`` is the measured source/residual of
that finite-interval balance. This identity follows from the definition of
``S``; grammar-valid operator labels alone do not prove that it vanishes or is
small. Likewise, the non-negative quadratic structural energy exposed here is
a Lyapunov *candidate*: monotonicity requires trajectory evidence or a
model-specific proof.
These sums use the engine's normalized numeric field convention. With raw
units, pressure has EPI units, the inverse-square potential also carries
inverse distance squared, and phase discrepancies are angles. They cannot be
added without declared reference scales. The neighbor-difference divergence
also supplies no time-rate factor: ``dt`` and the current normalization must
share a declared time convention before this diagnostic can represent a
physical continuity equation. The implementation does not derive those scales.
The exact conservation result owned elsewhere is the degree-weighted EPI total
for fixed symmetric pure diffusion under its stated capacity assumptions. It
must not be conflated with the tetrad charge reported by this module.
STATUS
======
CANONICAL DIAGNOSTIC INTERFACE. Residuals, charge drift, and energy change are
observations of the supplied trajectory, not consequences of U1-U6 by label.
References
----------
- Nodal identity and complete-law premises: theory/FUNDAMENTAL_THEORY.md
- Grammar U1-U6: theory/UNIFIED_GRAMMAR_RULES.md
- Structural fields: src/tnfr/physics/canonical.py
- Extended fields: src/tnfr/physics/extended.py
"""
from __future__ import annotations
import math
from collections.abc import Mapping
from copy import deepcopy
from dataclasses import dataclass, field
from dataclasses import fields as dataclass_fields
from dataclasses import replace
from fractions import Fraction
from typing import Any, Sequence
import networkx as nx # noqa: F401 - retain the existing module attribute
from .._exact_time import finite_represented_real
from ..constants.canonical import (
K_PHI_CANONICAL_THRESHOLD,
PI,
U6_STRUCTURAL_POTENTIAL_LIMIT,
)
from ..mathematics._exact_weighted import exact_weighted_sum_ratio
from ..mathematics._neighbor_differences import mean_neighbor_difference
from ..mathematics.unified_numerical import np
from ..metrics.common import (
finite_mean_absolute,
finite_pearson_correlation,
finite_population_std,
)
from ._helpers import finite_real_scalar
from .canonical import compute_phase_curvature, compute_structural_potential
from .extended import compute_dnfr_flux, compute_phase_current
from .unified import (
_capture_structural_fields,
_total_charge_from_density,
_total_energy_from_fields,
)
# ---------------------------------------------------------------------------
# Conservation diagnostic alert levels
# ---------------------------------------------------------------------------
_BALANCE_RMS_ALERT = 1.0
_SECTOR_IMBALANCE_RATIO = 1.5
# ---------------------------------------------------------------------------
# Data structures
# ---------------------------------------------------------------------------
class ConservationAlertLevels(dict[str, float]):
"""Backward-compatible numeric alert mapping with explicit scope metadata.
The historical API returned a plain ``dict[str, float]`` from
:func:`compute_grammar_conservation_bounds`. This subclass preserves that
mapping behaviour and its legacy keys while exposing why the values must
not be read as mathematical bounds or as grammar-rule classifiers.
"""
scope = "finite_structural_balance_alerts"
thresholds_are_proven_bounds = False
grammar_validation_applicable = False
applicable_grammar_rules: tuple[str, ...] = ()
u6_drift_requires_reference = True
@property
def metadata(self) -> dict[str, Any]:
"""Return detached scope metadata without changing numeric iteration."""
return {
"scope": self.scope,
"thresholds_are_proven_bounds": self.thresholds_are_proven_bounds,
"grammar_validation_applicable": self.grammar_validation_applicable,
"applicable_grammar_rules": self.applicable_grammar_rules,
"u6_drift_requires_reference": self.u6_drift_requires_reference,
"legacy_pi_scaled_alerts": True,
}
@dataclass(frozen=True)
class ConservationSnapshot:
"""Single-time snapshot of structural balance fields at every node.
Attributes
----------
charge_density : dict[Any, float]
ρ(i) = Φ_s(i) + K_φ(i) at each node.
phi_s : dict[Any, float]
Structural potential Φ_s per node.
k_phi : dict[Any, float]
Phase curvature K_φ per node.
j_phi : dict[Any, float]
Phase current J_φ per node.
j_dnfr : dict[Any, float]
ΔNFR flux J_ΔNFR per node.
grad_phi : dict[Any, float]
Phase gradient |∇φ| per node.
divergence : dict[Any, float]
Discrete divergence div(J) at each node.
divergence_phi, divergence_dnfr : dict or None
Captured applications of that same graph operator to each current.
Legacy manually constructed snapshots may omit them; their sector
decomposition is then unavailable, rather than inferred from magnitudes.
"""
charge_density: dict[Any, float]
phi_s: dict[Any, float]
k_phi: dict[Any, float]
j_phi: dict[Any, float]
j_dnfr: dict[Any, float]
grad_phi: dict[Any, float]
divergence: dict[Any, float]
divergence_phi: dict[Any, float] | None = None
divergence_dnfr: dict[Any, float] | None = None
def _observed_scalar(value: Any, name: str) -> float:
"""Admit represented evidence, retaining this module's ValueError API."""
try:
return finite_represented_real(value, name)[0]
except TypeError as exc:
raise ValueError(str(exc)) from exc
def _positive_interval(dt: float) -> float:
value = _observed_scalar(dt, "dt")
if value <= 0.0:
raise ValueError("dt must be strictly positive")
return value
def _observed_secant(before: float, after: float, dt: float, name: str) -> float:
"""Compute a finite represented secant without false zero or range loss.
Ordinary differences retain their historical rounding. Exceptional
subtraction/division uses the shared exact difference kernel and rounds
only the final quotient; a nonzero unrepresentable rate is unavailable.
"""
before = _observed_scalar(before, name)
after = _observed_scalar(after, name)
result = (after - before) / dt
if math.isfinite(result) and (result != 0.0 or before == after):
return result
numerator, denominator = exact_weighted_sum_ratio(
(1.0,), (after,), center=before, normalize=False
)
time_num, time_den = dt.as_integer_ratio()
return _observed_scalar(
Fraction(numerator * time_den, denominator * time_num), name
)
def _snapshot_nodes(snapshot: ConservationSnapshot, fields: Sequence[str]) -> tuple:
"""Admit complete finite maps without fabricating missing observations."""
if not isinstance(snapshot, ConservationSnapshot):
raise TypeError("expected a ConservationSnapshot")
nodes = tuple(snapshot.charge_density)
if not nodes:
raise ValueError("conservation observations require nonempty node support")
support = set(nodes)
for name in fields:
values = getattr(snapshot, name)
if not isinstance(values, Mapping) or set(values) != support:
raise ValueError(f"snapshot {name} must match the complete node support")
for node in nodes:
_observed_scalar(values[node], f"snapshot {name}[{node!r}]")
return nodes
def _snapshot_pair_nodes(before, after, fields: Sequence[str]) -> tuple:
nodes = _snapshot_nodes(before, fields)
if set(nodes) != set(_snapshot_nodes(after, fields)):
raise ValueError("snapshot comparison requires identical node support")
return nodes
def _rms(values: Sequence[float]) -> float:
"""Reduce finite residuals without squaring their absolute scale."""
scale = max(map(abs, values), default=0.0)
if scale == 0.0:
return 0.0
return scale * math.sqrt(
math.fsum((value / scale) ** 2 for value in values) / len(values)
)
@dataclass
class ConservationBalance:
"""Result of the continuity equation verification across two snapshots.
Uses **Crank-Nicolson (trapezoidal)** discretization for O(Δt²)
accuracy:
* ``residual[i] = Δρ(i)/Δt + ½[div J_before(i) + div J_after(i)]``
— a finite-interval balance diagnostic, not a grammar validator.
* ``mean_residual``, ``max_residual`` — aggregate diagnostics.
* ``conservation_quality`` — represented ``1/(1+RMS)`` in [0, 1].
Rounding can produce one for a small nonzero residual; inspect the RMS
itself when testing represented zero.
* ``grammar_violation_index`` — legacy name for the mean absolute residual;
zero does not certify grammar compliance.
"""
residual: dict[Any, float]
delta_rho: dict[Any, float]
divergence_after: dict[Any, float] # trapezoidal average (before+after)/2
mean_residual: float
std_residual: float
max_residual: float
rms_residual: float
conservation_quality: float
grammar_violation_index: float
total_charge_before: float
total_charge_after: float
charge_drift: float
diagnostic_scope: str = "two_snapshot_structural_balance"
grammar_validation_applicable: bool = False
assessed_grammar_rules: tuple[str, ...] = ()
@property
def balance_alert_index(self) -> float:
"""Return the mean absolute residual under an accurate public name."""
return self.grammar_violation_index
@dataclass
class ConservationTimeSeries:
"""Full time-series of conservation diagnostics.
Built incrementally via :meth:`ConservationTracker.record`.
"""
times: list[float] = field(default_factory=list)
total_charge: list[float] = field(default_factory=list)
mean_residuals: list[float] = field(default_factory=list)
rms_residuals: list[float] = field(default_factory=list)
conservation_quality: list[float] = field(default_factory=list)
grammar_violation_index: list[float] = field(default_factory=list)
charge_drift: list[float] = field(default_factory=list)
@property
def is_conserved(self) -> bool:
"""Return the legacy finite-series quality alert classification.
This alias neither proves a conservation law nor validates grammar.
Prefer :attr:`aggregate_balance_within_alert` in new code.
"""
return self.aggregate_balance_within_alert
@property
def aggregate_balance_within_alert(self) -> bool:
"""Whether measured interval quality reaches the legacy alert cut.
The synthetic baseline stored for the first snapshot has no preceding
interval and is excluded.
"""
if len(self.conservation_quality) <= 1:
return False
return self.sampled_mean_quality >= 0.9
@property
def grammar_validation_applicable(self) -> bool:
"""Grammar cannot be inferred from this residual time series."""
return False
@property
def sampled_mean_quality(self) -> float:
"""Average quality over actual two-snapshot balance intervals."""
if len(self.conservation_quality) <= 1:
return 0.0
return float(np.mean(self.conservation_quality[1:]))
@property
def mean_quality(self) -> float:
"""Compatibility name for :attr:`sampled_mean_quality`."""
return self.sampled_mean_quality
@property
def mean_quality_including_baseline(self) -> float:
"""Return the historical mean including the synthetic first value."""
if not self.conservation_quality:
return 0.0
return float(np.mean(self.conservation_quality))
# ---------------------------------------------------------------------------
# Core computation: structural charge density and divergence
# ---------------------------------------------------------------------------
def compute_charge_density(G: Any) -> dict[Any, float]:
r"""Compute structural charge density ρ(i) = Φ_s(i) + K_φ(i).
This is the Noether-like charge-density diagnostic used by TNFR:
- Φ_s captures global structural potential (long-range coupling)
- K_φ captures local geometric curvature (short-range confinement)
Their sum combines global and local structural fields. Conservation of its
total must be checked on the actual trajectory or derived for a specified
auxiliary model.
Parameters
----------
G : TNFRGraph
Returns
-------
dict[node, float]
ρ(i) per node.
"""
phi_s = compute_structural_potential(G)
k_phi = compute_phase_curvature(G)
return _charge_density_from_fields(phi_s, k_phi)
def _charge_density_from_fields(
phi_s: dict[Any, float], k_phi: dict[Any, float]
) -> dict[Any, float]:
"""Shared charge definition for live and captured field maps."""
return {n: phi_s[n] + k_phi.get(n, 0.0) for n in phi_s}
def compute_current_divergence(G: Any) -> dict[Any, float]:
r"""Compute discrete divergence of structural current div J(i).
The structural current is J = (J_φ, J_ΔNFR). On a graph, the
stored quantity at node i uses the legacy neighbor-minus-center sign:
div J(i) = (1/|N(i)|) Σ_{j∈N(i)} [
(J_φ(j) - J_φ(i)) + (J_ΔNFR(j) - J_ΔNFR(i))
]
Thus it is ``-L_rw`` applied to each current component for an unweighted
graph, conventionally an inward rather than outward flux. The public name
is retained for compatibility; all balance routines use this same sign.
This is a normalized graph diagnostic, with no metric-length divisor or
transport-rate factor. Summing its phase and pressure components assumes
declared field reference scales, not equality of their raw physical units.
Parameters
----------
G : TNFRGraph
Returns
-------
dict[node, float]
div J(i) per node.
"""
j_phi = compute_phase_current(G)
j_dnfr = compute_dnfr_flux(G)
return _current_divergence_from_fields(G, j_phi, j_dnfr)
def _current_divergence_from_fields(
G: Any, j_phi: dict[Any, float], j_dnfr: dict[Any, float]
) -> dict[Any, float]:
"""Apply the existing neighbor-mean divergence to recorded currents."""
phase, pressure = _current_divergence_components_from_fields(G, j_phi, j_dnfr)
return {node: phase[node] + pressure[node] for node in phase}
def _current_divergence_components_from_fields(G, j_phi, j_dnfr):
"""Read each linear current channel on the actual graph neighborhood."""
nodes = tuple(G.nodes())
phase, pressure = {}, {}
for i in nodes:
neighbors = list(G.neighbors(i))
# Legacy neighbor-minus-center (inward-flux / -L_rw) convention.
phase[i] = mean_neighbor_difference(j_phi[i], [j_phi[j] for j in neighbors])
pressure[i] = mean_neighbor_difference(
j_dnfr[i], [j_dnfr[j] for j in neighbors]
)
return phase, pressure
# ---------------------------------------------------------------------------
# Snapshot capture
# ---------------------------------------------------------------------------
def capture_conservation_snapshot(G: Any) -> ConservationSnapshot:
"""Capture structural charge, currents, and fields at one instant.
This is a *read-only* operation that never mutates EPI.
The caller must hold graph state fixed during the complete call, including
the topology-dependent divergence. Returned maps are detached; capture is
not atomic with concurrent evolution.
Parameters
----------
G : TNFRGraph
Network in its current state.
Returns
-------
ConservationSnapshot
"""
fields = _capture_structural_fields(G)
phi_s, k_phi, grad_phi = fields.phi_s, fields.k_phi, fields.grad_phi
j_phi, j_dnfr = fields.j_phi, fields.j_dnfr
charge = _charge_density_from_fields(phi_s, k_phi)
div_phi, div_dnfr = _current_divergence_components_from_fields(G, j_phi, j_dnfr)
div_j = {node: div_phi[node] + div_dnfr[node] for node in div_phi}
return ConservationSnapshot(
charge_density=charge,
phi_s=phi_s,
k_phi=k_phi,
j_phi=j_phi,
j_dnfr=j_dnfr,
grad_phi=grad_phi,
divergence=div_j,
divergence_phi=div_phi,
divergence_dnfr=div_dnfr,
)
# ---------------------------------------------------------------------------
# Conservation balance (two-snapshot comparison)
# ---------------------------------------------------------------------------
def verify_conservation_balance(
before: ConservationSnapshot,
after: ConservationSnapshot,
dt: float = 1.0,
) -> ConservationBalance:
r"""Verify the structural continuity equation between two snapshots.
Computes the residual of the continuity equation using a
**Crank-Nicolson (trapezoidal)** discretization:
Δρ(i)/Δt + ½[div J_before(i) + div J_after(i)] ≈ 0
For sufficiently smooth evolution on fixed support, the trapezoidal
approximation has O(Δt²) accuracy, compared to the O(Δt) of a
right-endpoint scheme. A small residual records agreement with this
balance over the sampled interval; it does not prove sequence-wide
conservation or grammar compliance. Large residuals can reflect numerical
error, changing topology or node support, source terms, or a failure of the
assumed balance. Their cause requires separate investigation.
Requires nonempty identical node support, complete finite charge/divergence
maps and a finite positive interval. A support change needs explicit source
and correspondence accounting outside this observer; it is never filled
with missing-node zeros. All inputs use a common declared normalization
and time convention. The
routine does not convert the raw units of potential, curvature, currents
or ``dt``; a small numeric residual alone does not validate those units.
A nonzero rate outside binary64 range raises instead of becoming a zero
residual. Recoverable intermediate subtraction overflow uses an exact
represented difference before the final quotient is rounded.
Parameters
----------
before : ConservationSnapshot
State before operator application.
after : ConservationSnapshot
State after operator application.
dt : float
Step in the declared diagnostic time coordinate (default 1.0).
Returns
-------
ConservationBalance
Finite-interval structural-balance diagnostics.
"""
dt = _positive_interval(dt)
nodes = _snapshot_pair_nodes(before, after, ("charge_density", "divergence"))
delta_rho: dict[Any, float] = {}
residual: dict[Any, float] = {}
average_divergence: dict[Any, float] = {}
for n in nodes:
rho_before = before.charge_density[n]
rho_after = after.charge_density[n]
d_rho = _observed_secant(rho_before, rho_after, dt, "charge rate")
delta_rho[n] = d_rho
# Crank-Nicolson: trapezoidal average of divergence at both endpoints
div_j = mean_neighbor_difference(
0.0, (before.divergence[n], after.divergence[n])
)
average_divergence[n] = div_j
# Continuity: ∂ρ/∂t + div J = S → residual = ∂ρ/∂t + div J
residual[n] = finite_real_scalar(d_rho + div_j, "balance residual")
residual_vals = tuple(residual.values())
mean_res = mean_neighbor_difference(0.0, residual_vals)
std_res = finite_population_std(residual_vals, name="balance residual")
max_res = max(map(abs, residual_vals))
rms_res = _rms(residual_vals)
# Conservation quality: 1/(1 + RMS) maps [0, ∞) → (0, 1]
quality = 1.0 / (1.0 + rms_res)
# Legacy field name. This is only the mean absolute balance residual and
# has no rule-classification semantics.
gvi = finite_mean_absolute(residual_vals, name="balance residual")
# Total charge tracking
q_before = _total_charge_from_density(before.charge_density)
q_after = _total_charge_from_density(after.charge_density)
charge_drift = finite_real_scalar(abs(q_after - q_before), "charge drift")
return ConservationBalance(
residual=residual,
delta_rho=delta_rho,
divergence_after=average_divergence,
mean_residual=mean_res,
std_residual=std_res,
max_residual=max_res,
rms_residual=rms_res,
conservation_quality=quality,
grammar_violation_index=gvi,
total_charge_before=q_before,
total_charge_after=q_after,
charge_drift=charge_drift,
)
# ---------------------------------------------------------------------------
# Conservation tracker (multi-step)
# ---------------------------------------------------------------------------
class ConservationTracker:
"""Track finite structural-balance diagnostics across an operator sequence.
Usage
-----
>>> tracker = ConservationTracker(G)
>>> tracker.record(t=0.0) # initial snapshot
>>> Emission()(G, node)
>>> tracker.record(t=1.0) # after operator
>>> Coherence()(G, node)
>>> tracker.record(t=2.0)
>>> report = tracker.report()
>>> print(f"Within alert: {report.aggregate_balance_within_alert}")
"""
def __init__(self, G: Any) -> None:
self._G = G
self._snapshots: list[tuple[float, ConservationSnapshot]] = []
self._series = ConservationTimeSeries()
def record(
self, t: float = 0.0, *, _require_energy: bool = False
) -> ConservationSnapshot:
"""Capture current state and compute balance against previous snapshot.
Parameters
----------
t : float
Finite timestamp, strictly greater than the previous timestamp.
Equal timestamps do not imply an invented unit-duration step.
Returns
-------
ConservationSnapshot
A detached copy of the captured snapshot. Editing it cannot alter
the tracker's retained evidence.
Rejected samples leave the retained snapshots and series unchanged.
The private energy flag lets the SDK admit its combined balance/energy
report before commit; pure balance tracking does not require energy.
"""
t = _observed_scalar(t, "snapshot timestamp")
if self._snapshots:
t_prev, snap_prev = self._snapshots[-1]
dt = _positive_interval(t - t_prev)
snap = capture_conservation_snapshot(self._G)
_snapshot_nodes(snap, ("charge_density", "divergence"))
if self._snapshots:
balance = verify_conservation_balance(snap_prev, snap, dt=dt)
if _require_energy:
compute_lyapunov_derivative(snap_prev, snap, dt=dt)
# Commit only after timestamp, capture and interval admission pass.
self._snapshots.append((t, snap))
self._series.times.append(t)
self._series.total_charge.append(balance.total_charge_after)
self._series.mean_residuals.append(balance.mean_residual)
self._series.rms_residuals.append(balance.rms_residual)
self._series.conservation_quality.append(balance.conservation_quality)
self._series.grammar_violation_index.append(balance.grammar_violation_index)
self._series.charge_drift.append(balance.charge_drift)
else:
# First snapshot — record initial charge only
if _require_energy:
_energy_from_snapshot(snap)
q_total = _total_charge_from_density(snap.charge_density)
self._snapshots.append((t, snap))
self._series.times.append(t)
self._series.total_charge.append(q_total)
self._series.mean_residuals.append(0.0)
self._series.rms_residuals.append(0.0)
self._series.conservation_quality.append(1.0)
self._series.grammar_violation_index.append(0.0)
self._series.charge_drift.append(0.0)
# Copy maps without copying node identifiers: labels may use object
# identity, and they must still address the caller's original nodes.
return replace(
snap,
**{
descriptor.name: dict(values)
for descriptor in dataclass_fields(snap)
if (values := getattr(snap, descriptor.name)) is not None
},
)
def report(self) -> ConservationTimeSeries:
"""Return detached accumulated diagnostics, not editable retained evidence."""
return deepcopy(self._series)
@property
def latest_balance(self) -> ConservationBalance | None:
"""Return the most recent balance check, or None."""
if len(self._snapshots) < 2:
return None
t_prev, snap_prev = self._snapshots[-2]
t_curr, snap_curr = self._snapshots[-1]
dt = t_curr - t_prev
return verify_conservation_balance(snap_prev, snap_curr, dt=dt)
# ---------------------------------------------------------------------------
# Decomposed analysis: which field component contributes most to residual
# ---------------------------------------------------------------------------
def decompose_conservation_residual(
before: ConservationSnapshot,
after: ConservationSnapshot,
dt: float = 1.0,
) -> dict[str, dict[Any, float]]:
r"""Decompose the continuity residual into Φ_s and K_φ contributions.
The charge density ρ = Φ_s + K_φ, so:
Δρ/Δt = ΔΦ_s/Δt + ΔK_φ/Δt
This function separates potential-field and curvature-field contributions
to the measured residual. Their magnitudes do not classify U2 or U3, and
potential drift evaluates the U6 policy only when compared with the
canonical two-snapshot threshold through a dedicated U6 checker.
Divergence is evaluated using the **Crank-Nicolson (trapezoidal)**
average of the before and after snapshots for O(Δt²) accuracy.
Its sector components are captured independently on the graph. Local
current magnitudes cannot recover their divergences or even their signs.
Snapshots missing this component evidence must be recaptured.
Returns
-------
dict with keys:
'phi_s_drift' : per-node ΔΦ_s/Δt
'k_phi_drift' : per-node ΔK_φ/Δt
'j_phi_div' : per-node div(J_φ) contribution
'j_dnfr_div' : per-node div(J_ΔNFR) contribution
'potential_residual' : ΔΦ_s/Δt + div(J_ΔNFR) [potential sector]
'geometric_residual' : ΔK_φ/Δt + div(J_φ) [geometric sector]
"""
dt = _positive_interval(dt)
if any(
getattr(snapshot, field) is None
for snapshot in (before, after)
for field in ("divergence_phi", "divergence_dnfr")
):
raise ValueError("sector divergences are unavailable; recapture both snapshots")
nodes = _snapshot_pair_nodes(
before,
after,
("phi_s", "k_phi", "divergence_phi", "divergence_dnfr"),
)
phi_s_drift: dict[Any, float] = {}
k_phi_drift: dict[Any, float] = {}
j_phi_div: dict[Any, float] = {}
j_dnfr_div: dict[Any, float] = {}
potential_residual: dict[Any, float] = {}
geometric_residual: dict[Any, float] = {}
for n in nodes:
# Rate of change of each charge component
d_phi_s = _observed_secant(
before.phi_s[n], after.phi_s[n], dt, "potential rate"
)
d_k_phi = _observed_secant(
before.k_phi[n], after.k_phi[n], dt, "curvature rate"
)
phi_s_drift[n] = d_phi_s
k_phi_drift[n] = d_k_phi
j_phi_div[n] = mean_neighbor_difference(
0.0, (before.divergence_phi[n], after.divergence_phi[n])
)
j_dnfr_div[n] = mean_neighbor_difference(
0.0, (before.divergence_dnfr[n], after.divergence_dnfr[n])
)
potential_residual[n] = finite_real_scalar(
d_phi_s + j_dnfr_div[n], "potential residual"
)
geometric_residual[n] = finite_real_scalar(
d_k_phi + j_phi_div[n], "geometric residual"
)
return {
"phi_s_drift": phi_s_drift,
"k_phi_drift": k_phi_drift,
"j_phi_div": j_phi_div,
"j_dnfr_div": j_dnfr_div,
"potential_residual": potential_residual,
"geometric_residual": geometric_residual,
}
# ---------------------------------------------------------------------------
# Legacy pi-scaled conservation alert levels
# ---------------------------------------------------------------------------
def compute_grammar_conservation_bounds(G: Any) -> ConservationAlertLevels:
r"""Compute legacy grammar-scaled diagnostic alert levels.
The legacy alert construction combines:
- U2's stabilizer/debt role as qualitative context;
- the U6 drift policy ``ΔPhi_s < pi/2`` as a numeric scale;
- the exact trigonometric bound ``|J_phi| <= 1``.
These values combine historical pi-scaled policies into monitoring alert
levels. They are not derived U2/U3/U6 bounds, do not evaluate any grammar
rule, and must not be used as a conservation or grammar certificate. The
returned object remains a ``dict`` subclass containing only numeric legacy
keys; its :attr:`ConservationAlertLevels.metadata` property exposes this
scope without breaking callers that iterate the numeric mapping.
Returns
-------
ConservationAlertLevels
'max_charge_density' : legacy policy-scaled alert level for |ρ|
'max_current_magnitude' : legacy alert level for |J|
'max_allowed_residual' : legacy alert level for |Δρ/Δt + div J|
'phi_s_confinement' : legacy key for the π/2 U6 *drift alert scale*
'k_phi_hotspot' : 0.9×π ≈ 2.8274 (curvature hotspot threshold)
"""
n_nodes = G.number_of_nodes()
# Legacy key/value retained. U6 constrains two-snapshot mean |ΔΦ_s|;
# it does not bound the magnitude |Φ_s| in one graph.
phi_s_alert = U6_STRUCTURAL_POTENTIAL_LIMIT
# K_φ is bounded by π (wrapped angle difference)
k_phi_bound = PI
# Historical composite alert, not a maximum charge-density theorem.
max_charge = phi_s_alert + k_phi_bound
# J_φ = mean(sin(Δθ)), bounded by 1
j_phi_bound = 1.0
# Legacy J_ΔNFR alert proxy. U2/U6 do not bound pressure spread.
j_dnfr_alert = 2.0 * phi_s_alert
# Maximum current magnitude
max_current = math.sqrt(j_phi_bound**2 + j_dnfr_alert**2)
# Historical divergence alert derived from the composite current scale.
avg_degree = 2.0 * G.number_of_edges() / max(n_nodes, 1)
max_div = 2.0 * max_current
# Historical residual alert, not a maximum allowed by grammar.
max_residual = max_charge + max_div
return ConservationAlertLevels(
{
"max_charge_density": max_charge,
"max_current_magnitude": max_current,
"max_allowed_residual": max_residual,
"phi_s_confinement": phi_s_alert,
"k_phi_hotspot": K_PHI_CANONICAL_THRESHOLD,
"average_degree": avg_degree,
}
)
# ---------------------------------------------------------------------------
# Legacy grammar-named entry point for balance alerts
# ---------------------------------------------------------------------------
def detect_grammar_violations_from_conservation(
balance: ConservationBalance,
bounds: dict[str, float] | None = None,
) -> dict[str, Any]:
r"""Report legacy-scaled balance alerts without classifying grammar.
Residuals and charge drift contain no operator-history evidence and no
direct phase-admissibility evidence. They therefore cannot classify U2,
U3, or U6, and cannot validate U1-U6. Numerical discretization, topology
changes, source terms, or an external pressure law can all produce the
same values for grammatically different histories.
The function name and the legacy ``violations_*`` keys remain for API
compatibility. Those keys now report that no grammar verdict was made.
New ``alerts_*`` keys contain the actual finite-balance alerts.
Parameters
----------
balance : ConservationBalance
Result from verify_conservation_balance.
bounds : dict[str, float], optional
Legacy alert levels from :func:`compute_grammar_conservation_bounds`.
Returns
-------
dict with:
``violations_detected`` is always ``False`` because grammar is not
assessed; ``alerts_detected``, ``alert_types``, ``severity`` and
``nodes_alerted`` expose the legacy-scaled observations. Scope and
applicability metadata are included explicitly.
"""
threshold = U6_STRUCTURAL_POTENTIAL_LIMIT
if bounds is not None:
threshold = bounds.get("max_allowed_residual", U6_STRUCTURAL_POTENTIAL_LIMIT)
threshold = _observed_scalar(threshold, "max_allowed_residual")
if threshold <= 0.0:
raise ValueError("max_allowed_residual must be strictly positive")
alert_types: list[str] = []
nodes_alerted: list[Any] = []
for node, res in balance.residual.items():
if abs(res) > threshold:
nodes_alerted.append(node)
if nodes_alerted:
alert_types.append("balance_residual_above_legacy_alert")
if balance.charge_drift > U6_STRUCTURAL_POTENTIAL_LIMIT:
alert_types.append("charge_drift_above_legacy_pi_alert")
if balance.rms_residual > _BALANCE_RMS_ALERT:
alert_types.append("balance_rms_above_legacy_alert")
if balance.max_residual > 2 * threshold:
alert_types.append("balance_peak_above_legacy_alert")
severity = min(1.0, balance.rms_residual / max(threshold, 1e-10))
return {
# Backward-compatible grammar-shaped fields: no grammar assessment was
# made, so these must never carry inferred U-rule failures.
"violations_detected": False,
"violation_count": 0,
"violation_types": [],
"nodes_violating": [],
# Accurate finite-balance alert surface.
"alerts_detected": bool(alert_types),
"alert_count": len(alert_types),
"alert_types": alert_types,
"severity": severity,
"nodes_alerted": nodes_alerted,
"alert_threshold": threshold,
# Applicability metadata.
"diagnostic_scope": "two_snapshot_structural_balance_alerts",
"grammar_validation_applicable": False,
"grammar_validated": False,
"grammar_rules_assessed": (),
"thresholds_are_proven_bounds": False,
"u6_drift_requires_phi_s_reference": True,
}
# ---------------------------------------------------------------------------
# Structural charge (historical Noether-like name)
# ---------------------------------------------------------------------------
def compute_noether_charge(G: Any) -> float:
r"""Compute the historically named tetrad charge candidate.
``Q = Σ_i ρ(i) = Σ_i [Φ_s(i) + K_φ(i)]``.
The charge Q integrates global (potential) and local (geometric)
structural information into a single scalar. Its drift must be measured
along the actual trajectory; grammar compliance is neither sufficient nor
inferred from a small drift.
This tetrad charge candidate is distinct from the EPI-channel
degree-weighted total ``Σ_i deg(i)·EPI(i)``
(:func:`tnfr.physics.structural_diffusion.degree_weighted_total`). The
latter has an exact restricted conservation theorem for fixed symmetric
random-walk diffusion; this function provides no corresponding theorem for
the full tetrad dynamics.
Parameters
----------
G : TNFRGraph
Returns
-------
float
Total structural-charge candidate.
"""
charge = compute_charge_density(G)
return _total_charge_from_density(charge)
def compute_energy_functional(G: Any) -> float:
r"""Compute the TNFR structural energy functional.
E = (1/2) Σ_i ℰ(i)
where ℰ(i) = Φ_s² + |∇φ|² + K_φ² + J_φ² + J_ΔNFR² is the raw
energy density defined by :func:`unified.compute_energy_density`.
**Single source of truth**: delegates to
the shared normalized-total helper in ``unified`` for the same quadratic
form and ½ normalization. It avoids materializing unrepresentable squares
when the final total remains representable.
**Mathematical normalization**:
``E = sum(variational.compute_hamiltonian_density(G).values())``
``E = 0.5 * sum(unified.compute_energy_density(G).values())``
These equalities identify the real quadratic form, not bitwise equality
after independent per-node rounding. Raw densities can underflow/overflow
even when the normalized network total is representable.
The result is non-negative. It is a Lyapunov candidate only: U2 validity
alone does not prove ``dE/dt <= 0`` for an arbitrary pressure law or
operator sequence.
Parameters
----------
G : TNFRGraph
Returns
-------
float
Total structural energy.
See Also
--------
unified.compute_energy_density : Raw ℰ(i) per node.
variational.compute_hamiltonian_density : H(i) = ½·ℰ(i) per node.
"""
fields = _capture_structural_fields(G)
return _total_energy_from_fields(
fields.phi_s, fields.grad_phi, fields.k_phi, fields.j_phi, fields.j_dnfr
)
def _energy_from_snapshot(snapshot: ConservationSnapshot) -> float:
r"""E = ½ Σ_i (Φ_s² + |∇φ|² + K_φ² + J_φ² + J_ΔNFR²) from a captured snapshot.
Snapshot-field counterpart of :func:`compute_energy_functional` (which reads
the live graph): both evaluate the same canonical quadratic form, so the