Thank you for your interest in contributing to TNFR! This document provides guidelines for contributing to the Resonant Fractal Nature Theory computational engine.
- Code of Conduct
- Getting Started
- Development Workflow
- TNFR Principles
- Code Standards
- Testing Requirements
- Documentation
- Pull Request Process
- Theoretical Contributions
We are committed to providing a welcoming and inclusive environment for all contributors, regardless of background, identity, or experience level.
Expected behavior:
- Use welcoming and inclusive language
- Respect differing viewpoints and experiences
- Accept constructive criticism gracefully
- Focus on what's best for the community Show empathy towards other community members
Unacceptable behavior:
- Harassment, discrimination, or derogatory comments
- Trolling, insulting, or personal attacks
- Public or private harassment
- Publishing others' private information without permission
- Other conduct inappropriate for a professional setting
Instances of unacceptable behavior may be reported to the project maintainers. All complaints will be reviewed and investigated promptly and fairly.
- Python 3.10 or higher
- Git
- Basic understanding of TNFR concepts (see TNFR_CONCEPTS.md)
-
Fork and clone the repository:
git clone https://github.com/YOUR_USERNAME/TNFR-Python-Engine.git cd TNFR-Python-Engine -
Create a virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install in development mode:
pip install -e ".[dev-minimal]" -
Install pre-commit hooks (optional but recommended):
pre-commit install
-
Verify installation:
pytest tests/examples/test_u6_sequential_demo.py
git checkout -b feature/your-feature-name
# or
git checkout -b fix/issue-descriptionBranch naming conventions:
feature/- New functionalityfix/- Bug fixesdocs/- Documentation improvementsrefactor/- Code restructuring without behavior changestest/- Test additions or improvementsperf/- Performance optimizations
- Follow TNFR principles (see below)
- Write clear, descriptive commit messages
- Keep commits focused and atomic
- Add tests for new functionality
- Update documentation as needed
# Run smoke tests (fast validation)
make smoke-tests # Unix/Linux
.\make.cmd smoke-tests # Windows
# Run full test suite
pytest
# Check code quality
ruff check src/
mypy src/tnfr/If adding validation, health, or telemetry logic:
- Use
run_structural_validationto produce aValidationReport. - Derive
compute_structural_health(report)for recommendations. - Include performance timing (pass
perf_registry=PerformanceRegistry()). - Ensure added overhead ratio < 0.10 baseline (see perf tests).
- Never mutate graph state inside validation / health functions.
- Document physics traceability (why each threshold is used).
Telemetry additions must:
- Remain read-only (no operator side effects).
- Export coherence (
coherence_total), sense index, Φ_s, |∇φ|, K_φ, ξ_C. - Provide deterministic timestamps when seeds fixed.
Performance guardrails:
- Wrap optional expensive helpers with
perf_guard(label, registry). - Add/adjust tests under
tests/unit/performance/for new instrumentation. - Avoid micro-optimizing at expense of clarity unless overhead > target.
- Add docstrings to new functions/classes
- Update relevant README files
- Add examples if introducing new features
- Update CHANGELOG.md if applicable
See Pull Request Process below.
Before contributing, familiarize yourself with AGENTS.md - the canonical guide for TNFR development.
- Physics First: Every feature must derive from TNFR physics
- No Arbitrary Choices: All decisions traceable to nodal equation or invariants
- Coherence Over Convenience: Preserve theoretical integrity even if code is harder
- Reproducibility Always: Every simulation must be reproducible
- Document the Chain: Theory → Math → Code → Tests
All contributions must preserve these invariants:
- EPI as Coherent Form - Changes only via structural operators
- Structural Units - νf in Hz_str, never relabel
- ΔNFR Semantics - Physical reorganization gradient, not ML loss
- Operator Closure - Composition must yield valid TNFR states
- Phase Verification - No coupling without |φᵢ - φⱼ| ≤ Δφ_max check
- Node Birth/Collapse - Explicit lifecycle conditions
- Operational Fractality - EPIs can nest without losing identity
- Controlled Determinism - Stochastic but reproducible (seeds)
- Structural Metrics - Expose C(t), Si, phase, νf in telemetry
- Domain Neutrality - Trans-scale, trans-domain core
def should_implement(feature):
"""Decision framework for TNFR changes."""
if weakens_tnfr_fidelity(feature):
return False # Reject, even if "cleaner"
if not maps_to_operators(feature):
return False # Must map or be new operator
if violates_invariants(feature):
return False # Hard constraint
if not derivable_from_physics(feature):
return False # No organizational convenience ≠ physical necessity
if not testable(feature):
return False # No untestable magic
return True # Implement with full documentation- Follow PEP 8 with line length ≤ 100 characters
- Use type hints for all function signatures
- Prefer explicit over implicit - clarity trumps brevity
- Document intent, not just behavior - explain why, not just what
# Linting
ruff check src/
# Type checking
mypy src/tnfr/
# Formatting (if using black)
black src/ --line-length 100- Functions/methods:
snake_case - Classes:
PascalCase - Constants:
UPPER_SNAKE_CASE - Private members:
_leading_underscore - Operators: Canonical names (AL, EN, IL, OZ, UM, RA, SHA, VAL, NUL, THOL, ZHIR, NAV, REMESH)
# Standard library
from __future__ import annotations
import sys
from pathlib import Path
from typing import Optional, List, Dict
# Third-party
import networkx as nx
import numpy as np
# TNFR modules
from tnfr.operators.definitions import Emission, Coherence
from tnfr.metrics.coherence import compute_coherence
from tnfr.utils import get_loggerThe TNFR codebase is organized into focused modules for maintainability and cognitive load reduction:
Operators (tnfr.operators.*):
- Individual operator modules:
emission.py,coherence.py, etc. (13 operators) - Base class:
definitions_base.py- Shared operator infrastructure - Facade:
definitions.py- Backward-compatible imports
Grammar (tnfr.operators.grammar.*):
- Constraint modules:
u1_initiation_closure.py,u2_convergence_boundedness.py, etc. (8 rules) - Facade:
grammar.py- Unified validation interface
Metrics (tnfr.metrics.*):
- Focused metrics:
coherence.py,sense_index.py,phase_sync.py,telemetry.py - Facade:
metrics.py- Backward-compatible exports
Adding New Code:
- New operator: Add to appropriate operator file (e.g.,
coupling.pyfor coupling modifications) - New metric: Create new file in
tnfr.metrics/or extend existing metric module - New grammar rule: Add to relevant constraint module or create new
uN_*.pyfile - Always update facades: If adding new exports, add to facade files for backward compatibility
Module Guidelines:
- Keep files under 600 lines (ideally 200-400)
- One primary concept per module
- Use facade pattern for public APIs
- Document module purpose at top of file
- Core modules: ≥90% coverage
- Operators: 100% coverage (all contracts verified)
- Grammar rules: 100% coverage (U1-U6)
- Utilities: ≥80% coverage
- Unit tests - Test individual functions/classes
- Integration tests - Test operator sequences
- Property tests - Verify invariants hold (using Hypothesis)
- Example tests - Validate domain applications
def test_coherence_monotonicity():
"""Coherence operator must not decrease C(t)."""
G = nx.erdos_renyi_graph(20, 0.3)
initialize_network(G)
C_before = compute_coherence(G)
apply_operator(G, node, Coherence())
C_after = compute_coherence(G)
assert C_after >= C_before, "Coherence must not decrease"test_<function_name>- Unit teststest_<feature>_<scenario>- Integration teststest_invariant_<invariant_name>- Invariant verification
# Smoke tests (fast)
make smoke-tests
# Full suite
pytest
# Specific module
pytest tests/unit/operators/
# With coverage
pytest --cov=src/tnfr --cov-report=htmlUse Google style docstrings:
def apply_operator(G: nx.Graph, node: int, operator: Operator) -> None:
"""Apply a structural operator to a network node.
Args:
G: NetworkX graph representing TNFR network
node: Node identifier to apply operator to
operator: Structural operator instance (AL, EN, IL, etc.)
Raises:
ValueError: If node not in graph
GrammarViolation: If operator application violates grammar
Examples:
>>> G = nx.erdos_renyi_graph(10, 0.3)
>>> apply_operator(G, 0, Emission())
>>> apply_operator(G, 0, Coherence())
"""All contributions must include:
- Docstrings for all public functions/classes
- Type hints for function signatures
- Examples demonstrating usage
- Physics rationale linking to TNFR theory
- Tests covering documented behavior
If adding features, update:
- Main README.md (if user-facing)
- Relevant subsystem READMEs
- Examples directory
- API documentation
- Tests pass locally (
make smoke-tests) - Code follows style guidelines (
ruff check) - Documentation updated
- Commit messages are clear and descriptive
- Branch is up to date with main
- CHANGELOG.md updated (if applicable)
## Description
[Clear description of what this PR does]
## Motivation
[Why is this change needed? What problem does it solve?]
## TNFR Alignment
- [ ] Preserves all 10 canonical invariants
- [ ] Maps to structural operators (specify which)
- [ ] Derivable from TNFR physics (reference TNFR.pdf or UNIFIED_GRAMMAR_RULES.md)
- [ ] Maintains reproducibility (seeds, determinism)
## Testing
- [ ] Unit tests added/updated
- [ ] Integration tests added/updated
- [ ] Examples demonstrate usage
- [ ] All tests pass locally
## Documentation
- [ ] Docstrings added/updated
- [ ] README updated (if needed)
- [ ] Examples added (if new feature)
- [ ] Physics rationale documented
## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] No unintended files committed
- [ ] Branch name follows conventions
- [ ] Commit messages are descriptive
## Affected Components
[List modules/files modified]
## Breaking Changes
[List any breaking changes, or write "None"]
## Additional Notes
[Any other context, screenshots, or information]- Automated checks run (CI/CD)
- Maintainer review (typically 1-3 days)
- Feedback addressed by contributor
- Approval by maintainer
- Merge to main branch
- Celebrate! 🎉
- Your contribution will be included in the next release
- Consider contributing to documentation or examples
If proposing a new operator:
- Justify physically - Derive from nodal equation
- Define contracts - Pre/post-conditions
- Map to grammar - Which sets (generator, stabilizer, etc.)?
- Test rigorously - All invariants + specific contracts
- Document thoroughly - Physics → Math → Code chain
Template:
## Proposed Operator: [Name]
### Physical Basis
[How it emerges from TNFR physics]
### Nodal Equation Impact
∂EPI/∂t = ... [specific form]
### Contracts
- Pre: [conditions required]
- Post: [guaranteed effects]
### Grammar Classification
[Generator? Closure? Stabilizer? Destabilizer? etc.]
### Tests
- [List specific test requirements]If proposing new grammar rules:
- Start from physics - Derive from nodal equation or invariants
- Prove canonicity - Show inevitability (Absolute/Strong)
- Document thoroughly - [Rule] → [Physics] → [Derivation] → [Canonicity]
- Test extensively - Valid/invalid sequence examples
- General questions: GitHub Discussions
- Bug reports: GitHub Issues
- TNFR theory: Consult AGENTS.md, UNIFIED_GRAMMAR_RULES.md, or TNFR.pdf
If a change "prettifies the code" but weakens TNFR fidelity, it is NOT accepted.
If a change strengthens structural coherence and paradigm traceability, GO AHEAD.
Reality is not made of things—it's made of resonance. Contribute accordingly.