Skip to main content

Resonant Fractal Nature Theory (TNFR) - Computational engine for modeling coherent patterns through resonance dynamics

Project description

TNFR Python Engine

DOI PyPI version Python 3.10+ License: MIT

Canonical computational implementation of TNFR - A paradigm shift from modeling "things" to modeling coherent patterns that persist through resonance.

What is TNFR?

Resonant Fractal Nature Theory proposes a radical reconceptualization of reality:

Traditional ViewTNFR View:

  • Objects exist independently → Patterns exist through resonance
  • Causality (A causes B) → Co-organization (A and B synchronize)
  • Static properties → Dynamic reorganization
  • Isolated systems → Coupled networks
  • Descriptive models → Generative dynamics

Reality is not made of "things" but of coherence—structures that persist in networks because they resonate with their environment.

Key Features

🎯 The 13 Structural Operators

The complete TNFR operator set for modeling coherent structural dynamics.

Canonical Status: The operator registry is now immutable – exactly these 13 operators, no more. Dynamic discovery, auto-registration decorators, metaclass telemetry and reload scripts were removed (see CHANGELOG 9.1.0). All structural evolution MUST occur through this fixed set (grammar U1-U4).

  • AL (Emission) - Pattern creation from vacuum
  • EN (Reception) - Information capture and integration
  • IL (Coherence) - Stabilization through negative feedback
  • OZ (Dissonance) - Controlled instability and exploration
  • UM (Coupling) - Network formation via phase sync
  • RA (Resonance) - Pattern amplification and propagation
  • SHA (Silence) - Temporal pause, observation windows
  • VAL (Expansion) - Structural complexity increase
  • NUL (Contraction) - Dimensionality reduction
  • THOL (Self-organization) - Spontaneous autopoietic structuring
  • ZHIR (Mutation) - Phase transformation at threshold
  • NAV (Transition) - Regime shift, state changes
  • REMESH (Recursivity) - Multi-scale fractal operations

📏 Unified Grammar (U1-U6)

Rigorous physics-derived rules ensuring structural validity:

  • U1: Structural Initiation & Closure
  • U2: Convergence & Boundedness
  • U3: Resonant Coupling (phase verification)
  • U4: Bifurcation Dynamics
  • U5: Frequency Constraints
  • U6: Sequential Composition

🔬 Four Canonical Fields

Essential structural field computations:

  • Φ_s: Structural potential
  • |∇φ|: Phase gradient (reorganization pressure)
  • K_φ: Phase curvature (bifurcation predictor)
  • ξ_C: Coherence length (network correlation scale)

📊 Telemetry & Metrics

Comprehensive observability:

  • C(t): Total coherence [0, 1]
  • Si: Sense index (reorganization capacity)
  • ΔNFR: Reorganization gradient
  • νf: Structural frequency (Hz_str)
  • φ: Phase synchrony [0, 2π]

🧪 Phase 3 Structural Instrumentation

Unified observability and safety layers (read-only):

  • run_structural_validation combines grammar (U1-U4) + field thresholds.
  • compute_structural_health converts validation output to recommendations.
  • TelemetryEmitter streams coherence, sense index, Φ_s, |∇φ|, K_φ, ξ_C.
  • PerformanceRegistry + perf_guard measure overhead (< ~8% in tests).

Usage:

from tnfr.validation.aggregator import run_structural_validation
from tnfr.validation.health import compute_structural_health
from tnfr.performance.guardrails import PerformanceRegistry

perf = PerformanceRegistry()
report = run_structural_validation(
  G,
  sequence=["AL","UM","IL","SHA"],
  perf_registry=perf,
)
health = compute_structural_health(report)
print(report.risk_level, health.recommendations)
print(perf.summary())

Telemetry:

from tnfr.metrics.telemetry import TelemetryEmitter

with TelemetryEmitter("results/run.telemetry.jsonl", human_mirror=True) as em:
  for step, op in enumerate(["AL","UM","IL","SHA"]):
    em.record(G, step=step, operator=op, extra={"sequence_id": "demo"})

Risk levels:

  • low – Grammar valid; no thresholds exceeded.
  • elevated – Local stress: max |∇φ|, |K_φ| pocket, ξ_C watch.
  • critical – Grammar invalid or ΔΦ_s / ξ_C critical breach.

CLI health report:

python scripts/structural_health_report.py --graph random:50:0.15 --sequence AL,UM,IL,SHA

All instrumentation preserves TNFR physics (no state mutation).

Installation

From PyPI (Stable)

pip install tnfr

From Source (Development)

git clone https://github.com/fermga/TNFR-Python-Engine.git
cd TNFR-Python-Engine
pip install -e ".[dev-minimal]"

Dependency Profiles

# Core functionality only
pip install .

# Development tools (linting, formatting, type checking)
pip install -e ".[dev-minimal]"

# Full test suite
pip install -e ".[test-all]"

# Documentation building
pip install -e ".[docs]"

# Visualization support
pip install -e ".[viz-basic]"

# Alternative backends
pip install -e ".[compute-jax]"   # JAX backend
pip install -e ".[compute-torch]"  # PyTorch backend

Quick Start

Hello World (3 lines!)

from tnfr.sdk import TNFRNetwork

network = TNFRNetwork("hello_world")
network.add_nodes(10).connect_nodes(0.3, "random")
results = network.apply_sequence("basic_activation", repeat=3).measure()

print(f"Coherence: {results.coherence:.3f}")

Using Operators Directly

import networkx as nx
from tnfr.operators.definitions import Emission, Coherence, Resonance
from tnfr.operators.grammar import validate_sequence
from tnfr.metrics.coherence import compute_coherence

# Create network
G = nx.erdos_renyi_graph(20, 0.2)

# Apply operator sequence
sequence = ["AL", "IL", "RA", "SHA"]
result = validate_sequence(sequence)

if result.valid:
    for node in G.nodes():
        Emission().apply(G, node)
        Coherence().apply(G, node)
        Resonance().apply(G, node)
    
    # Measure
    C_t = compute_coherence(G)
    print(f"Network coherence: {C_t:.3f}")

Domain Applications

# Therapeutic patterns (crisis, trauma, healing)
python examples/domain_applications/therapeutic_patterns.py

# Educational patterns (learning, mastery, breakthrough)
python examples/domain_applications/educational_patterns.py

# Biological systems (metabolism, evolution)
python examples/domain_applications/biological_patterns.py

Documentation

📚 Complete Documentation - Full API reference, tutorials, and theory

🎓 Key Resources:

🔬 Advanced Topics:

Repository Structure

TNFR-Python-Engine/
├── src/tnfr/              # Core TNFR implementation
│   ├── operators/         # Canonical operator system (immutable registry)
│   │   ├── definitions.py        # Facade (backward compatibility)
│   │   ├── definitions_base.py   # Operator base class (no dynamic metaclass)
│   │   ├── emission.py           # AL operator
│   │   ├── coherence.py          # IL operator
│   │   └── ... (13 operators)    # Individual operator modules (canonical)
│   ├── operators/grammar/ # Unified grammar constraints (Phase 1)
│   │   ├── grammar.py            # Facade (unified validation)
│   │   ├── u1_initiation_closure.py
│   │   ├── u2_convergence_boundedness.py
│   │   └── ... (8 constraint modules)
│   ├── metrics/           # Modular metrics system (Phase 1)
│   │   ├── metrics.py            # Facade (backward compatibility)
│   │   ├── coherence.py          # C(t) computation
│   │   ├── sense_index.py        # Si measurement
│   │   ├── phase_sync.py         # Phase synchronization
│   │   └── telemetry.py          # Execution tracing
│   ├── physics/           # Canonical fields (Φ_s, |∇φ|, K_φ, ξ_C)
│   ├── dynamics/          # Nodal equation integration
│   ├── sdk/               # High-level API
│   └── tutorials/         # Educational modules
├── tests/                 # Comprehensive test suite (975/976 passing)
├── examples/              # Domain applications
├── docs/                  # Documentation source
├── notebooks/             # Jupyter notebooks
├── benchmarks/            # Performance testing
└── scripts/               # Maintenance utilities

Testing

# Run all tests
pytest

# Fast smoke tests (examples + telemetry)
make smoke-tests          # Unix/Linux
.\make.cmd smoke-tests    # Windows

# Specific test suites
pytest tests/unit/mathematics/         # Math tests
pytest tests/examples/                 # Example validation
pytest tests/integration/              # Integration tests

Repository Maintenance

# Clean generated artifacts
make clean                # Unix/Linux
.\make.cmd clean          # Windows

# Check repository health
python scripts/repo_health_check.py

# Verify documentation references
python scripts/verify_internal_references.py

# Security audit
pip-audit

See REPO_OPTIMIZATION_PLAN.md for cleanup routines and targeted test bundles.

Performance

Grammar 2.0 optimizations deliver:

  • Sequence validation: <1ms for typical sequences (10-20 operators)
  • Coherence computation: O(N) for N nodes
  • Phase gradient: O(E) for E edges
  • Memory footprint: ~50MB for 10k-node networks

See tools/performance/ for benchmarking tools.

Note on Python executable for local runs

  • Windows: prefer ./test-env/Scripts/python.exe
  • macOS/Linux: prefer ./test-env/bin/python

Using the workspace virtual environment avoids mismatches with system Pythons that may lack the latest telemetry aliases or configuration.

Parse precision_modes drift (benchmark_results.json)

After running ./test-env/Scripts/python.exe run_benchmark.py (Windows) or ./test-env/bin/python run_benchmark.py (macOS/Linux), parse numeric drift for the precision_modes track:

import json

with open("benchmark_results.json", "r", encoding="utf-8") as f:
  data = json.load(f)

drift_entries = data.get("precision_modes", {}).get("drift", [])
for entry in drift_entries:
  size = entry.get("size")
  phi_s = entry.get("phi_s_max_abs")
  grad = entry.get("grad_max_abs")
  curv = entry.get("curv_max_abs")
  xi_c = entry.get("xi_c_abs")
  print(
    f"N={size:>4}  ΔΦ_s_max={phi_s:.3e}  |∇φ|_max={grad:.3e}  "
    f"K_φ_max={curv:.3e}  ξ_C_abs={xi_c if xi_c is not None else 'nan'}"
  )

This reports the maximum absolute difference between standard and high precision modes for the canonical fields per graph size.

PowerShell one-liners (Windows)

# Largest ΔΦ_s drift row
Get-Content .\benchmark_results.json | ConvertFrom-Json |
  Select-Object -ExpandProperty precision_modes |
  Select-Object -ExpandProperty drift |
  Sort-Object -Property phi_s_max_abs -Descending |
  Select-Object -First 1

# Largest |∇φ| drift row
Get-Content .\benchmark_results.json | ConvertFrom-Json |
  Select-Object -ExpandProperty precision_modes |
  Select-Object -ExpandProperty drift |
  Sort-Object -Property grad_max_abs -Descending |
  Select-Object -First 1

# Largest K_φ drift row
Get-Content .\benchmark_results.json | ConvertFrom-Json |
  Select-Object -ExpandProperty precision_modes |
  Select-Object -ExpandProperty drift |
  Sort-Object -Property curv_max_abs -Descending |
  Select-Object -First 1

# Largest ξ_C drift row (skip NaNs)
Get-Content .\benchmark_results.json | ConvertFrom-Json |
  Select-Object -ExpandProperty precision_modes |
  Select-Object -ExpandProperty drift |
  Where-Object { $_.xi_c_abs -ne $null -and -not [double]::IsNaN([double]$_.xi_c_abs) } |
  Sort-Object -Property xi_c_abs -Descending |
  Select-Object -First 1

Contributing

We welcome contributions! Please see CONTRIBUTING.md for:

  • Code of conduct
  • Development workflow
  • Testing requirements
  • Documentation standards
  • Pull request process

For TNFR theory development, consult AGENTS.md - the canonical guide for maintaining theoretical integrity. Phase 3 adds structural validation, health assessment and guardrails; see docs/STRUCTURAL_HEALTH.md for thresholds & recommendations.

Citation

If you use TNFR in your research, please cite:

@software{tnfr_python_engine,
  author = {Martinez Gamo, F. F.},
  title = {TNFR-Python-Engine: Resonant Fractal Nature Theory Implementation},
  year = {2025},
  version = {9.0.2},
  doi = {10.5281/zenodo.17602861},
  url = {https://github.com/fermga/TNFR-Python-Engine}
}

See CITATION.cff for machine-readable citation metadata.

License

This project is licensed under the MIT License - see LICENSE.md for details.

Support & Community

Acknowledgments

TNFR represents a fundamental reconceptualization of modeling approaches, prioritizing coherence over objects, resonance over causality, and structural dynamics over static properties.

Think in patterns, not objects. Think in dynamics, not states. Think in networks, not individuals.


Reality is not made of things—it's made of resonance. Code accordingly.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tnfr-9.0.4.tar.gz (822.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tnfr-9.0.4-py3-none-any.whl (1.0 MB view details)

Uploaded Python 3

File details

Details for the file tnfr-9.0.4.tar.gz.

File metadata

  • Download URL: tnfr-9.0.4.tar.gz
  • Upload date:
  • Size: 822.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.6

File hashes

Hashes for tnfr-9.0.4.tar.gz
Algorithm Hash digest
SHA256 7b9cc675555cc1589aafa6eedd95737b30ea7893564bb644fc061fb53f344d96
MD5 cecaf9ae1a3d4eb99d74c1bb1cc578d3
BLAKE2b-256 4c25bfd08ee0c3f0fde9ef16fc0c8839159c49b65a4837987f0f4a9adbfa3a81

See more details on using hashes here.

File details

Details for the file tnfr-9.0.4-py3-none-any.whl.

File metadata

  • Download URL: tnfr-9.0.4-py3-none-any.whl
  • Upload date:
  • Size: 1.0 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.6

File hashes

Hashes for tnfr-9.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 d585f018696d5eee6d8b96e6af06439a83c0a6563cc7680b4f902606b38dccea
MD5 d7e582b25c3cfe29d97faaad004f6a23
BLAKE2b-256 e214f9ec5becfa7e31f6f6a6bd3ce049d5b83f2e735a18c99b9b7d68ab8e6667

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page