"""QGC-1 reference simulator: abstract five-level (qudit) quantum circuits.

This is a pedagogical state-vector simulator for the mathematical QGC register model.
It is NOT a simulator of quantum gravity, relativistic spin-2 fields, or real gravitons.
Requires Python 3.10+ and NumPy. No external quantum SDK is required.

Convention: computational basis digits are 0..4; a register of n qudits is ordered
left-to-right as q[0], ..., q[n-1], and a controlled-add gate maps
|a,b> -> |a, b+a mod 5> (control first, target second).
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable, Sequence
import re
import numpy as np

D = 5
OMEGA = np.exp(2j * np.pi / D)


def fourier5(inverse: bool = False) -> np.ndarray:
    """Return the 5-point quantum Fourier transform or its adjoint."""
    j = np.arange(D)
    sign = -1 if inverse else 1
    return (OMEGA ** (sign * np.outer(j, j))) / np.sqrt(D)


def shift5(power: int = 1) -> np.ndarray:
    """Generalized Pauli X: X|j> = |j+power mod 5>."""
    u = np.zeros((D, D), dtype=complex)
    for j in range(D):
        u[(j + power) % D, j] = 1.0
    return u


def clock5(power: int = 1) -> np.ndarray:
    """Generalized Pauli Z: Z|j> = omega**j |j>."""
    return np.diag([OMEGA ** (power * j) for j in range(D)]).astype(complex)


def phase_ramp5(theta: float) -> np.ndarray:
    """Encode a dimensionless phase theta as |j> -> exp(i*j*theta)|j>."""
    return np.diag(np.exp(1j * theta * np.arange(D))).astype(complex)


def _check_unitary(u: np.ndarray, tol: float = 1e-10) -> None:
    if u.ndim != 2 or u.shape[0] != u.shape[1]:
        raise ValueError("Gate must be a square matrix")
    ident = np.eye(u.shape[0], dtype=complex)
    if not np.allclose(u.conj().T @ u, ident, atol=tol):
        raise ValueError("Gate is not unitary within tolerance")


@dataclass
class QGCRegister:
    """Pure-state register of n five-level qudits, with stochastic measurement."""
    n: int
    seed: int | None = None

    def __post_init__(self) -> None:
        if not isinstance(self.n, int) or self.n < 1:
            raise ValueError("n must be a positive integer")
        self.dim = D ** self.n
        self.rng = np.random.default_rng(self.seed)
        self.psi = np.zeros(self.dim, dtype=complex)
        self.psi[0] = 1.0

    def _check_q(self, q: int) -> None:
        if not isinstance(q, int) or not (0 <= q < self.n):
            raise IndexError(f"qdit index must be in 0..{self.n-1}")

    def reset_basis(self, digits: Sequence[int] | None = None) -> None:
        """Reset to a computational basis state; digits default to all zero."""
        if digits is None:
            digits = [0] * self.n
        if len(digits) != self.n or any((not isinstance(x, int)) or x not in range(D) for x in digits):
            raise ValueError(f"digits must be {self.n} integers in 0..4")
        idx = int(np.ravel_multi_index(tuple(digits), (D,) * self.n))
        self.psi[:] = 0.0
        self.psi[idx] = 1.0

    def set_state(self, amplitudes: Sequence[complex]) -> None:
        """Set a normalized full-register state vector."""
        a = np.asarray(amplitudes, dtype=complex).reshape(-1)
        if a.size != self.dim:
            raise ValueError(f"state vector length must be {self.dim}")
        norm = np.linalg.norm(a)
        if not np.isfinite(norm) or norm <= 0:
            raise ValueError("state must have finite nonzero norm")
        self.psi = a / norm

    def assert_norm(self, tol: float = 1e-10) -> None:
        norm2 = float(np.vdot(self.psi, self.psi).real)
        if not np.isclose(norm2, 1.0, atol=tol):
            raise AssertionError(f"state norm squared is {norm2}, not 1")

    def probabilities(self) -> np.ndarray:
        """Return full computational-basis outcome probabilities."""
        p = np.abs(self.psi) ** 2
        return p / p.sum()

    def apply_local(self, u: np.ndarray, q: int, check_unitary: bool = True) -> None:
        """Apply a 5x5 gate to one qdit using tensor-axis contraction."""
        self._check_q(q)
        u = np.asarray(u, dtype=complex)
        if u.shape != (D, D):
            raise ValueError("single-qdit gate must be 5x5")
        if check_unitary:
            _check_unitary(u)
        tensor = self.psi.reshape((D,) * self.n)
        tensor = np.moveaxis(tensor, q, 0)
        tensor = (u @ tensor.reshape(D, -1)).reshape((D,) * self.n)
        tensor = np.moveaxis(tensor, 0, q)
        self.psi = tensor.reshape(-1)

    def f5(self, q: int, inverse: bool = False) -> None:
        self.apply_local(fourier5(inverse=inverse), q)

    def x5(self, q: int, power: int = 1) -> None:
        self.apply_local(shift5(power), q)

    def z5(self, q: int, power: int = 1) -> None:
        self.apply_local(clock5(power), q)

    def phase_ramp(self, q: int, theta: float) -> None:
        self.apply_local(phase_ramp5(theta), q)

    def cadd5(self, control: int, target: int, power: int = 1) -> None:
        """Apply SUM_5^power: |a,b> -> |a,b+power*a mod 5>."""
        self._check_q(control)
        self._check_q(target)
        if control == target:
            raise ValueError("control and target must be different qdits")
        src_tensor = self.psi.reshape((D,) * self.n)
        dst = np.zeros_like(src_tensor)
        # Iterate over the 5**n basis entries. This is clear and adequate for small demos.
        for idx in np.ndindex((D,) * self.n):
            out_idx = list(idx)
            out_idx[target] = (idx[target] + power * idx[control]) % D
            dst[tuple(out_idx)] = src_tensor[idx]
        self.psi = dst.reshape(-1)

    def cphase5(self, control: int, target: int, theta: float = 2 * np.pi / D) -> None:
        """Apply diagonal controlled phase exp(i*theta*a*b)."""
        self._check_q(control)
        self._check_q(target)
        if control == target:
            raise ValueError("control and target must be different qdits")
        tensor = self.psi.reshape((D,) * self.n).copy()
        for idx in np.ndindex((D,) * self.n):
            tensor[idx] *= np.exp(1j * theta * idx[control] * idx[target])
        self.psi = tensor.reshape(-1)

    def apply_full(self, u: np.ndarray, check_unitary: bool = True) -> None:
        """Apply a full-register unitary of dimension 5**n."""
        u = np.asarray(u, dtype=complex)
        if u.shape != (self.dim, self.dim):
            raise ValueError(f"full-register gate must be {self.dim}x{self.dim}")
        if check_unitary:
            _check_unitary(u)
        self.psi = u @ self.psi

    def measure(self, q: int, basis: np.ndarray | None = None) -> int:
        """Measure one qdit; optionally measure in a basis whose columns are basis vectors.

        For basis B, computational measurement is performed after B†, so outcome k
        corresponds to projection onto column k of B. The conditional state is retained.
        """
        self._check_q(q)
        if basis is not None:
            basis = np.asarray(basis, dtype=complex)
            if basis.shape != (D, D):
                raise ValueError("measurement basis must be 5x5")
            _check_unitary(basis)
            self.apply_local(basis.conj().T, q)
        tensor = self.psi.reshape((D,) * self.n)
        other_axes = tuple(i for i in range(self.n) if i != q)
        probs = np.sum(np.abs(tensor) ** 2, axis=other_axes) if other_axes else np.abs(tensor) ** 2
        probs = np.asarray(probs, dtype=float)
        probs = np.maximum(probs, 0.0)
        probs /= probs.sum()
        outcome = int(self.rng.choice(D, p=probs))
        mask_shape = [1] * self.n
        mask_shape[q] = D
        mask = (np.arange(D) == outcome).reshape(mask_shape)
        tensor = np.where(mask, tensor, 0.0)
        norm = np.linalg.norm(tensor)
        if norm <= 0:
            raise RuntimeError("measurement selected a zero-probability branch")
        self.psi = (tensor / norm).reshape(-1)
        if basis is not None:
            self.apply_local(basis, q)
        return outcome

    def dephase_trajectory(self, q: int, coherence_keep: float) -> int | None:
        """Apply the trajectory ensemble for rho -> eta*rho + (1-eta)*Delta_q(rho).

        With probability eta, do nothing; otherwise perform a computational-basis
        measurement and discard its outcome. Averaging many trajectories reproduces
        the stated single-qdit dephasing channel. This is a stochastic trajectory
        implementation, not a density-matrix solver.
        """
        self._check_q(q)
        if not (0.0 <= coherence_keep <= 1.0):
            raise ValueError("coherence_keep must be between 0 and 1")
        if self.rng.random() < coherence_keep:
            return None
        return self.measure(q)

    def reduced_probabilities(self, q: int) -> np.ndarray:
        """Return diagonal probabilities for a chosen qdit, ignoring other registers."""
        self._check_q(q)
        tensor = self.psi.reshape((D,) * self.n)
        other_axes = tuple(i for i in range(self.n) if i != q)
        p = np.sum(np.abs(tensor) ** 2, axis=other_axes) if other_axes else np.abs(tensor) ** 2
        p = np.asarray(p, dtype=float)
        return p / p.sum()

    def density_matrix(self) -> np.ndarray:
        """Return the full pure-state density operator |psi><psi|."""
        return np.outer(self.psi, self.psi.conj())

    def reduced_density_matrix(self, keep: Sequence[int]) -> np.ndarray:
        """Partial-trace all but the listed qdits (indices must be sorted)."""
        keep = tuple(keep)
        if len(set(keep)) != len(keep) or any(not isinstance(q, int) or q not in range(self.n) for q in keep):
            raise ValueError("keep must contain unique valid qdit indices")
        if tuple(sorted(keep)) != keep:
            raise ValueError("keep indices must be in ascending register order")
        tensor = self.density_matrix().reshape((D,) * (2 * self.n))
        current_n = self.n
        for q in reversed([i for i in range(self.n) if i not in keep]):
            tensor = np.trace(tensor, axis1=q, axis2=q + current_n)
            current_n -= 1
        d_keep = D ** len(keep)
        reduced = np.asarray(tensor).reshape((d_keep, d_keep))
        if not np.allclose(reduced, reduced.conj().T, atol=1e-10):
            raise AssertionError("partial trace produced a non-Hermitian state")
        if not np.isclose(np.trace(reduced), 1.0, atol=1e-10):
            raise AssertionError("reduced density matrix does not have unit trace")
        return reduced

    def prepare_ghz5(self) -> None:
        """Prepare |GHZ_5,n> = (1/sqrt(5))*sum_j |j>**tensor n."""
        self.psi[:] = 0.0
        for j in range(D):
            idx = int(np.ravel_multi_index((j,) * self.n, (D,) * self.n))
            self.psi[idx] = 1.0 / np.sqrt(D)



def partial_transpose(rho: np.ndarray, dims: Sequence[int], subsystems: Sequence[int]) -> np.ndarray:
    """Partial transpose a density matrix on the requested subsystem indices."""
    dims = tuple(int(d) for d in dims)
    subsystems = tuple(subsystems)
    if not dims or any(d < 1 for d in dims):
        raise ValueError("dims must be a nonempty sequence of positive integers")
    if len(set(subsystems)) != len(subsystems) or any(not isinstance(i, int) or i not in range(len(dims)) for i in subsystems):
        raise ValueError("subsystems must be unique valid subsystem indices")
    total = int(np.prod(dims))
    rho = np.asarray(rho, dtype=complex)
    if rho.shape != (total, total):
        raise ValueError("density matrix shape does not match subsystem dimensions")
    tensor = rho.reshape(dims + dims)
    axes = list(range(2 * len(dims)))
    for i in subsystems:
        axes[i], axes[i + len(dims)] = axes[i + len(dims)], axes[i]
    return tensor.transpose(axes).reshape((total, total))


def entanglement_negativity(reg: QGCRegister, subsystem_a: Sequence[int]) -> float:
    """Compute bipartite negativity from a pure-register density matrix.

    Positive negativity witnesses entanglement across the declared partition;
    zero does not prove separability for every mixed-state/high-dimensional case.
    """
    transposed = partial_transpose(reg.density_matrix(), (D,) * reg.n, subsystem_a)
    eigvals = np.linalg.eigvalsh((transposed + transposed.conj().T) / 2)
    return float(np.sum(np.abs(eigvals[eigvals < 0.0])))


def bell5_state(seed: int | None = 7) -> QGCRegister:
    """Prepare |Phi_5> = sum_j |j,j>/sqrt(5) via F5 + CADD5."""
    reg = QGCRegister(2, seed=seed)
    reg.f5(0)
    reg.cadd5(0, 1)
    reg.assert_norm()
    return reg


def ghz5_state(n: int = 3, seed: int | None = 7) -> QGCRegister:
    """Prepare a 5-level GHZ state by the direct state-vector initializer."""
    reg = QGCRegister(n, seed=seed)
    reg.prepare_ghz5()
    reg.assert_norm()
    return reg


def phase_sensor_shots(theta: float, shots: int = 1000, seed: int = 7) -> np.ndarray:
    """Run the simple five-level phase experiment and return counts for outcomes 0..4."""
    if shots < 1:
        raise ValueError("shots must be >= 1")
    counts = np.zeros(D, dtype=int)
    rng = np.random.default_rng(seed)
    for _ in range(shots):
        reg = QGCRegister(1, seed=int(rng.integers(0, 2**32 - 1)))
        reg.f5(0)
        reg.phase_ramp(0, theta)
        reg.f5(0, inverse=True)
        counts[reg.measure(0)] += 1
    return counts


def phase_probabilities(theta: float) -> np.ndarray:
    """Analytic P(k|theta) after F5, phase encoding, and inverse F5."""
    j = np.arange(D)
    k = np.arange(D)
    amps = np.array([np.sum(np.exp(1j * j * theta) * (OMEGA ** (-ki * j))) / D for ki in k])
    p = np.abs(amps) ** 2
    return p / p.sum()


def maximum_likelihood_phase(counts: Sequence[int], grid_size: int = 4001) -> float:
    """Crude grid maximum-likelihood estimate on [-pi, pi); for demonstration only."""
    counts = np.asarray(counts, dtype=int)
    if counts.shape != (D,) or np.any(counts < 0) or counts.sum() == 0:
        raise ValueError("counts must contain five nonnegative integers with positive total")
    grid = np.linspace(-np.pi, np.pi, grid_size, endpoint=False)
    best_theta, best_loglike = 0.0, -np.inf
    for theta in grid:
        p = np.maximum(phase_probabilities(float(theta)), 1e-15)
        loglike = float(np.dot(counts, np.log(p)))
        if loglike > best_loglike:
            best_theta, best_loglike = float(theta), loglike
    return best_theta


# Minimal executable QCL-1.0 interpreter for the documented abstract subset.
# Inserted below QGCRegister and helpers so the same reference module executes examples.
@dataclass
class QCLRunResult:
    """Aggregated result from a minimal QCL-1.0 program run."""
    program: str
    shots: int
    measurement_counts: dict[str, dict[object, int]]
    joint_counts: dict[tuple[object, ...], int]
    estimates: dict[str, float]
    report_name: str | None = None


def _resolve_scalar(token: str, parameters: dict[str, float] | None = None) -> float:
    """Resolve a finite numeric literal or a declared scalar parameter."""
    token = token.strip()
    parameters = parameters or {}
    if token in parameters:
        value = float(parameters[token])
    else:
        value = float(token)
    if not np.isfinite(value):
        raise ValueError(f"parameter {token!r} must be finite")
    return value


def run_qcl(source: str, parameters: dict[str, float] | None = None,
            shots_override: int | None = None, seed: int = 7) -> QCLRunResult:
    """Execute the supported QCL-1.0 abstract subset and aggregate measurements.

    Supported statements: PROGRAM, REGISTER Q5, PREP BASIS, GATE F5/X5/Z5/
    PHASE5/CADD5/CPHASE5, ASSERT NORM, computational MEASURE, REPEAT SHOTS,
    ESTIMATE MLE for the PHASE5_LIKELIHOOD model, REPORT, END.

    This is an interpreter for finite-dimensional qdit circuits—not a physical
    gravity solver. Unsupported instructions fail explicitly instead of being
    silently ignored. Each shot receives a fresh register and RNG stream.
    """
    parameters = dict(parameters or {})
    lines = []
    for raw in source.splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or line.startswith("//"):
            continue
        lines.append(line)
    if not lines:
        raise ValueError("QCL source is empty")

    program = "UNNAMED"
    shots = 1
    report_name = None
    registers: dict[str, int] = {}
    actions: list[tuple] = []
    measurements: list[tuple[str, str, int | None]] = []
    estimators: list[tuple[str, str, str]] = []

    for line in lines:
        m = re.fullmatch(r'PROGRAM\s+([A-Za-z_][\w]*)\s+VERSION\s+["\']([^"\']+)["\']', line, re.I)
        if m:
            program = m.group(1)
            continue
        m = re.fullmatch(r'REGISTER\s+([A-Za-z_]\w*)\s*:\s*Q5(?:\[COUNT\s*=\s*(\d+)\])?', line, re.I)
        if m:
            name, count = m.group(1), m.group(2)
            n = int(count) if count else 1
            if n < 1:
                raise ValueError(f"register {name} must have COUNT >= 1")
            if name in registers:
                raise ValueError(f"register {name} declared more than once")
            registers[name] = n
            continue
        m = re.fullmatch(r'REPEAT\s+SHOTS\s*=\s*([A-Za-z_]\w*|\d+)', line, re.I)
        if m:
            shots = int(parameters[m.group(1)]) if m.group(1) in parameters else int(m.group(1))
            continue
        m = re.fullmatch(r'REPORT\s+([A-Za-z_]\w*)', line, re.I)
        if m:
            report_name = m.group(1)
            continue
        m = re.fullmatch(r'PREP\s+([A-Za-z_]\w*)\s*=\s*BASIS\s*\(([^)]*)\)', line, re.I)
        if m:
            name = m.group(1)
            if name not in registers:
                raise ValueError(f"register {name} must be declared before PREP")
            digits = [int(x.strip()) for x in m.group(2).split(',') if x.strip()]
            if len(digits) != registers[name]:
                raise ValueError(f"PREP BASIS for {name} needs {registers[name]} digits")
            if any(x not in range(D) for x in digits):
                raise ValueError("basis digits must be integers in 0..4")
            actions.append(("prep", name, digits))
            continue
        m = re.fullmatch(r'GATE\s+F5\s+([A-Za-z_]\w*)\[(\d+)\](?:\s+(INVERSE))?', line, re.I)
        if m:
            actions.append(("f5", m.group(1), int(m.group(2)), bool(m.group(3))))
            continue
        m = re.fullmatch(r'GATE\s+(X5|Z5)\s+([A-Za-z_]\w*)\[(\d+)\](?:\s+POWER\s*=\s*(-?\d+))?', line, re.I)
        if m:
            actions.append((m.group(1).lower(), m.group(2), int(m.group(3)), int(m.group(4) or 1)))
            continue
        m = re.fullmatch(r'GATE\s+PHASE5\s+([A-Za-z_]\w*)\[(\d+)\]\s+THETA\s*=\s*([\w.+\-]+)', line, re.I)
        if m:
            actions.append(("phase", m.group(1), int(m.group(2)), m.group(3)))
            continue
        m = re.fullmatch(r'GATE\s+CADD5\s+([A-Za-z_]\w*)\[(\d+)\]\s*->\s*([A-Za-z_]\w*)\[(\d+)\](?:\s+POWER\s*=\s*(-?\d+))?', line, re.I)
        if m:
            if m.group(1) != m.group(3):
                raise ValueError("minimal QCL runner currently requires CADD5 control/target in the same register")
            actions.append(("cadd", m.group(1), int(m.group(2)), int(m.group(4)), int(m.group(5) or 1)))
            continue
        m = re.fullmatch(r'GATE\s+CPHASE5\s+([A-Za-z_]\w*)\[(\d+)\]\s*->\s*([A-Za-z_]\w*)\[(\d+)\]\s+THETA\s*=\s*([\w.+\-]+)', line, re.I)
        if m:
            if m.group(1) != m.group(3):
                raise ValueError("minimal QCL runner currently requires CPHASE5 control/target in the same register")
            actions.append(("cphase", m.group(1), int(m.group(2)), int(m.group(4)), m.group(5)))
            continue
        m = re.fullmatch(r'ASSERT\s+NORM\s+([A-Za-z_]\w*)', line, re.I)
        if m:
            actions.append(("norm", m.group(1)))
            continue
        m = re.fullmatch(r'MEASURE\s+([A-Za-z_]\w*)(?:\[(\d+)\])?\s+BASIS\s*=\s*COMP\s+INTO\s+([A-Za-z_]\w*)', line, re.I)
        if m:
            register, q, alias = m.group(1), m.group(2), m.group(3)
            if register not in registers:
                raise ValueError(f"unknown register {register} in MEASURE")
            if q is not None:
                q = int(q)
                if q not in range(registers[register]):
                    raise IndexError(f"qdit index {q} outside register {register}")
            measurements.append((alias, register, q))
            actions.append(("measure", alias, register, q))
            continue
        m = re.fullmatch(r'ESTIMATE\s+MLE\s+([A-Za-z_]\w*)\s+FROM\s+([A-Za-z_]\w*)\s+MODEL\s*=\s*([A-Za-z_]\w*)', line, re.I)
        if m:
            estimators.append((m.group(1), m.group(2), m.group(3).upper()))
            continue
        if line.upper() in ("END", "NOP") or line.upper().startswith("#"):
            continue
        raise ValueError(f"unsupported or malformed QCL statement: {line}")

    if not registers:
        raise ValueError("QCL program must declare at least one register")
    if shots_override is not None:
        shots = int(shots_override)
    if shots < 1:
        raise ValueError("SHOTS must be >= 1")
    if shots > 1_000_000:
        raise ValueError("SHOTS > 1,000,000 is disabled in the reference interpreter")

    counts: dict[str, dict[object, int]] = {alias: {} for alias, _, _ in measurements}
    joint_counts: dict[tuple[object, ...], int] = {}
    estimates: dict[str, float] = {}
    seed_rng = np.random.default_rng(seed)

    # Only measurement instructions contribute result aliases; prepare/gate/assert
    # operations are replayed each shot. This is the standard repeated-shot model.
    for _shot in range(shots):
        regs = {name: QGCRegister(n, seed=int(seed_rng.integers(0, 2**32 - 1)))
                for name, n in registers.items()}
        shot_values: dict[str, object] = {}
        for action in actions:
            op = action[0]
            if op == "prep":
                _, name, digits = action
                regs[name].reset_basis(digits)
            elif op == "f5":
                _, name, q, inverse = action
                regs[name].f5(q, inverse=inverse)
            elif op == "x5":
                _, name, q, power = action
                regs[name].x5(q, power=power)
            elif op == "z5":
                _, name, q, power = action
                regs[name].z5(q, power=power)
            elif op == "phase":
                _, name, q, token = action
                regs[name].phase_ramp(q, _resolve_scalar(token, parameters))
            elif op == "cadd":
                _, name, control, target, power = action
                regs[name].cadd5(control, target, power=power)
            elif op == "cphase":
                _, name, control, target, token = action
                regs[name].cphase5(control, target, theta=_resolve_scalar(token, parameters))
            elif op == "norm":
                regs[action[1]].assert_norm()
            elif op == "measure":
                _, alias, name, q = action
                reg = regs[name]
                if q is None:
                    result: object = tuple(reg.measure(k) for k in range(reg.n))
                else:
                    result = reg.measure(q)
                shot_values[alias] = result
        ordered = tuple(shot_values.get(alias) for alias, _, _ in measurements)
        joint_counts[ordered] = joint_counts.get(ordered, 0) + 1
        for alias, value in shot_values.items():
            alias_counts = counts.setdefault(alias, {})
            alias_counts[value] = alias_counts.get(value, 0) + 1

    for target, source, model in estimators:
        if source not in counts:
            raise ValueError(f"ESTIMATE source alias {source!r} is not measured")
        if model != "PHASE5_LIKELIHOOD":
            raise ValueError(f"unsupported estimator model: {model}")
        source_counts = counts[source]
        vec = np.array([source_counts.get(k, 0) for k in range(D)], dtype=int)
        estimates[target] = maximum_likelihood_phase(vec)

    return QCLRunResult(program, shots, counts, joint_counts, estimates, report_name)


def _self_test() -> None:
    # Gate unitarity.
    for u in (fourier5(), shift5(), clock5(), phase_ramp5(0.37)):
        _check_unitary(u)
    # Bell-like entangled state has support only on |j,j> outcomes.
    bell = bell5_state()
    prob = bell.probabilities().reshape(D, D)
    assert np.allclose(np.diag(prob), np.full(D, 1 / D))
    assert np.allclose(prob - np.diag(np.diag(prob)), 0.0)
    # GHZ state has support only on |j,j,j>.
    ghz = ghz5_state(3)
    ghz.assert_norm()
    probs = ghz.probabilities().reshape(D, D, D)
    support = np.zeros_like(probs)
    for j in range(D):
        support[j, j, j] = 1 / D
    assert np.allclose(probs, support)
    # Phase probabilities normalize for multiple values.
    for theta in (-1.2, 0.0, 0.44, 2.3):
        assert np.isclose(phase_probabilities(theta).sum(), 1.0)
    reduced = bell.reduced_density_matrix([0])
    assert np.allclose(reduced, np.eye(D) / D)
    assert np.isclose(entanglement_negativity(bell, [0]), 2.0, atol=1e-10)
    bell_src = "\n".join([
        'PROGRAM BELL5 VERSION "1.0"', 'REGISTER R : Q5[COUNT=2]',
        'PREP R = BASIS(0,0)', 'GATE F5 R[0]', 'GATE CADD5 R[0] -> R[1]',
        'ASSERT NORM R', 'MEASURE R[0] BASIS=COMP INTO a',
        'MEASURE R[1] BASIS=COMP INTO b', 'REPEAT SHOTS=200', 'REPORT bell5_run', 'END'])
    qcl_bell = run_qcl(bell_src, seed=123)
    assert qcl_bell.shots == 200
    assert all(a == b for (a, b) in qcl_bell.joint_counts)
    phase_src = "\n".join([
        'PROGRAM PHASE5 VERSION "1.0"', 'REGISTER S : Q5', 'PREP S = BASIS(0)',
        'GATE F5 S[0]', 'GATE PHASE5 S[0] THETA=theta', 'GATE F5 S[0] INVERSE',
        'MEASURE S[0] BASIS=COMP INTO k', 'REPEAT SHOTS=1200',
        'ESTIMATE MLE theta FROM k MODEL=PHASE5_LIKELIHOOD', 'REPORT phase5_run', 'END'])
    qcl_phase = run_qcl(phase_src, parameters={"theta": 0.44}, seed=123)
    assert "theta" in qcl_phase.estimates and abs(qcl_phase.estimates["theta"] - 0.44) < 0.12
    print("QGC reference simulator and QCL interpreter self-test: PASS")
    print("Bell5 ideal joint probabilities (diagonal):", np.round(np.diag(prob), 3))
    counts = phase_sensor_shots(theta=0.44, shots=3000, seed=123)
    estimate = maximum_likelihood_phase(counts)
    print("Phase demo counts:", counts.tolist())
    print("True phase=0.44 rad; grid-MLE estimate=%.4f rad" % estimate)


if __name__ == "__main__":
    _self_test()
