"""
Gate-level (circuit-level) qubit-architecture QRAM simulator.
An independent re-implementation of the qubit-architecture QRAM loading circuit
(the symbolic sparse-tree engine of ``qram_qubit::QRAMCircuit``) as an explicit
quantum circuit, simulated gate by gate on the UnifiedQuantum (``uniqc``) QuTiP
density-matrix backend. Serves as the semi-quantitative baseline against
:class:`qram_simulator.QRAMCircuitQubit` (see ``qram_simulator.baseline.compare``).
Why only 1-2 tree layers
------------------------
The density matrix lives on ``addr + data + 2*(2^addr - 1)`` qubits
(9 qubits for addr=2/data=1); addr=3 already needs 25 qubits (2^50 amplitudes).
With ``addr_size = 1`` every step has ``layer_entangle_max == 0``, so Pauli
noise on the active front vanishes. Whole-tree amplitude damping still acts;
the one-layer case is not a noise-free bridge when damping is nonzero.
Encoding (identical to ``Experiments/QRAM/ChannelCorrespondence``)
------------------------------------------------------------------
- address register: ``addr_size`` qubits, address bit ``b`` = qubit ``b``;
- data bus: ``data_size`` qubits starting at ``addr_size``;
- routing-tree node ``v`` (heap numbering, ``v in [0, 2^addr - 1)``): two
qubits -- ``a = addr + data + 2v`` (routing/addr slot) and
``d = addr + data + 2v + 1`` (data slot); the tree is at ``|0...0>`` ground.
- noise position convention: ``pos = 2v + lr`` with ``lr = 0 -> a, 1 -> d``.
Gate translation (bitwise-verified against the C++ engine by the
ChannelCorrespondence experiment, Stage 0/1)
------------------------------------------------
- ``FirstCopy{l}`` -> CNOT(addr[addr-1-l], node0.d) (MSB-first)
- ``CopyIn{d}`` -> H on all bus qubits when d == 0, SWAP(bus[d], node0.d)
- ``CopyOut{d}`` -> SWAP(bus[d], node0.d), H on all bus qubits when d == last
- ``SwapInternal{l}``-> SWAP(a, d) on every node of layer l
- ``ControlSwap{l}`` -> per node v of layer l: SWAP(d_v, d_2v+1) controlled by
a_v == 0 and SWAP(d_v, d_2v+2) controlled by a_v == 1
- ``FetchData{k}`` -> U1(pi) on each leaf d_v controlled by (a_v == lr) for
every memory cell whose bit k is set (phase-kickback fetch)
The gate sequence and the per-step entangled-layer counts are pulled from the
C++ ``TimeStep`` scheduler through ``qram_simulator._core`` (single source of
truth) -- this module never re-derives the schedule.
Noise model (channel level, mirrors the C++ trajectory sampler)
---------------------------------------------------------------
Noise channels are placed **only on the routing-tree qubits** (never on the
address register or the bus). After the gates of each time slice with
entangled-layer count ``l``, a channel acts on every active position
``[0, 2*(2^l - 1))`` with marginal probability ``p`` -- the channel-level
counterpart of the C++ per-trajectory sampler (``nerror ~ Binomial(N, p)``
placed uniformly on the N active positions, hence each position is hit with
probability exactly ``p``). Depolarizing applies the ``{I, X, Z, Y}``
unitary mixture (all unitary after the Y-flip fix, so the textbook TP channel
and the faithful mixture coincide). Damping uses fixed standard Kraus matrices
on every tree qubit, matching the current exact joint trajectory sampler.
Its trajectory norm and the density trace are one. ``mode="legacy"`` retains
the retired state-dependent, non-TP mirror for archived comparisons only;
``mode="nojump"`` retains only K0 and reports its sub-normalized weight.
"""
from __future__ import annotations
import math as math
import numpy
import numpy as np
from qram_simulator._core import OperationType
from qram_simulator._core import TimeStep
import typing
__all__: list = ['CircuitQRAMQubit', 'QubitQRAMEncoding']
[文档]
class QubitQRAMEncoding:
"""
Qubit-index layout of the encoded QRAM circuit.
"""
def __init__(self, addr_size: int, data_size: int):
...
[文档]
def addr_qubit(self, bit: int) -> int:
...
[文档]
def bus_qubit(self, digit: int) -> int:
...
[文档]
def layer_nodes(self, layer: int) -> list[int]:
...
[文档]
def node_a(self, v: int) -> int:
...
[文档]
def node_d(self, v: int) -> int:
...
[文档]
def noise_qubit(self, pos: int) -> int:
"""
Tree qubit of flat noise position ``pos = 2v + lr`` (lr: 0 -> a, 1 -> d).
"""
@property
[文档]
def address_qubits(self) -> list[int]:
...
@property
[文档]
def bus_qubits(self) -> list[int]:
...
@property
[文档]
def num_nodes(self) -> int:
...
@property
[文档]
def num_qubits(self) -> int:
...
@property
[文档]
def tree_qubits(self) -> list[int]:
...
[文档]
class CircuitQRAMQubit:
"""
Circuit-level baseline of the qubit-architecture QRAM loading circuit.
Parameters
----------
addr_size : int
Address width = tree depth. Only 1 or 2 is supported (density-matrix
size limit); addr=1 only exercises the noise-free bridge (plus the
whole-tree part of Damping).
data_size : int
Bits per memory cell (1 or 2).
memory : sequence of int
Data tree, length 2**addr_size, every entry < 2**data_size (the C++
fidelity XORs raw values; out-of-range entries are silently scored 0).
depolarizing, damping : float
Noise probabilities of the two supported channels, mirroring
``QRAMCircuitQubit.set_noise_models``. Applied on tree qubits only.
input_mode : {"zerobus", "uniform"}
"zerobus" (default): uniform superposition of addresses, bus = 0 --
the discriminating input; "uniform": uniform address and bus.
"""
def __init__(self, addr_size: int, data_size: int, memory: typing.Sequence[int], *, depolarizing: float = 0.0, damping: float = 0.0, bit_flip: float = 0.0, phase_flip: float = 0.0, input_mode: str = 'zerobus'):
...
def _apply_damping(self, be, entangle: int, gamma: float, textbook: bool, nojump: bool) -> None:
...
def _apply_depolarizing(self, be, q: int, p: float, textbook: bool) -> None:
...
def _apply_gate(self, be, gate: Gate) -> None:
...
def _init_backend(self, backend_cls):
...
def _translate_op(self, op, step: int) -> list[Gate]:
...
[文档]
def fidelity_with_ideal(self, rho: np.ndarray, rho_ideal: np.ndarray = None) -> float:
"""
<psi_ideal|rho|psi_ideal>, the same convention as the C++ overlap_fid.
For the pure ideal state this equals Re Tr(rho @ rho_ideal); it is the
statistic that matches the QRAM-Simulator trajectory average
``E|<psi_ideal|psi_traj>|^2`` (avg_overlap_fid).
"""
[文档]
def ideal_density_matrix(self) -> np.ndarray:
"""
Density matrix of the noise-free circuit (pure state, trace 1).
"""
[文档]
def logical_density_matrix(self, rho: np.ndarray) -> np.ndarray:
"""
Trace out tree qubits; visible index is address + (bus << addr_size).
This retains address/bus coherences and sums only equal environment
indices. It is independent of the sparse engine's observable code.
"""
[文档]
def logical_fidelity_with_ideal(self, rho: np.ndarray) -> float:
"""
Overlap with the pure ideal address/bus query after a physical partial trace.
No router reset or postselection is imposed. This differs from the
full-circuit ``fidelity_with_ideal`` and tree-insensitive conventions.
"""
[文档]
def marginal_distribution(self, rho: np.ndarray) -> dict[str, float]:
"""
Marginal (address:bus) distribution of a density matrix.
Same key convention as ``QRAMCircuitQubit.get_output_distribution``
("addr:bus" with the plain integers), so the two sides compare
key-for-key.
"""
[文档]
def run(self, mode: str = 'faithful') -> dict[str, typing.Any]:
"""
Convenience wrapper: ideal + noisy density matrices and all metrics.
Returns a dict with ``ideal_rho``/``ideal_dist``, ``rho``/``dist``/``trace``
and ``fidelity`` (= fidelity_with_ideal). The modern complete channels
have trace one. Only explicit legacy/nojump diagnostics may return
sub-normalized distributions; their trace is not the core's trajectory norm.
"""
[文档]
def simulate_density(self, mode: str = 'faithful') -> np.ndarray:
"""
Run the noisy circuit on the uniqc QuTiP density-matrix backend.
Parameters
----------
mode : {"faithful", "textbook", "legacy", "nojump"}
"faithful" (default): depolarizing as the {I,X,Z,Y} mixture and
fixed whole-tree amplitude damping, matching the current core;
"textbook": equivalent standard TP channels; "legacy": retired
rho-dependent damping mirror, not a standard channel certificate;
"nojump": damping K0 branch only (trace = no-jump weight).
"""
[文档]
def to_gate_list(self) -> list[Gate]:
"""
Flat noise-free gate list (input preparation gates excluded).
"""
def _backend_bit_order(backend_cls) -> str:
"""
Probe whether qubit 0 is the LSB or the MSB of the density-matrix index.
"""
def _require_uniqc():
"""
Import the uniqc QuTiP density-matrix backend lazily with a helpful error.
"""
ARCH_QUBIT: int = 6939
Gate: typing._GenericAlias
_BIT_ORDER_CACHE: dict = {}
_QUBIT_M: numpy.ndarray