Repository navigation
Expand file tree
/
Copy pathspectral_paley.py
More file actions
3186 lines (2802 loc) · 117 KB
/
Copy pathspectral_paley.py
File metadata and controls
3186 lines (2802 loc) · 117 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
"""Spectral factor-candidate heuristics on supplied Jacobi-residue graphs.
Arithmetic telemetry factors the input independently of the spectral route.
The partial pure policy does not remove all arithmetic from the pipeline.
Lab field names include proxies, and configured acceptance labels do not
replace arithmetic divisibility checks; see the subproject README."""
from __future__ import annotations
import gzip
import hashlib
import importlib
import json
import math
import os
import time
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
cast,
)
import networkx as nx
import numpy as np
from tnfr.cache import CacheLevel, cache_tnfr_computation
from tnfr.config.operator_names import CANONICAL_OPERATOR_NAMES
from tnfr.config.parsing import parse_bool
from tnfr.constants.canonical import (
GRAD_PHI_CANONICAL_THRESHOLD, # general |∇φ|: γ/π ≈ 0.1837 (heuristic, not derived)
)
from tnfr.constants.canonical import (
K_PHI_CANONICAL_THRESHOLD, # general K_φ: 0.9×π ≈ 2.8274 (phase wrap)
)
from tnfr.constants.canonical import (
PHI_S_VON_KOCH_THRESHOLD, # general Φ_s: 0.7711 (von Koch, empirical)
)
from tnfr.dynamics.advanced_fft_arithmetic import TNFRAdvancedFFTEngine
from tnfr.dynamics.fft_backend import FFTBackend
from tnfr.mathematics.number_theory import (
ArithmeticStructuralTerms,
ArithmeticTNFRFormalism,
ArithmeticTNFRParameters,
)
from tnfr.operators.grammar import SequenceValidationResult, validate_sequence
from tnfr.operators.strategies import (
ResourceEstimate,
StrategyContext,
StrategyRegistry,
StructuralFields,
)
from tnfr.sdk.utils import export_to_json
from .failure_telemetry import FailureTelemetryManager
from .partitioning import (
PaleyPartition,
PartitionedPaleyGraph,
PartitionPlannerConfig,
aggregate_partition_metrics,
annotate_partition_candidates,
plan_paley_partitions,
)
from .self_opt_support import attach_self_opt_sequences, run_partition_self_optimization
# Certificate versioning and hashing constants
_CERTIFICATE_VERSION = "1.0"
_PARTITION_HASH_ALGORITHM = "sha256"
_REPLAY_METADATA_VERSION = "1.0"
# ---------------------------------------------------------------------------
# Configured lab thresholds for spectral proxies.
# They are not canonical nodewise tetrad bounds or constants derived from
# nodal dynamics. Imported reference policies support legacy ratio checks;
# those checks establish neither calibration quality nor factor correctness.
# ---------------------------------------------------------------------------
# Retained heuristic values; numerical ratios to reference policies do not
# imply validation across the prime/composite distribution.
_ARITHMETIC_PHI_S_THRESHOLD = 0.7452
_ARITHMETIC_GRAD_PHI_THRESHOLD = 0.2591
_ARITHMETIC_K_PHI_THRESHOLD = 3.2275
# Compatibility ratio checks only; they are not physical provenance proofs.
assert (
0.93 < _ARITHMETIC_PHI_S_THRESHOLD / PHI_S_VON_KOCH_THRESHOLD < 0.97
), "§7.5 Φ_s recalibration ratio drifted from canonical PHI_S_VON_KOCH_THRESHOLD"
assert (
1.3 < _ARITHMETIC_GRAD_PHI_THRESHOLD / GRAD_PHI_CANONICAL_THRESHOLD < 1.5
), "§7.5 |∇φ| recalibration ratio drifted from canonical GRAD_PHI_CANONICAL_THRESHOLD"
assert (
1.0 < _ARITHMETIC_K_PHI_THRESHOLD / K_PHI_CANONICAL_THRESHOLD < 1.3
), "§7.5 K_φ recalibration ratio drifted from canonical K_PHI_CANONICAL_THRESHOLD"
# Dual-lever operator classification (§8, TNFR_NUMBER_THEORY.md)
_CAPACITY_LEVER_OPERATORS = frozenset({"um", "sha", "val", "nul"})
_PRESSURE_LEVER_OPERATORS = frozenset({"il", "oz", "thol", "zhir", "nav"})
Dispatcher = Callable[[str, Dict[str, Any]], Any]
def _generate_partition_hash_chain(
partitioning: PartitionedPaleyGraph | None,
) -> Dict[str, Any] | None:
"""Hash selected partition records in their supplied iteration order.
Each record includes sorted node/boundary/factor membership, the selected
telemetry fields below and metadata. Phase references, other telemetry,
graph state and execution history are outside this digest. Matching hashes
neither authenticate provenance nor establish complete replay equivalence.
"""
if not partitioning:
return None
partitions = list(partitioning.iter_partitions())
if not partitions:
return None
partition_hashes = []
chain_data = {
"algorithm": _PARTITION_HASH_ALGORITHM,
"version": _CERTIFICATE_VERSION,
"partition_count": len(partitions),
"total_nodes": sum(len(p.node_indices) for p in partitions),
"partitions": [],
}
for partition in partitions:
# Deterministic partition state serialization
partition_state = {
"partition_id": partition.partition_id,
"node_indices": sorted(partition.node_indices),
"boundary_nodes": sorted(partition.boundary_nodes),
"candidate_factors": sorted(partition.candidate_factors),
"telemetry": {
"phi_s": partition.telemetry.phi_s if partition.telemetry else None,
"phase_gradient": (
partition.telemetry.phase_gradient if partition.telemetry else None
),
"phase_curvature": (
partition.telemetry.phase_curvature if partition.telemetry else None
),
"coherence_length": (
partition.telemetry.coherence_length
if partition.telemetry
else None
),
"notes": partition.telemetry.notes if partition.telemetry else "",
},
"metadata": partition.metadata if partition.metadata else None,
}
# Generate deterministic hash for this partition
partition_blob = json.dumps(
partition_state, sort_keys=True, separators=(",", ":")
).encode("utf-8")
partition_hash = hashlib.sha256(partition_blob).hexdigest()
partition_hashes.append(partition_hash)
chain_data["partitions"].append(
{
"partition_id": partition.partition_id,
"hash": partition_hash,
"node_count": len(partition.node_indices),
"boundary_count": len(partition.boundary_nodes),
"factor_count": len(partition.candidate_factors),
}
)
# Generate chain hash linking all partitions
chain_blob = json.dumps(
{
"partition_hashes": partition_hashes,
"algorithm": _PARTITION_HASH_ALGORITHM,
"version": _CERTIFICATE_VERSION,
},
sort_keys=True,
separators=(",", ":"),
).encode("utf-8")
chain_data["chain_hash"] = hashlib.sha256(chain_blob).hexdigest()
return chain_data
def _generate_replay_metadata(
result: Any,
arithmetic: Any | None = None,
partitioning: PartitionedPaleyGraph | None = None,
) -> Dict[str, Any]:
"""Record selected parameters, backend information and environment settings.
This metadata assists replay comparisons. It is not a complete capture of
all runtime state and does not itself guarantee exact reproducibility."""
metadata = {
"version": _REPLAY_METADATA_VERSION,
"timestamp": time.time(),
"algorithm_version": _CERTIFICATE_VERSION,
"environment": {
"pure_mode": os.getenv("TNFR_PURE_MODE", "false").lower()
in {"1", "true", "yes", "on"},
"pure_mode_verify_divisibility": os.getenv(
"TNFR_PURE_MODE_VERIFY_DIVISIBILITY", "false"
).lower()
in {"1", "true", "yes", "on"},
},
"parameters": {
"n": getattr(result, "n", None),
"modulus": getattr(result, "modulus", None),
"node_count": getattr(result, "node_count", None),
"edge_count": getattr(result, "edge_count", None),
},
"backend": {
"fft_backend": getattr(result, "fft_backend", None),
"fft_capabilities": getattr(result, "fft_capabilities", None),
},
}
# Add arithmetic seeds if available
if arithmetic:
metadata["arithmetic"] = {
"delta_nfr": getattr(arithmetic, "delta_nfr", None),
"local_coherence": getattr(arithmetic, "local_coherence", None),
"components": getattr(arithmetic, "components", {}),
}
return metadata
def _capture_deterministic_seeds() -> Dict[str, Any]:
"""Capture all RNG seeds and spectral parameters for deterministic replay.
Records numpy random state, backend-specific seeds, and any other
sources of non-determinism for complete reproducibility.
"""
seeds: Dict[str, Any] = {
"capture_timestamp": time.time(),
"numpy_random_state": None,
"environment_seeds": {},
"backend_seeds": {},
}
# Capture numpy random state
try:
random_state = np.random.get_state()
# Convert state to JSON-serializable format
if isinstance(random_state, tuple) and len(random_state) >= 5:
seeds["numpy_random_state"] = {
"state_type": str(random_state[0]),
"state_array": (
random_state[1].tolist() if random_state[1] is not None else None
),
"state_pos": (
int(random_state[2]) if random_state[2] is not None else None
),
"state_has_gauss": (
int(random_state[3]) if random_state[3] is not None else None
),
"state_cached_gaussian": (
float(random_state[4]) if random_state[4] is not None else None
),
}
except Exception as e:
seeds["numpy_random_state_error"] = str(e)
# Capture environment-based seeds
seed_envs = [
"PYTHONHASHSEED",
"TNFR_SPECTRAL_SEED",
"TNFR_FFT_SEED",
"TNFR_PARTITION_SEED",
"NUMPY_SEED",
"RANDOM_SEED",
]
for env_var in seed_envs:
value = os.getenv(env_var)
if value is not None:
seeds["environment_seeds"][env_var] = value
return seeds
_DISPATCHER_METADATA_ATTR = "__tnfr_dispatcher_metadata__"
_REPO_ROOT = Path(__file__).resolve().parents[3]
_RESULTS_ROOT = _REPO_ROOT / "results"
_DEFAULT_CERTIFICATE_DIR = _RESULTS_ROOT / "certificates"
_DEFAULT_PARTITION_ROOT = _DEFAULT_CERTIFICATE_DIR / "partitioned"
_PARTITION_OUTPUT_ENV = "TNFR_PARTITION_OUTPUT_DIR"
_PARTITION_FILELIST_THRESHOLD_ENV = "TNFR_PARTITION_FILELIST_THRESHOLD"
_DEFAULT_FILELIST_THRESHOLD = 1000
_MANIFEST_FILENAME = "_manifest.json"
_MANIFEST_SUMMARY_FILENAME = "_manifest_summary.json"
_PARTITION_FILELIST_ARCHIVE = "_partition_files.txt.gz"
_FAILURE_RISK_ORDER = {"low": 0, "medium": 1, "high": 2}
_FALLBACK_MAX_DIVISOR_ENV = "TNFR_FACTOR_FALLBACK_MAX_DIVISOR"
_DEFAULT_MAX_NODES = 4097
def _annotate_dispatcher(dispatcher: Dispatcher, metadata: Mapping[str, Any]) -> None:
payload = dict(metadata)
try:
setattr(dispatcher, _DISPATCHER_METADATA_ATTR, payload)
return
except AttributeError:
pass
func = getattr(dispatcher, "__func__", None)
if func is not None:
try:
setattr(func, _DISPATCHER_METADATA_ATTR, payload)
except AttributeError:
return
def _default_certificate_dir() -> Path:
return _DEFAULT_CERTIFICATE_DIR
def _partition_filelist_threshold() -> int:
threshold = _read_threshold_env(
_PARTITION_FILELIST_THRESHOLD_ENV, _DEFAULT_FILELIST_THRESHOLD
)
if threshold is None:
return _DEFAULT_FILELIST_THRESHOLD
return max(1, threshold)
def _resolve_partition_directory(base_name: str) -> tuple[Path, Path | None]:
target_root = os.getenv(_PARTITION_OUTPUT_ENV)
if target_root:
partition_root = Path(target_root).expanduser()
if not partition_root.is_absolute():
partition_root = (_REPO_ROOT / target_root).resolve()
else:
partition_root = _DEFAULT_PARTITION_ROOT
partition_root.mkdir(parents=True, exist_ok=True)
partition_dir = partition_root / base_name
relative_dir: Path | None = None
try:
relative_dir = partition_dir.relative_to(_default_certificate_dir())
except ValueError:
relative_dir = None
return partition_dir, relative_dir
try:
from tnfr.engines.self_optimization import TNFRSelfOptimizingEngine
except Exception: # pragma: no cover - optional dependency in trimmed installs
TNFRSelfOptimizingEngine = None # type: ignore[assignment]
@dataclass
class SpectralAnalysisResult:
"""Spectral proxies, arithmetic telemetry, candidates and heuristic reports.
The legacy ``tnfr_certified_factors`` field reports the lab acceptance rule,
which records ``support_divisible`` separately from its final condition.
``phi_s`` is edge density; phase-gradient and curvature fields are spectral
ratios. ``coherence_length`` is a backend value or inverse selected gap.
These are not automatically the canonical nodewise tetrad."""
n: int
modulus: int
node_count: int
edge_count: int
laplacian_gap: float
candidate_factors: List[int]
coherence_score: float
phi_s: float
phase_gradient: float
phase_curvature: float
coherence_length: float
arithmetic_delta_nfr: float
arithmetic_terms: ArithmeticStructuralTerms
arithmetic_components: Dict[str, float]
arithmetic_local_coherence: float
arithmetic_epi: float
arithmetic_nu_f: float
notes: str
certificate_path: str | None = None
optimizer_metadata: Dict[str, Any] | None = None
fft_backend: str | None = None
fft_capabilities: Dict[str, Any] | None = None
partition_summary: Dict[str, Any] | None = None
partition_aggregation: Dict[str, Any] | None = None
partition_artifact_dir: str | None = None
partition_manifest_path: str | None = None
partition_manifest_index_path: str | None = None
partition_file_archive_path: str | None = None
dispatcher_telemetry: Dict[str, Any] | None = None
operator_strategy_plan: Dict[str, Any] | None = None
nodal_decoding: Dict[str, Any] | None = None
tnfr_certified_factors: List[int] | None = None
tnfr_verification: Dict[str, Any] | None = None
tnfr_factor_signature: Dict[str, Any] | None = None
tnfr_composite_signature: Dict[str, Any] | None = (
None # multi-factor / power structure
)
dual_lever_analysis: Dict[str, Any] | None = None # §8 capacity vs pressure
self_optimization_summary: Dict[str, Any] | None = None
failure_diagnostics: Dict[str, Any] | None = None
@dataclass
class OperatorCertificate:
"""Serialized candidate analysis with a proposed operator word.
Grammar metadata, hashes and recorded telemetry do not by themselves prove
that the word was executed, that replay is bitwise identical, or that a
candidate divides the input."""
n: int
candidate_factor: int | None
operators: List[str]
canonical_operators: List[str]
telemetry: Dict[str, float]
timestamp: float
notes: str
validation: Dict[str, Any] | None = None
optimizer: Dict[str, Any] | None = None
partitions: Dict[str, Any] | None = None
partition_directory: str | None = None
partition_directory_absolute: str | None = None
partition_files: List[str] | None = None
partition_manifest: str | None = None
partition_manifest_index: str | None = None
partition_file_archive: str | None = None
partition_states: Dict[str, Any] | None = None
strategy_plan_snapshot: Dict[str, Any] | None = None
invariant_report: Dict[str, Any] | None = None
nodal_decoding_snapshot: Dict[str, Any] | None = None
tnfr_verification_snapshot: Dict[str, Any] | None = None
tnfr_factor_signature: Dict[str, Any] | None = None
tnfr_composite_signature: Dict[str, Any] | None = None
self_optimization_summary: Dict[str, Any] | None = None
certificate_hash_chain: Dict[str, Any] | None = None
replay_metadata: Dict[str, Any] | None = None
@dataclass
class OperatorSequenceSelection:
"""Optimized operator sequences aligned with TNFR auto-optimization."""
canonical_sequence: List[str]
glyph_sequence: List[str]
optimizer_metadata: Dict[str, Any]
@dataclass
class PartitionManifestArtifacts:
"""Paths for manifest-related artifacts emitted during partition export."""
manifest_relative: str | None = None
manifest_absolute: Path | None = None
summary_relative: str | None = None
summary_absolute: Path | None = None
archive_relative: str | None = None
archive_absolute: Path | None = None
class SpectralPaleyFactorizer:
"""Experimental spectral and arithmetic candidate-analysis pipeline.
The default constructor cap is 4097; explicitly passing ``max_nodes=None``
disables it. The algorithm is not a factorization complexity improvement:
arithmetic telemetry already computes a factorization of the input."""
def __init__(
self,
*,
max_nodes: int | None = _DEFAULT_MAX_NODES,
fft_engine: FFTBackend | None = None,
failure_telemetry: bool | None = None,
failure_telemetry_root: Path | None = None,
) -> None:
self._history: List[SpectralAnalysisResult] = []
self._max_nodes = max_nodes
self._fft_backend: FFTBackend = fft_engine or _select_fft_backend(max_nodes)
self._partition_config = _partition_config_from_env()
self._optimizer: Optional[TNFRSelfOptimizingEngine] = None
self._optimizer_disabled = os.getenv("TNFR_DISABLE_OPTIMIZER", "").lower() in {
"1",
"true",
"on",
}
env_failure = os.getenv("TNFR_FAILURE_TELEMETRY")
if failure_telemetry is None:
failure_telemetry = env_failure not in {"0", "false", "False", "off", "OFF"}
self._failure_telemetry_manager: FailureTelemetryManager | None = None
if failure_telemetry:
try:
self._failure_telemetry_manager = FailureTelemetryManager(
failure_telemetry_root
)
except Exception:
self._failure_telemetry_manager = None
if TNFRSelfOptimizingEngine is not None and not self._optimizer_disabled:
try:
self._optimizer = TNFRSelfOptimizingEngine()
except Exception: # pragma: no cover - fallback if engine bootstrap fails
self._optimizer = None
def analyze(
self,
n: int,
*,
modulus: int | None = None,
trace_certificates: bool = False,
certificate_dir: Path | None = None,
) -> SpectralAnalysisResult:
"""Analyze a supplied integer with graph spectra and arithmetic telemetry.
Return candidates and heuristic acceptance metadata, including independent
divisibility observations where available. Pure mode changes selected
candidate paths; it does not bypass input factorization for telemetry or
the unguarded empty-candidate trial-division fallback. Trace records can
include proposed grammar-valid sequences and optional workflow results;
no general executed-factorization certificate follows."""
if n <= 1:
raise ValueError("n must be > 1")
auto_even_hint = []
working_modulus = modulus or self._derive_modulus(n)
if self._max_nodes is not None and working_modulus > self._max_nodes:
raise ValueError(
f"Requested modulus {working_modulus} exceeds max_nodes={self._max_nodes}. "
"Provide a smaller modulus or increase the limit."
)
if n % 2 == 0:
auto_even_hint.append(2)
graph = _build_paley_graph(working_modulus)
_annotate_graph_for_fft(graph)
spectral_state = None
backend_name: str | None = None
backend_capabilities: Dict[str, Any] | None = None
dispatcher_telemetry: Dict[str, Any] | None = None
if self._fft_backend is not None:
try:
spectral_state = self._fft_backend.get_spectral_state(graph)
except Exception:
spectral_state = None
else:
eigenvalues = spectral_state.eigenvalues
backend_name = getattr(
self._fft_backend,
"backend_name",
self._fft_backend.__class__.__name__,
)
get_capabilities = getattr(self._fft_backend, "get_capabilities", None)
if callable(get_capabilities):
try:
capabilities_obj = get_capabilities()
except Exception:
capabilities_obj = None
else:
backend_capabilities = _json_safe(asdict(capabilities_obj))
get_dispatcher_info = getattr(
self._fft_backend, "get_dispatcher_telemetry", None
)
if callable(get_dispatcher_info):
try:
dispatcher_telemetry = _json_safe(get_dispatcher_info())
except Exception:
dispatcher_telemetry = None
if spectral_state is None:
eigenvalues = _laplacian_eigenvalues(graph)
laplacian_gap = _first_positive_eigenvalue(eigenvalues)
node_count = graph.number_of_nodes()
edge_count = graph.number_of_edges()
phi_s = _structural_potential(node_count, edge_count)
phase_gradient = laplacian_gap / max(node_count, 1)
phase_curvature = (eigenvalues[-1] if eigenvalues.size else 0.0) / max(
node_count, 1
)
coherence_length = (
spectral_state.coherence_length
if spectral_state is not None and spectral_state.coherence_length > 0
else _coherence_length(laplacian_gap)
)
coherence_score = _coherence_score(
phi_s, phase_gradient, phase_curvature, coherence_length
)
arithmetic = _compute_arithmetic_telemetry(n)
candidates = _candidate_factors(
n=n,
hints=auto_even_hint,
gap=laplacian_gap,
modulus=working_modulus,
arithmetic=arithmetic,
)
fallback_used = False
if not candidates:
fallback = _fallback_factor_candidates(n)
if fallback:
fallback_used = True
candidates = sorted({*candidates, *fallback})
sequence_selection = self._select_operator_sequence(graph)
partitioning = self._plan_partitions(
graph,
working_modulus,
phi_s=phi_s,
phase_gradient=phase_gradient,
phase_curvature=phase_curvature,
coherence_length=coherence_length,
)
annotate_partition_candidates(partitioning, candidates)
nodal_decoding = self._decode_partitions_nodally(
partitioning=partitioning,
graph=graph,
n=n,
modulus=working_modulus,
parent_gap=laplacian_gap,
parent_phi_s=phi_s,
parent_phase_gradient=phase_gradient,
parent_phase_curvature=phase_curvature,
parent_coherence_length=coherence_length,
)
if nodal_decoding:
dynamic_factors = nodal_decoding.get("dynamic_factors") or []
if dynamic_factors:
candidates = sorted({*candidates, *dynamic_factors})
tnfr_certified_factors: List[int] = []
tnfr_verification: Dict[str, Any] | None = None
if partitioning and nodal_decoding:
tnfr_certified_factors, tnfr_verification = _verify_factors_tnfr(
n=n,
partitioning=partitioning,
nodal_decoding=nodal_decoding,
parent_phi_s=phi_s,
parent_phase_gradient=phase_gradient,
parent_phase_curvature=phase_curvature,
)
if tnfr_certified_factors:
candidates = sorted({*candidates, *tnfr_certified_factors})
# Generate reproducibility metadata for certificates
partition_hash_chain = _generate_partition_hash_chain(partitioning)
# Create temporary result for replay metadata generation
temp_result = type(
"TempResult",
(),
{
"n": n,
"modulus": working_modulus,
"node_count": node_count,
"edge_count": edge_count,
"fft_backend": backend_name,
"fft_capabilities": backend_capabilities,
},
)()
replay_metadata = _generate_replay_metadata(
temp_result, arithmetic, partitioning
)
# Add deterministic seeds to replay metadata
if replay_metadata:
replay_metadata["deterministic_seeds"] = _capture_deterministic_seeds()
tnfr_signature = _build_factor_signature(
n, tnfr_verification, partition_hash_chain, replay_metadata
)
tnfr_composite_signature = _build_composite_signature(
n, tnfr_verification, partition_hash_chain, replay_metadata
)
if tnfr_certified_factors:
tnfr_order = sorted({int(value) for value in tnfr_certified_factors})
remaining = [value for value in candidates if value not in tnfr_order]
candidates = tnfr_order + remaining
partition_aggregation = aggregate_partition_metrics(
partitioning,
parent_phi_s=phi_s,
parent_phase_gradient=phase_gradient,
parent_phase_curvature=phase_curvature,
parent_coherence_length=coherence_length,
total_candidate_count=len(candidates),
)
note_bits = [
f"modulus={working_modulus} (auto {'yes' if modulus is None else 'no'})",
f"nodes={node_count}",
f"laplacian_gap={laplacian_gap:.4f}",
f"ΔNFR={arithmetic.delta_nfr:.3e}",
"even factor 2 flagged" if auto_even_hint else "",
(
"candidates=" + ",".join(str(c) for c in candidates)
if candidates
else "no nodal factors"
),
]
if fallback_used:
note_bits.append("fallback=trial-division")
notes = "; ".join(bit for bit in note_bits if bit)
strategy_plan = self._plan_operator_strategies(
partitioning,
sequence_selection,
phi_s=phi_s,
phase_gradient=phase_gradient,
phase_curvature=phase_curvature,
coherence_length=coherence_length,
backend_capabilities=backend_capabilities,
)
dual_lever = _classify_dual_lever(
sequence_selection.canonical_sequence,
arithmetic,
)
result = SpectralAnalysisResult(
n=n,
modulus=working_modulus,
node_count=node_count,
edge_count=edge_count,
laplacian_gap=laplacian_gap,
candidate_factors=candidates,
coherence_score=coherence_score,
phi_s=phi_s,
phase_gradient=phase_gradient,
phase_curvature=phase_curvature,
coherence_length=coherence_length,
arithmetic_delta_nfr=arithmetic.delta_nfr,
arithmetic_terms=arithmetic.terms,
arithmetic_components=arithmetic.components,
arithmetic_local_coherence=arithmetic.local_coherence,
arithmetic_epi=arithmetic.epi,
arithmetic_nu_f=arithmetic.nu_f,
notes=notes,
optimizer_metadata=_json_safe(sequence_selection.optimizer_metadata),
fft_backend=backend_name,
fft_capabilities=backend_capabilities,
partition_summary=(
_json_safe(partitioning.summary()) if partitioning else None
),
partition_aggregation=(
_json_safe(partition_aggregation.to_mapping())
if partition_aggregation
else None
),
dispatcher_telemetry=dispatcher_telemetry,
operator_strategy_plan=_json_safe(strategy_plan) if strategy_plan else None,
nodal_decoding=_json_safe(nodal_decoding) if nodal_decoding else None,
tnfr_certified_factors=(
list(tnfr_certified_factors) if tnfr_certified_factors else None
),
tnfr_verification=(
_json_safe(tnfr_verification) if tnfr_verification else None
),
tnfr_factor_signature=(
_json_safe(tnfr_signature) if tnfr_signature else None
),
tnfr_composite_signature=(
_json_safe(tnfr_composite_signature)
if tnfr_composite_signature
else None
),
dual_lever_analysis=_json_safe(dual_lever),
)
if trace_certificates:
certificate_path, partition_dir, manifest_artifacts = _emit_certificate(
result=result,
arithmetic=arithmetic,
certificate_dir=certificate_dir,
sequence=sequence_selection,
partitioning=partitioning,
)
result.certificate_path = str(certificate_path)
if partition_dir is not None:
result.partition_artifact_dir = str(partition_dir)
if manifest_artifacts:
if manifest_artifacts.manifest_absolute is not None:
result.partition_manifest_path = str(
manifest_artifacts.manifest_absolute
)
if manifest_artifacts.summary_absolute is not None:
result.partition_manifest_index_path = str(
manifest_artifacts.summary_absolute
)
if manifest_artifacts.archive_absolute is not None:
result.partition_file_archive_path = str(
manifest_artifacts.archive_absolute
)
if self._failure_telemetry_manager and not tnfr_certified_factors:
stage, reason = self._classify_failure_context(
candidates=candidates,
nodal_decoding=nodal_decoding,
tnfr_verification=tnfr_verification,
)
extra_context = {
"fallback_used": fallback_used,
"auto_even_hint": bool(auto_even_hint),
}
try:
record = self._failure_telemetry_manager.record_failure(
result,
failure_stage=stage,
failure_reason=reason,
snapshot_analysis=None,
replay_metadata=replay_metadata,
extra_context=extra_context,
)
except Exception:
result.failure_diagnostics = {
"failure_stage": stage,
"failure_reason": reason,
"telemetry_status": "recording_failed",
}
else:
result.failure_diagnostics = record.to_mapping()
self._history.append(result)
return result
def _classify_failure_context(
self,
*,
candidates: Sequence[int],
nodal_decoding: Mapping[str, Any] | None,
tnfr_verification: Mapping[str, Any] | None,
) -> Tuple[str, str]:
if not candidates:
return "spectral", "no_candidate_clusters"
if not nodal_decoding:
return "nodal_decoding", "nodal_decoder_inactive"
if tnfr_verification:
return "verification", "verification_rejection"
return "verification", "verification_unavailable"
def _plan_partitions(
self,
graph: nx.Graph,
modulus: int,
*,
phi_s: float,
phase_gradient: float,
phase_curvature: float,
coherence_length: float,
) -> PartitionedPaleyGraph:
config = self._partition_config
if config and isinstance(config.notes, str) and config.notes.startswith("auto"):
adaptive_target = max(8, modulus // 4)
adaptive_target = (
min(config.target_size, adaptive_target)
if adaptive_target
else config.target_size
)
if adaptive_target != config.target_size:
config = PartitionPlannerConfig(
target_size=adaptive_target,
boundary_overlap=config.boundary_overlap,
notes=f"{config.notes}|auto_scaled",
)
return plan_paley_partitions(
graph,
modulus,
phi_s=phi_s,
phase_gradient=phase_gradient,
phase_curvature=phase_curvature,
coherence_length=coherence_length,
config=config,
)
def _decode_partitions_nodally(
self,
*,
partitioning: PartitionedPaleyGraph,
graph: nx.Graph,
n: int,
modulus: int,
parent_gap: float,
parent_phi_s: float,
parent_phase_gradient: float,
parent_phase_curvature: float,
parent_coherence_length: float,
) -> Dict[str, Any] | None:
partitions = list(partitioning.iter_partitions())
if not partitions:
return None
outcomes: List[Dict[str, Any]] = []
dynamic_factors: List[int] = []
assigned_factors: Dict[int, str] = {}
for partition in partitions:
outcome = _evaluate_partition_nodal_sequence(
partition=partition,
graph=graph,
modulus=modulus,
n=n,
parent_gap=parent_gap,
parent_phi_s=parent_phi_s,
parent_phase_gradient=parent_phase_gradient,
parent_phase_curvature=parent_phase_curvature,
parent_coherence_length=parent_coherence_length,
)
factor = outcome.get("inferred_factor")
if factor is not None and 1 < factor < n:
if factor not in assigned_factors:
assigned_factors[factor] = partition.partition_id
if factor not in partition.candidate_factors:
partition.candidate_factors.append(factor)
dynamic_factors.append(factor)
outcome["factor_assignment"] = "primary"
else:
outcome["factor_assignment"] = assigned_factors[factor]
partition.metadata.setdefault("nodal_state", {})
partition.metadata["nodal_state"] = {
"dnfr_after": outcome.get("dnfr_after"),
"coherence_ratio": outcome.get("coherence_ratio"),
"inferred_factor": outcome.get("inferred_factor"),
"sequence": list(_NODAL_OPERATOR_SEQUENCE),
}
outcomes.append(outcome)
converged = sum(1 for outcome in outcomes if outcome.get("dnfr_converged"))
return {
"sequence": list(_NODAL_OPERATOR_SEQUENCE),
"dynamic_factors": sorted(set(dynamic_factors)),
"converged_partitions": converged,
"partitions": outcomes,
"notes": "nodal-decoder",
}
def _derive_modulus(self, n: int) -> int:
"""Lift ``n`` to the nearest Paley-compatible modulus (odd and 1 mod 4)."""
candidate = n if n % 2 else n + 1
candidate = max(candidate, 5)
return _lift_to_paley_modulus(candidate)
def _select_operator_sequence(self, graph: nx.Graph) -> OperatorSequenceSelection:
"""Use the TNFR self-optimizing engine to choose operator sequences."""
if TNFRSelfOptimizingEngine is None or self._optimizer is None:
reason = (
"optimizer_disabled"
if getattr(self, "_optimizer_disabled", False)
else "optimizer_unavailable"
)
return _default_sequence_selection(reason)
try:
recommendations = self._optimizer.recommend_optimization_strategy(
graph,
"paley_factorization",
)
canonical_sequence = _sequence_from_recommendations(
recommendations.recommended_strategies
) or list(_DEFAULT_CANONICAL_SEQUENCE)
metadata = _json_safe(
{
"recommended_strategies": recommendations.recommended_strategies,
"predicted_speedups": recommendations.predicted_speedups,
"optimization_improvements": recommendations.optimization_improvements,
"adaptive_configuration": recommendations.adaptive_configurations,
"execution_time": recommendations.execution_time,
"mathematical_insights": recommendations.mathematical_insights,
}
)
glyph_sequence = _canonical_to_glyph_sequence(canonical_sequence)
return OperatorSequenceSelection(
canonical_sequence=canonical_sequence,
glyph_sequence=glyph_sequence,
optimizer_metadata=metadata,
)
except Exception as exc: # pragma: no cover - defensive fallback path
return _default_sequence_selection("optimizer_error", str(exc))
def _plan_operator_strategies(
self,