.. _core-backend:

Core Module
===========

The **qmlhc.core** module establishes the formal contracts, typed data structures, 
and minimal abstractions that define the triadic interaction among inputs, quantum 
backends, and hypercausal nodes. It provides the formal and structural foundation 
for all higher layers of the system, ensuring interoperability, reproducibility, 
and implementation independence across heterogeneous computational contexts.

This core implements the three-phase hypercausal semantics 
(**input → state → projected future**) and unifies the execution logic 
between quantum-inspired backends and deterministic models, bridging 
formal design and experimental execution.


Architecture Overview
---------------------

::

   +------------------------+
   |      qmlhc.core       |
   +-----------+------------+
               |
       +-------v--------+        +--------------------+        +--------------------+
       |     types      |  --->  |      backend       |  --->  |      registry      |
       | (protocols &   |        | (base & validators)|        | (factory & lookup) |
       |  datatypes)    |        +--------------------+        +--------------------+
       |                |                     \
       +--------+-------+                      \
                |                               \
                |                                \
                |                  +-----------------------------+
                |                  |           model             |
                +----------------->| (HCModel: forward/chain/seq)|
                                   +-----------------------------+


The core architecture is not purely hierarchical but **causally cyclic**: 
outputs generated by a model feed back into subsequent states of the system. 
Each internal module contributes to this causal continuity:

- ``types`` – defines universal **protocols and typed interfaces** for runtime validation.  
  It formalizes structures such as ``QuantumBackend``, ``HypercausalNode``, and 
  ``ProjectionPolicy``, ensuring semantic coherence across the entire pipeline.

- ``backend`` – provides the **abstract execution base** that enforces dimensional, 
  numerical, and structural validation of inputs, states, and future projections.  
  It represents the bridge between abstract models and real or simulated quantum devices.

- ``registry`` – implements a **declarative registration system** that enables discovery 
  and instantiation of available backends at runtime. It connects the abstract interface 
  definitions with concrete executable backends.

- ``model`` – orchestrates the **temporal and causal propagation** of states through 
  one or more nodes, supporting single-step evaluation, chained-node composition, 
  and full sequence prediction.

.. _core-example:

Minimal Execution Flow
----------------------

The following self-contained example demonstrates a minimal hypercausal iteration 
that can be executed directly as a standalone script. It shows how a backend is registered, 
instantiated, and coupled with a hypercausal node to perform the triadic process 
(**input → state → projected futures → representative next state**).

.. code-block:: python

   from qmlhc.core.backend import BackendConfig, QuantumBackend
   from qmlhc.core.registry import register_backend, create_backend
   from qmlhc.core.model import HCModel, ModelConfig
   import numpy as np

   # Define a minimal backend extending QuantumBackend
   class MyBackend(QuantumBackend):
       """Normalized input and stochastic projection backend."""
       def run(self, params=None):
           x = self._require_input()
           return self._validate_state(x / np.linalg.norm(x))

       def project_future(self, s_t, branches=2):
           s_t = self._validate_state(s_t)
           noise = np.random.normal(scale=0.05, size=(branches, self.output_dim))
           fut = s_t + noise
           return self._validate_branches(fut)

   # Register backend
   capabilities = {
       "backend_name": "MyBackend",
       "backend_version": "1.0",
       "max_qubits": 0,
       "output_dim": 3,
       "supports_shots": False,
       "min_shots": 0,
       "max_shots": 0,
       "supports_noise": True,
       "supports_batch": False,
       "gradient": "none",
       "notes": "demo backend",
   }
   register_backend("my-backend", lambda cfg: MyBackend(cfg), capabilities)

   # Instantiate backend
   backend = create_backend("my-backend", BackendConfig(output_dim=3))

   # Define node using the backend
   class MyNode:
       def forward(self, x_t, s_tm1=None, branches=3):
           backend.encode(x_t)
           s_t = backend.run()
           fut = backend.project_future(s_t, branches=branches)
           s_tp1_hat = fut.mean(axis=0)
           return s_t, s_tp1_hat, {"branches": fut, "policy": "mean"}

   # Build and run model
   model = HCModel([MyNode()], config=ModelConfig(default_branches=3))
   x_t = np.array([1.0, 2.0, 3.0])
   s_t, s_tp1_hat, info = model.forward(x_t)

   # Display results
   print("Input vector (x_t):", x_t)
   print("Current state (s_t):", s_t)
   print("Projected future branches:\n", info["branches"])
   print("Selected representative state (ŝ_t+1):", s_tp1_hat)

Expected Output 
---------------

.. code-block:: text

   Input vector (x_t): [1. 2. 3.]
   Current state (s_t): [0.26726124 0.53452248 0.80178373]
   Projected future branches:
    [[0.28892093 0.49983569 0.80628565]
     [0.2702395  0.49588077 0.83320491]
     [0.22502986 0.55135436 0.80622541]]
   Selected representative state (ŝ_t+1): [0.26139676 0.51569027 0.81523866]

This demonstration executes a complete triadic hypercausal step, 
where the backend normalizes the input vector, produces stochastic future projections, 
and the node applies a mean selection policy to obtain the representative next state.


Core Contracts
--------------

The following contracts define the fundamental behavioral guarantees of the core system.  
Each interface is validated at runtime through the formal protocols established in 
``qmlhc.core.types``.

.. list-table::
   :header-rows: 1
   :widths: 24 76

   * - Component
     - Contract Description
   * - ``HypercausalNode.forward(x_t, s_tm1, branches)``
     - Executes the triadic propagation step and returns 
       ``(s_t: (D,), ŝ_{t+1}: (D,), info: dict)``, optionally including the 
       projected futures ``(K, D)`` in the diagnostics map.
   * - ``QuantumBackend``
     - Implements ``encode(x)``, ``run()``, ``project_future(s_t, K)``, and 
       ``capabilities()``; ensures shape, type, and coherence across heterogeneous backends.
   * - ``ProjectionPolicy.select(futures)``
     - Reduces ``(K, D)`` candidate futures into a representative state ``(D,)`` 
       while producing auxiliary diagnostics.
   * - ``Capabilities`` / ``GradientKind``
     - Specify backend properties, available features, and gradient computation strategy.

Extension Points
----------------

The module is fully backend-agnostic and supports seamless integration of custom 
components:

- **Backend implementation** — inherit from ``QuantumBackend`` and define the methods 
  ``run`` and ``project_future`` according to the required physical or simulated logic.
- **Backend registration** — use the global registry to declare and instantiate backends 
  declaratively at runtime.
- **Hypercausal nodes** — implement components that conform to the triadic ``forward`` 
  interface and integrate them within ``HCModel`` chains.
- **Branch configuration** — control the number of projected branches using 
  ``ModelConfig`` or runtime parameters during execution.
- **Hierarchical composition** — multiple nodes may be chained to simulate 
  complex temporal or causal dependencies.

Invariants and Mathematical Coherence
-------------------------------------

- State vectors maintain fixed dimension ``(D,)``; future projections adopt form 
  ``(K, D)`` with ``K ≥ 2``.
- Interfaces enforce strict dimensional and type validation, ensuring the preservation 
  of the hypercausal state-space structure.
- These constraints guarantee **dimensional conservation** and **statistical comparability** 
  among projected futures, forming the mathematical backbone of system coherence.
- NumPy serves as the canonical numeric container for deterministic, reproducible computation.

Module References
-----------------

The following documents provide the detailed API specifications and implementation 
contracts for each component of the core module.

.. toctree::
   :maxdepth: 1
   :titlesonly:

   Backend Interface <qmlhc.core.backend>
   Quantum Model Abstractions <qmlhc.core.model>
   Backend Registry <qmlhc.core.registry>
   Core Types <qmlhc.core.types>
