Repository navigation
Expand file tree
/
Copy pathtypes.py
More file actions
981 lines (766 loc) · 29.5 KB
/
Copy pathtypes.py
File metadata and controls
981 lines (766 loc) · 29.5 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
"""type definitions and protocols shared across the engine."""
from __future__ import annotations
import math
from collections.abc import (
Callable,
Hashable,
Iterable,
Mapping,
MutableMapping,
MutableSequence,
Sequence,
)
from dataclasses import dataclass
from enum import Enum
from numbers import Complex, Real
from types import SimpleNamespace
from typing import (
TYPE_CHECKING,
Any,
ContextManager,
Protocol,
TypeAlias,
TypedDict,
runtime_checkable,
)
from ._exact_time import finite_represented_real
from .errors import TNFRValueError
if TYPE_CHECKING:
from .mathematics import BEPIElement
class CacheLevel(Enum):
"""Cache levels organized by persistence and computational cost.
Levels are ordered from most persistent (rarely changes) to least
persistent (frequently recomputed):
- GRAPH_STRUCTURE: Topology, adjacency matrices (invalidated on add/remove node/edge)
- NODE_PROPERTIES: EPI, νf, θ per node (invalidated on property updates)
- DERIVED_METRICS: Si, coherence, ΔNFR (invalidated on dependency changes)
- TEMPORARY: Intermediate computations (short-lived, frequently evicted)
"""
GRAPH_STRUCTURE = "graph_structure"
NODE_PROPERTIES = "node_properties"
DERIVED_METRICS = "derived_metrics"
TEMPORARY = "temporary"
@dataclass
class CacheStats:
"""Statistics for a cache region."""
hits: int = 0
misses: int = 0
evictions: int = 0
size: int = 0
max_size: int = 0
timings: int = 0
total_time: float = 0.0
@property
def hit_rate(self) -> float:
total = self.hits + self.misses
return (self.hits / total) if total > 0 else 0.0
@property
def total_accesses(self) -> int:
return self.hits + self.misses
def merge(self, other: CacheStats) -> CacheStats:
"""Merge with another stats object."""
return CacheStats(
hits=self.hits + other.hits,
misses=self.misses + other.misses,
evictions=self.evictions + other.evictions,
size=self.size + other.size,
max_size=max(self.max_size, other.max_size),
timings=self.timings + other.timings,
total_time=self.total_time + other.total_time,
)
if TYPE_CHECKING:
try:
import numpy as np
import numpy.typing as npt
except ImportError:
np = Any # type: ignore
npt = Any # type: ignore
else:
try:
import numpy as _np
import numpy.typing as _npt
except ImportError:
_np = None
_npt = None
if _np is None:
np = SimpleNamespace(ndarray=Any, float64=float) # type: ignore[assignment]
else:
np = _np
if _npt is None:
npt = SimpleNamespace(NDArray=Any) # type: ignore[assignment]
else:
npt = _npt
__all__ = (
"CacheLevel",
"CacheStats",
"TNFRGraph",
"TNFRNode",
"Graph",
"ValidatorFunc",
"NodeId",
"Node",
"GammaSpec",
"EPIValue",
"BEPIProtocol",
"ensure_bepi",
"require_finite_real_scalar_epi",
"real_scalar_epi",
"scalarize_epi",
"serialize_bepi",
"serialize_bepi_json",
"deserialize_bepi_json",
"ZERO_BEPI_STORAGE",
"DeltaNFR",
"SecondDerivativeEPI",
"Phase",
"StructuralFrequency",
"SenseIndex",
"CouplingWeight",
"CoherenceMetric",
"DeltaNFRHook",
"GraphLike",
"IntegratorProtocol",
"Glyph",
"GlyphCode",
"GlyphLoadDistribution",
"GlyphSelector",
"SelectorPreselectionMetrics",
"SelectorPreselectionChoices",
"SelectorPreselectionPayload",
"SelectorMetrics",
"SelectorNorms",
"SelectorThresholds",
"SelectorWeights",
"TraceCallback",
"CallbackError",
"TraceFieldFn",
"TraceFieldMap",
"TraceFieldRegistry",
"TraceMetadata",
"TraceSnapshot",
"RemeshMeta",
"HistoryState",
"DiagnosisNodeData",
"DiagnosisSharedState",
"DiagnosisPayload",
"DiagnosisResult",
"DiagnosisPayloadChunk",
"DiagnosisResultList",
"DnfrCacheVectors",
"DnfrVectorMap",
"NeighborStats",
"TimingContext",
"PresetTokens",
"ProgramTokens",
"ArgSpec",
"TNFRConfigValue",
"SigmaVector",
"SigmaTrace",
"FloatArray",
"FloatMatrix",
"NodeInitAttrMap",
"NodeAttrMap",
"GlyphogramRow",
"GlyphTimingTotals",
"GlyphTimingByNode",
"GlyphCounts",
"GlyphMetricsHistoryValue",
"GlyphMetricsHistory",
"MetricsListHistory",
"ParallelWijPayload",
)
if TYPE_CHECKING: # pragma: no cover - import-time typing hook
import networkx as nx
from .glyph_history import HistoryDict as _HistoryDict
from .tokens import Token as _Token
TNFRGraph: TypeAlias = nx.Graph
else: # pragma: no cover - runtime fallback without networkx
TNFRGraph: TypeAlias = Any
_HistoryDict = Any # type: ignore[assignment]
_Token = Any # type: ignore[assignment]
#: Graph container storing TNFR nodes, edges and their coherence telemetry.
TNFRNode: TypeAlias = MutableMapping[str, Any]
#: Mutable mapping representing a TNFR node's state (EPI, νf, ΔNFR, etc.).
if TYPE_CHECKING:
FloatArray: TypeAlias = npt.NDArray[np.float64]
FloatMatrix: TypeAlias = npt.NDArray[np.float64]
else: # pragma: no cover - runtime fallback without NumPy
FloatArray: TypeAlias = Any
FloatMatrix: TypeAlias = Any
Graph: TypeAlias = TNFRGraph
#: Backwards-compatible alias for :data:`TNFRGraph`.
ValidatorFunc: TypeAlias = Callable[[TNFRGraph], None]
"""Callable signature enforced by graph validation hooks."""
NodeId: TypeAlias = Hashable
#: Hashable identifier for a coherent TNFR node.
Node: TypeAlias = NodeId
#: Backwards-compatible alias for :data:`NodeId`.
NodeInitAttrMap: TypeAlias = MutableMapping[str, float]
#: Mutable mapping storing scalar node attributes during initialization.
NodeAttrMap: TypeAlias = Mapping[str, Any]
#: Read-only mapping exposing resolved node attributes during execution.
GammaSpec: TypeAlias = Mapping[str, Any]
#: Mapping describing Γ evaluation parameters for a node or graph.
@runtime_checkable
class BEPIProtocol(Protocol):
"""Structural contract describing BEPI-compatible values."""
f_continuous: Any
a_discrete: Any
x_grid: Any
def direct_sum(self, other: Any) -> Any: ...
def tensor(self, vector: Sequence[complex] | np.ndarray) -> np.ndarray: ...
def adjoint(self) -> Any: ...
def compose(
self,
transform: Callable[[np.ndarray], np.ndarray],
*,
spectral_transform: Callable[[np.ndarray], np.ndarray] | None = None,
) -> Any: ...
def real_scalar_embedding(self) -> float | None: ...
def scalar_projection(self) -> float: ...
EPIValue: TypeAlias = BEPIProtocol
#: BEPI Primary Information Structure carried by a node.
ZERO_BEPI_STORAGE: dict[str, tuple[complex, ...] | tuple[float, ...]] = {
"continuous": (0j, 0j),
"discrete": (0j, 0j),
"grid": (0.0, 1.0),
}
"""Canonical zero element used as fallback when EPI data is missing."""
def _is_scalar(value: Any) -> bool:
scalar_types: tuple[type[Any], ...]
np_scalar = getattr(np, "generic", None)
if np_scalar is None:
scalar_types = (int, float, complex, Real)
else:
scalar_types = (int, float, complex, Real, np_scalar)
return isinstance(value, scalar_types)
def _decode_serialized_bepi_component(values: Any) -> Any:
"""Decode JSON real/imag entries while leaving native components intact."""
try:
entries = tuple(values)
except TypeError:
return values
decoded: list[Any] = []
changed = False
for entry in entries:
if isinstance(entry, Mapping):
try:
real = finite_represented_real(entry["real"], "EPI.real")[0]
imaginary = finite_represented_real(entry["imag"], "EPI.imag")[0]
except KeyError as exc:
raise TNFRValueError(
"Serialized complex EPI entries require 'real' and 'imag'.",
context={"received_keys": list(entry.keys())},
) from exc
except (TypeError, ValueError, OverflowError) as exc:
raise TNFRValueError(
"Serialized complex EPI entries require finite representable components."
) from exc
entry = complex(real, imaginary)
changed = True
decoded.append(entry)
return tuple(decoded) if changed else values
def ensure_bepi(value: Any) -> "BEPIElement":
"""Normalise arbitrary inputs into a :class:`~tnfr.mathematics.BEPIElement`."""
from .mathematics import BEPIElement as _BEPIElement
if isinstance(value, _BEPIElement):
return value
if _is_scalar(value):
return _BEPIElement((value, value), (value, value), (0.0, 1.0))
if isinstance(value, Mapping):
try:
continuous = value["continuous"]
discrete = value["discrete"]
grid = value["grid"]
except KeyError as exc: # pragma: no cover - defensive
missing = exc.args[0]
raise TNFRValueError(
f"Missing '{missing}' key for BEPI serialization.",
context={"missing_key": missing, "received_keys": list(value.keys())},
) from exc
return _BEPIElement(
_decode_serialized_bepi_component(continuous),
_decode_serialized_bepi_component(discrete),
grid,
)
if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)):
if len(value) != 3:
raise TNFRValueError(
"Sequential BEPI representations must contain 3 elements.",
context={"length": len(value), "value": value},
)
continuous, discrete, grid = value
return _BEPIElement(continuous, discrete, grid)
raise TypeError(f"Unsupported BEPI value type: {type(value)!r}")
def scalarize_epi(value: Any) -> float:
"""Return the canonical scalar EPI read-out for any BEPI representation.
Normalising first makes live :class:`BEPIElement` instances and canonical
``continuous/discrete/grid`` storage mappings follow exactly the same rule:
uniform real scalar embeddings retain their sign, while genuinely
non-scalar or complex elements reduce to their maximum component magnitude.
"""
return float(ensure_bepi(value))
def real_scalar_epi(value: Any) -> float | None:
"""Return an exact signed scalar EPI embedding, or ``None`` if richer."""
return ensure_bepi(value).real_scalar_embedding()
def require_finite_real_scalar_epi(value: Any, label: str = "EPI") -> float:
"""Return a finite signed scalar EPI embedding or raise ``TNFRValueError``.
Scalar-only diagnostics must not collapse a richer BEPI element to a
magnitude, parse textual values, or turn logical state into physical
zero/one. Admission precedes materialization so nonzero real inputs cannot
underflow to zero, including components of serialized BEPI values.
"""
numpy_bool = getattr(np, "bool_", None)
if isinstance(value, bool) or (
numpy_bool is not None and isinstance(value, numpy_bool)
):
raise TNFRValueError(f"{label} must be a finite uniform-real EPI value")
try:
if isinstance(value, Complex):
return _represented_real_epi_component(value, label)
if isinstance(value, Mapping):
value = {
"continuous": tuple(
_represented_real_epi_component(item, label)
for item in value["continuous"]
),
"discrete": tuple(
_represented_real_epi_component(item, label)
for item in value["discrete"]
),
"grid": value["grid"],
}
elif isinstance(value, Sequence) and not isinstance(
value, (str, bytes, bytearray)
):
continuous, discrete, grid = value
value = (
tuple(
_represented_real_epi_component(item, label) for item in continuous
),
tuple(
_represented_real_epi_component(item, label) for item in discrete
),
grid,
)
scalar = real_scalar_epi(value)
except (KeyError, OverflowError, TypeError, ValueError) as exc:
raise TNFRValueError(
f"{label} must be a finite uniform-real EPI value"
) from exc
if scalar is None or not math.isfinite(scalar):
raise TNFRValueError(f"{label} must be a finite uniform-real EPI value")
return float(scalar)
def _represented_real_epi_component(value: Any, label: str) -> float:
"""Admit a scalar or a serialized complex component before BEPI coercion."""
if isinstance(value, Mapping):
imaginary = finite_represented_real(value["imag"], label)[0]
value = value["real"]
elif isinstance(value, Complex) and not isinstance(value, Real):
imaginary = value.imag
value = value.real
else:
imaginary = 0.0
if imaginary != 0.0:
raise ValueError(f"{label} must be real")
return finite_represented_real(value, label)[0]
def serialize_bepi(value: Any) -> dict[str, tuple[complex, ...] | tuple[float, ...]]:
"""Serialise a BEPI element into canonical ``continuous/discrete/grid`` tuples."""
element = ensure_bepi(value)
continuous = tuple(complex(v) for v in element.f_continuous.tolist())
discrete = tuple(complex(v) for v in element.a_discrete.tolist())
grid = tuple(float(v) for v in element.x_grid.tolist())
return {"continuous": continuous, "discrete": discrete, "grid": grid}
def serialize_bepi_json(value: Any) -> dict[str, list[dict[str, float]] | list[float]]:
"""Serialize a BEPI element into JSON-compatible format.
Complex numbers are represented as dicts with 'real' and 'imag' keys.
This enables full JSON/YAML serialization while preserving structural coherence.
Parameters
----------
value : Any
A BEPIElement instance or value convertible to one.
Returns
-------
dict
Dictionary with 'continuous', 'discrete', and 'grid' keys, where
complex values are represented as ``{"real": float, "imag": float}``
and grid values remain as floats.
Examples
--------
>>> from tnfr.mathematics import BEPIElement
>>> bepi = BEPIElement((1+2j, 3+0j), (4+5j,), (0.0, 1.0))
>>> serialize_bepi_json(bepi) # doctest: +SKIP
{
'continuous': [{'real': 1.0, 'imag': 2.0}, {'real': 3.0, 'imag': 0.0}],
'discrete': [{'real': 4.0, 'imag': 5.0}],
'grid': [0.0, 1.0]
}
"""
element = ensure_bepi(value)
def _complex_to_dict(c: complex) -> dict[str, float]:
return {"real": float(c.real), "imag": float(c.imag)}
continuous = [_complex_to_dict(v) for v in element.f_continuous.tolist()]
discrete = [_complex_to_dict(v) for v in element.a_discrete.tolist()]
grid = [float(v) for v in element.x_grid.tolist()]
return {"continuous": continuous, "discrete": discrete, "grid": grid}
def deserialize_bepi_json(
data: dict[str, list[dict[str, float]] | list[float]],
) -> "BEPIElement":
"""Deserialize a BEPI element from JSON-compatible format.
Reconstructs complex numbers from dicts with 'real' and 'imag' keys.
Parameters
----------
data : dict
Dictionary with 'continuous', 'discrete', and 'grid' keys in JSON format.
The 'continuous' and 'discrete' values should be lists of dicts with
'real' and 'imag' keys, while 'grid' should be a list of floats.
Returns
-------
BEPIElement
Reconstructed BEPI element with validated structural integrity.
Examples
--------
>>> data = {
... 'continuous': [{'real': 1.0, 'imag': 2.0}, {'real': 3.0, 'imag': 0.0}],
... 'discrete': [{'real': 4.0, 'imag': 5.0}],
... 'grid': [0.0, 1.0]
... }
>>> bepi = deserialize_bepi_json(data) # doctest: +SKIP
"""
return ensure_bepi(data)
DeltaNFR: TypeAlias = float
#: Scalar internal reorganisation driver ΔNFR applied to a node.
SecondDerivativeEPI: TypeAlias = float
#: Second derivative ∂²EPI/∂t² tracking bifurcation pressure.
Phase: TypeAlias = float
#: Phase (φ) describing a node's synchrony relative to its neighbors.
StructuralFrequency: TypeAlias = float
#: Structural frequency νf expressed in Hz_str.
SenseIndex: TypeAlias = float
#: Sense index Si capturing a node's reorganising capacity.
CouplingWeight: TypeAlias = float
#: Weight attached to edges describing coupling coherence strength.
CoherenceMetric: TypeAlias = float
#: Aggregated measure of coherence such as C(t) or Si.
TimingContext: TypeAlias = ContextManager[None]
#: Context manager used to measure execution time for cache operations.
ProgramTokens: TypeAlias = Sequence[_Token]
#: Sequence of execution tokens composing a TNFR program.
PresetTokens: TypeAlias = Sequence[_Token]
#: Sequence of execution tokens composing a preset program.
ArgSpec: TypeAlias = tuple[str, Mapping[str, Any]]
#: CLI argument specification pairing an option flag with keyword arguments.
TNFRConfigScalar: TypeAlias = bool | int | float | str | None
"""Primitive value allowed within TNFR configuration stores."""
TNFRConfigSequence: TypeAlias = Sequence[TNFRConfigScalar]
"""Homogeneous sequence of scalar TNFR configuration values."""
TNFRConfigValue: TypeAlias = (
TNFRConfigScalar | TNFRConfigSequence | MutableMapping[str, "TNFRConfigValue"]
)
"""Permissible configuration entry for TNFR coherence defaults.
The alias captures the recursive structure used by TNFR defaults: scalars
express structural thresholds, booleans toggle operators, and nested
mappings
or sequences describe coherent parameter bundles such as γ grammars,
selector advice or trace capture lists.
Configuration dictionaries support the full
:class:`~collections.abc.MutableMapping` protocol, enabling dict-like
operations such as ``.get()``, ``__setitem__``,
and ``.update()`` for runtime configuration adjustments.
"""
class _SigmaVectorRequired(TypedDict):
"""Mandatory components for a σ-vector in the sense plane."""
x: float
y: float
mag: float
angle: float
n: int
class _SigmaVectorOptional(TypedDict, total=False):
"""Optional metadata captured when tracking σ-vectors."""
glyph: str
w: float
t: float
class SigmaVector(_SigmaVectorRequired, _SigmaVectorOptional):
"""Typed dictionary describing σ-vector telemetry."""
class SigmaTrace(TypedDict):
"""Position-aligned σ trace with explicit missing samples and clocks."""
t: list[float | None]
sigma_x: list[float | None]
sigma_y: list[float | None]
mag: list[float | None]
angle: list[float | None]
class SelectorThresholds(TypedDict):
"""Normalised thresholds applied by the glyph selector."""
si_hi: float
si_lo: float
dnfr_hi: float
dnfr_lo: float
accel_hi: float
accel_lo: float
class SelectorWeights(TypedDict):
"""Normalised weights controlling selector scoring."""
w_si: float
w_dnfr: float
w_accel: float
SelectorMetrics: TypeAlias = tuple[float, float, float]
"""tuple grouping normalised Si, |ΔNFR| and acceleration values."""
SelectorNorms: TypeAlias = Mapping[str, float]
"""Mapping storing maxima used to normalise selector metrics."""
@runtime_checkable
class _DeltaNFRHookProtocol(Protocol):
"""Callable signature expected for ΔNFR update hooks.
Hooks receive the graph instance and may expose optional keyword
arguments such as ``n_jobs`` or cache controls. Additional positional
arguments are reserved for future extensions and ignored by the core
engine, keeping compatibility with user-provided hooks that only need the
graph reference.
Notes
-----
Marked with @runtime_checkable to enable isinstance() checks for validating
hook implementations conform to the expected callable signature.
"""
def __call__(
self,
graph: TNFRGraph,
/,
*args: Any,
**kwargs: Any,
) -> None: ...
DeltaNFRHook: TypeAlias = _DeltaNFRHookProtocol
#: Callable hook invoked to compute ΔNFR for a :data:`TNFRGraph`.
@runtime_checkable
class _NodeViewLike(Protocol):
"""Subset of :class:`networkx.NodeView` behaviour relied on by TNFR.
Notes
-----
Marked with @runtime_checkable to enable isinstance() checks for validating
node view implementations conform to the expected interface.
"""
def __iter__(self) -> Iterable[Any]: ...
def __call__(self, data: bool = ...) -> Iterable[Any]: ...
def __getitem__(self, node: Any) -> Mapping[str, Any]: ...
@runtime_checkable
class _EdgeViewLike(Protocol):
"""Subset of :class:`networkx.EdgeView` behaviour relied on by TNFR.
Notes
-----
Marked with @runtime_checkable to enable isinstance() checks for validating
edge view implementations conform to the expected interface.
"""
def __iter__(self) -> Iterable[Any]: ...
def __call__(self, data: bool = ...) -> Iterable[Any]: ...
@runtime_checkable
class GraphLike(Protocol):
"""Protocol describing graph objects consumed by TNFR subsystems.
Graph-like containers must expose cached-property style ``nodes`` and
``edges`` views compatible with :mod:`networkx`, a ``neighbors`` iterator,
``number_of_nodes`` introspection and a metadata mapping via ``.graph``.
Metrics, cache utilities and CLI diagnostics assume this interface when
traversing structural coherence data.
Notes
-----
Marked with @runtime_checkable to enable isinstance() checks for validating
graph implementations conform to the expected TNFR graph interface.
"""
graph: MutableMapping[str, Any]
nodes: _NodeViewLike
edges: _EdgeViewLike
def number_of_nodes(self) -> int:
"""Return the total number of coherent nodes in the graph."""
...
def neighbors(self, n: Any) -> Iterable[Any]:
"""Yield adjacent nodes coupled to ``n`` within the structure."""
...
def __getitem__(self, node: Any) -> MutableMapping[Any, Any]:
"""Expose adjacency metadata for ``node`` using ``G[node]``
semantics."""
...
def __iter__(self) -> Iterable[Any]:
"""Iterate over nodes to allow direct structural traversals."""
...
@runtime_checkable
class IntegratorProtocol(Protocol):
"""Interface describing configurable nodal equation integrators.
Notes
-----
Marked with @runtime_checkable to enable isinstance() checks for validating
integrator implementations conform to the expected interface.
"""
def integrate(
self,
graph: TNFRGraph,
*,
dt: float | None,
t: float | None,
method: str | None,
n_jobs: int | None,
) -> None:
"""Advance the nodal equation for ``graph`` using integrator
configuration."""
...
class Glyph(str, Enum):
"""Canonical TNFR structural symbols (glyphs).
Glyphs are the structural symbols (AL, EN, IL, etc.) that represent the
application of structural operators. Each structural operator (Emission,
Reception, Coherence, etc.) is associated with a specific glyph symbol.
For public-facing documentation and APIs, refer to these by their
structural operator names rather than the internal glyph codes.
"""
AL = "AL"
EN = "EN"
IL = "IL"
OZ = "OZ"
UM = "UM"
RA = "RA"
SHA = "SHA"
VAL = "VAL"
NUL = "NUL"
THOL = "THOL"
ZHIR = "ZHIR"
NAV = "NAV"
REMESH = "REMESH"
GlyphCode: TypeAlias = Glyph | str
"""Structural operator symbol (glyph) identifier accepted by selector
pipelines and grammars."""
GlyphLoadDistribution: TypeAlias = dict[Glyph | str, float]
"""Normalised load proportions keyed by structural operator symbol
(glyph) or aggregate labels."""
@runtime_checkable
class _SelectorLifecycle(Protocol):
"""Protocol describing the selector lifecycle supported by the runtime.
Notes
-----
Marked with @runtime_checkable to enable isinstance() checks for validating
selector implementations conform to the expected lifecycle interface.
"""
def __call__(self, graph: TNFRGraph, node: NodeId) -> GlyphCode: ...
def prepare(self, graph: TNFRGraph, nodes: Sequence[NodeId]) -> None: ...
def select(self, graph: TNFRGraph, node: NodeId) -> GlyphCode: ...
GlyphSelector: TypeAlias = Callable[[TNFRGraph, NodeId], GlyphCode] | _SelectorLifecycle
"""Selector callable or object returning the structural operator symbol
(glyph) to apply for a node."""
SelectorPreselectionMetrics: TypeAlias = Mapping[Any, SelectorMetrics]
"""Mapping of nodes to their normalised selector metrics."""
SelectorPreselectionChoices: TypeAlias = Mapping[Any, Glyph | str]
"""Mapping of nodes to their preferred structural operator symbol
(glyph) prior to grammar filters."""
SelectorPreselectionPayload: TypeAlias = tuple[
SelectorPreselectionMetrics,
SelectorPreselectionChoices,
]
#: tuple grouping selector metrics and base decisions for preselection steps.
TraceFieldFn: TypeAlias = Callable[[TNFRGraph], "TraceMetadata"]
#: Callable producing :class:`tnfr.trace.TraceMetadata` from a
#: :data:`TNFRGraph`.
TraceFieldMap: TypeAlias = Mapping[str, "TraceFieldFn"]
#: Mapping of trace field names to their producers for a given phase.
TraceFieldRegistry: TypeAlias = dict[str, dict[str, "TraceFieldFn"]]
#: Registry grouping trace field producers by capture phase.
class TraceMetadata(TypedDict, total=False):
"""Metadata captured by trace field producers across phases."""
gamma: Mapping[str, Any]
grammar: Mapping[str, Any]
selector: str | None
dnfr_weights: Mapping[str, Any]
si_weights: Mapping[str, Any]
si_sensitivity: Mapping[str, Any]
callbacks: Mapping[str, list[str] | None]
thol_open_nodes: int
kuramoto: Mapping[str, float]
sigma: Mapping[str, float]
glyphs: Mapping[str, int]
class TraceSnapshot(TraceMetadata, total=False):
"""Trace metadata snapshot recorded in TNFR history."""
t: float
phase: str
HistoryState: TypeAlias = _HistoryDict | dict[str, Any]
#: History container used to accumulate glyph metrics and logs for the graph.
class CallbackError(TypedDict):
"""Metadata captured for a failed callback invocation."""
event: str
step: int | None
error: str
traceback: str
fn: str
name: str | None
TraceCallback: TypeAlias = Callable[[TNFRGraph, dict[str, Any]], None]
#: Callback signature used by :func:`tnfr.trace.register_trace`.
DiagnosisNodeData: TypeAlias = Mapping[str, Any]
#: Raw nodal measurement payload used prior to computing diagnostics.
DiagnosisSharedState: TypeAlias = Mapping[str, Any]
#: Shared read-only state propagated to diagnosis workers.
DiagnosisPayload: TypeAlias = dict[str, Any]
#: Structured diagnostics exported for a single node.
DiagnosisResult: TypeAlias = tuple[NodeId, DiagnosisPayload]
#: Node identifier paired with its :data:`DiagnosisPayload`.
DiagnosisPayloadChunk: TypeAlias = list[DiagnosisNodeData]
#: Chunk of nodal payloads processed together by diagnosis workers.
DiagnosisResultList: TypeAlias = list[DiagnosisResult]
#: Collection of diagnosis results matching worker output shape.
DnfrCacheVectors: TypeAlias = tuple[
np.ndarray | None,
np.ndarray | None,
np.ndarray | None,
np.ndarray | None,
np.ndarray | None,
]
"""tuple grouping cached NumPy vectors for θ, EPI, νf and trigonometric
projections."""
DnfrVectorMap: TypeAlias = dict[str, np.ndarray | None]
"""Mapping of TNFR state aliases to their NumPy buffers synchronized
from lists."""
NeighborStats: TypeAlias = tuple[
Sequence[float],
Sequence[float],
Sequence[float],
Sequence[float],
Sequence[float] | None,
Sequence[float] | None,
Sequence[float] | None,
]
"""Bundle of neighbour accumulators for cosine, sine, EPI, νf and
topology totals."""
GlyphogramRow: TypeAlias = MutableMapping[str, float]
"""Row exported by glyph timing summaries."""
GlyphTimingTotals: TypeAlias = MutableMapping[str, float]
"""Aggregate glyph timing totals keyed by glyph code."""
GlyphTimingByNode: TypeAlias = MutableMapping[
Any, MutableMapping[str, MutableSequence[float]]
]
"""Glyph timing segments stored per node during audits."""
GlyphCounts: TypeAlias = Mapping[str, int]
"""Glyph occurrence counters keyed by glyph code."""
GlyphMetricsHistoryValue: TypeAlias = MutableMapping[Any, Any] | MutableSequence[Any]
"""Flexible container used by glyph history accumulators."""
GlyphMetricsHistory: TypeAlias = MutableMapping[str, GlyphMetricsHistoryValue]
"""History map storing glyph metrics by identifier."""
MetricsListHistory: TypeAlias = MutableMapping[str, list[Any]]
"""Mapping associating glyph metric identifiers with time series."""
class RemeshMeta(TypedDict, total=False):
"""Event metadata persisted after applying REMESH coherence operators."""
alpha: float
alpha_source: str
tau_global: int
tau_local: int
step: int | None
topo_hash: str | None
epi_mean_before: float
epi_mean_after: float
epi_raw_mean_after: float
clip_mode: str
clipped_node_count: int
epi_checksum_before: str
epi_checksum_after: str
stable_frac_last: float
phase_sync_last: float
glyph_disr_last: float
class ParallelWijPayload(TypedDict):
"""Container for broadcasting Wij coherence components to worker pools."""
epi_vals: Sequence[float]
vf_vals: Sequence[float]
si_vals: Sequence[float]
cos_vals: Sequence[float]
sin_vals: Sequence[float]
weights: tuple[float, float, float, float]
epi_range: float
vf_range: float