TNFR Logo
TheoryLearnSoftwareResearch

On this page

TNFR

Resonant Fractal Nature Theory — a mathematical framework for coherent patterns on graph-coupled networks.

About
  • Project history
  • Editorial policy
  • Contact
Resources
  • GitHub
  • PyPI
  • DOI · Zenodo
Legal
  • MIT License
  • Citation
© 2026 TNFR project — MIT licensed.DOI 10.5281/zenodo.17602860
docs
grammar
PHYSICS_VERIFICATION.md
API_CONTRACTS.mdCANONICAL_OZ_SEQUENCES.mdEMPIRICAL_CONFRONTATION_EEG.mdREADME.mdSTRUCTURAL_FIELDS_TETRAD.mdSTRUCTURAL_INTERFACE_THEORY.md
theory
APPLIED_STRUCTURAL_ANALYSIS.mdCATALOG_TYPE_HYGIENE_PROGRAMME.mdDISSIPATIVE_AND_OPEN_SYSTEMS.mdEMERGENT_ONTOLOGY.mdEXTENDED_FIELDS_AND_DERIVED_QUANTITIES.mdFUNDAMENTAL_THEORY.mdGAUGE_SYMMETRY_AND_UNIFICATION.mdGLOSSARY.mdMATHEMATICAL_DYNAMICS_BASIS.mdMINIMAL_STRUCTURAL_DEGREES.mdNUCLEUS_A_PRIME_LADDER_ATLAS.mdNUCLEUS_B_EQUIVARIANCE_OBSTRUCTIONS.mdPHYSICAL_REGIME_CORRESPONDENCES.mdREADME.mdREMESH_INFINITY_DERIVATION.mdSTRUCTURAL_CONSERVATION_THEOREM.mdSTRUCTURAL_OPERATORS.mdSTRUCTURAL_STABILITY_AND_DYNAMICS.mdTNFR_BSD_RESEARCH_NOTES.mdTNFR_HODGE_RESEARCH_NOTES.mdTNFR_NAVIER_STOKES_RESEARCH_NOTES.mdTNFR_NUMBER_THEORY.mdTNFR_P_VS_NP_RESEARCH_NOTES.mdTNFR_RIEMANN_RESEARCH_NOTES.mdTNFR_VARIATIONAL_PRINCIPLE.mdTNFR_YANG_MILLS_RESEARCH_NOTES.mdTNFR.pdfUNIFIED_GRAMMAR_RULES.md
factorization-lab
analysis
analyze_patterns.pycertificate_manifest.py
benchmarks
benchmark_analysis.pybenchmark_expansion_suite.pyfull_spectrum_factorization.pypaley_gap_extended.pypaley_gap_smoke.pytest_benchmark_suite.py
demos
experiment_contexts
exp_0b1663cd19b7.jsonexp_0bf0054b7474.jsonexp_75a4c8ca616a.jsonexp_848ee0fd1857.jsonexp_f6fe00562193.jsonexp_fdf3da424e1e.json
failure_telemetry_batch.pyfeedback_integration_demo.pyintegration_demo_snapshots.dbseed_management_integration_demo.pysnapshot_integration_demo.pytrajectory_143.jsontrajectory_77.jsontrajectory_89.jsontrajectory_91.jsontrajectory_97.json
docs
FACTORING_PLAYBOOK.mdFALSE_POSITIVE_TEST_SUITE.mdOPERATOR_CERTIFICATES.mdROADMAP.mdSPECTRAL_ROUTE.md
experiment_contexts
exp_cebe1d9e7d8e.json
notebooks
spectral_history.ipynb
scripts
run_false_positive_tests.py
tests
run_false_positive_test_suite.pytest_cli.pytest_false_positive_methodology.pytest_false_positive_verifier.pytest_feedback_integration.pytest_partitioning.pytest_seed_management.pytest_self_opt_support.pytest_snapshot_system.pytest_spectral_paley.pytest_verification_robustness.py
tnfr_factorization
__init__.pyapi.pycli.pyfailure_telemetry.pyfeedback_adapter.pyfeedback_integration.pypartitioning.pyself_opt_support.pyspectral_paley.py
demo_snapshots.dbLICENSE_SNAPSHOT.mdPACKAGE_SUMMARY.mdREADME.mdseed_management.pysnapshot_system.pytest_certificate_hashing.pytest_installation.pyverification_trajectory_77.json
benchmarks
analyze_tetrad_universality.pyb0star_alpha_canonical_product_graphs.pybenchmark_optimization_tracks.pybenchmark_utils.pyboundary_vibration.pybridge_primes_riemann.pychiral_involution.pycli_utils.pycoherence_projector_sense_index.pycommutant_bridge.pycomposition_arithmetic.pyconfinement_zones_test.pyconservation_law_validation.pydirected_paley_bridge.pyemergent_arithmetic_pulse.pyemergent_atom_dynamics.pyemergent_atomic_shells.pyemergent_base_dimension.pyemergent_dimension_dynamics.pyemergent_fractal_pulse.pyemergent_fractal_simplex_dimension.pyemergent_integers_symmetry.pyemergent_musical_nfr.pyemergent_nfr_geometry.pyemergent_nfr_where.pyemergent_rationals.pyemergent_rhythm.pyemergent_screening.pyemergent_shell_cardinals.pyemergent_shell_ordering.pyemergent_simplex_dimension.pyemergent_substrate_symmetry.pyequivariance_wall.pyexternal_phase_gate_validation.pyfield_methods_battery.pygolden_residue_remesh_bridge.pyintegrated_force_regime_study.pyinverse_spectrum_to_symmetry.pyk_phi_safety_demo.pykuramoto_farey_bridge.pymissing_piece_bridge.pymultichannel_interface_benchmark.pynavier_stokes_recipe_bridge.pynodal_propagator_residue_bridge.pyns_moment_hierarchy_cascade.pyoperational_irreducibility.pypaley_bridge.pyphase_curvature_investigation.pyphase_wall.pyphi_s_confinement_investigation.pyprimes_as_consequence.pypulse_phase_coherence_budget.pyREADME.mdremesh_infinity_riemann_baseline.pyremesh_infinity_riemann_composed.pyremesh_infinity_riemann_modified_graph.pyremesh_infinity_riemann_operator.pyremesh_infinity_riemann_spectral_basis.pyremesh_infinity_riemann_spectral_robustness.pyremesh_infinity_riemann_spectral.pyresidue_phase_vs_riemann.pystructural_interface_benchmark.pytemporal_interface_benchmark.pytetrad_results_aggregate.pyu2_destabilization_irreversibility.pyuniversality_clusters.pyxi_c_fast_experiment.py
primality-test
benchmarks
comprehensive_benchmark.py
docs
ADVANCED_INTEGRATION.mdmathematical_foundation.mdperformance_analysis.md
examples
advanced_examples.pybasic_usage.py
tnfr_primality
__init__.py__main__.pyadvanced_cli.pyadvanced_core.pycli.pyconstants.pycore.pyoptimized.py
MANIFEST.inPACKAGE_SUMMARY.mdREADME.mdRELEASE_NOTES_v1.0.mdsetup.pytest_installation.py
tests
core_physics
__init__.pytest_conservation_laws.pytest_delta_nfr_computation_paths.pytest_delta_nfr.pytest_dispersion_coherence_sign_invariance.pytest_emergent_constants_guard.pytest_lyapunov_operators.pytest_nodal_equation.pytest_structural_triad.py
data
replay_manifests
sample_run
_manifest_summary.json_manifest.json_partition_files.txt.gz
self_opt_validation
seed_alpha
paley.json
seed_beta
integration.json
seed_gamma
unknown.json
self_optimization
test_run
partitioned
test_run
test_run_p0.jsontest_run_p1.json
_manifest_summary.json_manifest.json
engines
test_pattern_discovery_manifest.pytest_self_optimization_engine.py
mathematics
__init__.pytest_autodiff.pytest_backends.pytest_dissipative_dynamics.pytest_epi.pytest_factory_patterns.pytest_metrics.pytest_navier_stokes_refounded.pytest_number_theory_canonical.pytest_operators.pytest_residue_networks.pytest_riemann_nodal_pulse.pytest_riemann_pulse_coherence.pytest_spaces.pytest_transforms.pytest_validator.py
operators
test_canonical_operators_modern.pytest_grammar_canon.pytest_grammar_canonical_consistency.pytest_grammar_dynamics.pytest_operator_contracts.pytest_operator_strategies.py
parallel
test_fractal_partition_manifest.py
physics
test_conservation_gauge_unification.pytest_dissipative_conservation.pytest_emergent_chemistry.pytest_field_cache_invalidation.pytest_gauge.pytest_phase_transition.pytest_signatures.pytest_spectral_conservation.pytest_structural_diffusion.pytest_structural_integrity.pytest_symplectic_substrate.pytest_tetrad_bounds.pytest_variational.pytest_yang_mills_closure.pytest_yang_mills_derivability.pytest_yang_mills_scaling.pytest_yang_mills_structural_gap.pytest_yang_mills_u6_sweep.py
scripts
test_run_self_opt_validation.pytest_run_self_optimization.py
sdk
__init__.pytest_simple_advanced.py
__init__.pyconftest.pyREADME.mdtest_breast_cancer_phase_gate_demo.pytest_classical_mechanics.pytest_distributed_fft.pytest_external_phase_gate_validation.pytest_factorization_entrypoint.pytest_multichannel_interface.pytest_nodal_optimizer.pytest_phase_gate_api.pytest_replay_register_manifest.pytest_signal_confrontation.pytest_structural_interface_api.pytest_structural_interface_baselines.pytest_structural_interface_benchmark.pytest_temporal_interface.pytest_vectorized_coherence_length_regression.pytest_wine_quality_phase_gate_demo.pyutils.py
examples
01_foundations
01_hello_world.py02_musical_resonance.py03_network_formation.py04_operator_sequences.py05_coherence_evolution.py06_network_topologies.py07_phase_transitions.py08_emergent_phenomena.py09_visualization_suite.py10_simplified_sdk_showcase.py
02_physics_regimes
11_classical_limit_comparison.py115_operator_contract_audit.py12_classical_mechanics_demo.py13_quantum_mechanics_demo.py14_uncertainty_and_interference.py15_train_crossing_demo.py17_conservation_law_demo.py26_gauge_structure_demo.py27_variational_principle_demo.py28_dissipative_systems_demo.py29_lyapunov_stability_demo.py30_self_optimization_demo.py31_mathematical_constants_basis.py33_complex_field_unification.py34_conservation_protocol_suite.py35_tetrad_irreducibility.py36_grammar_violation_detector.py37_operator_tetrad_synergy.py38_grammar_energy_landscape.py39_nodal_equation_decomposition.py
03_riemann_zeta
157_nodal_pulse_phase_attack.py41_von_mangoldt_zeta_demo.py42_riemann_zeros_as_resonances.py43_prime_ladder_hamiltonian_demo.py44_weil_explicit_formula_demo.py45_li_keiper_demo.py46_weil_tnfr_positivity_demo.py47_alpha_sweep_demo.py48_admissible_family_sweep_demo.py49_nodeaware_gauge_sweep_demo.py50_uniform_coercivity_demo.py51_adaptive_coercivity_demo.py52_paley_gap_coercivity_demo.py53_lyapunov_spectral_positivity_demo.py54_hilbert_polya_demo.py55_structural_zero_density_demo.py56_spectral_emergence_demo.py57_admissible_rescaling_demo.py58_oscillatory_correction_demo.py
04_riemann_L_twisted
59_dirichlet_l_function_demo.py60_dirichlet_l_continuation_demo.py61_dirichlet_l_hamiltonian_demo.py62_dirichlet_weil_explicit_formula_demo.py63_dirichlet_li_keiper_demo.py64_twisted_weil_positivity_demo.py65_twisted_alpha_sweep_demo.py66_twisted_admissible_family_sweep_demo.py67_twisted_nodeaware_gauge_sweep_demo.py68_twisted_hermite_family_demo.py69_twisted_coercivity_uniform_demo.py70_twisted_paley_gap_coercivity_demo.py71_twisted_lyapunov_spectral_demo.py72_twisted_hilbert_polya_demo.py73_twisted_structural_zero_density_demo.py74_twisted_spectral_emergence_demo.py75_twisted_admissible_rescaling_demo.py76_twisted_oscillatory_correction_demo.py
05_type_hygiene
77_remesh_infinity_residue_split_demo.py78_nuf_type_signature_demo.py79_epi_type_signature_demo.py80_phi_type_signature_demo.py81_dnfr_type_signature_demo.py82_remesh_window_type_signature_demo.py83_delta_phi_max_type_signature_demo.py84_coupling_weights_type_signature_demo.py85_tetrad_closure_signature_demo.py86_currents_closure_signature_demo.py87_aggregates_closure_signature_demo.py88_urules_consistency_signature_demo.py89_operator_catalog_discipline_signature_demo.py
06_navier_stokes
158_navier_stokes_two_face_refounded.py
07_number_theory
100_prime_families_orbits.py101_numbers_as_coupled_network.py102_nodal_flow_primes_equilibria.py116_nuf_emergent_prime_visibility.py146_primality_grammatical_inertness.py147_numbers_as_free_monoid_words.py148_capacity_arm_carries_von_mangoldt.py149_p14_is_the_capacity_arm_operator.py153_structural_frequency_rank_cyclotomy.py40_arithmetic_number_theory.py94_generative_number_construction.py95_primes_from_spectral_waves.py96_spectral_vibration_of_coherence.py97_goldbach_additive_multiplicative.pyemergent_chemistry_particles_demo.py
08_emergent_geometry
103_emergent_substrate_meets_riemann.py106_per_node_polarization_geometry.py107_orthogonal_structure_emergent_geometry.py108_emergent_field_generating_structure.py112_structure_predicts_coherence_flow.py113_overdamped_projection_bridge.py114_substrate_conserved_quantities.py117_emergent_geometry_residue_graph.py118_emergent_vs_classical_operator.py119_phase_sector_directed_residue.py120_symmetry_wall_substrate_vs_spectrum.py121_canonical_symmetry_break_negative.py122_factorization_phase_sector.py123_symmetry_sector_decomposition.py124_emergent_metric_fractal_consistency.py125_node_is_the_emergent_substrate.py126_two_layers_base_fiber.py127_base_is_emergent_not_imposed.py128_base_substrate_coemergence.py129_spectral_gap_base_fiber_clock.py130_operators_break_substrate_charges.py131_coemergent_loop_convergence.py132_geometric_phase_holonomy.py133_psi_topological_defects.py134_spectral_dimension_heat_kernel.py135_arrow_of_time_h_theorem.py136_heat_kernel_coefficients.py137_synchronization_transition.py138_structure_frequency_synchronization.py139_grammar_formal_language.py140_grammar_automaton.py141_grammar_rule_decomposition.py142_grammar_operator_quotient.py143_glyphic_function_sublanguage.py144_branching_combinator.py145_syntactic_monoid_starfree.py150_emergent_grammatical_pattern_parry.py151_grammar_in_emergent_geometry.py152_operator_contract_tetrahedron.py154_conductor_annotated_qr_spectrum.py155_ontological_position_of_numbers.py156_emergence_directness_law.py98_emergent_symplectic_substrate.py99_structural_diffusion.pyunified_fields_showcase.py
09_millennium
109_p_vs_np_coherence_synthesis.py110_bsd_rank_structural_pressure.py111_hodge_discrete_and_honest_gap.py
10_applications
159_empirical_confrontation_pipeline.py90_phase_gate_monitor_demo.py91_breast_cancer_phase_gate_demo.py92_wine_quality_phase_gate_demo.py93_structural_interface_demo.pypytorch_cuda_demo.py
README.md
scripts
replay
__init__.pyregister_manifest.py
__init__.pyREADME.mdrebuild_failure_manifest.pyrun_reproducible_benchmarks.pyrun_self_opt_validation.pyrun_self_optimization.pytnfr_is_prime.pyvalidate_conservation_law.pyverify_internal_references.py
src
core
__init__.pyevaluation.py
tnfr
backends
__init__.pyjax_backend.pynumpy_backend.pyoptimized_numpy.pyREADME.mdtorch_backend.py
cli
__init__.py__init__.pyiarguments.pyarguments.pyiexecution.pyexecution.pyiinteractive_validator.pyREADME.mdutils.pyutils.pyi
compat
__init__.pydataclass.pyjsonschema_stub.pymatplotlib_stub.pynumpy_stub.pyREADME.md
config
__init__.py__init__.pyiconstants.pyconstants.pyidefaults_core.pydefaults_init.pydefaults_metric.pydefaults.pyfeature_flags.pyfeature_flags.pyiglyph_constants.pyoperator_names.pyoperator_names.pyiphysics_derivation.pyprecision_modes.pypresets.pypresets.pyiREADME.mdsecurity.pythresholds.pytnfr_config.py
constants
__init__.py__init__.pyialiases.pyaliases.pyicanonical.pymetric.pymetric.pyioperational.py
core
__init__.pycontainer.pydefault_implementations.pyexceptions.pyinterfaces.pyREADME.md
dynamics
__init__.py__init__.pyiadaptation.pyadaptation.pyiadaptive_sequences.pyadaptive_sequences.pyiadelic.pyadvanced_cache_optimizer.pyadvanced_fft_arithmetic.pyaliases.pyaliases.pyibifurcation.pycache_aware_fft_engine.pycanonical.pycanonical.pyicomputational_hub.pycoordination.pycoordination.pyidistributed_fft.pydnfr.pydnfr.pyidynamic_limits.pyemergent_centralization.pyemergent_integration_engine.pyfeedback.pyfeedback.pyifft_backend.pyfft_cache_coordinator.pyfft_dispatchers.pyfft_engine.pyfft_workers.pyfused_dnfr.pyhomeostasis.pyhomeostasis.pyiintegrators.pyintegrators.pyilearning.pylearning.pyimetabolism.pymulti_modal_cache.pynbody_tnfr.pynbody.pynodal_optimizer.pyoptimization_orchestrator.pypropagation.pyREADME.mdruntime.pyruntime.pyisampling.pysampling.pyiselectors.pyselectors.pyiself_optimizing_engine.pyspectral_structural_fusion.pystructural_cache.pystructural_clip.pysymplectic.pyunified_backend.pyunified_mathematical_cache_orchestrator.py
engines
computation
__init__.pyfft_engine.pyunified_fft_engine.pyunified_gpu_system.py
constants
__init__.pycanonical.pyoperational.py
integration
__init__.pyemergent_integration.py
pattern_discovery
__init__.pymathematical_patterns.pymulti_modal_cache.py
self_optimization
__init__.pyengine.py
__init__.pyREADME.md
errors
__init__.pycontextual.py
factorization
__init__.py
flatten
README.md
gamma
README.md
glyph_history
README.md
glyph_runtime
README.md
immutable
README.md
initialization
README.md
io
README.md
math
__init__.pyfields_symbolic.pygrammar_validators.pyoptimizer.pyREADME.mdsymbolic.py
mathematics
__init__.pybackend.pybackend.pyidynamics.pydynamics.pyiepi.pyepi.pyigenerators.pygenerators.pyiliouville.pymetrics.pymetrics.pyinumber_theory.pyoperators_factory.pyoperators_factory.pyioperators.pyoperators.pyioptimized_primality.pyprojection.pyprojection.pyiREADME.mdruntime.pyruntime.pyispaces.pyspaces.pyispectral.pytransforms.pytransforms.pyiunified_cache.pyunified_numerical.pyzeta.py
metrics
__init__.py__init__.pyibuffer_cache.pybuffer_cache.pyicache_utils.pycoherence.pycoherence.pyicommon.pycommon.pyicore.pycore.pyidiagnosis.pydiagnosis.pyiemergence.pyexport.pyexport.pyiglyph_timing.pyglyph_timing.pyilearning_metrics.pylearning_metrics.pyilocal_coherence.pyphase_coherence.pyphase_compatibility.pyREADME.mdreporting.pyreporting.pyisense_index.pysense_index.pyitelemetry.pytetrad.pytrig_cache.pytrig_cache.pyitrig.pytrig.pyi
multiscale
__init__.pyhierarchical.pyREADME.md
navier_stokes
__init__.pyconservative_face.pyoperator.py
node
README.md
observers
README.md
operators
network_analysis
__init__.pysource_detection.py
postconditions
__init__.pymutation.py
preconditions
__init__.pycoherence.pydissonance.pyemission.pymutation.pyreception.pyresonance.py
strategies
__init__.pydefaults.pygpu_strategies.pystrategy.py
__init__.py__init__.pyialgebra.pycanonical_patterns.pycascade.pycoherence.pycontraction.pycoupling.pycycle_detection.pydefinitions_base.pydefinitions.pydefinitions.pyidissonance.pyemission.pyexpansion.pygrammar_application.pygrammar_canon.pygrammar_context.pygrammar_core.pygrammar_dynamics.pygrammar_error_factory.pygrammar_memoization.pygrammar_patterns.pygrammar_telemetry.pygrammar_types.pygrammar_u6.pygrammar_validate.pygrammar.pygrammar.pyihamiltonian.pyhealth_analyzer.pyintrospection.pyjitter.pyjitter.pyilifecycle.pymetabolism.pymetrics_basic.pymetrics_core.pymetrics_network.pymetrics_structural.pymetrics_u6.pymetrics.pymutation.pynodal_equation.pyoperator_contracts.pypattern_detection.pypatterns.pyREADME.mdreception.pyrecursivity.pyregistry.pyregistry.pyiremesh.pyremesh.pyiresonance.pyself_organization.pysilence.pystructural_units.pytransition.py
parallel
__init__.pyauto_scaler.pydistributed.pyengine.pymonitoring.pypartitioner.pyREADME.md
performance
guardrails.py
physics
__init__.py_helpers.pycalibration.pycanonical.pycell.pyclassical_mechanics.pyconservation_gauge_unification.pyconservation.pydissipative_conservation.pyemergent_chemistry.pyemergent_particles.pyextended.pyfields.pygauge.pyintegrity.pyinteractions.pylife.pylyapunov.pypatterns.pyphase_transition.pyquantum_mechanics.pyREADME.mdsignatures.pyspectral_conservation.pyspectral_metrics.pystructural_diffusion.pysymplectic_substrate.pytelemetry.pyunified.pyvariational.pyvectorized_ops.py
primality
__init__.py
recipes
__init__.pycookbook.pyREADME.md
riemann
__init__.pyadmissible_family_sweep.pyadmissible_rescaling.pyaggregates_closure_signature.pyalpha_sweep.pyanalytic_continuation_dirichlet.pyanalytic_continuation.pycoercivity_uniform.pycoupling_weights_type_signature.pycurrents_closure_signature.pydelta_phi_max_type_signature.pydirichlet_l.pydnfr_type_signature.pyepi_type_signature.pyhilbert_polya.pyli_keiper.pylyapunov_spectral_positivity.pynodal_pulse.pynodeaware_gauge_sweep.pynuf_type_signature.pyoperator_catalog_discipline_signature.pyoperator.pyoscillatory_correction.pypaley_gap_coercivity.pyphi_type_signature.pyprime_ladder_hamiltonian.pypulse_coherence.pyremesh_infinity_residue_split.pyremesh_window_type_signature.pyspectral_emergence.pystructural_zero_density.pytelemetry.pytetrad_closure_signature.pytwisted_admissible_family_sweep.pytwisted_admissible_rescaling.pytwisted_alpha_sweep.pytwisted_coercivity_uniform.pytwisted_hermite_family.pytwisted_hilbert_polya.pytwisted_li_keiper.pytwisted_lyapunov_spectral_positivity.pytwisted_nodeaware_gauge_sweep.pytwisted_oscillatory_correction.pytwisted_paley_gap_coercivity.pytwisted_prime_ladder_hamiltonian.pytwisted_spectral_emergence.pytwisted_structural_zero_density.pytwisted_weil_explicit_formula.pytwisted_weil_positivity.pyurules_consistency_signature.pyvon_mangoldt.pyweil_explicit_formula.pyweil_positivity.py
schemas
__init__.pygrammar.jsonREADME.md
sdk
__init__.py__init__.pyiadaptive_system.pyadaptive_system.pyibuilders.pybuilders.pyifluent.pyfluent.pyiREADME.mdself_opt.pysimple.pytemplates.pytemplates.pyiutils.py
security
__init__.pycrypto.pydatabase.pyREADME.mdsubprocess.pyvalidation.py
sequencing
__init__.pypatterns.pyREADME.md
services
__init__.pyorchestrator.pyREADME.md
sparse
__init__.pyREADME.mdrepresentations.py
structural
README.md
telemetry
__init__.pycache_metrics.pycache_metrics.pyiconstants.pynu_f.pynu_f.pyiREADME.mdunified_telemetry_system.pyverbosity.pyverbosity.pyi
tools
__init__.pydomain_templates.pyREADME.mdsequence_generator.pytnfr_is_prime_cli_optimized.pytnfr_is_prime_cli.py
topology
__init__.pyasymmetry.pyREADME.md
utils
cache_layers.pycache.pycache.pyicallbacks.pycallbacks.pyichunks.pychunks.pyidata.pydata.pyifast_diameter.pygraph.pygraph.pyiinit.pyinit.pyiio.pyio.pyinumeric.pynumeric.pyiREADME.mdtopology.pyunified_cache.py
validation
__init__.py__init__.pyiaggregator.pybase.pycompatibility.pycompatibility.pyiconfig.pygraph.pygraph.pyihealth.pyinput_validation.pyinterface_baselines.pyinvariants.pymultichannel_interface.pyphase_gate.pyREADME.mdrules.pyrules.pyiruntime.pyruntime.pyisequence_validator.pysignal_confrontation.pysoft_filters.pysoft_filters.pyispectral.pyspectral.pyistructural_interface.pytemporal_interface.pyunified_validation_system.pyvalidator.pywindow.pywindow.pyi
visualization
__init__.pycascade_viz.pyhierarchy.pyREADME.mdsequence_plotter.py
yang_mills
__init__.pyclosure.pyderivability.pyscaling.pystructural_gap.pyu6_sweep.py
__init__.py__init__.pyi_compat.py_version.py_version.pyialias.pyalias.pyibackend_config.pycache.pycache.pyiexecution.pyexecution.pyiflatten.pyflatten.pyigamma.pygamma.pyiglyph_history.pyglyph_history.pyiglyph_runtime.pyglyph_runtime.pyiimmutable.pyimmutable.pyiinitialization.pyinitialization.pyiio.pyio.pyilocking.pylocking.pyinode.pynode.pyiobservers.pyobservers.pyiontosim.pyontosim.pyipy.typedrng.pyrng.pyisecure_config.pyselector.pyselector.pyisense.pysense.pyistructural.pystructural.pyitokens.pytokens.pyitrace.pytrace.pyitypes.pytypes.pyiunits.pyunits.pyi
tetrad_evaluator.py
.pre-commit-config.yaml.semgrep.yaml.zenodo.jsonARCHITECTURE.mdbandit.yamlCHANGELOG.mdCITATION.cffCONTRIBUTING.mdEMERGENT_CANON_AUDIT.mdEMERGENT_DERIVATION_PLAN.mdLICENSE.mdMakefileMANIFEST.inpyproject.tomlpyrightconfig.jsonPYTORCH_CUDA_INTEGRATION.mdREADME.mdSECURITY.mdTESTING.mdTNFR_Website_Content_Brief.md
FILE: src/tnfr/dynamics/nbody_tnfr.py

nbody_tnfr.py

N-body dynamics using pure TNFR physics (no external potentials).

This module implements N-body dynamics derived STRICTLY from TNFR structural framework, without assuming any classical potentials (Newtonian, Coulomb, etc.).

Key Differences from Classical N-Body

Classical Approach (nbody.py):

  • Assumes gravitational potential: U = -Gmm/r
  • Force computed as: F = -∇U
  • ΔNFR = F/m (external assumption)

TNFR Approach (this module):

  • NO assumed potential
  • Coherence potential emerges from network structure
  • ΔNFR computed from Hamiltonian commutator: ΔNFR = i[H_int, ·]/ℏ_str
  • Attraction/repulsion emerges from phase synchronization and coupling

Theoretical Foundation

The nodal equation: ∂EPI/∂t = νf · ΔNFR(t)

Where ΔNFR emerges from the internal Hamiltonian: H_int = H_coh + H_freq + H_coupling

Components:

  1. H_coh: Coherence potential from structural similarity (phase, EPI, νf, Si)
  2. H_freq: Diagonal operator encoding each node's νf
  3. H_coupling: Network topology-induced interactions

The crucial insight: Attractive forces emerge naturally from maximizing coherence between nodes, NOT from assuming gravity.

Phase-Dependent Interaction

Unlike classical gravity (always attractive), TNFR coupling depends on phase:

  • |φᵢ - φⱼ| small → strong coherence → attraction
  • |φᵢ - φⱼ| ≈ π → destructive interference → repulsion

This captures wave-like behavior absent in classical mechanics.

Emergence of Classical Limit

In the low-dissonance limit (ε → 0) with:

  • Nearly synchronized phases: |φᵢ - φⱼ| → 0
  • Strong coupling: all nodes connected
  • High coherence: C(t) ≈ 1

The TNFR dynamics reproduces classical-like behavior, but from first principles.

References

  • TNFR.pdf § 2.3: Nodal equation
  • src/tnfr/operators/hamiltonian.py: H_int construction
  • docs/source/theory/07_emergence_classical_mechanics.md: Classical limit
  • AGENTS.md § Canonical Invariants: TNFR physics principles

Examples

Two-body orbital resonance (no gravitational assumption):

from tnfr.dynamics.nbody_tnfr import TNFRNBodySystem import numpy as np

Create 2-body system

system = TNFRNBodySystem( ... n_bodies=2, ... masses=[1.0, 0.1], # Actually νf^-1 ... positions=np.array([[0, 0, 0], [1, 0, 0]]), ... velocities=np.array([[0, 0, 0], [0, 1, 0]]), ... phases=np.array([0.0, 0.0]) # Synchronized initially ... )

Evolve via pure TNFR dynamics

history = system.evolve(t_final=10.0, dt=0.01)

Check that orbital behavior emerges without assuming gravity

print(f"Energy conservation: {history['energy_drift']:.2e}")

Source Code

python
"""N-body dynamics using pure TNFR physics (no external potentials).

This module implements N-body dynamics derived STRICTLY from TNFR structural
framework, without assuming any classical potentials (Newtonian, Coulomb, etc.).

Key Differences from Classical N-Body
--------------------------------------

**Classical Approach** (nbody.py):
- Assumes gravitational potential: U = -G*m*m/r
- Force computed as: F = -∇U
- ΔNFR = F/m (external assumption)

**TNFR Approach** (this module):
- NO assumed potential
- Coherence potential emerges from network structure
- ΔNFR computed from Hamiltonian commutator: ΔNFR = i[H_int, ·]/ℏ_str
- Attraction/repulsion emerges from phase synchronization and coupling

Theoretical Foundation
----------------------

The nodal equation:
    ∂EPI/∂t = νf · ΔNFR(t)

Where ΔNFR emerges from the internal Hamiltonian:
    H_int = H_coh + H_freq + H_coupling

Components:
1. **H_coh**: Coherence potential from structural similarity (phase, EPI, νf, Si)
2. **H_freq**: Diagonal operator encoding each node's νf
3. **H_coupling**: Network topology-induced interactions

The crucial insight: Attractive forces emerge naturally from maximizing
coherence between nodes, NOT from assuming gravity.

Phase-Dependent Interaction
----------------------------

Unlike classical gravity (always attractive), TNFR coupling depends on phase:
- |φᵢ - φⱼ| small → strong coherence → attraction
- |φᵢ - φⱼ| ≈ π → destructive interference → repulsion

This captures wave-like behavior absent in classical mechanics.

Emergence of Classical Limit
-----------------------------

In the low-dissonance limit (ε → 0) with:
- Nearly synchronized phases: |φᵢ - φⱼ| → 0
- Strong coupling: all nodes connected
- High coherence: C(t) ≈ 1

The TNFR dynamics reproduces classical-like behavior, but from first principles.

References
----------
- TNFR.pdf § 2.3: Nodal equation
- src/tnfr/operators/hamiltonian.py: H_int construction
- docs/source/theory/07_emergence_classical_mechanics.md: Classical limit
- AGENTS.md § Canonical Invariants: TNFR physics principles

Examples
--------
Two-body orbital resonance (no gravitational assumption):

>>> from tnfr.dynamics.nbody_tnfr import TNFRNBodySystem
>>> import numpy as np
>>>
>>> # Create 2-body system
>>> system = TNFRNBodySystem(
...     n_bodies=2,
...     masses=[1.0, 0.1],  # Actually νf^-1
...     positions=np.array([[0, 0, 0], [1, 0, 0]]),
...     velocities=np.array([[0, 0, 0], [0, 1, 0]]),
...     phases=np.array([0.0, 0.0])  # Synchronized initially
... )
>>>
>>> # Evolve via pure TNFR dynamics
>>> history = system.evolve(t_final=10.0, dt=0.01)
>>>
>>> # Check that orbital behavior emerges without assuming gravity
>>> print(f"Energy conservation: {history['energy_drift']:.2e}")
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from numpy.typing import NDArray

from ..constants.canonical import EPI_MAX_CANONICAL
from ..errors.contextual import NetworkConfigError
from ..mathematics.unified_numerical import np
from ..operators.hamiltonian import InternalHamiltonian
from ..structural import create_nfr
from ..types import TNFRGraph

if TYPE_CHECKING:
    from matplotlib.figure import Figure

__all__ = (
    "TNFRNBodySystem",
    "compute_tnfr_coherence_potential",
    "compute_tnfr_delta_nfr",
)


def compute_tnfr_coherence_potential(
    G: TNFRGraph,
    positions: NDArray[np.floating],
    hbar_str: float = 1.0,
) -> float:
    """Compute coherence potential from TNFR network structure.

    This is the pure TNFR potential - NO classical assumptions.

    The potential emerges from:
    - Structural similarity (coherence matrix)
    - Network coupling topology
    - Phase synchronization

    NOT from Newtonian gravity or any other classical force law.

    Parameters
    ----------
    G : TNFRGraph
        Network graph with nodes containing TNFR attributes
    positions : ndarray, shape (N, 3)
        Current positions (affect phase evolution, not potential directly)
    hbar_str : float, default=1.0
        Structural Planck constant

    Returns
    -------
    U : float
        Coherence potential energy (lower = more stable)

    Notes
    -----
    In TNFR, the potential U encodes structural stability landscape.
    Nodes evolve toward configurations that maximize coherence (minimize U).
    """
    # Build internal Hamiltonian
    ham = InternalHamiltonian(G, hbar_str=hbar_str)

    # Potential is encoded in ground state energy
    eigenvalues, _ = ham.get_spectrum()

    # Total potential: sum of eigenvalues (trace of H_int)
    # For energy conservation, we use ground state as reference
    U = float(eigenvalues[0])  # Ground state energy

    return U


def compute_tnfr_delta_nfr(
    G: TNFRGraph,
    node_ids: list[str],
    hbar_str: float = 1.0,
) -> NDArray[np.floating]:
    """Compute ΔNFR from Hamiltonian commutator (pure TNFR).

    This is the correct TNFR computation of ΔNFR:
        ΔNFR = i[H_int, ·]/ℏ_str

    NOT from classical forces: F = -∇U (external assumption).

    Parameters
    ----------
    G : TNFRGraph
        Network graph with TNFR attributes
    node_ids : list of str
        Node identifiers in order
    hbar_str : float, default=1.0
        Structural Planck constant

    Returns
    -------
    dnfr : ndarray, shape (N,)
        ΔNFR values for each node (structural reorganization pressure)

    Notes
    -----
    The ΔNFR values represent the "reorganization pressure" driving
    structural evolution via the nodal equation: ∂EPI/∂t = νf · ΔNFR
    """
    # Build Hamiltonian
    ham = InternalHamiltonian(G, hbar_str=hbar_str)

    # Compute ΔNFR for each node
    dnfr = np.zeros(len(node_ids))
    for i, node_id in enumerate(node_ids):
        dnfr[i] = ham.compute_node_delta_nfr(node_id)

    return dnfr


class TNFRNBodySystem:
    """N-body system using pure TNFR physics (no classical assumptions).

    This implementation computes dynamics from TNFR structural coherence,
    without assuming any classical potentials (gravity, Coulomb, etc.).

    Attributes
    ----------
    n_bodies : int
        Number of bodies
    masses : ndarray, shape (N,)
        Masses (m = 1/νf, structural inertia)
    positions : ndarray, shape (N, 3)
        Current positions
    velocities : ndarray, shape (N, 3)
        Current velocities
    phases : ndarray, shape (N,)
        Current phases (θ ∈ [0, 2π])
    time : float
        Current structural time
    graph : TNFRGraph
        TNFR network representation
    hbar_str : float
        Structural Planck constant

    Notes
    -----
    Dynamics follow from nodal equation: ∂EPI/∂t = νf · ΔNFR
    where ΔNFR is computed from Hamiltonian commutator.

    Attraction/repulsion emerges from phase synchronization,
    NOT from assumed gravitational potential.
    """

    def __init__(
        self,
        n_bodies: int,
        masses: list[float] | NDArray[np.floating],
        positions: NDArray[np.floating],
        velocities: NDArray[np.floating],
        phases: NDArray[np.floating] | None = None,
        hbar_str: float = 1.0,
        coupling_strength: float = 0.1,
        coherence_strength: float = -1.0,
    ):
        """Initialize TNFR N-body system.

        Parameters
        ----------
        n_bodies : int
            Number of bodies
        masses : array_like, shape (N,)
            Masses (m = 1/νf, must be positive)
        positions : ndarray, shape (N, 3)
            Initial positions
        velocities : ndarray, shape (N, 3)
            Initial velocities
        phases : ndarray, shape (N,), optional
            Initial phases. If None, initialized to zero (synchronized)
        hbar_str : float, default=1.0
            Structural Planck constant
        coupling_strength : float, default=0.1
            Network coupling strength (J_0 in H_coupling)
        coherence_strength : float, default=-1.0
            Coherence potential strength (C_0 in H_coh)
            Negative = attractive potential well

        Raises
        ------
        ValueError
            If dimensions mismatch or masses non-positive
        """
        if n_bodies < 1:
            raise NetworkConfigError(
                parameter="n_bodies",
                value=n_bodies,
                reason="Must have at least one body",
            )

        self.n_bodies = n_bodies
        self.masses = np.array(masses, dtype=float)

        if len(self.masses) != n_bodies:
            raise NetworkConfigError(
                parameter="masses",
                value=len(self.masses),
                reason=f"Masses length must match n_bodies ({n_bodies})",
            )

        if np.any(self.masses <= 0):
            raise NetworkConfigError(
                parameter="masses",
                value="[contains non-positive]",
                reason="All masses must be positive",
            )

        # State vectors
        self.positions = np.asarray(positions, dtype=float).copy()
        self.velocities = np.asarray(velocities, dtype=float).copy()

        if phases is None:
            self.phases = np.zeros(n_bodies, dtype=float)
        else:
            self.phases = np.asarray(phases, dtype=float).copy()

        # Validate shapes
        expected_shape = (n_bodies, 3)
        if self.positions.shape != expected_shape:
            raise NetworkConfigError(
                parameter="positions",
                value=str(self.positions.shape),
                reason=f"Shape mismatch, expected {expected_shape}",
            )
        if self.velocities.shape != expected_shape:
            raise NetworkConfigError(
                parameter="velocities",
                value=str(self.velocities.shape),
                reason=f"Shape mismatch, expected {expected_shape}",
            )
        if self.phases.shape != (n_bodies,):
            raise NetworkConfigError(
                parameter="phases",
                value=str(self.phases.shape),
                reason=f"Shape mismatch, expected ({n_bodies},)",
            )

        self.time = 0.0
        self.hbar_str = float(hbar_str)

        # TNFR parameters
        self.coupling_strength = float(coupling_strength)
        self.coherence_strength = float(coherence_strength)

        # Build TNFR graph
        self._build_graph()

    def _build_graph(self) -> None:
        """Build TNFR graph representation.

        Each body becomes a resonant node with:
        - νf = 1/m (structural frequency)
        - EPI encoding (position, velocity)
        - Phase θ
        - All-to-all coupling (full network)
        """
        import networkx as nx

        self.graph: TNFRGraph = nx.Graph()
        self.graph.graph["name"] = "tnfr_nbody_system"
        self.graph.graph["H_COUPLING_STRENGTH"] = self.coupling_strength
        self.graph.graph["H_COH_STRENGTH"] = self.coherence_strength

        epi_seed = min(0.5, EPI_MAX_CANONICAL * 0.95)

        # Add nodes with TNFR attributes
        for i in range(self.n_bodies):
            node_id = f"body_{i}"

            # Structural frequency: νf = 1/m
            nu_f = 1.0 / self.masses[i]

            # Create NFR node with structured EPI
            epi_state = {
                "position": self.positions[i].copy(),
                "velocity": self.velocities[i].copy(),
            }

            # Note: create_nfr expects scalar epi for initialization
            # We'll override it immediately
            _, _ = create_nfr(
                node_id,
                epi=epi_seed,  # Temporary, will be overwritten
                vf=nu_f,
                theta=float(self.phases[i]),
                graph=self.graph,
            )

            # Override with structured EPI
            self.graph.nodes[node_id]["epi"] = epi_state

        # Add edges (all-to-all coupling)
        # In TNFR, coupling strength depends on structural similarity
        # Here we use uniform coupling for simplicity
        for i in range(self.n_bodies):
            for j in range(i + 1, self.n_bodies):
                node_i = f"body_{i}"
                node_j = f"body_{j}"

                # Edge weight: coupling strength
                # (In more sophisticated version, could depend on distance)
                weight = self.coupling_strength
                self.graph.add_edge(node_i, node_j, weight=weight)

    def compute_energy(self) -> tuple[float, float, float]:
        """Compute system energy (kinetic + coherence potential).

        Returns
        -------
        kinetic : float
            Kinetic energy K = Σ (1/2) m v²
        potential : float
            Coherence potential U from TNFR Hamiltonian
        total : float
            Total energy H = K + U

        Notes
        -----
        Unlike classical n-body (assumes U = -Gm₁m₂/r), the potential
        here emerges from TNFR coherence matrix and coupling topology.
        """
        # Kinetic energy (same as classical)
        v_squared = np.sum(self.velocities**2, axis=1)
        kinetic = 0.5 * np.sum(self.masses * v_squared)

        # Coherence potential from TNFR Hamiltonian
        # This is the key difference: NO assumption about gravity
        potential = compute_tnfr_coherence_potential(
            self.graph, self.positions, self.hbar_str
        )

        total = kinetic + potential

        return kinetic, potential, total

    def compute_momentum(self) -> NDArray[np.floating]:
        """Compute total linear momentum.

        Returns
        -------
        momentum : ndarray, shape (3,)
            Total momentum P = Σ m v
        """
        momentum = np.sum(self.masses[:, np.newaxis] * self.velocities, axis=0)
        return momentum

    def compute_angular_momentum(self) -> NDArray[np.floating]:
        """Compute total angular momentum.

        Returns
        -------
        angular_momentum : ndarray, shape (3,)
            Total L = Σ r × (m v)
        """
        L = np.zeros(3)
        for i in range(self.n_bodies):
            L += self.masses[i] * np.cross(self.positions[i], self.velocities[i])
        return L

    def step(self, dt: float) -> None:
        """Advance system by one time step using TNFR dynamics.

        This implements the nodal equation: ∂EPI/∂t = νf · ΔNFR
        where ΔNFR is computed from Hamiltonian commutator.

        Parameters
        ----------
        dt : float
            Time step (structural time units)

        Notes
        -----
        Uses velocity Verlet-like integration for position/velocity,
        but accelerations come from TNFR ΔNFR via coherence gradients.
        """
        # Update graph with current state
        self._update_graph()

        # Compute accelerations from TNFR coherence-based forces
        # This is the key: forces emerge from coherence gradient, not gravity
        accel = self._compute_tnfr_accelerations()

        # Velocity Verlet integration
        # v(t+dt/2) = v(t) + a(t) * dt/2
        v_half = self.velocities + 0.5 * accel * dt

        # r(t+dt) = r(t) + v(t+dt/2) * dt
        self.positions += v_half * dt

        # Update graph with new positions
        self._update_graph()

        # Recompute accelerations at new positions
        accel_new = self._compute_tnfr_accelerations()

        # v(t+dt) = v(t+dt/2) + a(t+dt) * dt/2
        self.velocities = v_half + 0.5 * accel_new * dt

        # Update phases based on ΔNFR
        # Compute scalar ΔNFR for phase evolution
        node_ids = [f"body_{i}" for i in range(self.n_bodies)]
        dnfr_values = compute_tnfr_delta_nfr(self.graph, node_ids, self.hbar_str)

        # Phase evolution: dθ/dt ~ ΔNFR
        self.phases += dnfr_values * dt
        self.phases = np.mod(self.phases, 2 * np.pi)  # Keep in [0, 2π]

        # Update time
        self.time += dt

    def _compute_tnfr_accelerations(self) -> NDArray[np.floating]:
        """Compute accelerations from TNFR coherence-based forces.

        This is where TNFR physics determines motion:
        - Forces emerge from coherence gradient (NOT gravity!)
        - Phase differences create attraction/repulsion
        - Coupling strength determines force magnitude

        Returns
        -------
        accelerations : ndarray, shape (N, 3)
            Acceleration vectors for each body

        Notes
        -----
        The key TNFR insight: Forces emerge from maximizing coherence.

        Coherence between nodes i and j depends on:
        1. Phase difference: cos(θᵢ - θⱼ) (in-phase → attractive)
        2. Coupling strength: J₀ (from network edges)
        3. Distance dependence: Coherence decreases with separation

        This gives rise to attraction/repulsion WITHOUT assuming gravity!
        """
        # Vectorized implementation for O(N^2) -> O(1) Python overhead
        # r_ij = r_j - r_i (vector from i to j)
        # Shape: (N, N, 3) via broadcasting: (1, N, 3) - (N, 1, 3)
        r = self.positions
        r_ij = r[None, :, :] - r[:, None, :]

        # Distances
        dist = np.linalg.norm(r_ij, axis=2)

        # Avoid singularity (diagonal)
        # We set diagonal distance to 1.0 to avoid division by zero
        # The force will be zeroed out later anyway
        np.fill_diagonal(dist, 1.0)

        # Unit vectors
        r_hat = r_ij / dist[:, :, None]

        # Phase diffs: theta_j - theta_i
        theta = self.phases
        phase_diff: NDArray[np.floating] = theta[None, :] - theta[:, None]

        # Coherence factor: positive when in-phase, negative when anti-phase
        coherence_factor = np.cos(phase_diff)

        # Distance factor: Softened power law
        distance_factor = 1.0 / (dist**2 + 0.1)
        np.fill_diagonal(distance_factor, 0.0)  # No self-force

        # Frequency factor: sqrt(nu_i * nu_j)
        nu = 1.0 / self.masses
        freq_factor = np.sqrt(np.outer(nu, nu))

        # Total TNFR force magnitude
        force_mag = (
            self.coupling_strength
            * self.coherence_strength
            * coherence_factor
            * distance_factor
            * freq_factor
        )

        # Force vectors: F_ij directed along r_hat
        force_vec = force_mag[:, :, None] * r_hat

        # Sum forces on i (sum over j)
        total_force = np.sum(force_vec, axis=1)

        # Acceleration: a_i = F_i * nu_i
        accelerations = total_force * nu[:, None]

        return accelerations

    def _update_graph(self) -> None:
        """Update graph representation with current state."""
        for i in range(self.n_bodies):
            node_id = f"body_{i}"

            # Update EPI
            epi_state = {
                "position": self.positions[i].copy(),
                "velocity": self.velocities[i].copy(),
            }
            self.graph.nodes[node_id]["epi"] = epi_state

            # Update phase
            self.graph.nodes[node_id]["theta"] = float(self.phases[i])

    def evolve(
        self,
        t_final: float,
        dt: float,
        store_interval: int = 1,
    ) -> dict[str, Any]:
        """Evolve system using pure TNFR dynamics.

        Parameters
        ----------
        t_final : float
            Final time
        dt : float
            Time step
        store_interval : int, default=1
            Store state every N steps

        Returns
        -------
        history : dict
            Contains: time, positions, velocities, phases,
                     energy, kinetic, potential, momentum, angular_momentum

        Notes
        -----
        Evolution follows nodal equation with ΔNFR from Hamiltonian.
        NO classical gravitational assumptions.
        """
        n_steps = int((t_final - self.time) / dt)

        if n_steps < 1:
            raise NetworkConfigError(
                parameter="t_final",
                value=t_final,
                reason=f"Must be greater than current time {self.time}",
            )

        # Pre-allocate storage
        n_stored = (n_steps // store_interval) + 1
        times = np.zeros(n_stored)
        positions_hist = np.zeros((n_stored, self.n_bodies, 3))
        velocities_hist = np.zeros((n_stored, self.n_bodies, 3))
        phases_hist = np.zeros((n_stored, self.n_bodies))
        energies = np.zeros(n_stored)
        kinetic_energies = np.zeros(n_stored)
        potential_energies = np.zeros(n_stored)
        momenta = np.zeros((n_stored, 3))
        angular_momenta = np.zeros((n_stored, 3))

        # Store initial state
        store_idx = 0
        times[store_idx] = self.time
        positions_hist[store_idx] = self.positions.copy()
        velocities_hist[store_idx] = self.velocities.copy()
        phases_hist[store_idx] = self.phases.copy()
        K, U, E = self.compute_energy()
        kinetic_energies[store_idx] = K
        potential_energies[store_idx] = U
        energies[store_idx] = E
        momenta[store_idx] = self.compute_momentum()
        angular_momenta[store_idx] = self.compute_angular_momentum()
        store_idx += 1

        # Evolution loop
        for step in range(n_steps):
            self.step(dt)

            # Store state if needed
            if (step + 1) % store_interval == 0 and store_idx < n_stored:
                times[store_idx] = self.time
                positions_hist[store_idx] = self.positions.copy()
                velocities_hist[store_idx] = self.velocities.copy()
                phases_hist[store_idx] = self.phases.copy()
                K, U, E = self.compute_energy()
                kinetic_energies[store_idx] = K
                potential_energies[store_idx] = U
                energies[store_idx] = E
                momenta[store_idx] = self.compute_momentum()
                angular_momenta[store_idx] = self.compute_angular_momentum()
                store_idx += 1

        # Compute energy drift
        energy_drift = abs(energies[-1] - energies[0]) / abs(energies[0])

        return {
            "time": times[:store_idx],
            "positions": positions_hist[:store_idx],
            "velocities": velocities_hist[:store_idx],
            "phases": phases_hist[:store_idx],
            "energy": energies[:store_idx],
            "kinetic": kinetic_energies[:store_idx],
            "potential": potential_energies[:store_idx],
            "momentum": momenta[:store_idx],
            "angular_momentum": angular_momenta[:store_idx],
            "energy_drift": energy_drift,
        }

    def plot_trajectories(
        self,
        history: dict[str, Any],
        show_energy: bool = True,
        show_phases: bool = True,
    ) -> Figure:
        """Plot trajectories, energy, and phase evolution.

        Parameters
        ----------
        history : dict
            Result from evolve()
        show_energy : bool, default=True
            Show energy conservation plot
        show_phases : bool, default=True
            Show phase evolution plot

        Returns
        -------
        fig : matplotlib Figure

        Raises
        ------
        ImportError
            If matplotlib not available
        """
        try:
            import matplotlib.pyplot as plt
        except ImportError as exc:
            raise ImportError(
                "matplotlib required for plotting. "
                "Install with: pip install 'tnfr[viz-basic]'"
            ) from exc

        n_plots = 1 + int(show_energy) + int(show_phases)
        fig = plt.figure(figsize=(6 * n_plots, 5))

        plot_idx = 1

        # 3D trajectories
        ax_3d = fig.add_subplot(1, n_plots, plot_idx, projection="3d")
        plot_idx += 1

        positions = history["positions"]
        colors = plt.cm.rainbow(np.linspace(0, 1, self.n_bodies))

        for i in range(self.n_bodies):
            traj = positions[:, i, :]
            ax_3d.plot(
                traj[:, 0],
                traj[:, 1],
                traj[:, 2],
                color=colors[i],
                label=f"Body {i + 1} (m={self.masses[i]:.2f})",
                alpha=0.7,
            )
            ax_3d.scatter(
                traj[0, 0], traj[0, 1], traj[0, 2], color=colors[i], s=100, marker="o"
            )
            ax_3d.scatter(
                traj[-1, 0], traj[-1, 1], traj[-1, 2], color=colors[i], s=50, marker="x"
            )

        ax_3d.set_xlabel("X")
        ax_3d.set_ylabel("Y")
        ax_3d.set_zlabel("Z")
        ax_3d.set_title("TNFR N-Body Trajectories (No Gravitational Assumption)")
        ax_3d.legend()

        # Energy conservation
        if show_energy:
            ax_energy = fig.add_subplot(1, n_plots, plot_idx)
            plot_idx += 1

            time = history["time"]
            E = history["energy"]
            E0 = E[0]

            ax_energy.plot(
                time,
                (E - E0) / abs(E0) * 100,
                label="Energy drift (%)",
                color="red",
                linewidth=2,
            )
            ax_energy.axhline(0, color="black", linestyle="--", alpha=0.3)
            ax_energy.set_xlabel("Structural Time")
            ax_energy.set_ylabel("ΔE/E₀ (%)")
            ax_energy.set_title("Energy Conservation (TNFR Hamiltonian)")
            ax_energy.legend()
            ax_energy.grid(True, alpha=0.3)

        # Phase evolution
        if show_phases:
            ax_phases = fig.add_subplot(1, n_plots, plot_idx)

            time = history["time"]
            phases = history["phases"]

            for i in range(self.n_bodies):
                ax_phases.plot(
                    time,
                    phases[:, i],
                    color=colors[i],
                    label=f"Body {i + 1}",
                    linewidth=2,
                )

            ax_phases.set_xlabel("Structural Time")
            ax_phases.set_ylabel("Phase θ (rad)")
            ax_phases.set_title("Phase Evolution (TNFR Synchronization)")
            ax_phases.legend()
            ax_phases.grid(True, alpha=0.3)

        plt.tight_layout()
        return fig