Version: 0.0.3.5
Status: Production-ready framework with mathematical foundations
Foundation: the nodal equation ∂EPI/∂t = νf·ΔNFR(t) and its minimal structural-field tetrad (Φ_s, |∇φ|, K_φ, ξ_C)
This guide details the TNFR Python Engine architecture. The engine provides a complex systems framework whose physics derives from the nodal equation; structural state is read out through the four-field tetrad.
Core Principle: Physics derives from the nodal equation; structural state is read through the tetrad of fields.
On the constants. The four fields are the four orders of the discrete derivative tower (the tetrad), derived from the nodal equation. Only π is a genuine structural scale — the phase-wrap bound shared by |∇φ| and K_φ. The coherence length is set by the spectral gap (ξ_C ∝ 1/√λ₂) and the Φ_s confinement bound is π-derived; φ, γ, e are not structural scales. Every parameter other than π is either derived from the nodal dynamics / spectral gap or is a free operational parameter — not a derived structural constant. (γ/π is not the |∇φ| scale — the measured sync onset is ≈ 0.29 and σ-dependent.)
The TNFR Engine is built on four pillars:
TNFR Engine features a mature, production-grade architecture grounded in the nodal equation, with self-optimization capabilities and complete domain extensibility.
src/tnfr/ # ~346 files, ~104k LOC
├── constants/canonical.py # structural + operational constants (only π is a genuine structural scale)
├── operators/ # 13 Canonical operators + U1-U6 grammar
│ ├── grammar.py # Unified grammar validation
│ ├── grammar_dynamics.py # Grammar-aware dynamic selection
│ └── grammar_application.py # Pre-validated operator application
├── physics/ # Structural fields + conservation
│ ├── fields.py # Tetrad (Φ_s, |∇φ|, K_φ, ξ_C)
│ ├── conservation.py # Structural Conservation Theorem
│ └── integrity.py # Closed-loop integrity monitor
├── dynamics/ # Self-optimizing engine + integrators
├── engines/ # Centralized engines hub
├── mathematics/ # Number theory + nodal equation
├── metrics/ # Coherence, Si, phase sync
├── telemetry/ # Unified field monitoring
├── sdk/ # Fluent API + Simple SDK + builders
├── validation/ # Structural health + empirical-arm signal confrontation
├── riemann/ # TNFR-Riemann program (nodal-pulse foundation)
├── navier_stokes/ # TNFR-Navier-Stokes program (conservative two-face reading)
├── yang_mills/ # TNFR-Yang-Mills gap diagnostics
└── factorization/ # Spectral factorization workflowThe engine is structured around mathematically grounded interfaces that enforce TNFR canonicity:
| Interface | Responsibility | Mathematical Basis | Implementation |
|---|---|---|---|
| Canonical Constants | Structural + operational parameters | Nodal equation + field tetrad (π is the one genuine structural scale) | constants/canonical.py |
| Operator Registry | 13 canonical transformations | Nodal equation completeness | operators/definitions.py |
| Grammar Validation | U1-U6 sequence rules | Physics-derived constraints | operators/grammar.py |
| Grammar Dynamics | Grammar-aware operator selection | Incremental U1-U6 checks | operators/grammar_dynamics.py |
| Dynamics Engine | ∂EPI/∂t = νf·ΔNFR integration | Structural manifold calculus | dynamics/canonical.py |
| Field Telemetry | Tetrad monitoring (Φ_s, | ∇φ | ,Ψ,ξ_C) |
| Conservation | Structural conservation law | Noether-like derivation from U1-U6 | physics/conservation.py |
| Integrity Monitor | Operator postcondition verification | 13/13 operator contracts | physics/integrity.py |
| Self-Optimization | Autonomous improvement | Gradient descent on structure | dynamics/self_optimizing_engine.py |
The TNFR Engine has automated optimization of its own structure using unified field telemetry:
from tnfr.dynamics.self_optimizing_engine import TNFRSelfOptimizingEngine
from tnfr.sdk.fluent import TNFRNetwork
from tnfr.constants.canonical import *
# Self-optimizing engine with canonical parameters
engine = TNFRSelfOptimizingEngine(
G,
optimization_threshold=SELF_OPT_THRESHOLD, # ≈ 0.092 (operational)
max_iterations=SELF_OPT_MAX_ITER # 16 (operational)
)
# Auto-optimization using unified fields (Φ_s, |∇φ|, Ψ, ξ_C)
success, metrics = engine.step(node_id)
# Fluent API with auto-optimization
result = (TNFRNetwork(G)
.focus(node)
.auto_optimize() # One-line self-optimization
.execute())Physics: This is gradient descent on the structural manifold, driven by the nodal equation's pressure term ΔNFR.
### Parameter Usage
Validation uses the tetrad fields and a few telemetry thresholds. Only the π phase-wrap bounds and ξ_C ∝ 1/√λ₂ are genuine structural scales; the other thresholds are π-derived or free operational parameters, not derived structural constants.
```python
from tnfr.constants.canonical import *
from tnfr.physics.fields import compute_structural_tetrad
from tnfr.operators.grammar import validate_u1_through_u6
class CanonicalValidator:
def validate_sequence(self, sequence):
"""All validation uses canonical thresholds."""
# Grammar validation with canonical tolerances
return validate_u1_through_u6(
sequence,
phase_tolerance=PHASE_SYNC_TOLERANCE, # heuristic ≈ 0.18 (operational early-warning; bound is π)
coherence_minimum=HIGH_COHERENCE_THRESHOLD # π/(π+1) ≈ 0.7585 (emergent gate)
)
def validate_graph_state(self, graph):
"""Tetrad fields with telemetry thresholds."""
Phi_s, grad_phi, Psi, xi_C = compute_structural_tetrad(graph)
# Tetrad safety check (only the π phase-wrap bounds are genuine)
return (
abs(Phi_s) < PHI_S_ESCAPE_THRESHOLD and # < 0.771 (empirical, no closed form)
grad_phi < GRAD_PHI_STABILITY_LIMIT and # heuristic early-warning (kinematic bound is π)
abs(Psi.real) < K_PHI_CONFINEMENT_LIMIT # < 2.827 = 0.9π (phase wrap — genuine)
)
### Parameter Convention Benefits
1. **Traceability**: only π phase-wrap and ξ_C ∝ 1/√λ₂ are genuine structural scales; every other parameter is derived from the nodal dynamics or is a free operational parameter, explicitly labelled as such (never claimed as a derived structural constant).
2. **Predictable Behavior**: Deterministic system response via fixed parameters
3. **Cross-Domain Consistency**: Same nodal-equation foundation across physics, chemistry, and network science
4. **Self-Optimization**: Automated capability to improve its own structure
5. **Research Ready**: Mathematically pure framework suitable for scientific publication
6. **Production Stability**: No magic numbers that fail under extreme conditions
### Architecture Diagram
```mermaid
flowchart TB
subgraph Services["Service Layer"]
ORCH[TNFROrchestrator]
end
subgraph Interfaces["Core Interfaces"]
VAL[ValidationService]
REG[OperatorRegistry]
DYN[DynamicsEngine]
TEL[TelemetryCollector]
end
subgraph Implementation["Default Implementations"]
DVAL[DefaultValidationService]
DREG[DefaultOperatorRegistry]
DDYN[DefaultDynamicsEngine]
DTEL[DefaultTelemetryCollector]
end
subgraph Existing["Existing Modules"]
VMOD[tnfr.validation]
OMOD[tnfr.operators]
DYMOD[tnfr.dynamics]
MMOD[tnfr.metrics]
end
ORCH --> VAL
ORCH --> REG
ORCH --> DYN
ORCH --> TEL
VAL -.implements.- DVAL
REG -.implements.- DREG
DYN -.implements.- DDYN
TEL -.implements.- DTEL
DVAL --> VMOD
DREG --> OMOD
DDYN --> DYMOD
DTEL --> MMODThe TNFR grammar derives from the nodal equation; structural state is read through the four-field tetrad (the four orders of the discrete derivative tower). Each field is associated with a constant, but only π is a genuine structural scale:
| Field | Tower order | Grammar Rule | Structural scale |
|---|---|---|---|
| Φ_s (Structural Potential) | 0th (aggregation) | U6 Confinement | Empirical bound (no closed form); φ is motivation only |
| |∇φ| (Phase Gradient) | 1st (local) | U2 Convergence | π (phase wrap) — γ is NOT its scale |
| K_φ (Phase Curvature) | 2nd (local) | U3 Coupling | π (phase wrap); K_φ = L_rw·φ |
| ξ_C (Coherence Length) | correlation | U4 Bifurcation | spectral gap, ξ_C ∝ 1/√λ₂ — not e |
Every grammar constraint derives inevitably from physics - no arbitrary rules exist.
Complete Derivations: UNIFIED_GRAMMAR_RULES.md
Quick Reference: AGENTS.md § Unified Grammar
src/tnfr/operators/grammar.py canonical authority| Layer | Canonical Modules | Mathematical Foundation | TNFR Invariants |
|---|---|---|---|
| Constants Foundation | constants/canonical.py | Structural + operational parameters (only π genuine) | π phase-wrap is the one genuine structural scale |
| Operator Engine | operators/definitions.py, operators/grammar.py | 13 canonical transformations + U1-U6 physics | Structural completeness - all coherent dynamics covered |
| Grammar Dynamics | operators/grammar_dynamics.py, operators/grammar_application.py | Incremental U1-U6 validation + pre-filtered selection | Grammar-aware operator application at all code paths |
| Physics Core | physics/fields.py, physics/conservation.py, physics/integrity.py | Unified Field Tetrad + Conservation Theorem + 13/13 postconditions | Field universality + structural conservation + operator contracts |
| Dynamics Engine | dynamics/self_optimizing_engine.py, dynamics/canonical.py | Nodal equation ∂EPI/∂t = νf·ΔNFR(t) | Self-optimization - autonomous structural improvement |
| Telemetry System | telemetry/emit.py, metrics/telemetry.py | Structural coherence mathematics C(t), Si | Complete monitoring - all structural changes tracked |
| SDK Interface | sdk/simple.py, sdk/fluent.py, sdk/builders.py | Tetrad, conservation, grammar-aware dynamics, canonical parameters | Research-grade access + user-friendly canonical API |
flowchart LR
subgraph Preparation
DO[discover_operators]
VS[validate_sequence]
end
subgraph Execution
RS[run_sequence]
SH[set_delta_nfr_hook]
end
subgraph Dynamics
DN[default_compute_delta_nfr]
UE[update_epi_via_nodal_equation]
CP[coordinate_global_local_phase]
end
subgraph Telemetry
CC[compute_coherence]
SI[compute_Si]
TR[trace.register_trace_field]
end
DO --> VS --> RS
RS --> SH --> DN --> UE --> CP
DN --> CC
UE --> CC
CC --> SI
CC --> TR
CP --> TRThe following table highlights how ΔNFR values propagate through the engine and how related telemetry is persisted.
| Stage | Source module | Data emitted | Consumers |
|---|---|---|---|
| Hook install | tnfr.dynamics.set_delta_nfr_hook | Registers callable and metadata under G.graph['compute_delta_nfr'], seeding DNFR weights if absent.【F:src/tnfr/dynamics/dnfr.py†L1985-L2020】 | Structural loop (run_sequence), dynamics runners (step, run) |
| Gradient mix | tnfr.dynamics.dnfr.default_compute_delta_nfr | Updates per-node ΔNFR attributes and records hook metadata for traces.【F:src/tnfr/dynamics/dnfr.py†L1958-L1982】 | Nodal integrators, telemetry caches |
| Integration | tnfr.dynamics.integrators.update_epi_via_nodal_equation | Produces EPI, dEPI/dt, and d²EPI/dt² while advancing graph time.【F:src/tnfr/dynamics/integrators.py†L434-L483】 | Metrics (compute_coherence), trace snapshots |
| Coherence metrics | tnfr.metrics.common.compute_coherence | Aggregates C(t), mean | ΔNFR |
| Sense index | tnfr.metrics.sense_index.compute_Si | Evaluates Si with cached neighbour topology and harmonic weighting.【F:src/tnfr/metrics/sense_index.py†L40-L188】 | Trace captures, selectors |
| Trace capture | tnfr.trace.register_trace_field et al. | Stores ΔNFR weights, Kuramoto order, glyph counts, and callbacks into history buffers.【F:src/tnfr/trace.py†L169-L319】 | Audit tooling, reproducibility checks |
Operator classes apply the @register_operator decorator, which verifies unique ASCII names, binds glyphs, and inserts implementations into the shared OPERATORS map used by syntax validators and dynamic dispatch.【F:src/tnfr/operators/definitions.py†L45-L180】【F:src/tnfr/operators/registry.py†L13-L58】 The discovery routine scans the tnfr.operators package exactly once per interpreter session, importing every submodule except the registry itself so that registration side effects run reliably before the structural loop accesses them.【F:src/tnfr/operators/registry.py†L33-L58】
When introducing new operators:
name and canonical Glyph binding on the class definition.【F:src/tnfr/operators/definitions.py†L45-L180】TNFR 2.0 completes the transition to English-only operator identifiers. The registry, validation helpers, CLI, and documentation all use the same canonical ASCII tokens:
| Token | Role summary |
|---|---|
emission | Initiates resonance |
reception | Captures information |
coherence | Stabilises the form |
dissonance | Introduces controlled Δ |
coupling | Synchronises nodes |
resonance | Propagates coherence |
silence | Freezes evolution |
expansion | Scales the structure |
contraction | Densifies the form |
self_organization | Guides self-order |
mutation | Adjusts phase safely |
transition | Crosses thresholds |
recursivity | Maintains memory |
Only the canonical English spellings remain in the public API, the exported __all__ bindings,
and the validation layer. Downstream callers must use the names shown above; the registry no
longer performs alias canonicalisation and get_operator_class() raises :class:KeyError for
non-English identifiers.【F:src/tnfr/config/operator_names.py†L1-L77】【F:src/tnfr/operators/registry.py†L13-L45】
Runtime functions coordinate clamps, selectors, and job overrides to keep simulations reproducible without sacrificing performance:
apply_canonical_clamps enforces configured bounds for EPI, νf, and θ, optionally recording clamp alerts for strict graphs.【F:src/tnfr/validation/runtime.py†L46-L103】_normalize_job_overrides and _resolve_jobs_override map user overrides to canonical keys, ensuring distributed execution honours reproducibility contracts.【F:src/tnfr/dynamics/init.py†L114-L169】Together these layers ensure every structural change maps back to the TNFR grammar, preserves unit semantics, and leaves behind a telemetry trail suitable for coherence analysis.
In TNFR, the EPI range [-1.0, 1.0] represents the structural container of node identity. Boundaries are not arbitrary restrictions but intrinsic limits that preserve coherence:
These boundaries define the operational space within which a node maintains its structural identity. Exceeding them does not simply produce "out of range" values—it represents a transition beyond the node's capacity to maintain coherent form.
The engine implements a three-layer protection system that progressively enforces structural boundaries while preserving TNFR operational principles:
This layered approach embodies the TNFR principle that operators are the only paths for change—boundaries are maintained through operational awareness, not post-hoc corrections.
The VAL_scale parameter controls expansion rate for the VAL (expansion) operator:
This conservative value means that single VAL applications rarely approach boundaries under normal operation, reducing the need for downstream interventions.
Operators dynamically adapt near boundaries through edge-aware scaling, which adjusts the effective scale factor based on proximity to structural limits:
VAL (Expansion) edge-awareness:
scale_eff = min(VAL_scale, EPI_MAX / max(abs(EPI_current), ε))This ensures that EPI_current * scale_eff ≤ EPI_MAX, providing a gradual approach to boundaries without overshoot.
NUL (Contraction) edge-awareness:
if EPI_current < 0:
scale_eff = min(NUL_scale, abs(EPI_MIN / min(EPI_current, -ε)))
else:
scale_eff = NUL_scale # Normal contraction (always safe with scale < 1.0)For negative EPI values approaching EPI_MIN, the scale is adapted to prevent underflow.
Configuration:
EDGE_AWARE_ENABLED: Enable/disable edge-aware scaling (default: True)EDGE_AWARE_EPSILON: Small value to prevent division by zero (default: 1e-12)Telemetry: When scale adaptation occurs, the engine records intervention metadata in graph["edge_aware_interventions"], tracking:
The structural_clip() function provides the final enforcement layer, applied during nodal equation integration. See the "Structural Boundary Preservation" section below for detailed documentation.
This three-layer system preserves core TNFR principles:
The key insight is that boundary protection is integrated into the operational fabric, not imposed externally. Operators "know" about boundaries and adapt accordingly, maintaining the TNFR principle that structure emerges from resonance, not constraint.
TNFR maintains strict structural boundaries to preserve coherence and ensure that the Primary Information Structure (EPI) remains within valid ranges. This prevents numerical precision issues from violating structural invariants during operator application and integration.
The structural_clip function in tnfr.dynamics.structural_clip implements canonical TNFR boundary enforcement with two modes:
CLIP_SOFT_K steepness parameter.Structural clipping is automatically applied during nodal equation integration in DefaultIntegrator.integrate(). After computing the new EPI value via the canonical equation ∂EPI/∂t = νf · ΔNFR(t), the integrator applies structural_clip before updating node attributes:
# In src/tnfr/dynamics/integrators.py, line ~565
epi_clipped = structural_clip(
epi,
lo=epi_min, # From graph config or DEFAULTS
hi=epi_max, # From graph config or DEFAULTS
mode=clip_mode, # "hard" (default) or "soft"
k=clip_k, # Steepness for soft mode (default: 3.0)
)Structural boundary behavior is configured via graph-level parameters:
EPI_MIN: Lower boundary for EPI (default: -1.0)EPI_MAX: Upper boundary for EPI (default: 1.0)CLIP_MODE: Clipping mode, either "hard" or "soft" (default: "hard")CLIP_SOFT_K: Steepness parameter for soft mode (default: 3.0)This mechanism solves the VAL/NUL operator boundary issue documented in the issue tracker:
structural_clip provides secondary protection ensuring EPI ≤ EPI_MAX.structural_clip ensures EPI ≥ EPI_MIN.The structural_clip function supports optional telemetry via StructuralClipStats, which tracks:
This telemetry is disabled by default for performance but can be enabled via record_stats=True for debugging and tuning.
Structural boundary preservation aligns with core TNFR principles:
Test files use sys.modules manipulation to guarantee test isolation and enable
controlled re-import scenarios. This pattern is not URL validation or sanitization —
it is legitimate module cache management for testing purposes.
The canonical approach is to use the clear_test_module() utility from tests.utils:
from tests.utils import clear_test_module
# Clear a module before re-importing
clear_test_module('tnfr.utils.io')
import tnfr.utils.io # Fresh import with clean stateThe pattern 'module.name' in sys.modules may trigger false positives in static analysis
tools (e.g., CodeQL's py/incomplete-url-substring-sanitization). This is because:
tnfr.utils.io)Resolution: The repository includes .codeql/codeql-config.yml that excludes test files
from this specific rule, since test code legitimately uses module path checking for isolation,
not security validation.
While the following pattern works, it should be avoided in favor of the utility function:
# Discouraged: direct manipulation may trigger security scanners
if 'module.name' in sys.modules: # May be flagged as URL sanitization
del sys.modules['module.name']The utility function approach provides better clarity and centralizes the pattern in one well-documented location.
TNFR Engine is a complex-systems framework grounded in the nodal equation:
| Aspect | Status | Achievement |
|---|---|---|
| Mathematical Foundation | COMPLETE | Nodal equation + field tetrad |
| Operator System | COMPLETE | 13 canonical operators + U1-U6 grammar |
| Physics Engine | COMPLETE | Unified field tetrad + conservation theorem |
| Grammar Dynamics | COMPLETE | Grammar-aware selection + pre-validation + integrity monitor |
| Self-Optimization | COMPLETE | Autonomous structural improvement |
| Telemetry | COMPLETE | Complete system observability |
| Developer Experience | COMPLETE | Fluent API + Simple SDK (tetrad, conservation, telemetry) |
| Production Readiness | COMPLETE | 1,599 tests passing + benchmarks + validation |
TNFR Engine Architecture: Where mathematical foundations meet computational implementation.
Status: Architecturally mature - v1.0.0