Repository navigation
Expand file tree
/
Copy pathintegrators.py
More file actions
1364 lines (1167 loc) · 47.1 KB
/
Copy pathintegrators.py
File metadata and controls
1364 lines (1167 loc) · 47.1 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
"""Shared nodal integrators and explicitly configured additive forcing.
The unforced nodal law is ``dEPI/dt = vf * dnfr``. The optional Gamma registry
implements the broader configured equation:
∂EPI/∂t = νf · ΔNFR(t) + Γi(R)
The extended equation includes:
- Base term: νf · ΔNFR(t) - canonical structural evolution
- Additive term: Γi - optional Kuramoto-based or harmonic forcing
Gamma is an additional rate source, not a derivation from the nodal product.
At positive capacity it can be written as an effective pressure ``dnfr+Gamma/vf``;
this representation is singular at zero capacity. Nonzero Gamma can therefore
move EPI at ``vf=0``. Unforced certificates and Silence claims require Gamma
to vanish, or separate evidence for the extended model. No units or phase
synchronization theorem follows merely from calling this integrator.
The base term is ``vf * dnfr`` with stored frequency and pressure held fixed
during each call. For the built-in time-only forcing at fixed phases, ``rk4``
is fourth-order quadrature. It does not reevaluate a state-dependent pressure
law at Runge-Kutta stages. Optional clipping can alter the unconstrained ODE
trajectory, so the order claim applies while clipping is inactive.
These solvers evolve the signed real scalar EPI chart, including its exact
uniform-real BEPI embedding. Richer BEPI values require their own dynamics;
their magnitude read-out must not silently replace the evolved state.
"""
from __future__ import annotations
import math
import sys
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable, Iterator, Mapping
from concurrent.futures import ProcessPoolExecutor
from contextlib import contextmanager
from fractions import Fraction
from multiprocessing import get_context
from typing import Any, Literal, TypeAlias, cast
import networkx as nx
from .._exact_time import finite_represented_real
from ..alias import get_attr, get_attr_str, set_attr, set_attr_str
from ..config.parsing import parse_bool
from ..constants import DEFAULTS
from ..constants.aliases import (
ALIAS_D2EPI,
ALIAS_DEPI,
ALIAS_DNFR,
ALIAS_EPI,
ALIAS_EPI_KIND,
ALIAS_THETA,
ALIAS_VF,
)
from ..constants.canonical import (
INTEGRATORS_DNFR_BOUNDS_CANONICAL,
INTEGRATORS_HALF_STEP_CANONICAL,
INTEGRATORS_RK4_SIXTH_CANONICAL,
INTEGRATORS_SIGMOID_OFFSET_CANONICAL,
)
from ..errors.contextual import NetworkConfigError, TNFRUserError, TNFRValueError
from ..gamma import (
_get_gamma_spec,
_uses_builtin_gamma,
eval_gamma,
eval_gamma_vectorized,
)
from ..mathematics._exact_weighted import exact_weighted_sum_ratio
from ..mathematics._neighbor_differences import mean_neighbor_difference
from ..mathematics.unified_numerical import np
from ..types import NodeId, TNFRGraph, require_finite_real_scalar_epi
from ..utils import resolve_chunk_size
from ._euler_kernel import euler_update
from .structural_clip import resolve_clip_policy, structural_clip, structural_clip_array
__all__ = (
"AbstractIntegrator",
"DefaultIntegrator",
"prepare_integration_params",
"rk4_coupled_step",
"update_epi_via_nodal_equation",
)
GammaMap: TypeAlias = dict[NodeId, float]
"""Γ evaluation cache keyed by node identifier."""
NodeIncrements: TypeAlias = dict[NodeId, tuple[float, ...]]
"""Mapping of nodes to staged integration increments."""
NodalUpdate: TypeAlias = dict[NodeId, tuple[float, float, float]]
"""Mapping of nodes to ``(EPI, dEPI/dt, ∂²EPI/∂t²)`` tuples."""
IntegratorMethod: TypeAlias = Literal["euler", "rk4"]
"""Supported explicit integration schemes for nodal updates."""
ClipPolicy: TypeAlias = tuple[float, float, Literal["hard", "soft"], float]
_PARALLEL_GRAPH: TNFRGraph | None = None
def _read_scalar_epi(nd: dict[str, Any]) -> float:
"""Read the authoritative scalar chart without a magnitude projection."""
return cast(
float,
get_attr(
nd,
ALIAS_EPI,
0.0,
strict=True,
conv=require_finite_real_scalar_epi,
),
)
def _finite_output(value: Any, parameter: str = "derivative") -> float:
"""Admit represented-real solver scalars before coercion or commit."""
try:
return finite_represented_real(value, parameter)[0]
except (TypeError, ValueError) as exc:
raise NetworkConfigError(
parameter=parameter, value=value, reason=str(exc)
) from exc
def _integration_clip_policy(graph: TNFRGraph) -> ClipPolicy:
"""Validate the active boundary policy before any solver-side evaluation."""
try:
return resolve_clip_policy(graph.graph)
except ValueError as exc:
raise NetworkConfigError(
parameter="EPI clipping policy",
value={
key: graph.graph[key]
for key in ("EPI_MIN", "EPI_MAX", "CLIP_MODE", "CLIP_SOFT_K")
if key in graph.graph
},
reason=str(exc),
) from exc
def _validate_clock_grid(t0: float, dt_step: float, steps: int, method: str) -> float:
"""Validate the repeated-add clock actually used, without storing a grid."""
current = t0
for _ in range(steps):
following = current + dt_step
if not math.isfinite(following) or (dt_step > 0 and following <= current):
raise NetworkConfigError(
parameter="t",
value=following,
reason="Every positive solver substep must advance a finite represented clock",
)
if method == "rk4" and dt_step > 0:
midpoint = current + dt_step / INTEGRATORS_HALF_STEP_CANONICAL
if not math.isfinite(midpoint):
raise NetworkConfigError(
parameter="t",
value=midpoint,
reason="RK4 stage times must be finite",
)
current = following
return current
@contextmanager
def _restore_solver_outputs_on_error(
graph: TNFRGraph, keys: tuple[str, ...]
) -> Iterator[None]:
"""Restore owned node outputs after a later scalar/extended substep fails.
Callback effects, graph caches and external state are not transactional.
"""
saved = {
node: {key: nd[key] for key in keys if key in nd}
for node, nd in graph.nodes(data=True)
}
try:
yield
except Exception:
for node, original in saved.items():
if node not in graph:
continue
nd = graph.nodes[node]
for key in keys:
nd.pop(key, None)
nd.update(original)
raise
def _gamma_worker_init(graph: TNFRGraph) -> None:
"""Initialise process-local graph reference for Γ evaluation."""
global _PARALLEL_GRAPH
_PARALLEL_GRAPH = graph
def _gamma_worker(task: tuple[list[NodeId], float]) -> list[tuple[NodeId, float]]:
"""Evaluate Γ for ``task`` chunk using process-local graph."""
chunk, t = task
if _PARALLEL_GRAPH is None:
raise RuntimeError("Parallel Γ worker initialised without graph reference")
return [
(node, float(eval_gamma(_PARALLEL_GRAPH, node, t, strict=True)))
for node in chunk
]
def _normalise_jobs(n_jobs: int | None, total: int) -> int | None:
"""Return an effective worker count respecting serial fallbacks."""
if n_jobs is None:
return None
try:
workers = int(n_jobs)
except (TypeError, ValueError):
return None
if workers <= 1 or total <= 1:
return None
return max(1, min(workers, total))
def _chunk_nodes(nodes: list[NodeId], chunk_size: int) -> Iterable[list[NodeId]]:
"""Yield deterministic chunks from ``nodes`` respecting insertion order."""
for idx in range(0, len(nodes), chunk_size):
yield nodes[idx : idx + chunk_size]
def _exact_rk4_update(epi: float, dt_step: float, stages: tuple[float, ...]) -> float:
"""Round a range-limited quadrature after exact represented-input arithmetic."""
before = _finite_output(epi, "EPI")
step = _finite_output(dt_step, "dt")
rates = tuple(_finite_output(stage, "RK4 stage") for stage in stages)
numerator, denominator = exact_weighted_sum_ratio(
(1.0, 2.0, 2.0, 1.0), rates, normalize=True
)
exact = Fraction(before) + Fraction(step) * Fraction(numerator, denominator)
try:
result = float(exact)
except OverflowError as exc:
raise NetworkConfigError(
parameter="EPI", value="out of range", reason="Solver output must be finite"
) from exc
return _finite_output(result, "EPI")
def _rk4_update(epi: Any, dt_step: float, stages: tuple[Any, ...]) -> Any:
"""Apply one shared 1:2:2:1 quadrature to scalar or array supplied rates.
Ordinary values retain the existing separate arithmetic order. If h/6 is
subnormal or a weighted sum/proposal overflows, reuse the exact weighted
reducer and round the final represented-input expression for that row.
This avoids losing a finite response to an intermediate range limit; it
does not recompute state-dependent stages or add an evolution law.
"""
k1, k2, k3, k4 = stages
factor = dt_step / INTEGRATORS_RK4_SIXTH_CANONICAL
factor_underflow = dt_step != 0.0 and abs(factor) < sys.float_info.min
if np is not None and isinstance(epi, np.ndarray):
with np.errstate(over="ignore", invalid="ignore", under="ignore"):
weighted = k1 + 2 * k2 + 2 * k3 + k4
result = epi + factor * weighted
exceptional = ~np.isfinite(weighted) | ~np.isfinite(result)
if factor_underflow:
exceptional = np.ones_like(result, dtype=bool)
for index in np.flatnonzero(exceptional):
result[index] = _exact_rk4_update(
epi[index], dt_step, tuple(stage[index] for stage in stages)
)
return result
weighted = k1 + 2 * k2 + 2 * k3 + k4
result = epi + factor * weighted
if factor_underflow or not math.isfinite(weighted) or not math.isfinite(result):
return _exact_rk4_update(epi, dt_step, stages)
return result
def rk4_coupled_step(
state: tuple[float, ...],
rhs: Callable[[float, tuple[float, ...]], tuple[float, ...]],
*,
t: float,
dt: float,
) -> tuple[float, ...]:
"""Advance one explicitly supplied complete vector field by classical RK4.
Every stage receives an immutable, independently admitted full state and
reevaluates ``rhs(time, state)``. This opt-in kernel does not change the
graph integrator's held-pressure semantics. The caller owns the complete
law, pressure refresh, phase lifts, Gamma admission, boundary conditions,
numerical error certificate and association with graph state or history.
Only nonempty tuples are accepted for state and rates. Scalars use the
shared represented-real admission; dt is positive and all three distinct
stage clocks must remain finite and strictly ordered after rounding.
No clipping, wrapping, hidden substeps or graph writes occur. Callback
effects outside its immutable arguments are not rolled back on failure.
"""
if not callable(rhs):
raise TypeError("rhs must be callable")
def vector(values, label, *, size=None):
if type(values) is not tuple or not values:
raise TypeError(f"{label} must be a nonempty tuple")
if size is not None and len(values) != size:
raise ValueError(f"{label} dimension differs from the complete state")
return tuple(
finite_represented_real(value, f"{label}[{index}]")[0]
for index, value in enumerate(values)
)
initial = vector(state, "state")
start, _ = finite_represented_real(t, "t")
step, exact_step = finite_represented_real(dt, "dt")
if step <= 0:
raise ValueError("dt must be positive")
half, _ = finite_represented_real(exact_step / 2, "RK4 half-step")
midpoint, _ = finite_represented_real(start + half, "RK4 midpoint time")
endpoint, _ = finite_represented_real(start + step, "RK4 endpoint time")
if not start < midpoint < endpoint:
raise ValueError("RK4 stage clocks must remain strictly ordered")
def evaluate(time, values):
return vector(rhs(time, values), "rhs", size=len(initial))
def stage(rates, duration):
result = []
for index, (value, rate) in enumerate(zip(initial, rates, strict=True)):
updated = finite_represented_real(
euler_update(value, duration, rate), f"RK4 stage[{index}]"
)[0]
if (
updated == 0.0
and (Fraction(value) + Fraction(duration) * Fraction(rate)) != 0
):
raise ValueError("RK4 stage loses a nonzero represented-input result")
result.append(updated)
return tuple(result)
first = evaluate(start, initial)
second = evaluate(midpoint, stage(first, half))
third = evaluate(midpoint, stage(second, half))
fourth = evaluate(endpoint, stage(third, step))
result = []
for index, (value, *rates) in enumerate(
zip(initial, first, second, third, fourth, strict=True)
):
updated = finite_represented_real(
_rk4_update(value, step, tuple(rates)), f"RK4 endpoint[{index}]"
)[0]
if (
updated == 0.0
and (
Fraction(value)
+ exact_step
* (
Fraction(rates[0])
+ 2 * Fraction(rates[1])
+ 2 * Fraction(rates[2])
+ Fraction(rates[3])
)
/ 6
)
!= 0
):
raise ValueError("RK4 endpoint loses a nonzero represented-input result")
result.append(updated)
return tuple(result)
def _apply_increment_chunk(
chunk: list[tuple[NodeId, float, float, tuple[float, ...]]],
dt_step: float,
method: str,
) -> list[tuple[NodeId, tuple[float, float, float]]]:
"""Compute updated states for ``chunk`` using scalar arithmetic."""
results: list[tuple[NodeId, tuple[float, float, float]]] = []
dt_nonzero = dt_step != 0
for node, epi_i, dEPI_prev, ks in chunk:
if method == "rk4":
epi = _rk4_update(epi_i, dt_step, ks)
dEPI_dt = ks[3]
else:
(k1,) = ks
epi = euler_update(epi_i, dt_step, k1)
dEPI_dt = k1
d2epi = (dEPI_dt - dEPI_prev) / dt_step if dt_nonzero else 0.0
results.append(
(
node,
(
_finite_output(epi, "EPI"),
_finite_output(dEPI_dt),
_finite_output(d2epi),
),
)
)
return results
def _evaluate_gamma_map(
G: TNFRGraph,
nodes: list[NodeId],
t: float,
*,
n_jobs: int | None = None,
) -> GammaMap:
"""Return Γ evaluations for ``nodes`` at time ``t`` respecting parallelism."""
# Arbitrary callbacks may read graph state or keep invocation-side evidence;
# execute them once on the live staged path, not on process-local copies.
builtin = _uses_builtin_gamma(_get_gamma_spec(G, strict=True))
workers = _normalise_jobs(n_jobs, len(nodes)) if builtin else None
if workers is None:
return {n: float(eval_gamma(G, n, t, strict=True)) for n in nodes}
approx_chunk = math.ceil(len(nodes) / (workers * 4)) if workers > 0 else None
chunk_size = resolve_chunk_size(
approx_chunk,
len(nodes),
minimum=1,
)
mp_ctx = get_context("spawn")
tasks = ((chunk, t) for chunk in _chunk_nodes(nodes, chunk_size))
results: GammaMap = {}
with ProcessPoolExecutor(
max_workers=workers,
mp_context=mp_ctx,
initializer=_gamma_worker_init,
initargs=(G,),
) as executor:
futures = [executor.submit(_gamma_worker, task) for task in tasks]
for fut in futures:
for node, value in fut.result():
results[node] = value
return results
def prepare_integration_params(
G: TNFRGraph,
dt: float | None = None,
t: float | None = None,
method: Literal["euler", "rk4"] | None = None,
) -> tuple[float, int, float, Literal["euler", "rk4"]]:
"""Validate and normalise ``dt``, ``t`` and ``method`` for integration.
Explicit and graph-default timesteps must be finite nonnegative reals.
Boolean/text values and nonzero inputs lost in materialization reject for
the step, initial clock and minimum step alike.
Invalid parameters raise :class:`NetworkConfigError`. When ``dt``
exceeds a positive ``DT_MIN`` stored on ``G`` the span is deterministically
subdivided into integer steps so that the resulting ``dt_step`` never falls
below that minimum threshold.
Returns ``(dt_step, steps, t0, method)`` where ``dt_step`` is the effective
step, ``steps`` the number of substeps and ``t0`` the prepared initial
time.
"""
if dt is None:
dt = G.graph.get("DT", DEFAULTS.get("DT", 0.1))
dt = _finite_output(dt, "dt")
if not math.isfinite(dt) or dt < 0:
raise NetworkConfigError(
parameter="dt", value=dt, reason="Time step must be finite and non-negative"
)
t = _finite_output(G.graph.get("_t", 0.0) if t is None else t, "t")
if not math.isfinite(t):
raise NetworkConfigError(
parameter="t", value=t, reason="Initial time must be finite"
)
method_value = (
G.graph.get("INTEGRATOR_METHOD", DEFAULTS.get("INTEGRATOR_METHOD", "euler"))
if method is None
else method
)
method_value = (
method_value.lower() if isinstance(method_value, str) else method_value
)
if method_value not in ("euler", "rk4"):
raise NetworkConfigError(
parameter="method",
value=method_value,
reason="Integration method must be 'euler' or 'rk4'",
)
dt_min = _finite_output(
G.graph.get("DT_MIN", DEFAULTS.get("DT_MIN", 0.0)), "DT_MIN"
)
if not math.isfinite(dt_min) or dt_min < 0:
raise NetworkConfigError(
parameter="DT_MIN",
value=dt_min,
reason="Minimum time step must be finite and non-negative",
)
steps = 1
if dt_min > 0 and dt > dt_min:
ratio = dt / dt_min
if not math.isfinite(ratio):
raise NetworkConfigError(
parameter="DT_MIN",
value=dt_min,
reason="Time-step subdivision ratio must be finite",
)
steps = max(1, int(math.floor(ratio)))
dt_step = dt / steps if steps else 0.0
_validate_clock_grid(t, dt_step, steps, method_value)
return dt_step, steps, t, cast(Literal["euler", "rk4"], method_value)
def _apply_increments(
G: TNFRGraph,
dt_step: float,
increments: NodeIncrements,
*,
method: str,
n_jobs: int | None = None,
) -> NodalUpdate:
"""Combine precomputed increments to update node states."""
nodes: list[NodeId] = list(G.nodes)
if not nodes:
return {}
epi_initial: list[float] = []
dEPI_prev: list[float] = []
ordered_increments: list[tuple[float, ...]] = []
for node in nodes:
nd = G.nodes[node]
_, _, dEPI_dt_prev, epi_i = _node_state(nd)
epi_initial.append(float(epi_i))
dEPI_prev.append(float(dEPI_dt_prev))
ordered_increments.append(increments[node])
if np is not None:
epi_arr = np.asarray(epi_initial, dtype=float)
dEPI_prev_arr = np.asarray(dEPI_prev, dtype=float)
k_arr = np.asarray(ordered_increments, dtype=float)
if method == "rk4":
if k_arr.ndim != 2 or k_arr.shape[1] != 4:
raise TNFRUserError(
message="RK4 integration requires four staged increments",
suggestion="Check integrator implementation logic",
context={"shape": str(k_arr.shape)},
)
k1 = k_arr[:, 0]
k2 = k_arr[:, 1]
k3 = k_arr[:, 2]
k4 = k_arr[:, 3]
epi = _rk4_update(epi_arr, dt_step, (k1, k2, k3, k4))
dEPI_dt = k4
else:
if k_arr.ndim == 1:
k1 = k_arr
else:
k1 = k_arr[:, 0]
epi = euler_update(epi_arr, dt_step, k1)
dEPI_dt = k1
if dt_step != 0:
d2epi = (dEPI_dt - dEPI_prev_arr) / dt_step
else:
d2epi = np.zeros_like(dEPI_dt)
results: NodalUpdate = {}
for idx, node in enumerate(nodes):
results[node] = (
_finite_output(epi[idx], "EPI"),
_finite_output(dEPI_dt[idx]),
_finite_output(d2epi[idx]),
)
return results
payload: list[tuple[NodeId, float, float, tuple[float, ...]]] = list(
zip(nodes, epi_initial, dEPI_prev, ordered_increments)
)
workers = _normalise_jobs(n_jobs, len(nodes))
if workers is None:
return dict(_apply_increment_chunk(payload, dt_step, method))
approx_chunk = math.ceil(len(nodes) / (workers * 4)) if workers > 0 else None
chunk_size = resolve_chunk_size(
approx_chunk,
len(nodes),
minimum=1,
)
mp_ctx = get_context("spawn")
results: NodalUpdate = {}
with ProcessPoolExecutor(max_workers=workers, mp_context=mp_ctx) as executor:
futures = [
executor.submit(
_apply_increment_chunk,
chunk,
dt_step,
method,
)
for chunk in _chunk_nodes(payload, chunk_size)
]
for fut in futures:
for node, value in fut.result():
results[node] = value
return {node: results[node] for node in nodes}
def _collect_nodal_increments(
G: TNFRGraph,
gamma_maps: tuple[GammaMap, ...],
*,
method: str,
) -> NodeIncrements:
"""Combine node base state with staged Γ contributions.
Implements the canonical TNFR nodal equation in two parts:
1. **Base term** (canonical equation):
base = vf * dnfr → ∂EPI/∂t = νf · ΔNFR(t)
This is the fundamental TNFR equation where:
- vf (νf): structural frequency in Hz_str
- dnfr (ΔNFR): nodal gradient (reorganization operator)
- base: instantaneous rate of EPI evolution
2. **Network coupling term**:
Γi(R) from gamma_maps - optional Kuramoto order parameter
The full extended equation is: ∂EPI/∂t = νf·ΔNFR(t) + Γi(R)
Args:
G: TNFR graph with node attributes vf and dnfr
gamma_maps: Staged Γ evaluations (1 for Euler, 4 for RK4)
method: Integration method ('euler' or 'rk4')
Returns:
Mapping of nodes to staged integration increments
Pressure units are EPI units divided by capacity and the declared clock.
This numerical combination does not establish an operator closure theorem.
"""
nodes: list[NodeId] = list(G.nodes())
if not nodes:
return {}
if method == "rk4":
expected_maps = 4
elif method == "euler":
expected_maps = 1
else:
raise TNFRValueError(
"method must be 'euler' or 'rk4'",
context={"method": method, "available": ["euler", "rk4"]},
suggestion="Use 'euler' or 'rk4' as the integration method.",
)
if len(gamma_maps) != expected_maps:
raise TNFRValueError(
f"{method} integration requires {expected_maps} gamma maps",
context={
"method": method,
"required": expected_maps,
"provided": len(gamma_maps),
},
suggestion=f"Provide exactly {expected_maps} gamma maps for {method} integration.",
)
if np is not None:
states = [_node_state(G.nodes[node]) for node in nodes]
vf = np.asarray([state[0] for state in states], dtype=float)
dnfr = np.asarray([state[1] for state in states], dtype=float)
# CANONICAL TNFR EQUATION: ∂EPI/∂t = νf · ΔNFR(t)
# This implements the fundamental nodal equation explicitly
base = vf * dnfr
gamma_arrays = [
np.fromiter((gm.get(n, 0.0) for n in nodes), float, count=len(nodes))
for gm in gamma_maps
]
if gamma_arrays:
gamma_stack = np.stack(gamma_arrays, axis=1)
combined = base[:, None] + gamma_stack
else:
combined = base[:, None]
return {
node: tuple(float(value) for value in combined[idx])
for idx, node in enumerate(nodes)
}
increments: NodeIncrements = {}
for node in nodes:
nd = G.nodes[node]
vf, dnfr, *_ = _node_state(nd)
# CANONICAL TNFR EQUATION: ∂EPI/∂t = νf · ΔNFR(t)
# Scalar implementation of the fundamental nodal equation
base = vf * dnfr
gammas = [gm.get(node, 0.0) for gm in gamma_maps]
if method == "rk4":
k1, k2, k3, k4 = gammas
increments[node] = (
base + k1,
base + k2,
base + k3,
base + k4,
)
else:
(k1,) = gammas
increments[node] = (base + k1,)
return increments
def _build_gamma_increments(
G: TNFRGraph,
dt_step: float,
t_local: float,
*,
method: str,
n_jobs: int | None = None,
) -> NodeIncrements:
"""Evaluate Γ contributions and merge them with ``νf·ΔNFR`` base terms."""
if method == "rk4":
gamma_count = 4
elif method == "euler":
gamma_count = 1
else:
raise TNFRValueError(
"method must be 'euler' or 'rk4'",
context={"method": method, "available": ["euler", "rk4"]},
suggestion="Use 'euler' or 'rk4' as the integration method.",
)
gamma_spec = _get_gamma_spec(G, strict=True)
gamma_type = ""
if isinstance(gamma_spec, Mapping):
gamma_type = str(gamma_spec.get("type", ""))
if gamma_type == "none" and _uses_builtin_gamma(gamma_spec):
gamma_maps: tuple[GammaMap, ...] = tuple(
cast(GammaMap, {}) for _ in range(gamma_count)
)
return _collect_nodal_increments(G, gamma_maps, method=method)
nodes: list[NodeId] = list(G.nodes)
if not nodes:
gamma_maps = tuple(cast(GammaMap, {}) for _ in range(gamma_count))
return _collect_nodal_increments(G, gamma_maps, method=method)
if method == "rk4":
t_mid = t_local + dt_step / INTEGRATORS_HALF_STEP_CANONICAL
t_end = t_local + dt_step
g1_map = _evaluate_gamma_map(G, nodes, t_local, n_jobs=n_jobs)
g_mid_map = _evaluate_gamma_map(G, nodes, t_mid, n_jobs=n_jobs)
g4_map = _evaluate_gamma_map(G, nodes, t_end, n_jobs=n_jobs)
gamma_maps = (g1_map, g_mid_map, g_mid_map, g4_map)
else: # method == "euler"
gamma_maps = (_evaluate_gamma_map(G, nodes, t_local, n_jobs=n_jobs),)
return _collect_nodal_increments(G, gamma_maps, method=method)
def _integrate_euler(
G: TNFRGraph,
dt_step: float,
t_local: float,
*,
n_jobs: int | None = None,
) -> NodalUpdate:
"""One explicit Euler integration step."""
increments = _build_gamma_increments(
G,
dt_step,
t_local,
method="euler",
n_jobs=n_jobs,
)
return _apply_increments(
G,
dt_step,
increments,
method="euler",
n_jobs=n_jobs,
)
def _integrate_rk4(
G: TNFRGraph,
dt_step: float,
t_local: float,
*,
n_jobs: int | None = None,
) -> NodalUpdate:
"""Fourth-order forcing quadrature with the stored nodal base held fixed."""
increments = _build_gamma_increments(
G,
dt_step,
t_local,
method="rk4",
n_jobs=n_jobs,
)
return _apply_increments(
G,
dt_step,
increments,
method="rk4",
n_jobs=n_jobs,
)
def _integrate_vectorized_step(
G: TNFRGraph,
dt_step: float,
steps: int,
t0: float,
method: str,
np: Any,
clip_policy: ClipPolicy,
states: list[tuple[float, float, float, float]],
) -> float:
"""Perform full integration steps using vectorized operations.
Returns the final time t_local.
"""
from ..alias import get_theta_attr
nodes = list(G.nodes)
n_nodes = len(nodes)
if n_nodes == 0:
return _validate_clock_grid(t0, dt_step, steps, method)
# 1. Extract state into arrays
vf, dnfr, dEPI, epi = (
np.asarray([state[column] for state in states], dtype=float)
for column in range(4)
)
# The unforced row consumes no phase. Active built-ins validate raw aliases
# before array coercion, matching the scalar trigonometric-cache owner.
if _get_gamma_spec(G, strict=True).get("type", "none") == "none":
theta = np.zeros(n_nodes)
else:
theta = np.asarray(
[
get_theta_attr(
G.nodes[node],
0.0,
strict=True,
conv=lambda raw: _finite_output(raw, "Gamma phase"),
)
for node in nodes
]
)
# Base term: dEPI/dt = vf * dnfr
# Assumed constant during the step (dnfr doesn't change)
base = vf * dnfr
epi_min, epi_max, clip_mode, clip_k = clip_policy
t_local = t0
# Pre-allocate d2EPI
d2EPI = np.zeros_like(dEPI)
for _ in range(steps):
epi_previous = epi.copy()
dEPI_prev = dEPI.copy()
if method == "rk4":
# k1
gamma1 = eval_gamma_vectorized(G, theta, t_local, np, strict=True)
k1 = base + gamma1
# k2
gamma2 = eval_gamma_vectorized(
G,
theta,
t_local + dt_step / INTEGRATORS_HALF_STEP_CANONICAL,
np,
strict=True,
)
k2 = base + gamma2
# k3
gamma3 = gamma2 # Same time point
k3 = base + gamma3
# k4
gamma4 = eval_gamma_vectorized(G, theta, t_local + dt_step, np, strict=True)
k4 = base + gamma4
# Update
epi = _rk4_update(epi, dt_step, (k1, k2, k3, k4))
dEPI = k4
else: # Euler
gamma = eval_gamma_vectorized(G, theta, t_local, np, strict=True)
k1 = base + gamma
epi = euler_update(epi, dt_step, k1)
dEPI = k1
# d2EPI
if dt_step != 0:
d2EPI = (dEPI - dEPI_prev) / dt_step
else:
d2EPI[:] = 0.0
for values, parameter in (
(epi, "EPI"),
(dEPI, "dEPI_dt"),
(d2EPI, "d2EPI_dt2"),
):
if not np.isfinite(values).all():
raise NetworkConfigError(
parameter=parameter,
value=values,
reason="Solver output must be finite",
)
# Boundary projection must not move a node with zero integrated change.
changed = epi != epi_previous
if np.any(changed):
epi[changed] = structural_clip_array(
epi[changed], lo=epi_min, hi=epi_max, mode=clip_mode, k=clip_k
)
t_local += dt_step
# Preserve each mapping's authoritative spelling, as the scalar path does.
# A bulk primary-key write would shadow existing legacy state aliases.
for node, form, rate, acceleration in zip(nodes, epi, dEPI, d2EPI):
nd = G.nodes[node]
set_attr(nd, ALIAS_EPI, form)
set_attr(nd, ALIAS_DEPI, rate)
set_attr(nd, ALIAS_D2EPI, acceleration)
return t_local
class AbstractIntegrator(ABC):
"""Abstract base class encapsulating nodal equation integration."""
@abstractmethod
def integrate(
self,
graph: TNFRGraph,
*,
dt: float | None,
t: float | None,
method: str | None,
n_jobs: int | None,
) -> None:
"""Advance ``graph`` coherence states according to the nodal equation."""
class DefaultIntegrator(AbstractIntegrator):
"""Explicit integrator combining Euler and RK4 step implementations."""
def integrate(
self,
graph: TNFRGraph,
*,
dt: float | None,
t: float | None,
method: str | None,
n_jobs: int | None,
) -> None:
"""Integrate the nodal equation updating EPI, ΔEPI and Δ²EPI."""
if not isinstance(
graph, (nx.Graph, nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph)
):
raise TypeError("G must be a networkx graph instance")
dt_step, steps, t0, resolved_method = prepare_integration_params(
graph, dt, t, cast(IntegratorMethod | None, method)
)
if dt_step == 0.0:
return
clip_policy = _integration_clip_policy(graph)
# Validate all nodal inputs before resolving forcing can populate caches.
states = [_node_state(nd) for nd in graph.nodes.values()]