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/sdk/fluent.py

fluent.py

Fluent API for simplified TNFR network creation and simulation.

This module implements the core :class:TNFRNetwork class that provides a user-friendly, chainable interface for working with TNFR networks. The API hides low-level complexity while maintaining full theoretical fidelity to TNFR invariants and structural operators.

Examples

Create and simulate a simple TNFR network:

network = TNFRNetwork("my_experiment") network.add_nodes(10).connect_nodes(0.3, "random") network.apply_sequence("basic_activation", repeat=5) results = network.measure() print(results.summary())

Chain operations for rapid prototyping:

results = (TNFRNetwork("quick_test") ... .add_nodes(20) ... .connect_nodes(0.4, "ring") ... .apply_sequence("network_sync", repeat=10) ... .measure())

Source Code

python
"""Fluent API for simplified TNFR network creation and simulation.

This module implements the core :class:`TNFRNetwork` class that provides
a user-friendly, chainable interface for working with TNFR networks. The
API hides low-level complexity while maintaining full theoretical fidelity
to TNFR invariants and structural operators.

Examples
--------
Create and simulate a simple TNFR network:

>>> network = TNFRNetwork("my_experiment")
>>> network.add_nodes(10).connect_nodes(0.3, "random")
>>> network.apply_sequence("basic_activation", repeat=5)
>>> results = network.measure()
>>> print(results.summary())

Chain operations for rapid prototyping:

>>> results = (TNFRNetwork("quick_test")
...            .add_nodes(20)
...            .connect_nodes(0.4, "ring")
...            .apply_sequence("network_sync", repeat=10)
...            .measure())
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Any

import networkx as nx

from ..alias import get_attr
from ..constants.aliases import ALIAS_DNFR, ALIAS_THETA, ALIAS_VF
from ..constants.canonical import HIGH_COHERENCE_THRESHOLD as COHERENCE_STRONG
from ..constants.canonical import PI as _PI
from ..constants.canonical import (
    THOL_MIN_COLLECTIVE_COHERENCE as COHERENCE_FRAGMENTATION,
)
from ..mathematics.unified_numerical import NUMPY_AVAILABLE as _HAS_NUMPY
from ..mathematics.unified_numerical import np
from ..metrics.coherence import compute_coherence
from ..metrics.sense_index import compute_Si
from ..structural import create_nfr, run_sequence
from ..validation import validate_sequence

# ---------------------------------------------------------------------------
# Canonical coherence marks for adaptive sequence selection.
#
# These are the C(t) telemetry marks from AGENTS.md §7, reused from the
# canonical constants as a single source of truth (heuristic cuts -- not magic
# numbers, not fitted to data):
#   - COHERENCE_STRONG        (π/(π+1) ~0.7585, emergent): C(t) at/above -> strong
#   - COHERENCE_FRAGMENTATION (1/(pi+1)       ~ 0.2415): C(t) below   -> fragmenting
# Adaptive selection keys on these: below fragmentation the network is
# breaking up (heal); below the strong/target mark it consolidates
# (stabilize); at/above the strong mark it can explore (optimize/innovate).
# ---------------------------------------------------------------------------

# Minimum compute-engine speed-up worth reporting (display-only; NOT a TNFR
# coherence threshold).
_MIN_REPORTABLE_SPEEDUP = 1.1

# Auto-optimization imports (NEW - Nov 28, 2025)
try:
    from ..dynamics.self_optimizing_engine import (
        OptimizationObjective,
        TNFRSelfOptimizingEngine,
    )
    from ..physics.fields import (
        analyze_optimization_potential,
        auto_optimize_field_computation,
        recommend_field_optimization_strategy,
    )

    _AUTO_OPTIMIZATION_AVAILABLE = True
except ImportError:
    auto_optimize_field_computation = None
    analyze_optimization_potential = None
    recommend_field_optimization_strategy = None
    TNFRSelfOptimizingEngine = None
    OptimizationObjective = None
    _AUTO_OPTIMIZATION_AVAILABLE = False

__all__ = ["TNFRNetwork", "NetworkConfig", "NetworkResults"]

# Predefined operator sequences for common patterns (optimized with Grammar 2.0)
# All sequences must respect TNFR grammar rules:
# - Start with emission or recursivity
# - Include reception→coherence segment
# - Include coupling/dissonance/resonance segment
# - End with recursivity, silence, or transition
#
# Sequences optimized for structural health ≥ 0.7 using Grammar 2.0:
# - Balanced stabilizers/destabilizers
# - Harmonic frequency transitions
# - Proper closure operators
# - Pattern completeness
NAMED_SEQUENCES = {
    # Basic activation pattern - optimized with expansion for balance
    # Health: 0.79 (good) - Pattern: activation
    # Includes controlled expansion for structural balance
    "basic_activation": [
        "emission",  # AL: Initiate coherent structure
        "reception",  # EN: Stabilize incoming energy
        "coherence",  # IL: Primary stabilization (required)
        "expansion",  # VAL: Controlled growth (balance +0.33)
        "resonance",  # RA: Amplify coherent structure
        "silence",  # SHA: Sustainable pause state
    ],
    # Stabilization with expansion - optimized for regenerative cycles
    # Health: 0.76 (good) - Pattern: regenerative
    # Enables recursive consolidation with controlled expansion
    "stabilization": [
        "emission",  # AL: Initiate structure
        "reception",  # EN: Gather information
        "coherence",  # IL: Stabilize
        "expansion",  # VAL: Controlled growth (balance +0.50)
        "resonance",  # RA: Amplify through network
        "recursivity",  # REMESH: Enable fractal recursion
    ],
    # Creative mutation - corrected for OZ→IL physics
    # Pattern: stabilized transformation with controlled mutation
    "creative_mutation": [
        "emission",  # AL: Initiate exploration
        "coherence",  # IL: Establish stable base
        "dissonance",  # OZ: Introduce creative tension
        "mutation",  # ZHIR: Phase transformation (after OZ)
        "coherence",  # IL: Stabilize new state
        "resonance",  # RA: Amplify new patterns
        "silence",  # SHA: Integration pause
    ],
    # Network synchronization - optimized with transition for regenerative capability
    # Health: 0.77 (good) - Pattern: regenerative
    # Enables phase synchronization across multi-node networks with dissonance for balance
    "network_sync": [
        "emission",  # AL: Initiate network activity
        "reception",  # EN: Gather network state
        "coherence",  # IL: Stabilize local structure
        "coupling",  # UM: Establish phase synchronization
        "resonance",  # RA: Propagate through network
        "transition",  # NAV: Enable regenerative cycles (changed from silence)
    ],
    # Exploration - corrected for physics compliance
    # Pattern: stable exploration with controlled discovery
    "exploration": [
        "emission",  # AL: Begin exploration
        "reception",  # EN: Sense environment
        "coherence",  # IL: Stabilize base
        "dissonance",  # OZ: Introduce exploration tension
        "resonance",  # RA: Amplify discoveries
        "transition",  # NAV: Navigate to new state
    ],
    # Consolidation - optimized with expansion for structural balance
    # Health: 0.80 (good) - Pattern: stabilization
    # Recursive consolidation with controlled expansion
    "consolidation": [
        "recursivity",  # REMESH: Start from fractal structure
        "reception",  # EN: Gather current state
        "coherence",  # IL: Consolidate structure
        "expansion",  # VAL: Controlled growth (balance +0.25)
        "resonance",  # RA: Amplify consolidated state
        "coherence",  # IL: Re-stabilize after expansion
        "silence",  # SHA: Sustained stable state
    ],
    # === ADVANCED OPERATOR SEQUENCES ===
    # Healing pattern - for network recovery and coherence restoration
    "healing": [
        "emission",  # AL: Restart from clean state
        "reception",  # EN: Gather current network state
        "coherence",  # IL: Primary stabilization
        "coupling",  # UM: Restore connections
        "resonance",  # RA: Harmonize network
        "coherence",  # IL: Final stabilization
        "silence",  # SHA: Sustained healing state
    ],
    # Amplification - for boosting network activity and propagation
    "amplification": [
        "emission",  # AL: Initiate high-energy state
        "coupling",  # UM: Establish strong links
        "resonance",  # RA: Primary amplification
        "coherence",  # IL: Stabilize amplified state
        "expansion",  # VAL: Controlled growth
        "resonance",  # RA: Secondary amplification
        "transition",  # NAV: Navigate to sustained state
    ],
    # Deep transformation - for major structural changes
    "deep_transformation": [
        "emission",  # AL: Fresh start
        "coherence",  # IL: Stable foundation
        "expansion",  # VAL: Increase complexity
        "coherence",  # IL: Stabilize expansion
        "dissonance",  # OZ: Transformation trigger
        "mutation",  # ZHIR: Major phase change
        "coherence",  # IL: Integrate transformation
        "resonance",  # RA: Propagate new patterns
        "silence",  # SHA: Consolidate changes
    ],
    # Network harmonization - for multi-node synchronization
    "harmonization": [
        "recursivity",  # REMESH: Multi-scale start
        "reception",  # EN: Sense all nodes
        "coherence",  # IL: Local stabilization
        "coupling",  # UM: Phase synchronization
        "resonance",  # RA: Network-wide harmonics
        "coherence",  # IL: Lock in harmony
        "transition",  # NAV: Maintain sync state
    ],
    # Progressive learning - for adaptive behavior development
    "progressive_learning": [
        "emission",  # AL: New learning episode
        "reception",  # EN: Gather information
        "coherence",  # IL: Initial understanding
        "expansion",  # VAL: Broaden perspective
        "coupling",  # UM: Connect concepts
        "resonance",  # RA: Reinforce learning
        "recursivity",  # REMESH: Multi-level integration
    ],
    # Recovery pattern - for system restoration after disruption
    "recovery": [
        "emission",  # AL: Restart core functions (U1a generator)
        "reception",  # EN: Assess current state
        "coherence",  # IL: Restore stability
        "coupling",  # UM: Rebuild connections
        "resonance",  # RA: Stabilize recovery
        "transition",  # NAV: Return to normal operation
    ],
    # Innovation catalyst - for breakthrough discovery patterns
    "innovation": [
        "transition",  # NAV: Shift to exploration mode
        "reception",  # EN: Gather diverse inputs
        "coherence",  # IL: Stable processing base
        "dissonance",  # OZ: Creative tension
        "mutation",  # ZHIR: Breakthrough transformation
        "coherence",  # IL: Stabilize new insights (required after ZHIR)
        "resonance",  # RA: Amplify stabilized innovation
        "recursivity",  # REMESH: Scale innovation
    ],
    # Optimization cycle - for continuous improvement
    "optimization": [
        "recursivity",  # REMESH: Analyze current patterns
        "reception",  # EN: Gather performance data
        "coherence",  # IL: Stabilize baseline
        "expansion",  # VAL: Explore improvements
        "contraction",  # NUL: Focus on best options
        "coherence",  # IL: Optimize selection
        "transition",  # NAV: Implement improvements
    ],
    # Fractal growth - for self-similar expansion across scales
    "fractal_growth": [
        "emission",  # AL: Seed pattern
        "coherence",  # IL: Stabilize core
        "expansion",  # VAL: First scale growth
        "coherence",  # IL: Stabilize expansion (required after VAL)
        "recursivity",  # REMESH: Self-similar replication
        "coupling",  # UM: Connect scales
        "resonance",  # RA: Harmonize across levels
        "silence",  # SHA: Sustained fractal state
    ],
}


@dataclass
class NetworkConfig:
    """Configuration for TNFR network creation.

    Parameters
    ----------
    random_seed : int, optional
        Seed for random number generation to ensure reproducibility.
    validate_invariants : bool, default=True
        Whether to validate TNFR invariants after operator application.
    auto_stabilization : bool, default=True
        Whether to automatically apply stabilization after mutations.
    default_vf_range : tuple[float, float], default=(0.1, 1.0)
        Default range for structural frequency (νf) generation in Hz_str.
    default_epi_range : tuple[float, float], default=(0.1, 0.9)
        Default range for EPI (Primary Information Structure) generation.
    """

    random_seed: int | None = None
    validate_invariants: bool = True
    auto_stabilization: bool = True
    default_vf_range: tuple[float, float] = (0.1, 1.0)
    default_epi_range: tuple[float, float] = (0.1, 0.9)


@dataclass
class NetworkResults:
    """Results from TNFR network simulation.

    Attributes
    ----------
    coherence : float
        Global coherence C(t) of the network.
    sense_indices : dict[str, float]
        Sense index Si for each node, measuring stable reorganization capacity.
    delta_nfr : dict[str, float]
        Internal reorganization gradient ΔNFR for each node.
    graph : TNFRGraph
        The underlying NetworkX graph with full TNFR state.
    avg_vf : float, optional
        Average structural frequency across all nodes.
    avg_phase : float, optional
        Average phase angle across all nodes.
    """

    coherence: float
    sense_indices: dict[str, float]
    delta_nfr: dict[str, float]
    graph: Any  # TNFRGraph
    avg_vf: float | None = None
    avg_phase: float | None = None
    unified_fields: dict[str, Any] | None = (
        None  # Nov 28, 2025 - unified field telemetry
    )

    def summary(self) -> str:
        """Generate human-readable summary of network results.

        Returns
        -------
        str
            Formatted summary string with key metrics.
        """
        si_values = list(self.sense_indices.values())
        dnfr_values = list(self.delta_nfr.values())

        avg_si = sum(si_values) / len(si_values) if si_values else 0.0
        avg_dnfr = sum(dnfr_values) / len(dnfr_values) if dnfr_values else 0.0

        # Unified fields summary (if available)
        unified_summary = ""
        if self.unified_fields:
            try:
                cf = self.unified_fields.get("complex_field", {})
                correlation = cf.get("correlation", 0.0)
                ti = self.unified_fields.get("tensor_invariants", {})
                conservation = ti.get("conservation_quality", 0.0)
                unified_summary = f"""
  • K_φ ↔ J_φ Correlation: {correlation:.3f}
  • Conservation Quality: {conservation:.3f}"""
            except Exception:
                pass

        return f"""
TNFR Network Results:
  • Coherence C(t): {self.coherence:.3f}
  • Nodes: {len(self.sense_indices)}
  • Avg Sense Index Si: {avg_si:.3f}
  • Avg ΔNFR: {avg_dnfr:.3f}
  • Avg νf: {self.avg_vf:.3f} Hz_str{' (computed)' if self.avg_vf else ''}
  • Avg Phase: {self.avg_phase:.3f} rad{' (computed)' if self.avg_phase else ''}{unified_summary}
""".strip()

    def to_dict(self) -> dict[str, Any]:
        """Convert results to serializable dictionary.

        Returns
        -------
        dict[str, Any]
            Dictionary containing all metrics and summary statistics.
        """
        si_values = list(self.sense_indices.values())
        dnfr_values = list(self.delta_nfr.values())

        return {
            "coherence": self.coherence,
            "sense_indices": self.sense_indices,
            "delta_nfr": self.delta_nfr,
            "summary_stats": {
                "node_count": len(self.sense_indices),
                "avg_si": sum(si_values) / len(si_values) if si_values else 0.0,
                "avg_delta_nfr": (
                    sum(dnfr_values) / len(dnfr_values) if dnfr_values else 0.0
                ),
                "avg_vf": self.avg_vf,
                "avg_phase": self.avg_phase,
            },
        }


class TNFRNetwork:
    """Fluent API for creating and simulating TNFR networks.

    This class provides a simplified, chainable interface for working with
    TNFR networks. All methods return ``self`` to enable method chaining.
    The API automatically handles node creation, operator validation, and
    metric computation while preserving TNFR structural invariants.

    Parameters
    ----------
    name : str, default="tnfr_network"
        Name identifier for the network.
    config : NetworkConfig, optional
        Configuration settings. If None, uses default configuration.

    Examples
    --------
    Create a network with fluent interface:

    >>> network = TNFRNetwork("experiment_1")
    >>> network.add_nodes(15).connect_nodes(0.25, "random")
    >>> network.apply_sequence("basic_activation", repeat=3)
    >>> results = network.measure()

    One-line network creation and simulation:

    >>> results = (TNFRNetwork("test")
    ...            .add_nodes(10)
    ...            .connect_nodes(0.3)
    ...            .apply_sequence("network_sync", repeat=5)
    ...            .measure())
    """

    def __init__(self, name: str = "tnfr_network", config: NetworkConfig | None = None):
        """Initialize TNFR network with given name and configuration."""
        self.name = name
        self._config = config if config is not None else NetworkConfig()
        self._graph: nx.Graph | None = None
        self._results: NetworkResults | None = None
        self._node_counter = 0

        # Initialize RNG if seed provided
        if _HAS_NUMPY and self._config.random_seed is not None:
            self._rng = np.random.RandomState(self._config.random_seed)
        else:
            import random

            if self._config.random_seed is not None:
                random.seed(self._config.random_seed)
            self._rng = random  # type: ignore[assignment]

    def add_nodes(
        self,
        count: int,
        vf_range: tuple[float, float] | None = None,
        epi_range: tuple[float, float] | None = None,
        phase_range: tuple[float, float] = (0.0, 2.0 * _PI),  # (0, 2π)
        random_seed: int | None = None,
    ) -> TNFRNetwork:
        """Add nodes with random TNFR properties within valid ranges.

        Creates ``count`` new nodes with structural properties (EPI, νf, phase)
        randomly sampled within specified ranges. All values respect TNFR
        invariants and canonical units (νf in Hz_str, phase in radians).

        Parameters
        ----------
        count : int
            Number of nodes to create.
        vf_range : tuple[float, float], optional
            Range for structural frequency νf in Hz_str. If None, uses
            config default. Values should be positive.
        epi_range : tuple[float, float], optional
            Range for Primary Information Structure (EPI). If None, uses
            config default. Typical range is (0.1, 0.9) to avoid extremes.
        phase_range : tuple[float, float], default=(0, 2π)
            Range for phase in radians. Default covers full circle.
        random_seed : int, optional
            Override seed for this operation only. If None, uses network seed.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Examples
        --------
        Add nodes with default properties:

        >>> network = TNFRNetwork().add_nodes(5)

        Add nodes with custom frequency range:

        >>> network = TNFRNetwork().add_nodes(10, vf_range=(0.5, 2.0))
        """
        if self._graph is None:
            self._graph = nx.Graph()

        if vf_range is None:
            vf_range = self._config.default_vf_range
        if epi_range is None:
            epi_range = self._config.default_epi_range

        # Setup RNG for this operation
        if _HAS_NUMPY:
            rng = (
                np.random.RandomState(random_seed)
                if random_seed is not None
                else self._rng
            )

            for _ in range(count):
                node_id = f"node_{self._node_counter}"
                self._node_counter += 1

                # Generate valid TNFR properties
                vf = rng.uniform(*vf_range)
                phase = rng.uniform(*phase_range)
                epi = rng.uniform(*epi_range)

                # Create NFR node with structural properties
                self._graph, _ = create_nfr(
                    node_id,
                    graph=self._graph,
                    vf=vf,
                    theta=phase,
                    epi=epi,
                )
        else:
            # Fallback to standard random
            import random

            if random_seed is not None:
                random.seed(random_seed)

            for _ in range(count):
                node_id = f"node_{self._node_counter}"
                self._node_counter += 1

                vf = random.uniform(*vf_range)
                phase = random.uniform(*phase_range)
                epi = random.uniform(*epi_range)

                self._graph, _ = create_nfr(
                    node_id,
                    graph=self._graph,
                    vf=vf,
                    theta=phase,
                    epi=epi,
                )

        return self

    def connect_nodes(
        self,
        connection_probability: float = 0.3,
        connection_pattern: str = "random",
    ) -> TNFRNetwork:
        """Connect nodes according to specified topology pattern.

        Establishes coupling between nodes using common network patterns.
        Connections enable resonance and phase synchronization between nodes.

        Parameters
        ----------
        connection_probability : float, default=0.3
            For random pattern: probability of edge between any two nodes.
            For small_world: rewiring probability (Watts-Strogatz model).
        connection_pattern : str, default="random"
            Topology pattern to use. Options:
            - "random": Erdős-Rényi random graph
            - "ring": Each node connects to next in circle
            - "small_world": Watts-Strogatz small-world network

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Raises
        ------
        ValueError
            If graph has no nodes or invalid pattern specified.

        Examples
        --------
        Create random network:

        >>> network = TNFRNetwork().add_nodes(10).connect_nodes(0.3, "random")

        Create ring lattice:

        >>> network = TNFRNetwork().add_nodes(15).connect_nodes(pattern="ring")

        Create small-world network:

        >>> network = TNFRNetwork().add_nodes(20).connect_nodes(0.1, "small_world")
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No nodes in graph. Call add_nodes() first.")

        nodes = list(self._graph.nodes())

        if connection_pattern == "random":
            # Erdős-Rényi random graph
            if _HAS_NUMPY:
                for i, node1 in enumerate(nodes):
                    for node2 in nodes[i + 1 :]:
                        if self._rng.random() < connection_probability:
                            self._graph.add_edge(node1, node2)
            else:
                import random

                for i, node1 in enumerate(nodes):
                    for node2 in nodes[i + 1 :]:
                        if random.random() < connection_probability:
                            self._graph.add_edge(node1, node2)

        elif connection_pattern == "ring":
            # Ring lattice
            for i in range(len(nodes)):
                next_node = nodes[(i + 1) % len(nodes)]
                self._graph.add_edge(nodes[i], next_node)

        elif connection_pattern == "small_world":
            # Watts-Strogatz small-world network
            # Start with ring lattice, then rewire
            k = max(4, int(len(nodes) * 0.1))  # ~10% degree, minimum 4

            # Create initial ring with k nearest neighbors
            for i in range(len(nodes)):
                for j in range(1, k // 2 + 1):
                    target = (i + j) % len(nodes)
                    if nodes[i] != nodes[target]:  # Avoid self-loops
                        self._graph.add_edge(nodes[i], nodes[target])

            # Rewire edges with given probability
            edges = list(self._graph.edges())
            if _HAS_NUMPY:
                for u, v in edges:
                    if self._rng.random() < connection_probability:
                        # Remove edge and create new random edge
                        self._graph.remove_edge(u, v)
                        # Find node not already connected
                        candidates = [
                            n
                            for n in nodes
                            if n != u and not self._graph.has_edge(u, n)
                        ]
                        if candidates:
                            idx = int(self._rng.randint(0, len(candidates)))
                            if idx >= len(candidates):
                                idx = len(candidates) - 1
                            w = candidates[idx]
                            self._graph.add_edge(u, w)
            else:
                import random

                for u, v in edges:
                    if random.random() < connection_probability:
                        self._graph.remove_edge(u, v)
                        candidates = [
                            n
                            for n in nodes
                            if n != u and not self._graph.has_edge(u, n)
                        ]
                        if candidates:
                            w = random.choice(candidates)
                            self._graph.add_edge(u, w)

        else:
            available = ", ".join(["random", "ring", "small_world"])
            raise ValueError(
                f"Unknown connection pattern '{connection_pattern}'. "
                f"Available: {available}"
            )

        return self

    def apply_sequence(
        self,
        sequence: str | list[str],
        repeat: int = 1,
        context: dict[str, Any] | None = None,
    ) -> TNFRNetwork:
        """Apply structural operator sequence to evolve the network.

        Executes a validated sequence of TNFR operators that reorganize
        network structure according to the nodal equation ∂EPI/∂t = νf·ΔNFR(t).
        Sequences can be predefined names or custom operator lists. The
        sequence is applied to all nodes in the network.

        Parameters
        ----------
        sequence : str or list[str]
            Either a predefined sequence name or list of operator names.
            Predefined sequences:
            - "basic_activation": [emission, reception, coherence, resonance, silence]
            - "stabilization": [emission, reception, coherence, resonance, recursivity]
            - "creative_mutation": [emission, dissonance, reception, coherence, mutation, resonance, silence]
            - "network_sync": [emission, reception, coherence, coupling, resonance, silence]
            - "exploration": [emission, dissonance, reception, coherence, resonance, transition]
            - "consolidation": [recursivity, reception, coherence, resonance, silence]
        repeat : int, default=1
            Number of times to apply the sequence.
        context : dict, optional
            Additional context for sequence validation (e.g. 'initial_epi_nonzero').

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Raises
        ------
        ValueError
            If graph has no nodes or sequence name is invalid.

        Examples
        --------
        Apply predefined sequence:

        >>> network = (TNFRNetwork()
        ...            .add_nodes(10)
        ...            .connect_nodes(0.3)
        ...            .apply_sequence("basic_activation", repeat=5))

        Apply custom operator sequence:

        >>> network.apply_sequence(["emission", "reception", "coherence", "resonance", "silence"])
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No nodes in graph. Call add_nodes() first.")

        # Expand named sequences
        if isinstance(sequence, str):
            if sequence not in NAMED_SEQUENCES:
                available = ", ".join(sorted(NAMED_SEQUENCES.keys()))
                raise ValueError(
                    f"Unknown sequence '{sequence}'. Available: {available}"
                )
            operator_list = NAMED_SEQUENCES[sequence]
        else:
            operator_list = sequence

        # Validate sequence if configured
        if self._config.validate_invariants:
            validate_sequence(operator_list, context=context)

        # Lock-step network evolution from the canonical SDK primitive: each
        # operator is applied to every node before advancing, honouring the
        # temporal simultaneity of dEPI/dt = vf * dNFR(t). A row-major
        # schedule (whole sequence per node) fractures coupling symmetry.
        from .simple import _run_network_sequence

        _run_network_sequence(
            self._graph,
            operator_list,
            cycles=repeat,
            validate=False,
            context=context,
        )

        return self

    def apply_adaptive_sequence(
        self,
        base_sequence: str = "basic_activation",
        target_coherence: float = COHERENCE_STRONG,
    ) -> "TNFRNetwork":
        """Apply adaptive sequence selection based on network state.

        Selects a canonical sequence from the current coherence C(t), keyed
        on the canonical C(t) telemetry marks (AGENTS.md §7):

        - ``C < COHERENCE_FRAGMENTATION`` (~0.2415): the network is breaking
          up -> ``"healing"``.
        - ``COHERENCE_FRAGMENTATION <= C < target_coherence``: it consolidates
          -> ``"stabilization"``.
        - ``C >= target_coherence`` (default ``COHERENCE_STRONG`` ~0.75):
          strong enough to explore -> ``"optimization"`` (>5 nodes) or
          ``"innovation"``.

        Parameters
        ----------
        base_sequence : str, default="basic_activation"
            Fallback sequence when the graph has no nodes.
        target_coherence : float, default=COHERENCE_STRONG
            Upper coherence mark separating consolidation from exploration;
            defaults to the canonical strong-coherence mark.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.
        """
        if not self._graph.nodes:
            return self.apply_sequence(base_sequence)

        current_coherence = compute_coherence(self._graph)

        if current_coherence < COHERENCE_FRAGMENTATION:
            selected_sequence = "healing"
        elif current_coherence < target_coherence:
            selected_sequence = "stabilization"
        else:
            selected_sequence = (
                "optimization" if len(self._graph.nodes) > 5 else "innovation"
            )

        return self.apply_sequence(selected_sequence)

    def apply_multiple_sequences(
        self, sequences: list[tuple[str, dict[str, Any] | None, int]]
    ) -> "TNFRNetwork":
        """Apply multiple sequences in order.

        Parameters
        ----------
        sequences : list[tuple[str, dict[str, Any] | None, int]]
            list of (sequence_name, context, repeat) tuples.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.
        """
        for seq_name, context, repeat in sequences:
            self.apply_sequence(seq_name, context=context, repeat=repeat)
        return self

    def apply_sequence_chain(self, chain_pattern: str = "standard") -> "TNFRNetwork":
        """Apply predefined chains of sequences for complex behaviors.

        Parameters
        ----------
        chain_pattern : str, default="standard"
            type of sequence chain: "standard", "learning", "innovation", "recovery"

        Returns
        -------
        TNFRNetwork
            Self for method chaining.
        """
        chains = {
            "standard": [
                ("basic_activation", None, 1),
                ("harmonization", None, 1),
                ("optimization", None, 1),
            ],
            "learning": [
                ("basic_activation", None, 1),
                ("progressive_learning", None, 2),
                ("consolidation", None, 1),
            ],
            "innovation": [
                ("stabilization", None, 1),
                ("innovation", None, 1),
                ("amplification", None, 1),
                ("consolidation", None, 1),
            ],
            "recovery": [
                ("recovery", None, 1),
                ("healing", None, 2),
                ("harmonization", None, 1),
            ],
            "transformation": [
                ("stabilization", None, 1),
                ("deep_transformation", None, 1),
                ("healing", None, 1),
                ("consolidation", None, 1),
            ],
        }

        if chain_pattern not in chains:
            available = ", ".join(chains.keys())
            raise ValueError(
                f"Unknown chain pattern '{chain_pattern}'. Available: {available}"
            )

        return self.apply_multiple_sequences(chains[chain_pattern])

    def measure(self) -> NetworkResults:
        """Calculate TNFR metrics and return structured results.

        Computes coherence C(t), sense indices Si, and ΔNFR values for
        all nodes, plus aggregate statistics. Results are cached internally
        and returned as a :class:`NetworkResults` instance.

        Returns
        -------
        NetworkResults
            Structured container with all computed metrics.

        Raises
        ------
        ValueError
            If no network has been created.

        Examples
        --------
        Measure and display results:

        >>> results = network.measure()
        >>> print(results.summary())

        Access specific metrics:

        >>> coherence = results.coherence
        >>> si_values = results.sense_indices
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No network created. Use add_nodes() first.")

        # Compute coherence C(t)
        coherence = compute_coherence(self._graph)

        # Compute sense indices Si for all nodes
        si_dict = compute_Si(self._graph, inplace=False)

        # Extract ΔNFR values
        delta_nfr_dict = {}
        for node_id in self._graph.nodes():
            delta_nfr_dict[node_id] = get_attr(
                self._graph.nodes[node_id], ALIAS_DNFR, 0.0
            )

        # Compute aggregate statistics
        vf_sum = 0.0
        phase_sum = 0.0
        node_count = self._graph.number_of_nodes()

        for node_id in self._graph.nodes():
            node_data = self._graph.nodes[node_id]
            vf_sum += get_attr(node_data, ALIAS_VF, 0.0)
            phase_sum += get_attr(node_data, ALIAS_THETA, 0.0)

        avg_vf = vf_sum / node_count if node_count > 0 else 0.0
        avg_phase = phase_sum / node_count if node_count > 0 else 0.0

        # Unified field telemetry (Nov 28, 2025 - comprehensive audit integration)
        unified_telemetry = {}
        try:
            from ..physics.fields import compute_unified_telemetry

            unified_telemetry = compute_unified_telemetry(self._graph)
        except (ImportError, Exception):
            # Graceful degradation if unified fields not available
            pass

        # Create and cache results
        self._results = NetworkResults(
            coherence=coherence,
            sense_indices=si_dict,
            delta_nfr=delta_nfr_dict,
            graph=self._graph,
            avg_vf=avg_vf,
            avg_phase=avg_phase,
            unified_fields=unified_telemetry,  # New field for unified telemetry
        )

        return self._results

    def apply_canonical_sequence(
        self,
        sequence_name: str,
        node: int | None = None,
        collect_metrics: bool = True,
    ) -> TNFRNetwork:
        """Apply a canonical predefined operator sequence from TNFR theory.

        Executes one of the 6 archetypal sequences involving OZ (Dissonance)
        from "El pulso que nos atraviesa" (Table 2.5). These sequences represent
        validated structural patterns with documented use cases and domain contexts.

        Parameters
        ----------
        sequence_name : str
            Name of canonical sequence. Available sequences:
            - 'bifurcated_base': OZ → ZHIR (mutation path)
            - 'bifurcated_collapse': OZ → NUL (collapse path)
            - 'therapeutic_protocol': Complete healing cycle
            - 'theory_system': Epistemological construction
            - 'full_deployment': Complete reorganization trajectory
            - 'mod_stabilizer': OZ → ZHIR → IL (reusable macro)
        node : int, optional
            Target node ID. If None, applies to the most recently added node.
        collect_metrics : bool, default=True
            Whether to collect detailed operator metrics during execution.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Raises
        ------
        ValueError
            If sequence_name is not recognized or network has no nodes.

        Examples
        --------
        Apply therapeutic protocol:

        >>> net = TNFRNetwork("therapy_session")
        >>> net.add_nodes(1).apply_canonical_sequence("therapeutic_protocol")
        >>> results = net.measure()
        >>> print(f"Coherence: {results.coherence:.3f}")

        Apply MOD_STABILIZER as reusable transformation module:

        >>> net = TNFRNetwork("modular")
        >>> net.add_nodes(1)
        >>> net.apply_canonical_sequence("mod_stabilizer").measure()

        See Also
        --------
        list_canonical_sequences : list available sequences with filters
        apply_sequence : Apply predefined or custom operator sequences

        Notes
        -----
        Canonical sequences are archetypal patterns from TNFR theory documented
        in "El pulso que nos atraviesa", Tabla 2.5. Each sequence has been
        validated for structural coherence and grammar compliance.
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No nodes in graph. Call add_nodes() first.")

        # Import canonical sequences registry
        from ..operators.canonical_patterns import CANONICAL_SEQUENCES

        if sequence_name not in CANONICAL_SEQUENCES:
            available = ", ".join(sorted(CANONICAL_SEQUENCES.keys()))
            raise ValueError(
                f"Unknown canonical sequence '{sequence_name}'. "
                f"Available: {available}"
            )

        sequence = CANONICAL_SEQUENCES[sequence_name]

        # Determine target node
        if node is None:
            # Use last added node
            nodes_list = list(self._graph.nodes())
            target_node = nodes_list[-1] if nodes_list else 0
        else:
            target_node = node
            if target_node not in self._graph.nodes():
                raise ValueError(f"Node {target_node} not found in network")

        # Configure metrics collection
        self._graph.graph["COLLECT_OPERATOR_METRICS"] = collect_metrics

        # Map glyphs to operator instances via the canonical single sources:
        # grammar_types.GLYPH_TO_FUNCTION (glyph -> function name) and
        # registry.OPERATORS (function name -> operator class).
        from ..operators.grammar_types import GLYPH_TO_FUNCTION
        from ..operators.registry import OPERATORS, _ensure_loaded

        _ensure_loaded()
        operators = [OPERATORS[GLYPH_TO_FUNCTION[g]]() for g in sequence.glyphs]
        run_sequence(self._graph, target_node, operators)

        return self

    def list_canonical_sequences(
        self,
        domain: str | None = None,
        with_oz: bool = False,
    ) -> dict[str, Any]:
        """list available canonical sequences with optional filters.

        Returns a dictionary of canonical operator sequences from TNFR theory.
        Sequences can be filtered by domain or by presence of OZ (Dissonance).

        Parameters
        ----------
        domain : str, optional
            Filter by domain. Options:
            - 'general': Cross-domain patterns
            - 'biomedical': Therapeutic and healing sequences
            - 'cognitive': Epistemological and learning patterns
            - 'social': Organizational and collective sequences
        with_oz : bool, default=False
            If True, only return sequences containing OZ (Dissonance) operator.

        Returns
        -------
        dict
            Dictionary mapping sequence names to CanonicalSequence objects.
            Each entry contains: name, glyphs, pattern_type, description,
            use_cases, domain, and references.

        Examples
        --------
        list all canonical sequences:

        >>> net = TNFRNetwork("explorer")
        >>> sequences = net.list_canonical_sequences()
        >>> for name in sequences:
        ...     print(name)
        bifurcated_base
        bifurcated_collapse
        therapeutic_protocol
        theory_system
        full_deployment
        mod_stabilizer

        list only sequences with OZ:

        >>> oz_sequences = net.list_canonical_sequences(with_oz=True)
        >>> print(f"Found {len(oz_sequences)} sequences with OZ")
        Found 6 sequences with OZ

        list biomedical domain sequences:

        >>> bio_sequences = net.list_canonical_sequences(domain="biomedical")
        >>> for name, seq in bio_sequences.items():
        ...     print(f"{name}: {seq.description[:50]}...")

        See Also
        --------
        apply_canonical_sequence : Apply a canonical sequence to the network
        """
        from ..operators.canonical_patterns import CANONICAL_SEQUENCES
        from ..types import Glyph

        sequences = CANONICAL_SEQUENCES.copy()

        # Filter by domain if specified
        if domain is not None:
            sequences = {
                name: seq for name, seq in sequences.items() if seq.domain == domain
            }

        # Filter by OZ presence if requested
        if with_oz:
            sequences = {
                name: seq for name, seq in sequences.items() if Glyph.OZ in seq.glyphs
            }

        return sequences

    def visualize(self, **kwargs: Any) -> TNFRNetwork:
        """Visualize the network with TNFR metrics.

        Creates a visual representation of the network showing node states
        and connections. Requires matplotlib to be installed.

        Parameters
        ----------
        **kwargs
            Additional arguments passed to visualization function.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Raises
        ------
        ImportError
            If matplotlib is not installed.
        ValueError
            If no network has been created.

        Notes
        -----
        This is a placeholder for future visualization functionality.
        Current implementation will raise NotImplementedError.
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No network created. Use add_nodes() first.")

        # Compute metrics if not done yet
        if self._results is None:
            self.measure()

        # Visualization will be implemented in future PR
        raise NotImplementedError(
            "Visualization functionality will be added in a future update. "
            "Use NetworkX's drawing functions directly on network._graph for now."
        )

    def save(self, filepath: str | Path) -> TNFRNetwork:
        """Save network state and results to file.

        Serializes the network graph and computed metrics to a file for
        later analysis or reproduction.

        Parameters
        ----------
        filepath : str or Path
            Path where network data should be saved.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Raises
        ------
        ValueError
            If no network has been created.

        Notes
        -----
        This is a placeholder for future I/O functionality.
        Current implementation will raise NotImplementedError.
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No network created. Use add_nodes() first.")

        # Compute metrics if not done yet
        if self._results is None:
            self.measure()

        # I/O functionality will be implemented in future PR
        raise NotImplementedError(
            "Save functionality will be added in a future update. "
            "Use networkx.write_gpickle or similar for now."
        )

    @property
    def graph(self) -> nx.Graph:
        """Access the underlying NetworkX graph.

        Returns
        -------
        nx.Graph
            The NetworkX graph with TNFR node attributes.

        Raises
        ------
        ValueError
            If no network has been created yet.
        """
        if self._graph is None:
            raise ValueError("No network created. Use add_nodes() first.")
        return self._graph

    def get_node_count(self) -> int:
        """Get the number of nodes in the network.

        Returns
        -------
        int
            Number of nodes.

        Raises
        ------
        ValueError
            If no network has been created.
        """
        if self._graph is None:
            raise ValueError("No network created. Use add_nodes() first.")
        return self._graph.number_of_nodes()

    def get_edge_count(self) -> int:
        """Get the number of edges in the network.

        Returns
        -------
        int
            Number of edges.

        Raises
        ------
        ValueError
            If no network has been created.
        """
        if self._graph is None:
            raise ValueError("No network created. Use add_nodes() first.")
        return self._graph.number_of_edges()

    def get_average_degree(self) -> float:
        """Get the average degree of nodes in the network.

        Returns
        -------
        float
            Average node degree.

        Raises
        ------
        ValueError
            If no network has been created.
        """
        if self._graph is None:
            raise ValueError("No network created. Use add_nodes() first.")
        if self._graph.number_of_nodes() == 0:
            return 0.0
        return 2.0 * self._graph.number_of_edges() / self._graph.number_of_nodes()

    def get_density(self) -> float:
        """Get the density of the network.

        Network density is the ratio of actual edges to possible edges.

        Returns
        -------
        float
            Network density between 0 and 1.

        Raises
        ------
        ValueError
            If no network has been created.
        """
        if self._graph is None:
            raise ValueError("No network created. Use add_nodes() first.")
        n = self._graph.number_of_nodes()
        if n <= 1:
            return 0.0
        m = self._graph.number_of_edges()
        max_edges = n * (n - 1) / 2
        return m / max_edges if max_edges > 0 else 0.0

    def clone(self) -> TNFRNetwork:
        """Create a copy of the network structure.

        Returns
        -------
        TNFRNetwork
            A new network with copied structure. Note that this copies
            the graph structure but not all internal state (like locks).

        Raises
        ------
        ValueError
            If no network has been created.
        """
        if self._graph is None:
            raise ValueError("No network created. Use add_nodes() first.")

        import networkx as nx

        new_network = TNFRNetwork(f"{self.name}_copy", config=self._config)
        # Use NetworkX's copy method which handles TNFR graphs properly
        new_network._graph = nx.Graph(self._graph)
        new_network._node_counter = self._node_counter
        return new_network

    def reset(self) -> TNFRNetwork:
        """Reset the network to empty state.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.
        """
        self._graph = None
        self._results = None
        self._node_counter = 0
        return self

    # -------------------------------------------------------------------------
    # Auto-optimization methods (NEW - Nov 28, 2025)
    # -------------------------------------------------------------------------

    def analyze_optimization_potential(self) -> dict[str, Any]:
        """
        Analyze mathematical optimization potential for the current network.

        Uses unified field analysis and mathematical structure inspection
        to identify optimization opportunities automatically.

        Returns
        -------
        dict[str, Any]
            Analysis results including:
            - field_analysis: Unified field characteristics
            - optimization_recommendations: Specific strategies
            - predicted_improvements: Expected performance gains

        Raises
        ------
        ValueError
            If no network has been created.

        Examples
        --------
        Analyze optimization opportunities:

        >>> analysis = network.analyze_optimization_potential()
        >>> print(f"Recommendations: {analysis['optimization_recommendations']}")
        >>> print(f"Predicted speedup: {analysis['predicted_improvements']}")
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No network created. Use add_nodes() first.")

        if not _AUTO_OPTIMIZATION_AVAILABLE:
            return {
                "optimization_available": False,
                "error": "Auto-optimization engine not available",
                "field_analysis": {},
                "optimization_recommendations": [],
                "predicted_improvements": {},
            }

        try:
            analysis = analyze_optimization_potential(self._graph)
            return {"optimization_available": True, **analysis}
        except Exception as e:
            return {
                "optimization_available": False,
                "error": str(e),
                "field_analysis": {},
                "optimization_recommendations": [],
                "predicted_improvements": {},
            }

    def auto_optimize(self, operation_type: str = "network_simulation") -> TNFRNetwork:
        """
        Automatically apply optimization strategies based on mathematical analysis.

        This method uses the self-optimizing engine to analyze the current
        network state and automatically apply the best optimization strategy.

        Parameters
        ----------
        operation_type : str, default="network_simulation"
            type of operation to optimize for.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Raises
        ------
        ValueError
            If no network has been created.

        Examples
        --------
        Apply automatic optimization:

        >>> network.auto_optimize("network_simulation")
        >>> results = network.measure()  # Optimized computation
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No network created. Use add_nodes() first.")

        if not _AUTO_OPTIMIZATION_AVAILABLE:
            print("Warning: Auto-optimization engine not available, skipping.")
            return self

        try:
            optimization_result = auto_optimize_field_computation(
                self._graph, operation_type=operation_type
            )

            # Store optimization information for future reference
            if not hasattr(self, "_optimization_history"):
                self._optimization_history = []

            self._optimization_history.append(
                {
                    "timestamp": __import__("time").time(),
                    "operation_type": operation_type,
                    "result": optimization_result,
                }
            )

            if optimization_result.get("optimization_applied", False):
                print(
                    f"Optimization applied: {optimization_result.get('strategy_used', 'unknown')}"
                )
                improvement = optimization_result.get("performance_improvement", 1.0)
                if improvement > _MIN_REPORTABLE_SPEEDUP:
                    print(f"   Expected speedup: {improvement:.2f}x")
            else:
                print("No optimization applied (using standard computation)")

        except Exception as e:
            print(f"Warning: Auto-optimization failed: {e}")

        return self

    def learn_from_performance(
        self, performance_data: dict[str, Any] | None = None
    ) -> TNFRNetwork:
        """
        Learn optimization strategies from performance data.

        Records performance experience and updates optimization policies
        for future automatic optimization decisions.

        Parameters
        ----------
        performance_data : dict[str, Any], optional
            Performance metrics to learn from. If None, uses internal timing.

        Returns
        -------
        TNFRNetwork
            Self for method chaining.

        Examples
        --------
        Record performance learning:

        >>> network.learn_from_performance({"execution_time": 1.23, "accuracy": 0.99})
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No network created. Use add_nodes() first.")

        if not _AUTO_OPTIMIZATION_AVAILABLE:
            return self

        try:
            # Create self-optimizing engine
            engine = TNFRSelfOptimizingEngine(
                optimization_objective=OptimizationObjective.BALANCE_ALL
            )

            # Prepare experience data
            experience_data = {
                "graph_properties": {
                    "nodes": self._graph.number_of_nodes(),
                    "edges": self._graph.number_of_edges(),
                    "density": (
                        2
                        * self._graph.number_of_edges()
                        / max(
                            1,
                            self._graph.number_of_nodes()
                            * (self._graph.number_of_nodes() - 1),
                        )
                    ),
                },
                "operation_type": "sdk_operation",
                "performance_metrics": performance_data or {},
                "timestamp": __import__("time").time(),
                "success": True,
            }

            # This would normally create and record an OptimizationExperience
            # For now, just store the learning data
            if not hasattr(self, "_learning_history"):
                self._learning_history = []

            self._learning_history.append(experience_data)

        except Exception as e:
            print(f"Warning: Performance learning failed: {e}")

        return self

    def get_optimization_recommendations(
        self, operation_type: str = "measurement"
    ) -> dict[str, Any]:
        """
        Get optimization strategy recommendations for specific operation.

        Parameters
        ----------
        operation_type : str, default="measurement"
            type of operation to get recommendations for.

        Returns
        -------
        dict[str, Any]
            Optimization recommendations and strategy analysis.

        Raises
        ------
        ValueError
            If no network has been created.
        """
        if self._graph is None or self._graph.number_of_nodes() == 0:
            raise ValueError("No network created. Use add_nodes() first.")

        if not _AUTO_OPTIMIZATION_AVAILABLE:
            return {
                "recommendations_available": False,
                "error": "Auto-optimization engine not available",
            }

        try:
            recommendations = recommend_field_optimization_strategy(
                self._graph, operation_type
            )
            return {"recommendations_available": True, **recommendations}
        except Exception as e:
            return {"recommendations_available": False, "error": str(e)}

    def export_to_dict(self) -> dict:
        """Export network structure to dictionary format.

        Returns
        -------
        dict
            Dictionary with network metadata and structure.

        Raises
        ------
        ValueError
            If no network has been created.
        """
        if self._graph is None:
            raise ValueError("No network created. Use add_nodes() first.")

        # Measure if not done yet
        if self._results is None:
            self.measure()

        return {
            "name": self.name,
            "metadata": {
                "nodes": self.get_node_count(),
                "edges": self.get_edge_count(),
                "density": self.get_density(),
                "average_degree": self.get_average_degree(),
            },
            "metrics": self._results.to_dict() if self._results else None,
            "config": {
                "random_seed": self._config.random_seed,
                "validate_invariants": self._config.validate_invariants,
                "vf_range": self._config.default_vf_range,
                "epi_range": self._config.default_epi_range,
            },
        }