# TQCE — Temporal Quantum Causal Engine

[![PyPI version](https://img.shields.io/pypi/v/tqce?color=%2334D058&label=pypi)](https://pypi.org/project/tqce/)
[![Downloads](https://img.shields.io/pypi/dm/tqce?color=%2334D058&label=downloads)](https://pypi.org/project/tqce/)
[![Python](https://img.shields.io/pypi/pyversions/tqce?color=blue)](https://pypi.org/project/tqce/)
[![License](https://img.shields.io/github/license/utachicodes/tqce?color=yellow)](https://github.com/utachicodes/tqce/blob/main/LICENSE)
[![Tests](https://img.shields.io/github/actions/workflow/status/utachicodes/tqce/tests.yml?label=tests)](https://github.com/utachicodes/tqce/actions/workflows/tests.yml)
[![GitHub stars](https://img.shields.io/github/stars/utachicodes/tqce?style=social)](https://github.com/utachicodes/tqce)

**A novel computational paradigm based on causal loop mechanics.**

Paradox resolution in closed timelike curves is computationally equivalent to optimization under self-referential constraint systems. TQCE exploits this equivalence to build a new class of algorithms that solve problems standard approaches cannot handle — circular dependencies, self-referential optimization, and causal reasoning with feedback loops.

## Installation

```bash
pip install tqce
```

Or install from source:

```bash
git clone https://github.com/utachicodes/tqce.git
cd tqce
pip install -e ".[dev]"
```

Requirements: Python 3.11+, numpy, networkx, scipy, matplotlib.

## Quick Start

```python
import numpy as np
from tqce import CausalNode, TQCEOrchestrator
from tqce.viz import plot_convergence, plot_ctn_graph

np.random.seed(42)

# Build a causal loop: A -> B -> C with retrocausal C -> A
engine = TQCEOrchestrator("My Problem")
net = engine.build_network()

net.add_node(CausalNode("A", time_coordinate=0.0, state_dim=4))
net.add_node(CausalNode("B", time_coordinate=1.0, state_dim=4))
net.add_node(CausalNode("C", time_coordinate=2.0, state_dim=4))

net.add_causal_edge("A", "B", weight=0.8)
net.add_causal_edge("B", "C", weight=0.6)
net.add_retrocausal_edge("C", "A", weight=0.4)  # backward in time

# Solve for a self-consistent timeline
results = engine.solve(verbose=True)

# Visualize
plot_ctn_graph(net)
plot_convergence(results["fixed_point"]["iteration_history"])
```

## Five Core Components

### 1. Causal Tensor Networks (CTN)

Standard tensor networks are directed acyclic graphs. CTNs extend this by adding retrocausal edges — connections pointing backward in time — creating Closed Causal Loops (CCLs). The network state is computed not by forward propagation but by fixed-point iteration: repeatedly updating all nodes until the global state converges to a self-consistent solution. This is the computational analog of finding a valid timeline in a system with closed timelike curves.

**Class:** `CausalTensorNetwork`

### 2. Paradox Pressure Gradient Descent (PPGD)

PPGD is a gradient-based optimizer where the loss function is causal inconsistency itself. The "paradox pressure" at each node measures how far its current state is from what its causal parents demand. By treating this pressure as a differentiable loss surface, PPGD descends toward self-consistent basins using momentum and adaptive learning rates scaled by local paradox pressure.

**Class:** `ParadoxPressureGradientDescent`

### 3. Temporal Eigenstate Collapse (TEC)

Multiple candidate timelines are superposed as a "temporal wavefunction" with complex amplitudes. Causal interference between timelines amplifies consistent resolutions (constructive interference) and cancels paradoxical ones (destructive interference). After several rounds of interference, the system collapses to the timeline with the highest probability — the most self-consistent solution.

**Class:** `TemporalWavefunction`

### 4. Chrono-Entropic Regularization (CER)

Inspired by the second law of thermodynamics: entropy must be non-decreasing, even in causal loops. CER penalizes states where a past node has higher approximate entropy than its future retrocausal parents. This prevents information from growing unboundedly as it circulates through the loop, acting as a principled regularizer derived from physical constraints.

**Class:** `ChronoEntropicRegularizer`

### 5. Bootstrap Amplification (BA)

In a bootstrap paradox, information exists with no origin. BA exploits this computationally: a weak signal is injected into a causal loop where it influences itself at each pass. With the right resonance conditions (spectral radius of the loop kernel below 1), the signal amplifies to a stable fixed point that is larger than the input. Chrono-entropic damping prevents unbounded growth.

**Class:** `BootstrapAmplifier`

## Visualization

TQCE includes a dark-themed visualization module:

| Function | Description |
|----------|-------------|
| `plot_convergence()` | Fixed-point inconsistency over iterations, with optional PPGD loss overlay |
| `plot_paradox_pressure_landscape()` | Bar chart of paradox pressure per node |
| `plot_ctn_graph()` | Network graph with blue causal and red retrocausal edges |
| `plot_tec_probabilities()` | Timeline probability distribution after interference |
| `plot_amplification_trace()` | Amplification factor over loop iterations |
| `animate_convergence()` | Animated convergence showing per-node traces |

All functions are importable from `tqce.viz`.

## Examples

Three demo scripts are provided in `examples/`:

- **`circular_constraints.py`** — Solve a circular dependency problem (A depends on C, B on A, C on B) using the full TQCE pipeline.
- **`signal_amplification.py`** — Recover a weak signal buried below the noise floor using Bootstrap Amplification.
- **`anomaly_detection.py`** — Detect time series anomalies by measuring paradox pressure when data points are inserted into causal loops.

Run any example:
```bash
python examples/circular_constraints.py
```

See [docs/examples.md](docs/examples.md) for detailed walkthroughs.

## Architecture

```
tqce/
├── network/          # CausalNode, CausalTensorNetwork
├── optimization/     # ChronoEntropicRegularizer, ParadoxPressureGradientDescent
├── quantum/          # TemporalWavefunction
├── amplification/    # BootstrapAmplifier
├── engine/           # TQCEOrchestrator
└── viz/              # Plotting and animation
```

## Contributing

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## Code of Conduct

This project follows a code of conduct to ensure a welcoming community. See [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).

## References

- Deutsch, D. (1991). *Quantum mechanics near closed timelike lines.* Physical Review D, 44(10), 3197.
- Novikov, I. D. (1989). *An analysis of the operation of a time machine.* Soviet Physics JETP, 68(3), 439.
- Lloyd, S., Maccone, L., Garcia-Patron, R., Giovannetti, V., & Shikano, Y. (2011). *Quantum mechanics of time travel through post-selected teleportation.* Physical Review D, 84(2), 025007.

## License

MIT License. See [LICENSE](LICENSE) for details.
