qram_simulator

qram_simulator -- Python bindings for the QRAM-Simulator C++ core.

Exports QRAMCircuit for both QRAM architectures (qubit / qutrit), the full-amplitude bridge QRAMFullAmp, the timing & noise scheduler TimeStep, and global random-seed control. See the _core module docstring and the project documentation for details.

Submodules

Attributes

Classes

Operation

A single quantum operation: type, target qubits, and optional coefficients (noise parameters).

OperationPack

A set of operations executed concurrently within one time slice (identified by name).

OperationType

Enum of QRAM operation types.

QRAMCircuitQubit

Branch-based sparse simulator of the qubit-architecture QRAM loading circuit.

QRAMCircuitQutrit

Branch-based sparse simulator of the qutrit-architecture QRAM loading circuit.

QRAMFullAmp

Bridge from the QRAM circuit to a full-amplitude state vector (qutrit

ReferenceWordBackend

Named machine-word register file with exact X / controlled-X execution.

SparseStateVector

Exact amplitudes over arbitrary-width basis indices (dict-backed).

SparseWordMemory

A zero-default sparse memory with arbitrary-width unsigned words.

TimeSlices

The complete QRAM loading schedule: a sequence of OperationPacks ordered by time slice.

TimeStep

Timing and noise scheduler for the QRAM loading circuit.

Functions

get_seed() → int

Return the current seed of the global random engine.

set_seed(seed) → None

Set the seed of the global random engine (MT19937-64 singleton).

Package Contents

class qram_simulator.Operation

A single quantum operation: type, target qubits, and optional coefficients (noise parameters).

reverse() → Operation

Return the inverse of this operation.

to_string() → str

Return a human-readable string representation.

property coefficients: list[float]

Noise coefficients (e.g. gamma for Damping).

property dagger: bool

Whether this is the conjugate-transpose (inverse) operation.

property targets: list[int]

List of target qubit / node indices.

property type: OperationType

Operation type (OperationType).

class qram_simulator.OperationPack

A set of operations executed concurrently within one time slice (identified by name).

empty() → bool

Whether this operation group is empty.

reverse() → OperationPack

Return the inverse operation group (each operation inverted, then reordered as in the original).

to_string() → str

Return a human-readable string representation.

property name: str

Name of this operation group.

property operations: list[Operation]

Operations of this slice, in execution order (list[Operation]; reads return a copy).

class qram_simulator.OperationType(value: SupportsInt | SupportsIndex)

Enum of QRAM operation types.

Serves both as the key type of noise models (dict keys of set_noise_models) and as the type tag of an Operation. Noise members (BitFlip / PhaseFlip / BitPhaseFlip / Depolarizing / Damping, etc.) take occurrence probabilities in [0, 1]; Damping additionally requires gamma < 1 (gamma = 1 decays all excitations within a single step, breaking sampling and normalization).

Members:

ControlSwap

HadamardData

CopyIn

CopyOut

SwapInternal

FirstCopy

FetchData

SetZero

Damping

Damp_Common

Damp_Full

BitFlip

PhaseFlip

BitPhaseFlip

Depolarizing

Identity_Active

Identity_Inactive

BitFlip: ClassVar[OperationType]
BitPhaseFlip: ClassVar[OperationType]
ControlSwap: ClassVar[OperationType]
CopyIn: ClassVar[OperationType]
CopyOut: ClassVar[OperationType]
Damp_Common: ClassVar[OperationType]
Damp_Full: ClassVar[OperationType]
Damping: ClassVar[OperationType]
Depolarizing: ClassVar[OperationType]
FetchData: ClassVar[OperationType]
FirstCopy: ClassVar[OperationType]
HadamardData: ClassVar[OperationType]
Identity_Active: ClassVar[OperationType]
Identity_Inactive: ClassVar[OperationType]
PhaseFlip: ClassVar[OperationType]
SetZero: ClassVar[OperationType]
SwapInternal: ClassVar[OperationType]
property name: str
property value: int
class qram_simulator.QRAMCircuitQubit(addr_size: SupportsInt | SupportsIndex, data_size: SupportsInt | SupportsIndex)
class qram_simulator.QRAMCircuitQubit(addr_size: SupportsInt | SupportsIndex, data_size: SupportsInt | SupportsIndex, memory: collections.abc.Sequence[SupportsInt | SupportsIndex])

Branch-based sparse simulator of the qubit-architecture QRAM loading circuit.

Carries (address, bus_input) input branches as trajectories, evolves the sparse SystemState along the noisy operation sequence generated by TimeStep, and supports good/bad branch pruning (run_normal), the unpruned reference (run_full), and fidelity sampling.

Typical workflow:

qram = QRAMCircuitQubit(addr_size, data_size[, memory]) qram.set_noise_models({...}) # optional qram.set_input_uniform(n) # or set_input_random(n) qram.run_normal() # or run_full() / run("normal") qram.sample_and_get_fidelity()

Construct the QRAM circuit initialized with the given memory (memory length must be 2^addr_size).

get_fidelity() → float

Alias of sample_and_get_fidelity.

get_fidelity_conventions() → dict

Return the three no-post-selection fidelity statistics of the current run as a dict (call after run_full, before sample_and_get_fidelity):

overlap_fid: |<psi_ideal|psi_traj>|^2, tree-sensitive -- statistically

matches the channel-level <psi_ideal|rho|psi_ideal> of the baseline;

fid_nopost: same inner product but tree-insensitive (bus-correct

amplitudes with residual tree excitations still counted);

fid_incoh: incoherent (branch-projected) combination of the same.

get_logical_query_fidelity() → float

Fidelity of the address/bus reduced state after tracing out the routing tree. Requires canonical zero-bus input with one column per address. No postselection, measurement or RNG draws; call after run, before tree/output sampling. This differs from full-circuit overlap_fid and from the older tree-insensitive conventions.

get_memory() → list[int]

Return the data tree (reference view).

get_noise_models() → dict[OperationType, float]

Return the current noise models (reference view).

get_output_distribution() → dict[str, float]

Return the marginal (address:bus) output distribution of the current branch groups as a {"addr:bus": prob} dict (call after run_full / run_normal; mutating calls such as sample_and_get_fidelity invalidate it).

get_qubit_num() → int

Return the number of physical qubits used by the circuit: 2 * (2^addr_size - 1).

has_damping() → bool

Whether the current noise models include Damping.

initialize_system() → None

Generate the noisy operation sequence via TimeStep and reset all branch groups (called internally by the run family).

is_noise_free() → bool

Whether no noise has been set.

memory_size() → int

Return the total number of memory slots.

prepare_observables() → None

Materialize implicit pruned outputs before reading distribution/overlap; does not measure the tree or consume random draws. Call after run_normal, before sampling.

run() → None
run(version: str) → None

Run by version string: "full" (unpruned) / "normal" (pruned) / "fast" (good branches only).

run_full() → None

Unpruned run over all branches, serving as the ground-truth reference of the pruned result.

run_normal() → None

Pruned run: all bad branches plus one good branch as reference (the default entry point for daily use).

sample_and_get_fidelity() → float

Sample the output branches and compute the loading fidelity (squared modulus of the inner product between the ideal and actual states).

set_input_addresses(addresses: collections.abc.Sequence[SupportsInt | SupportsIndex]) → None

Equal coherent address superposition with an initially zero bus; addresses must be unique.

set_input_random(n_inputs: SupportsInt | SupportsIndex) → None

Randomly sample n input branches, drawing input probabilities ~ U(0,1) then normalizing.

set_input_uniform(n_inputs: SupportsInt | SupportsIndex) → None

Randomly sample n input branches with equal input probability each.

set_input_zerobus() → None

Set the zerobus input: an equal-probability branch per address, all with bus input 0 (deterministic, no RNG draw; the discriminating input used by the circuit-level baseline comparison).

set_memory(memory: collections.abc.Sequence[SupportsInt | SupportsIndex]) → None

Set the data tree (memory length must be 2^addr_size).

set_memory_random() → None

Randomly fill the entire data tree using the global random engine.

set_noise_models(noises: collections.abc.Mapping[OperationType, SupportsFloat | SupportsIndex]) → None

Set noise models {OperationType: probability}.

Probabilities must lie in [0,1]; Damping requires gamma < 1, otherwise a RuntimeError is raised.

to_string() → str

Return a summary of the circuit.

to_string_full_info() → str

Return the full information including branch details.

property addr_size: int

Address width.

property data_size: int

Data width.

class qram_simulator.QRAMCircuitQutrit(addr_size: SupportsInt | SupportsIndex, data_size: SupportsInt | SupportsIndex)
class qram_simulator.QRAMCircuitQutrit(addr_size: SupportsInt | SupportsIndex, data_size: SupportsInt | SupportsIndex, memory: collections.abc.Sequence[SupportsInt | SupportsIndex])

Branch-based sparse simulator of the qutrit-architecture QRAM loading circuit.

Each tree node is a three-level system (addr ∈ {W, L, R}, data), evolved along the noisy operation sequence via SubBranch trajectories. The workflow matches QRAMCircuitQubit: construct -> set memory -> set noise -> set_input_* -> run_normal/run_full -> sample_and_get_fidelity.

Construct the QRAM circuit initialized with the given memory.

get_branch_probs() → list[float]

Return the normalized probabilities of all branches (reference view).

get_memory() → list[int]

Return the data tree (reference view).

get_noise_models() → dict[OperationType, float]

Return the current noise models (reference view).

get_qubit_num() → int

Return the number of physical qubits used by the circuit: 2 * (2^address_size - 1).

has_damping() → bool

Whether the current noise models include Damping.

initialize_system() → None

Generate the noisy operation sequence via TimeStep and initialize the branch structure (called internally by the run family).

is_noise_free() → bool

Whether no noise has been set.

memory_size() → int

Return the total number of memory slots.

run(version: str) → None

Run by version string ("full" / "normal", etc.; same as QRAMCircuitQubit.run).

run_full() → None

Unpruned run over all branches, serving as the ground-truth reference of the pruned result.

run_normal() → None

Pruned run: all bad branches plus one good branch as reference (the default entry point for daily use).

sample_and_get_fidelity() → float

Sample the output branches and compute the loading fidelity.

set_input_random(n_inputs: SupportsInt | SupportsIndex) → None

Randomly sample n input branches and fill the branch probabilities.

set_input_uniform(n_inputs: SupportsInt | SupportsIndex) → None

Randomly sample n input branches with equal input probability each.

set_memory(memory: collections.abc.Sequence[SupportsInt | SupportsIndex]) → None

Set the data tree.

set_memory_random() → None

Randomly fill the entire data tree using the global random engine.

set_noise_models(noises: collections.abc.Mapping[OperationType, SupportsFloat | SupportsIndex]) → None

Set noise models {OperationType: probability}.

Probabilities must lie in [0,1]; Damping requires gamma < 1, otherwise a RuntimeError is raised.

to_string() → str

Return a summary of the circuit.

to_string_full_info() → str

Return the full information including branch details.

property address_size: int

Address width.

property data_size: int

Data width.

class qram_simulator.QRAMFullAmp(addr_size: SupportsInt | SupportsIndex, data_size: SupportsInt | SupportsIndex, memory: collections.abc.Sequence[SupportsInt | SupportsIndex])

Bridge from the QRAM circuit to a full-amplitude state vector (qutrit architecture only).

An external full-amplitude simulator (or a user script) supplies the state vector and qubit mapping; apply composites one QRAM loading onto that state vector and returns the new vector, embedding QRAM simulation into a larger circuit-evolution pipeline.

示例

manipulator = QRAMFullAmp(2, 2, [0, 1, 2, 3]) manipulator.set_noise_models({OperationType.Depolarizing: 1e-3}) out = manipulator.apply(state, [0, 1], [2, 3], [], version="normal")

Construct the bridge: internally creates a qutrit QRAMCircuit loaded with the given memory.

apply(state: collections.abc.Sequence[SupportsComplex | SupportsFloat | SupportsIndex], address_qubits: collections.abc.Sequence[SupportsInt | SupportsIndex], data_qubits: collections.abc.Sequence[SupportsInt | SupportsIndex], other_qubits: collections.abc.Sequence[SupportsInt | SupportsIndex], version: str = 'normal') → list[complex]

Composite one QRAM loading onto a full-amplitude state vector.

参数:
  • state -- list of complex amplitudes (length 2^total qubit count)

  • other_qubits (address_qubits / data_qubits /) -- indices of the three qubit groups

  • version -- "normal" (pruned) or "full" (unpruned)

返回:

the new state vector after loading (list of complex numbers)

set_noise_models(noises: collections.abc.Mapping[OperationType, SupportsFloat | SupportsIndex]) → None

Set the noise models of the internal QRAMCircuit (same constraints as QRAMCircuitQutrit).

class qram_simulator.ReferenceWordBackend(machine_word_bits: int = 64)[源代码]

Named machine-word register file with exact X / controlled-X execution.

Every operation is an exact unitary permutation of the amplitudes — a genuine statevector execution, not a call recorder. Bit indices are confined to one machine word; wider logical registers span several word registers (see word_layout()).

X_Bool(name: str, bit_index: int) → WordXOperator[源代码]
make_state() → SparseStateVector[源代码]
position(pair: tuple[str, int]) → int[源代码]
register(*views) → None[源代码]

Touch every coordinate so later state creation sees the layout.

word_slot(name: str) → int[源代码]
class qram_simulator.SparseStateVector[源代码]

Exact amplitudes over arbitrary-width basis indices (dict-backed).

amplitude(basis: int) → complex[源代码]
class qram_simulator.SparseWordMemory(address_width: int, data_width: int, cells: collections.abc.Mapping[int, int])[源代码]

A zero-default sparse memory with arbitrary-width unsigned words.

address_width and data_width are logical widths in bits; every stored value keeps its exact high bits in arbitrary-precision Python integers, so words are never packed into a single 64-bit machine word. Cells mapped to zero are dropped: the memory is zero by default.

apply_xor(state, address_bits: Sequence[BitCoordinate], data_bits: Sequence[BitCoordinate], backend, *, conditions=tuple()) → None[源代码]

Apply the exact coherent query on native machine-word bit coordinates.

address_bits[i] / data_bits[i] are the (word_register_name, bit_index) coordinates of logical bit i (little-endian) of the address / data registers; a logical register wider than one machine word spans several word registers. backend must be the caller's real native backend (see the module docstring protocol), not a mock. Conditions are (little_endian_bits, expected_value) pairs; a stored cell is queried only on basis states satisfying all of them. Shared bits between conditions and the address register are merged — a zero control coinciding with an address bit restricts the query to cells whose address agrees with it, and never re-addresses a cell.

For each stored cell the emission is: toggle the zero-valued address/control bits to 1, apply one controlled native X per set data bit conditioned on all required bits, then restore the toggles. This is exact: basis states not matching the merged pattern are untouched by the transient toggles.

xor(address: int, data: int = 0) → int[源代码]

Return data XOR the stored word at address (0 if absent).

property nominal_address_space: int

Number of addressable labels 2**address_width (no allocation).

property record_count: int

Number of non-zero stored records (the only existing entities).

class qram_simulator.TimeSlices

The complete QRAM loading schedule: a sequence of OperationPacks ordered by time slice.

clear() → None

Clear the schedule.

reverse() → TimeSlices

Return the reversed schedule (overall order flipped and each group inverted).

to_string() → str

Return a human-readable string representation.

property time_slices: list[OperationPack]

List of time slices (list[OperationPack]; reads return a copy).

class qram_simulator.TimeStep(addr_size: SupportsInt | SupportsIndex, data_size: SupportsInt | SupportsIndex)

Timing and noise scheduler for the QRAM loading circuit.

Derives the routing, copy, and swap operations of each time slice from the address / data widths, and can insert noise operations after every time slice according to the noise models, producing the complete TimeSlices schedule. QRAMCircuit holds a TimeStep instance internally and calls generate in initialize_system to produce the noisy operation sequence.

Construct the scheduler.

参数:
  • addr_size -- address width

  • data_size -- data width

full_step() → int

Total number of time slices of the full loading procedure.

generate(noises: collections.abc.Mapping[OperationType, SupportsFloat | SupportsIndex], arch_type: SupportsInt | SupportsIndex) → TimeSlices

Generate the noisy schedule.

参数:
  • noises -- noise models, a {OperationType: probability} dict (may be empty)

  • arch_type -- architecture constant, ARCH_QUBIT or ARCH_QUTRIT

generate_step(step: SupportsInt | SupportsIndex) → OperationPack

Generate the operation group of the given time slice (noise-free).

参数:

step -- time-slice index (1-based)

get_bad_range_qubit(bad_qubit: SupportsInt | SupportsIndex) → tuple[int, int]

Qubit architecture: the bad-branch address range [lo, hi] derived from the bad qubit.

get_bad_range_qutrit(bad_qubit: SupportsInt | SupportsIndex) → tuple[int, int]

Qutrit architecture: the bad-branch address range [lo, hi] derived from the bad qubit.

is_bad_branch(addr: SupportsInt | SupportsIndex) → bool

Check whether address addr falls inside the bad-branch range (bad range).

layer_entangle_max(step: SupportsInt | SupportsIndex) → int

Maximum number of tree layers entangled at the given time slice.

Position-sampled noise of that slice lives on the tree positions [0, 2*(2^l - 1)); steps with l = 0 carry none (addr_size = 1 therefore has no position-sampled noise; under Damping only Damp_Common acts).

print() → None

Print the detailed schedule of all time slices (fmt output to stdout).

property addr_size: int

Address width.

property data_size: int

Data width.

property time_slices_noise_free: TimeSlices

Noise-free schedule (TimeSlices).

qram_simulator.get_seed() → int

Return the current seed of the global random engine.

qram_simulator.set_seed(seed: SupportsInt | SupportsIndex) → None

Set the seed of the global random engine (MT19937-64 singleton). QRAMCircuit memory generation, input sampling and output sampling all use this engine; fixing the seed reproduces the whole simulation chain.

qram_simulator.ARCH_QUBIT: int = 6939[源代码]
qram_simulator.ARCH_QUTRIT: int = 6682[源代码]
qram_simulator.BitFlip: _core.OperationType[源代码]
qram_simulator.BitPhaseFlip: _core.OperationType[源代码]
qram_simulator.ControlSwap: _core.OperationType[源代码]
qram_simulator.CopyIn: _core.OperationType[源代码]
qram_simulator.CopyOut: _core.OperationType[源代码]
qram_simulator.Damp_Common: _core.OperationType[源代码]
qram_simulator.Damp_Full: _core.OperationType[源代码]
qram_simulator.Damping: _core.OperationType[源代码]
qram_simulator.Depolarizing: _core.OperationType[源代码]
qram_simulator.FetchData: _core.OperationType[源代码]
qram_simulator.FirstCopy: _core.OperationType[源代码]
qram_simulator.HadamardData: _core.OperationType[源代码]
qram_simulator.Identity_Active: _core.OperationType[源代码]
qram_simulator.Identity_Inactive: _core.OperationType[源代码]
qram_simulator.PhaseFlip: _core.OperationType[源代码]
qram_simulator.QUBIT_DAMPING_CONVENTION: str = 'joint_auxiliary_whole_tree_v1'[源代码]
qram_simulator.SetZero: _core.OperationType[源代码]
qram_simulator.SwapInternal: _core.OperationType[源代码]