C++ API 参考¶
本章由 Doxygen + Breathe 从源码头文件的注释自动生成, 按核心工作类组织。完整头文件(含自由函数与工具)见仓库 QRAM/include/ 与 Common/include/。
备注
各条目上方的 cppapi-* 显式锚点供其他文档页深链使用,
与自动生成的 Doxygen 锚点互不冲突。
QRAM 模块¶
电路(qubit 架构)¶
-
struct QRAMCircuit¶
Branch-based sparse simulator of the QRAM loading circuit (qubit architecture).
Uses (address, bus_input) input branches as trajectory carriers and evolves sparse SystemState along the noisy operation sequence generated by TimeStep; via good/bad branch pruning it compresses the simulation scale from all branches down to "fully simulate bad branches + one good branch as reference".
Typical workflow:
Construct the circuit and set the data tree (set_memory_random / set_memory)
Optionally inject noise (set_noise_models)
Sample input branches (set_input_random / set_input_uniform)
Run (run_normal pruned / run_full unpruned reference)
Sample the output and read the fidelity (sample_and_get_fidelity)
Public Types
-
using DampingMaskWeights = std::map<std::vector<size_t>, double>¶
Candidate-mask marginal of the complete represented state. Each key is C intersect X; weights include implicit good groups. An input-bus branch is an orthogonal input-column label in this API. Coherent superpositions must be combined inside a Branch; branch_probs alone does not encode interference between columns.
Public Functions
-
QRAMCircuit(size_t address_sz, size_t data_sz)¶
Constructs the QRAM circuit (memory uninitialized).
- 参数:
address_sz -- Address width
data_sz -- Data width
-
QRAMCircuit(size_t address_sz, size_t data_sz, memory_t &&memory)¶
Constructs the QRAM circuit and initializes it with the given data tree.
- 参数:
address_sz -- Address width
data_sz -- Data width
memory -- Data tree (length must be 2^address_sz)
-
inline void set_memory_random()¶
Randomly fills the entire data tree using the global random engine.
-
void set_memory(const memory_t &new_memory)¶
Sets the data tree (copy).
-
void set_memory(memory_t &&new_memory)¶
Sets the data tree (move).
-
inline auto &get_memory()¶
Returns a reference to the data tree.
-
inline auto &get_memory() const¶
Returns a const reference to the data tree.
-
inline size_t get_qubit_num() const¶
Number of physical qubits occupied by the circuit: 2 * (2^addr_size - 1).
-
inline size_t memory_size() const¶
Total number of memory slots.
-
inline void set_branches(const std::vector<BranchGroup> &branch_groups_)¶
Injects branch groups directly (for state_manipulator / tests; see init_state).
- 参数:
branch_groups_ -- Branch group collection
-
inline void set_branches(std::vector<BranchGroup> &&branch_groups_)¶
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void _set_input_impl(size_t n_inputs, bool uniform)¶
Samples n (addr, bus) input branches to fill branch_groups.
The input probabilities of the branches are normalized together at the end.
- 参数:
n_inputs -- Number of input branches to sample
uniform -- true: every branch has equal input probability; false: input probability ~ U(0,1)
-
inline void set_input_random(size_t n_inputs)¶
Randomly samples n input branches with input probability ~ U(0,1), then normalizes.
-
inline void set_input_uniform(size_t n_inputs)¶
Randomly samples n input branches with equal input probability each.
-
inline auto &get_branch_groups() const¶
Returns all branch groups (const).
-
inline auto &get_operations() const¶
Returns the noisy operation sequence actually executed (const).
-
inline auto &get_branch_groups()¶
Returns all branch groups.
-
inline auto &get_operations()¶
Returns the noisy operation sequence actually executed.
-
inline void clear_noise()¶
- Deprecated:
Clears the noise model; use set_noise_models instead
-
inline void add_noise_model(OperationType t, double v)¶
- Deprecated:
Appends a single noise entry; use set_noise_models to set all at once instead
-
inline void set_noise_models(const std::map<OperationType, double> &noises)¶
Sets the noise model.
Probability parameters are range-checked: all probabilities must lie in [0,1]; Damping additionally requires gamma < 1 (gamma = 1 would extinguish all excitations in a single step, zeroing the trajectory norm and breaking sample_output / normalization); out-of-range values throw std::runtime_error.
- 参数:
noises -- A {operation type: occurrence probability} map
-
inline bool is_noise_free() const¶
Whether no noise is currently set.
-
inline bool has_damping() const¶
Whether the noise model contains Damping.
-
void initialize_system()¶
Generates the noisy operation sequence and resets all branch groups.
The operation sequence is generated via time_step.generate(noise_parameters, arch_qubit), which also clears the good branch indices and the valid branch view (called internally by the run series).
-
double sample_and_get_fidelity()¶
Samples an output branch and computes the loading fidelity |<ideal|actual>|^2.
- 返回:
The fidelity under the sampled trajectory; returns 0 when there are no branches
-
inline double get_fidelity()¶
Alias of sample_and_get_fidelity.
-
void prepare_observables()¶
Materialize implicit pruned outputs without measuring or drawing RNG.
-
double logical_query_fidelity()¶
Fidelity of the reduced address/bus state with the ideal query. Requires one canonical ground-tree, zero-bus input column per address with normalized nonnegative branch probabilities. Call after a completed run, before any output/tree measurement. Traces out the routing tree; it does not postselect or demand that the tree return to its ground state. Materializes pruned outputs through prepare_observables() and consumes no RNG.
-
void prepare_bad()¶
Preparation phase of a pruned run (called internally by run()).
Builds valid_branch_group_view (including only the branch groups to be evolved)
Determines first_good_branch_group (the prediction reference)
Marks branches[i].good and sets its bus output
Collects good_branch_group_ids
-
void prepare_all()¶
Preparation phase of an unpruned run (called internally by run_all()).
Builds valid_branch_group_view (including all branch groups).
-
void prepare_good_only()¶
Preparation phase of a good-branches-only run (called internally by run_good_only()).
Builds the good_only valid_branch_group_view
Determines first_good_branch_group
Marks branches[i].good and sets its bus output
Collects good_branch_group_ids
-
void run_acopy(int layer)¶
Executes the address copy operation: nodes at layer layer write direction a.
-
void run_swap(size_t layer_id)¶
Executes the plain swap at layer layer_id.
-
void run_cswap(size_t layer_id)¶
Executes the controlled swap at layer layer_id.
-
void run_bitflip(size_t qubit_id)¶
Executes a bit flip on qubit qubit_id (noise).
-
void run_phaseflip(size_t qubit_id, double depol_id)¶
Executes a phase flip on qubit qubit_id (noise; depol_id is an associated parameter).
-
void run_bitphaseflip(size_t qubit_id)¶
Executes a combined bit-phase flip on qubit qubit_id (noise).
-
void run_depolarizing(size_t qubit_id, double depol_id)¶
Executes depolarizing on qubit qubit_id (noise).
-
void run_hadamard()¶
Executes the Hadamard transform on the bus.
-
void run_fetchdata(size_t digit)¶
Fetches bit digit from the data tree to the bus (FetchData).
-
void run_busin(size_t digit)¶
Bus input of bit digit.
-
void run_busout(size_t digit)¶
Bus output of bit digit.
-
void apply_damping_outcome(const std::vector<size_t> &jumps, double gamma)¶
Apply sorted, unique, in-range jump positions to every represented component; no sampling. The common sqrt(gamma)^|J| factor is omitted (conditional-state gauge).
-
void run_damping_layer(const std::vector<size_t> &candidates, size_t step, double gamma)¶
Resolve all candidates jointly, attenuate once, and normalize once. Empty candidate sets need no auxiliary random draw.
-
void run_damp_full(size_t qubit_id, size_t step, double gamma)¶
Legacy singleton-candidate primitive: projection only, no K0 layer. Multiple candidates MUST be passed together to run_damping_layer. This method is retained for source compatibility and fixed-outcome probes.
-
void run_damp_common(double gamma)¶
System-wide common amplitude damping (noise; multiplies the damping factor by the non-zero element count).
-
void clear_zero_elements()¶
Cleans up sparse elements with zero amplitude.
-
std::string to_string() const¶
Returns a circuit summary string.
-
std::string to_string_full_info() const¶
Returns the full info string including branch details.
-
double get_normalization_factor() const¶
Normalization factor without Damping.
-
double get_normalization_factor_with_damping() const¶
Normalization factor with Damping.
-
void normalization()¶
Normalizes all branch amplitudes under the current noise model.
-
void materialize_good_branches()¶
Materializes the reference good branch's system states for the remaining good branches (XOR mirror prediction).
-
void sample_output()¶
Samples an output bus state according to branch_probs.
The sampled result is written to each branch group and to final_system_state; the subsequent sample_and_get_fidelity computes the fidelity on that sampled trajectory.
-
inline std::string mem_to_string() const¶
- Deprecated:
Use fmt::format("{}", memory) instead
-
void run_good()¶
Evolves good branches only (internal debugging entry).
-
void run_bad()¶
Evolves the branches in valid_branch_group_view (the actual execution core of the run series).
-
void run()¶
Generates the operation sequence and runs in pruned mode (equivalent to run_normal).
-
void run_all()¶
Runs all branches without pruning (plain version for debugging, helps verify run()).
-
void run_full()¶
Runs all branches without pruning: the unpruned ground-truth reference.
-
void run_normal()¶
Pruned run: fully simulate bad branches + one good branch as reference (the everyday default entry).
-
void run(std::string version)¶
Runs according to a version string.
- 参数:
version -- "full"/"old": no pruning; "normal"/"new": pruning; "fast": good branches only; anything else throws an invalid-input exception
Public Members
-
size_t addr_size¶
Address width (depth of the data tree).
-
size_t data_size¶
Data width (number of bits per memory slot).
-
memory_t memory¶
Data tree: memory[i] is the data_size-bit integer stored at address i.
-
TimeSlices raw_operations¶
Raw operation sequence before noise injection (for debugging).
-
TimeSlices operations¶
Noisy operation sequence actually executed (generated by initialize_system).
-
noise_t noise_parameters¶
Noise model: {operation type: occurrence probability}.
-
std::vector<BranchGroup> branch_groups¶
All branch groups (one BranchGroup per address).
-
std::vector<BranchGroup*> valid_branch_group_view¶
View of the branch groups to be evolved in this run (after pruning).
-
ptrdiff_t first_good_branch_group = -1¶
Index of the first good branch group (serves as the prediction reference for the other good branches); -1 if none.
-
std::vector<size_t> good_branch_group_ids¶
Indices of the remaining good branch groups besides the reference.
-
double total_prob = 0¶
Total probability of the sampled output branches (for normalization checks).
-
size_t fired_jump_count = 0¶
Number of damping (K1) jumps fired during the last run (diagnostic: lets tests assert the fired-jump path was actually exercised).
-
qram_state_t final_system_state¶
Final system state obtained from sampling.
Public Static Attributes
-
static constexpr auto FULL_VER = "full"¶
Version string constant for run(version="full").
-
static constexpr auto NORMAL_VER = "normal"¶
Version string constant for run(version="normal").
-
struct DampingOutcome¶
One joint environment outcome per damping layer, retained for circuit replay.
电路(qutrit 架构)¶
-
struct QRAMCircuit¶
Branch-based sparse simulator of the QRAM loading circuit (qutrit architecture).
Every tree node is a three-level system (qutrit): address level addr ∈ {W, L, R} and data level data ∈ {0, 1}. SubBranch trajectories are evolved along the noisy operation sequence, with support for good/bad branch pruning and output-sampling fidelity evaluation.
The typical workflow matches qram_qubit::QRAMCircuit: construct → set memory → set noise → set_input_* → run_normal / run_full → sample_and_get_fidelity.
备注
run(version) requires a non-empty noise model to be set first; for noise-free scenarios call run_normal / run_full directly (this should be handled outside QRAMCircuit).
Public Functions
-
inline QRAMCircuit(size_t address_sz, size_t data_sz)¶
Constructs the QRAM circuit (memory uninitialized).
- 参数:
address_sz -- Address width
data_sz -- Data width
-
inline QRAMCircuit(size_t address_sz, size_t data_sz, const memory_t &memory_)¶
Constructs the QRAM circuit and initializes it with the given data tree (copy).
- 参数:
address_sz -- Address width
data_sz -- Data width
memory_ -- Data tree (length must be 2^address_sz)
-
inline QRAMCircuit(size_t address_sz, size_t data_sz, memory_t &&memory_)¶
Constructs the QRAM circuit and initializes it with the given data tree (move).
- 参数:
address_sz -- Address width
data_sz -- Data width
memory_ -- Data tree (rvalue)
-
inline size_t get_qubit_num() const¶
Number of physical qubits occupied by the circuit: 2 * (2^address_size - 1).
-
inline size_t memory_size() const¶
Total number of memory slots.
-
virtual void set_memory_random()¶
Randomly fills the entire data tree using the global random engine.
-
virtual void set_memory(const memory_t &new_memory)¶
Sets the data tree (copy).
-
virtual void set_memory(memory_t &&new_memory)¶
Sets the data tree (move).
-
inline auto &get_memory()¶
Returns a reference to the data tree.
-
inline auto &get_memory() const¶
Returns a const reference to the data tree.
-
inline auto &get_branches() const¶
Returns all branches (const).
-
inline auto &get_branches()¶
Returns all branches.
-
inline auto &get_branch_probs() const¶
Returns all branch probabilities (const).
-
inline auto &get_branch_probs()¶
Returns all branch probabilities.
-
inline auto &get_operations() const¶
Returns the noisy operation sequence (const).
-
inline auto &get_operations()¶
Returns the noisy operation sequence.
-
inline void set_noise_models(const noise_t &noises)¶
Sets the noise model.
Probability parameters are range-checked: all probabilities must lie in [0,1]; Damping additionally requires gamma < 1 (gamma = 1 would extinguish all excitations in a single step, zeroing the trajectory norm and breaking sample_output / normalization); out-of-range values throw std::runtime_error.
- 参数:
noises -- A {operation type: occurrence probability} map
-
inline auto &get_noise_models()¶
Returns the current noise model.
-
inline auto &get_noise_models() const¶
Returns the current noise model (const).
-
inline bool is_noise_free() const¶
Whether no noise is currently set.
-
inline bool has_damping() const¶
Whether the noise model contains Damping.
-
void initialize_system()¶
Generates the noisy operation sequence and initializes the branch structure (called internally by the run series).
-
void set_input_random(size_t n_inputs)¶
Randomly samples n input branches and randomly fills the branch probabilities.
-
void set_input_uniform(size_t n_inputs)¶
Randomly samples n input branches with equal input probability each.
-
double sample_and_get_fidelity()¶
Samples an output branch and computes the loading fidelity |<ideal|actual>|^2.
- 返回:
The fidelity under the sampled trajectory
-
void pick_good_bad()¶
Preparation phase of a pruned run (called internally by run_normal).
Builds valid_branch_view (including only the branches to be evolved)
Determines first_good_branch (the prediction reference)
Marks branches[i].good and sets its bus output
Collects good_branch_ids
-
void pick_all()¶
Preparation phase of an unpruned run (called internally by run_full).
Builds valid_branch_view (including all branches).
-
void run_acopy(int layer)¶
Executes the address copy operation: nodes at layer layer write direction a.
-
void run_swap(size_t layer_id)¶
Executes the plain swap at layer layer_id.
-
void run_cswap(size_t layer_id)¶
Executes the controlled swap at layer layer_id.
-
void run_bitflip(size_t qubit_id)¶
Executes a bit flip on qubit qubit_id (noise).
-
void run_phaseflip(size_t qubit_id, double depol_id)¶
Executes a phase flip on qubit qubit_id (noise; depol_id is an associated parameter).
-
void run_bitphaseflip(size_t qubit_id)¶
Executes a combined bit-phase flip on qubit qubit_id (noise).
-
void run_depolarizing(size_t qubit_id, double depol_id)¶
Executes depolarizing on qubit qubit_id (noise).
-
void run_hadamard()¶
Executes the Hadamard transform on the bus.
-
void run_fetchdata(size_t digit)¶
Fetches bit digit from the data tree to the bus (FetchData).
-
void run_busin(size_t digit)¶
Bus input of bit digit.
-
void run_busout(size_t digit)¶
Bus output of bit digit.
-
void run_damp_full(size_t qubit_id, size_t step, double gamma)¶
Full amplitude damping on the given qubit (noise; gamma is the decay rate).
-
void run_damp_common(double gamma)¶
System-wide common amplitude damping (noise).
-
void clear_zero_elements()¶
Cleans up sparse elements with zero amplitude.
-
double get_normalization_factor() const¶
Normalization factor under the current noise model (including Damping).
-
double get_normalization_factor_without_damping() const¶
Normalization factor without Damping.
-
double get_normalization_factor_with_damping() const¶
Normalization factor with Damping.
-
void normalization()¶
Normalizes all branch amplitudes under the current noise model.
-
void normalization_without_damping()¶
Normalization without Damping.
-
void normalization_with_damping()¶
Normalization with Damping.
-
void sample_output_without_normalization()¶
Output sampling (internal variant that skips normalization).
-
void sample_output_without_normalization_with_damping()¶
Output sampling (internal variant with Damping that skips normalization).
-
void sample_output_without_normalization_without_damping()¶
Output sampling (internal variant without Damping that skips normalization).
-
void sample_output()¶
Samples an output bus state according to branch_probs (path without Damping).
-
void run_good()¶
Marks good branches and determines the prediction reference (run precondition).
-
void run_valid_branches()¶
Evolves the branches in valid_branch_view (the actual execution core of the run series).
-
void run_normal()¶
Pruned run: fully simulate bad branches + one good branch as reference (the everyday default entry).
-
void run_good_only()¶
Runs good branches only (currently unimplemented).
-
void run_good_only_without_damping()¶
Runs good branches only (variant without Damping, currently unimplemented).
-
void run_good_only_with_damping()¶
Runs good branches only (variant with Damping, currently unimplemented).
-
void run(const std::string &version)¶
Runs according to a version string.
Returns immediately when there are no input branches; throws an invalid-input exception when no noise is set (noise-free scenarios should be handled outside QRAMCircuit).
- 参数:
version -- "full"/"old": no pruning; "new"/"normal": pruning; anything else throws an invalid-input exception
-
std::string to_string() const¶
Returns a circuit summary string.
-
std::string to_string_full_info() const¶
Returns the full info string including branch details.
Public Members
-
size_t address_size¶
Address width (depth of the data tree).
-
size_t data_size¶
Data width (number of bits per memory slot).
-
memory_t memory¶
Data tree: memory[i] is the data_size-bit integer stored at address i.
-
TimeSlices operations¶
Noisy operation sequence actually executed (generated by initialize_system).
-
noise_t noise_parameters¶
Noise model: {operation type: occurrence probability}.
-
std::vector<double> branch_probs¶
Probabilities of all branches (used for sampling and Damping noise evaluation).
-
std::vector<Branch*> valid_branch_view¶
View of the branches to be evolved in this run. version: "full" all branches; "normal" first good branch + all bad branches; "fast" no branches to evolve (short-circuit computation)
-
int64_t first_good_branch = -1¶
Index of the first good branch (serves as the prediction reference for the other good branches); -1 if none.
-
std::vector<size_t> good_branch_ids¶
Indices of the remaining good branches besides the reference.
-
qram_state_t final_system_state¶
Final system state obtained from sampling.
-
inline QRAMCircuit(size_t address_sz, size_t data_sz)¶
时序与噪声调度¶
-
struct TimeStep¶
Timing and noise scheduler for the QRAM loading circuit.
Derives the routing, copy, and swap operations of each time slice from the address / data width (generate_step), and can insert noise operations after each time slice according to a noise model, producing the complete TimeSlices schedule (generate). QRAMCircuit holds a TimeStep instance internally. Also provides bad branch range (bad range) derivation: given some faulty qubit / node, it derives the address range that would load wrong data.
Public Functions
-
TimeStep(size_t addr_sz, size_t data_sz)¶
Constructs the scheduler.
- 参数:
addr_sz -- Address width
data_sz -- Data width
-
size_t full_step() const¶
Total number of time slices of the full loading procedure.
-
size_t out(size_t in_step) const¶
Returns the output (copy-out) time slice index corresponding to step in_step.
-
size_t last_step() const¶
Index of the last time slice.
-
int acopy(size_t step) const¶
Target layer (direction) of the address copy at step step; returns -1 if there is no operation.
-
int acopy_out(size_t step) const¶
Output time slice of the address copy at step step; returns -1 if none.
-
int dcopy(size_t step) const¶
Target bit of the data copy at step step; returns -1 if there is no operation.
-
int dcopy_out(size_t step) const¶
Output time slice of the data copy at step step; returns -1 if none.
-
size_t route_begin(size_t layer) const¶
Starting time slice of the routing phase of layer layer.
-
size_t route_wait_begin(size_t layer) const¶
Starting time slice of the routing-wait phase of layer layer.
-
bool route_odd(size_t step, size_t layer) const¶
Whether step step routes through the odd (right) subtree at layer layer.
-
bool route_even(size_t step, size_t layer) const¶
Whether step step routes through the even (left) subtree at layer layer.
-
bool route(size_t step, size_t layer) const¶
Routing decision of step step at layer layer (odd/even dispatch).
-
int memory_copy(size_t step) const¶
Memory copy bit of step step; returns -1 if there is no operation.
-
int internal_swap(size_t time_step) const¶
Internal swap target of a node at step time_step; returns -1 if there is no operation.
-
int internal_swap_out(size_t time_step) const¶
Output time slice of the internal swap at step time_step; returns -1 if none.
-
OperationPack generate_step(size_t step) const¶
Generates the operation pack of time slice step (noise excluded).
-
size_t layer_entangle_max(size_t time_step) const¶
Maximum number of layers that can be entangled at step time_step (basis for the noise insertion range).
-
bool is_bad_branch(size_t addr) const¶
Checks whether address addr falls within the bad branch interval.
-
std::pair<size_t, size_t> get_bad_range_qubit(size_t bad_qubit) const¶
qubit architecture: derives the bad branch address range [lo, hi] from faulty qubit bad_qubit
-
std::pair<size_t, size_t> get_bad_range_qutrit(size_t bad_qubit) const¶
qutrit architecture: derives the bad branch address range [lo, hi] from faulty qubit bad_qubit
-
void fill_bad_range(size_t qubit, int arch_type)¶
Fills the bad branch interval set cr.
- 参数:
qubit -- The faulty qubit / node
arch_type -- Architecture constant (arch_qubit / arch_qutrit)
-
void noise_one_step(OperationPack &pack, size_t max_entangle_layer, const std::map<OperationType, double> &noises, int arch_type)¶
Appends the noise operations following one time slice to pack.
- 参数:
pack -- Target operation pack
max_entangle_layer -- Maximum number of layers that can be entangled in that time slice
noises -- Noise model
arch_type -- Architecture constant
-
void noise_one_step(size_t max_entangle_layer, const std::map<OperationType, double> &noises, int arch_type)¶
Generates the noise operations of one time slice (without inserting them into any OperationPack).
- 参数:
max_entangle_layer -- Maximum number of layers that can be entangled
noises -- Noise model
arch_type -- Architecture constant
-
void init_noise_free()¶
Generates the noise-free schedule and caches it in time_slices_noise_free.
-
void append_noise_range_only(const std::map<OperationType, double> &noises, int arch_type)¶
Appends noise intervals only (does not generate the noisy operation sequence).
-
TimeSlices append_noise(const std::map<OperationType, double> &noises, int arch_type)¶
Inserts noise into the cached noise-free schedule and returns the noisy schedule.
-
TimeSlices generate(const std::map<OperationType, double> &noises, int arch_type)¶
Generates the complete noisy schedule.
- 参数:
noises -- Noise model (may be empty, i.e. a noise-free schedule)
arch_type -- Architecture constant (arch_qubit / arch_qutrit)
- 返回:
The noisy TimeSlices schedule
-
ptrdiff_t _get_multiplier_impl_qubit(size_t step, size_t addr) const¶
qubit architecture: implementation of the damping multiplier exponent for address addr at step step
-
ptrdiff_t _get_multiplier_impl_qutrit(size_t step, size_t branch_id, const memory_t &mem) const¶
qutrit architecture: implementation computing the damping multiplier exponent from branchid
-
ptrdiff_t _get_multiplier_impl_qutrit(size_t step, size_t addr, size_t data, const memory_t &mem) const¶
qutrit architecture: implementation computing the damping multiplier exponent from (addr, data)
-
template<typename BranchType>
inline void get_multiplier_qubit(double gamma, size_t step, std::vector<BranchType> &branches, size_t first_good_branch, const std::vector<size_t> &good_branch_ids) const¶ qubit architecture: computes the relative Damping multiplier for good branches.
Using the first good branch as the reference, sets branch.relative_multiplier = (1-gamma)^(exponent difference) according to each good branch's address damping exponent difference.
- 参数:
gamma -- Damping decay rate
step -- Time slice
branches -- Branch collection
first_good_branch -- Index of the reference good branch
good_branch_ids -- Indices of the remaining good branches
-
template<typename BranchType>
inline void get_multiplier_qutrit(double gamma, size_t step, std::vector<BranchType> &branches, size_t first_good_branch, const std::vector<size_t> &good_branch_ids, const memory_t &memory) const¶ qutrit architecture: computes the relative Damping multiplier for good branches.
Semantics identical to get_multiplier_qubit, with the damping multiplier derived from branchid and the contents of the data tree.
- 参数:
gamma -- Damping decay rate
step -- Time slice
branches -- Branch collection
first_good_branch -- Index of the reference good branch
good_branch_ids -- Indices of the remaining good branches
memory -- Data tree
-
inline void print() const¶
Prints the schedule details of all time slices to stdout (fmt output).
Public Members
-
size_t addr_size¶
Address width.
-
size_t data_size¶
Data width.
-
ContinuousRange cr¶
Bad branch interval set (filled by fill_bad_range).
-
TimeSlices time_slices_noise_free¶
Cached noise-free schedule (generated by init_noise_free).
-
TimeStep(size_t addr_sz, size_t data_sz)¶
-
struct TimeSlices¶
Complete QRAM loading schedule: a sequence of OperationPacks ordered by time slice.
Public Functions
-
inline void clear()¶
Clears the schedule.
-
inline void append(const OperationPack &op)¶
Appends a single time slice.
-
inline void append(const TimeSlices &ts)¶
Appends all time slices of another schedule.
-
inline TimeSlices reverse()¶
Returns the inverse schedule: reversed as a whole with each pack inverted.
-
std::string to_string() const¶
Returns a human-readable string representation.
Public Members
-
std::vector<OperationPack> time_slices¶
List of time slices (the i-th element is the operation pack of the i-th time slice).
-
inline void clear()¶
-
struct OperationPack¶
A set of operations executed concurrently within one time slice.
Mutually non-adjacent nodes of the QRAM tree can be operated on in parallel within the same time slice; OperationPack bundles them into one scheduling unit identified by name.
Public Functions
-
inline OperationPack reverse()¶
Returns the inverse operation pack: reverses the order and inverts each operation.
-
inline bool empty() const¶
Whether this pack is empty.
-
inline void set_name(std::string s)¶
Sets the pack name.
-
inline void append(OperationPack ops)¶
Appends all operations of another pack and concatenates the names.
- 参数:
ops -- The pack being merged in
-
std::string to_string() const¶
Returns a human-readable string representation.
-
inline OperationPack reverse()¶
-
struct Operation¶
A single quantum operation.
Describes one gate / noise event: the type, the target qubit (or node) indices, and optional noise coefficients (e.g. gamma of Damping).
-
struct ContinuousRange¶
A set of continuous intervals (merged representation of bad branch ranges).
Represents an address set as an ordered collection of disjoint intervals [l1,r1],[l2,r2],...; merge incorporates a new interval [l,r] according to 4 intersection cases, and accept checks whether address t falls inside the set. Used for TimeStep's bad range computation.
Public Functions
-
ContinuousRange(int l, int r)¶
Constructs a single interval [l, r].
-
void clear()¶
Clears all intervals.
-
void merge(int l, int r)¶
Merges in a new interval [l, r] (staying ordered and disjoint).
-
bool accept(int t) const¶
Checks whether t falls within any interval.
-
operator std::string()¶
Returns a human-readable string representation.
Public Members
-
std::vector<int> range_bound¶
Sequence of interval endpoints: [l1,r1,l2,r2,...].
-
ContinuousRange(int l, int r)¶
分支结构(qubit 架构)¶
-
struct BranchGroup¶
Aggregation of all input branches at the same address (the pruning unit of the qubit architecture).
BranchGroup aggregates Branch per address: groups at good addresses only need to materialize the reference branch (XOR mirror prediction), while groups at bad addresses are evolved one by one; the group level provides probability, fidelity, and output sampling interfaces, and QRAMCircuit manages good/bad pruning at BranchGroup granularity.
Public Functions
-
inline BranchGroup(size_t addr)¶
Constructs an empty group at address addr.
-
void reset()¶
Resets all branches and flags.
-
void set_good(BranchGroup *good_ref_)¶
Marks as a good group and binds the prediction reference.
-
void set_empty_state()¶
Clears all branch states (branch skeleton kept).
-
void mark_annihilated()¶
Marks the group as annihilated by a fired damping jump (zero weight everywhere) and clears all branch states.
-
complex_t get_fidelity(const memory_t &memory) const¶
Fidelity amplitude against the data tree (modulus not squared).
-
Branch::damp_prob_type get_prob_damp(size_t qubit_id) const¶
Trajectory probability under Damping.
-
double get_prob() const¶
Total probability of all branches in this group.
-
bool sample_output_no_damping(Branch::element_type &output, double &r)¶
Output sampling without Damping: r is a uniform random number; returns whether sampling succeeded.
Public Members
-
size_t address¶
Group address.
-
std::vector<double> branch_probs¶
Per-branch probabilities <ui|ui>.
-
std::vector<double> state_probs¶
Per-state probabilities <ψi|ψi>.
-
bool is_good = false¶
Whether this group is a good group (address outside the bad branch interval).
-
BranchGroup *good_ref = nullptr¶
Prediction reference for good groups (pointer to the first good group).
-
double relative_multiplier = 1.0¶
Relative Damping multiplier (relative to the reference good group).
-
bool predicted = false¶
Whether final states have been reconstructed; probability and fidelity then use those states.
-
bool annihilated = false¶
Whether the predicted group has zero surviving weight.
Set during materialization when the shared reference has no surviving component. All probability, fidelity and sampling paths must then contribute zero. Mid-run estimates already inherit the reference norm. reset() clears this flag while retaining the original input weights.
-
inline BranchGroup(size_t addr)¶
-
struct Branch¶
Trajectory container of a single (address, bus_input) input branch.
Holds a set of SystemState (multiple trajectories split from the same input under noise / merging), and supports fidelity computation against the data tree and output sampling.
Public Types
-
using damp_prob_type = std::array<double, 1>¶
Damping probability array type (single element in the qubit architecture).
Public Functions
-
void set_good(Branch *first_good_ptr)¶
Marks this branch as a good branch and binds the prediction reference.
-
inline bool is_good() const¶
Whether this branch is a good branch (loading result consistent with the data tree).
-
inline auto iterbeg()¶
Iterator to the beginning of valid trajectories.
-
inline auto iterbeg() const¶
Iterator to the beginning of valid trajectories (const).
-
inline auto iterend()¶
Iterator to the end of valid trajectories.
-
inline auto iterend() const¶
Iterator to the end of valid trajectories (const).
-
template<typename Pred>
inline void remove_if(Pred pred)¶ Removes trajectories not satisfying predicate pred and shrinks the valid length.
-
inline void reset()¶
Resets to a single initial trajectory (initial bus value bus_input), clearing the good-branch flag.
-
Branch(size_t addr, size_t bus_sz, bus_t bus)¶
Constructs with an explicit (address, bus value).
- 参数:
addr -- Address
bus_sz -- Bus width
bus -- Bus value
-
Branch(size_t branchid, size_t bus_sz)¶
Constructs from a branch ID (address and bus value extracted automatically).
- 参数:
branchid -- (address << bus_sz) | bus_input
bus_sz -- Bus width
-
inline bool operator<(const Branch &other) const¶
Lexicographic comparison by (address, input bus, trajectory set).
-
double get_prob() const¶
Total probability of this branch's trajectories (sum of squared amplitude moduli).
-
complex_t get_fidelity(const memory_t &memory) const¶
Fidelity amplitude against the data tree (modulus not squared).
-
std::string to_string() const¶
Returns a human-readable string representation.
-
void run_fetchdata(memory_t &memory, size_t digit)¶
Fetches bit digit from the data tree memory to the bus (FetchData).
-
void run_hadamard()¶
Hadamard transform on the bus.
-
void try_merge()¶
Merges identical trajectories (amplitudes added up).
-
std::optional<element_type> get_good_branch_system() const¶
Tree state of the reference good branch trajectory (valid when this branch is a good branch).
-
void run_damp_common(double gamma)¶
Common amplitude damping (same as SystemState::run_damp_common).
-
damp_prob_type get_prob_damp(size_t qubit_id) const¶
Returns the trajectory probability under Damping (corrected by the excitation count at qubit_id).
-
void run_damp_full(size_t qubit_id, size_t k)¶
Full amplitude damping: splits trajectories at qubit_id by damping step count k.
-
void remove_mismatch_state(const State::element_type &target_state)¶
Removes trajectories not matching the target tree state (cleanup after output sampling).
-
void remove_all_state()¶
Removes all trajectories.
-
inline void clear_all_state()¶
Clears valid trajectories (sets system_states_sz = 0).
Public Members
-
size_t bus_size = 1¶
Bus width.
-
bus_t bus_input = 0¶
Input bus value.
-
double relative_multiplier = 1¶
Relative Damping multiplier (relative to the reference good branch, used for amplitude prediction).
-
Branch *good_ref = nullptr¶
Prediction reference for good branches (pointer to the first good branch).
-
std::vector<SystemState> system_states¶
All trajectories of this branch (including split ones).
-
size_t system_states_sz = 0¶
Number of valid trajectories (the first system_states_sz entries of system_states are valid).
Public Static Attributes
-
static constexpr int qunit_type = arch_qubit¶
Architecture identifier: qubit.
-
using damp_prob_type = std::array<double, 1>¶
-
struct SystemState¶
System state with a data bus and an amplitude (a single element of a branch trajectory).
Composed of the sparse tree state State, the data_size-bit data bus data_bus, and the complex amplitude; the run_* series applies gate / noise operations to the tree state and the bus simultaneously, evolving one trajectory.
Public Functions
-
inline SystemState(bus_t bus_, size_t bus_sz)¶
Constructs with the given initial bus value.
- 参数:
bus_ -- Bus value
bus_sz -- Bus width
-
inline bool operator<(const SystemState &rhs) const noexcept¶
Lexicographic comparison by (bus value, tree state).
-
inline bool operator==(const SystemState &rhs) const noexcept¶
Equality test (same bus value and tree state).
-
void run_acopy(bool a)¶
Address copy: writes into the data slot in direction a.
-
void run_swap(size_t node)¶
Plain swap at node node.
-
void run_cswap(size_t node)¶
Controlled swap at node node.
-
void run_bitflip(size_t qubit_id)¶
Bit flip at location qubit_id (noise).
-
void run_phaseflip(size_t qubit_id, double depol_id)¶
Phase flip at location qubit_id (noise, amplitude negated).
-
void run_bitphaseflip(size_t qubit_id)¶
Combined bit-phase flip at location qubit_id (noise).
-
void run_depolarizing(size_t qubit_id, double depol_id)¶
Depolarizing at location qubit_id (noise).
-
void set_zero(size_t qubit_id)¶
Set to zero at location qubit_id (noise).
-
void run_busin(size_t digit)¶
Bus input of bit digit.
-
void run_busout(size_t digit)¶
Bus output of bit digit.
-
inline void run_damp_common(double gamma)¶
Common amplitude damping: multiplies by sqrt(1-gamma)^|nz| per the number of non-zero elements.
-
inline void clear()¶
Clears the tree state and resets the amplitude.
-
inline SystemState(bus_t bus_, size_t bus_sz)¶
-
struct State¶
A sparse computational basis state represented by the set of non-zero basis nodes.
The state of a complete binary QRAM tree only needs to record the node positions in |1> (nz_elements); all other nodes are implicitly |0>. The level-order numbering of the tree satisfies the bitwise left/right/parent relations. All gate operations are implemented as insertions/deletions on the sparse set, with complexity on the order of the number of non-zero elements.
Public Functions
-
std::pair<iterator_type, iterator_type> get_layer_iter(size_t layerid)¶
Returns the element iterator range [begin, end) of layer layerid.
-
void get_layer_nonzero_nodes(size_t layerid, std::set<size_t> &nodes)¶
Collects the non-zero node indices of layer layerid.
-
void get_layer_nonzero_parent_nodes(size_t layerid, std::set<size_t> &nodes)¶
Collects the non-zero parent node indices of layer layerid.
-
inline void clear_zero_elements()¶
Compatibility interface: a qubit basis state has no zero-amplitude elements to clean up, so this is always a no-op.
-
bool state_of(size_t nz_location) const¶
Checks whether the qubit at location nz_location is |1>.
-
void busin(bus_t &bus, size_t digit)¶
Bus input: writes bus bit digit into the address slot.
-
void busout(bus_t &bus, size_t digit)¶
Bus output: reads the address slot out to bus bit digit.
-
void flip(size_t nz_location)¶
Flips the qubit at location nz_location (X gate).
-
void cnot(size_t nz_location, bool condition)¶
Conditional NOT: flips nz_location when condition is true.
-
void general_swap(size_t nz_l, size_t nz_r)¶
General swap between two arbitrary locations nz_l / nz_r.
-
void internal_swap(size_t node_location)¶
Internal (address slot - data slot) swap within node node_location.
-
void internal_swap_layer(size_t layerid)¶
Internal swap of all nodes at layer layerid.
-
void acopy(bool a)¶
Address copy: writes the address slot into the data slot in direction a (FirstCopy).
-
void cswap(size_t node_location)¶
Controlled swap (CSWAP) at node node_location.
-
void cswap_layer(size_t layerid)¶
Controlled swap of all nodes at layer layerid.
-
void set_zero(size_t qubit_id)¶
Sets the qubit at location qubit_id to zero (noise SetZero).
-
inline void clear()¶
Clears all non-zero elements (back to all |0>).
Public Members
-
std::set<size_t> nz_elements¶
Set of node positions in |1> (non-zero elements).
Public Static Functions
-
static constexpr size_t get_nz_location(size_t layer, size_t pos, size_t lr)¶
Encodes a non-zero element location from a layer number and an in-layer position.
- 参数:
layer -- Layer number
pos -- In-layer position
lr -- Left (0) / right (1) child
- 返回:
The location key of the node in nz_elements
-
static constexpr size_t get_nz_location(size_t node_location, size_t lr)¶
Encodes a non-zero element location from a node location and a left/right child flag.
- 参数:
node_location -- Node location
lr -- Left (0) / right (1) child
-
static constexpr size_t left_of(size_t node_location)¶
Location of the left child of node node_location.
-
static constexpr size_t right_of(size_t node_location)¶
Location of the right child of node node_location.
-
static constexpr size_t parent_of(size_t node_location)¶
Location of the parent of node node_location.
-
std::pair<iterator_type, iterator_type> get_layer_iter(size_t layerid)¶
分支结构(qutrit 架构)¶
-
struct Branch¶
Trajectory container of a single (address, bus_input) input branch (qutrit architecture).
Holds a set of SubBranch trajectories, providing fidelity against the data tree, output sampling, and Damping multiplier computation; get_multiplier forwards to the qutrit implementation of TimeStep.
Public Types
-
using damp_prob_type = std::array<double, 2>¶
Damping probability array type (two elements in the qutrit architecture).
Public Functions
-
inline Branch(size_t address_, size_t bus_sz_, memory_entry_t bus_input_)¶
Constructs with an explicit (address, bus value).
-
inline Branch(size_t branchid, size_t bus_sz)¶
Constructs from a branch ID (address and bus value extracted automatically).
- 参数:
branchid -- (address << bus_sz) | bus_input
bus_sz -- Bus width
-
inline auto iterbeg() const¶
Iterator to the beginning of trajectories (const).
-
inline auto iterend() const¶
Iterator to the end of trajectories (const).
-
inline auto iterbeg()¶
Iterator to the beginning of trajectories.
-
inline auto iterend()¶
Iterator to the end of trajectories.
-
inline auto system_size() const¶
Number of trajectories.
-
template<typename Pred>
inline void remove_if(Pred pred)¶ Removes trajectories not satisfying predicate pred (physical deletion).
-
inline void reset()¶
Resets to a single initial trajectory (initial bus value bus_input), clearing the good-branch flag.
-
void set_good(Branch *first_good_ptr)¶
Marks this branch as a good branch and binds the prediction reference.
-
inline bool is_good() const¶
Whether this branch is a good branch.
-
inline bool operator<(const Branch &other) const¶
Lexicographic comparison by (address, input bus, trajectory set).
-
double get_prob() const¶
Total probability of this branch's trajectories.
-
complex_t get_fidelity(const memory_t &memory) const¶
Fidelity amplitude against the data tree (modulus not squared).
-
std::string to_string() const¶
Returns a human-readable string representation.
-
void run_fetchdata(memory_t &memory, size_t digit)¶
Fetches bit digit from the data tree memory to the bus (FetchData).
-
void run_hadamard()¶
Hadamard transform on the bus.
-
void try_merge()¶
Merges identical trajectories (amplitudes added up).
-
std::optional<element_type> get_good_branch_system() const¶
Tree state of the reference good branch trajectory (valid when this branch is a good branch).
-
void run_damp_common(double gamma)¶
Common amplitude damping.
-
damp_prob_type get_prob_damp(size_t qubit_id) const¶
Trajectory probability under Damping.
-
void run_damp_full(size_t qubit_id, size_t k)¶
Full amplitude damping: splits trajectories at qubit_id by damping step count k.
-
void remove_mismatch_state(const QRAMState::element_type &target_state)¶
Removes trajectories not matching the target tree state.
-
void remove_all_state()¶
Removes all trajectories.
-
inline void clear_all_state()¶
Clears all trajectories.
Public Members
-
size_t bus_size = 1¶
Bus width.
-
memory_entry_t bus_input = 0¶
Input bus value.
-
double relative_multiplier = 1¶
Relative Damping multiplier (relative to the reference good branch).
-
Branch *good_ref = nullptr¶
Prediction reference for good branches (pointer to the first good branch).
-
double branch_prob = 0.0¶
Input probability of this branch.
Public Static Functions
-
static inline void get_multiplier(double gamma, const TimeStep &time_step, size_t step, std::vector<Branch> &branches, size_t first_good_branch, const std::vector<size_t> &good_branch_ids, const memory_t &memory)¶
Computes the relative Damping multiplier for good branches (forwards to TimeStep::get_multiplier_qutrit).
- 参数:
gamma -- Damping decay rate
time_step -- The scheduler
step -- Time slice
branches -- Branch collection
first_good_branch -- Index of the reference good branch
good_branch_ids -- Indices of the remaining good branches
memory -- Data tree
-
using damp_prob_type = std::array<double, 2>¶
-
struct SubBranch¶
Qutrit system state with a data bus and an amplitude (a trajectory unit).
Composed of the sparse tree state QRAMState, the data bus data_bus, and a complex amplitude; the run_* series executes gate / noise operations, evolving one trajectory.
Public Functions
-
inline SubBranch(memory_entry_t bus_, size_t bus_sz)¶
Constructs from an initial bus value.
- 参数:
bus_ -- Bus value
bus_sz -- Bus width
-
inline bool operator<(const SubBranch &rhs) const noexcept¶
Lexicographic comparison by (bus value, tree state).
-
void run_acopy(bool a)¶
Address copy: writes into the data level in direction a.
-
void run_swap(size_t node)¶
Plain swap at node node.
-
void run_cswap(size_t node)¶
Controlled swap at node node.
-
void run_bitflip(size_t qubit_id)¶
Data level flip at location qubit_id (noise).
-
void run_A1(size_t qubit_id)¶
A1 rotation gate at location qubit_id.
-
void run_A1_2(size_t qubit_id)¶
A1^2 rotation gate at location qubit_id.
-
void run_A2(size_t qubit_id)¶
A2 rotation gate at location qubit_id.
-
void run_A2_2(size_t qubit_id)¶
A2^2 rotation gate at location qubit_id.
-
void run_phaseflip(size_t qubit_id, double depol_id)¶
Phase flip at location qubit_id (noise, amplitude negated).
-
void run_bitphaseflip(size_t qubit_id)¶
Combined bit-phase flip at location qubit_id (noise).
-
void run_depolarizing(size_t qubit_id, double depol_id)¶
Depolarizing at location qubit_id (noise).
-
void set_zero(size_t qubit_id)¶
Reset to the ground state at location qubit_id (noise).
-
void run_busin(size_t digit)¶
Bus input of bit digit.
-
void run_busout(size_t digit)¶
Bus output of bit digit.
-
inline SubBranch(memory_entry_t bus_, size_t bus_sz)¶
-
struct QRAMState¶
A sparse qutrit tree state represented by a map of non-zero nodes.
Only nodes not in the (W,0) ground state are recorded (nz_elements, ordered by location); all other nodes are implicitly (W,0). Gate operations are implemented as insertions, deletions, and updates on the map.
Public Types
Public Functions
-
bool operator<(const QRAMState &rhs) const¶
Compares two sparse tree states (map lexicographic order).
-
void clear_zero_elements()¶
Cleans up zero-amplitude elements (a compatibility interface for qutrit tree states).
-
iterator_t iterof(size_t nnz_location)¶
Gets the iterator at location nnz_location (O(log n)).
-
const_iterator_t iterof(size_t nnz_location) const¶
Gets the constant iterator at location nnz_location (O(log n)).
-
iterator_t iterend()¶
End iterator (O(1)).
-
const_iterator_t iterend() const¶
Constant end iterator (O(1)).
-
void busin(bus_t &bus, size_t digit)¶
Bus input: writes bus bit digit into the node's data level.
-
void busout(bus_t &bus, size_t digit)¶
Bus output: reads the node's data level out to bus bit digit.
-
void acopy(bool a)¶
Address copy: writes the address level into the data level in direction a (FirstCopy).
-
void _unconditional_internal_swap(size_t node_location)¶
Unconditional within-node swap (underlying implementation of internal_swap).
-
void _impl_conditional_internal_swap(size_t node_location)¶
Conditional within-node swap (executed when the data level is 0).
-
void internal_swap_layer(size_t layerid)¶
Internal swap of all nodes at layer layerid.
-
void _impl_iter_swap(iterator_t iter, size_t target)¶
Moves the node at iterator iter to location target.
-
void cswap(size_t node_location)¶
Controlled swap (CSWAP) at node node_location.
-
void cswap_layer(size_t layerid)¶
Controlled swap of all nodes at layer layerid.
-
void flip(size_t qubit_id)¶
Flips the data level of the node at location qubit_id (noise).
-
void rotate_A1(size_t qubit_id)¶
Applies the A1 rotation gate at location qubit_id (phase w).
-
void rotate_A2(size_t qubit_id)¶
Applies the A2 rotation gate at location qubit_id (phase w^2).
-
int state_of(size_t qubit_id) const¶
Checks whether the node at location qubit_id is not in the ground state (returns a level tag).
-
void set_zero(size_t qubit_id)¶
Resets the node at location qubit_id back to the ground state (W,0) (noise SetZero).
-
std::string to_string() const¶
Returns a human-readable string representation.
Public Static Functions
-
static inline constexpr size_t get_nnz_location(size_t layer, size_t pos)¶
Encodes a node location from a layer number and an in-layer position (complete binary tree level-order numbering).
-
static inline constexpr size_t left_of(size_t node_location)¶
Location of the left child of node node_location.
-
static inline constexpr size_t right_of(size_t node_location)¶
Location of the right child of node node_location.
-
static inline constexpr size_t parent_of(size_t node_location)¶
Location of the parent of node node_location.
-
bool operator<(const QRAMState &rhs) const¶
-
struct QRAMNode¶
A single qutrit tree node: address level + data level.
The address level addr ∈ {W=-1, L=0, R=1} (W is the bus/waiting level), the data level data ∈ {0, 1}. Inline gate operations are implemented as level transitions: rotation gates A1/A2 (three-level unitaries carrying the w phase), internal swap, data flip, etc.
Public Functions
-
inline operator std::string() const¶
Converts to the readable string "(A,D)", e.g. "(W,0)".
-
inline QRAMNode(int a, int d)¶
Constructs from levels.
- 参数:
a -- Address level
d -- Data level
-
inline void data_flip()¶
Flips the data level 0↔1.
-
inline void addr_flip()¶
Flips the address level L↔R (W unchanged).
-
inline void data_setzero()¶
Sets the data level to 0.
-
inline void data_setone()¶
Sets the data level to 1.
-
inline void data_set(bool value)¶
Sets the data level to the given value.
-
inline void data_control_flip(bool classical_data)¶
Classically conditioned data flip: flips when classical_data is true.
-
inline void internal_swap()¶
Address-data level swap within a node (transfer between W and data).
-
inline bool rotate_A1()¶
A1 rotation gate (L→W→R→L). Returns whether a distinguishable state with data==0 is produced.
-
inline bool rotate_A2()¶
A2 rotation gate (R→W, L→R, W→L). Returns whether a distinguishable state with data==0 is produced.
-
inline bool check_0() const¶
Whether in the (W, 0) state.
-
inline operator std::string() const¶
Common 模块¶
全振幅桥接¶
-
class QRAMFullAmp¶
Bridge from a QRAM circuit to a full-amplitude state vector (adapted only for qram_qutrit::QRAMCircuit).
The external full-amplitude simulator provides the state vector and the qubit mapping; apply decomposes the state vector into QRAM input branches (_set_branches), runs one noisy QRAM loading on the branch circuit, samples the output, and reconstructs the result back into the complete state vector (_reconstruct), thereby embedding QRAM simulation into a larger circuit evolution workflow.
Typical usage (addr qubits {0,1}, data qubits {2,3}):
QRAMFullAmp qram(2, 2, {0,1,2,3}); qram->set_noise_models(noise); // run(version) requires a non-null noise model state = qram.apply(state, {0,1}, {2,3}, {}, "new");
Public Functions
-
inline QRAMFullAmp(size_t addr_sz, size_t data_sz, const memory_t &memory)¶
Construct the bridge: internally creates a qutrit QRAMCircuit and loads the data tree.
- 参数:
addr_sz -- Address width
data_sz -- Data width
memory -- Data tree (length must be 2^addr_sz)
-
inline ~QRAMFullAmp()¶
Release the internal circuit.
-
inline QRAMCircuit *get_instance()¶
Return the internal QRAMCircuit pointer.
-
inline QRAMCircuit *operator->()¶
Convenient access to internal QRAMCircuit members (e.g. set_noise_models).
-
void _set_branches_full(const std::vector<std::complex<double>> &state, const std::vector<size_t> &address_qubits, const std::vector<size_t> &data_qubits)¶
Full branch decomposition: fully decompose the state vector by (addr, data) into 2^(addr+data) branches.
Applicable when the total number of branches does not exceed 25 bits.
- 参数:
state -- Full-amplitude state vector
address_qubits -- Address qubit indices
data_qubits -- Data qubit indices
-
void _set_branches(const std::vector<std::complex<double>> &state, const std::vector<size_t> &address_qubits, const std::vector<size_t> &data_qubits)¶
Sparse branch decomposition: keep only branches with nonzero probability (enabled automatically above 25 bits).
- 参数:
state -- Full-amplitude state vector
address_qubits -- Address qubit indices
data_qubits -- Data qubit indices
-
void _reconstruct(std::vector<std::complex<double>> &ret, const std::vector<std::complex<double>> &state, const std::vector<size_t> &address_qubits, const std::vector<size_t> &data_qubits, const std::vector<size_t> &other_qubits)¶
Reconstruct the loading results on the branches back into a full-amplitude state vector.
Good branches are predicted by XOR mirroring of the reference trajectory (with Damping multipliers); bad branches are mapped trajectory by trajectory; the reconstructed result is checked for normalization.
- 参数:
ret -- Output state vector (zeroed before the call)
state -- Input state vector
address_qubits -- Address qubit indices
data_qubits -- Data qubit indices
other_qubits -- Indices of the remaining spectator qubits
-
std::vector<std::complex<double>> apply(const std::vector<std::complex<double>> &state, const std::vector<size_t> &address_qubits, const std::vector<size_t> &data_qubits, const std::vector<size_t> &other_qubits, std::string version)¶
Compose one QRAM loading onto a full-amplitude state vector.
- 参数:
state -- Input state vector (length 2^(addr+data+other))
address_qubits -- Address qubit indices (count must equal address_size)
data_qubits -- Data qubit indices (count must equal data_size)
other_qubits -- Spectator qubit indices (not involved in loading)
version -- "new"/"normal": pruning; "old"/"full": no pruning (internally calls run(version); a non-null noise model must be set first)
- 返回:
New state vector after loading (normalized)
-
inline QRAMFullAmp(size_t addr_sz, size_t data_sz, const memory_t &memory)¶
全振幅电路原语¶
-
struct MeasureResult¶
Measurement result over a specified set of bits (collapse + normalization).
矩阵¶
-
struct SparseMatrix¶
Fixed-point sparse matrix (a fixed number nnz_col of nonzeros per row).
Elements are stored as data_size-bit fixed-point integers (positive or two's complement), with sparsity storing the column positions; used for fixed-point linear solving in quantum arithmetic. After conversion via to_eigen to an Eigen dense double representation, classical linear algebra can be applied. Value ranges are checked at construction; out-of-range values throw an exception.
Public Functions
-
std::vector<size_t> get_data() const¶
Concatenate data and sparsity into a single vector (n_row * nnz_col layout).
-
size_t get_sparsity_offset() const¶
Return the byte offset of sparsity (for the concatenated layout of get_data).
-
double get_kappa() const¶
Estimate the condition number kappa (for deriving the iteration count of fixed-point solving).
-
double get_j0(double eps) const¶
Estimate the zeroth-order Bessel term j0 from the accuracy eps.
-
inline Eigen::SparseMatrix<double> to_eigen() const¶
Convert to an Eigen sparse matrix (fixed-point values restored to double by scaling).
-
std::vector<size_t> get_data() const¶
-
template<typename Ty>
struct DenseMatrix¶ Dense square matrix (row-major one-dimensional storage).
Provides Eigen conversion (to_eigen / from_eigen), unitarity / Hermiticity checks (is_unitary / is_Hermitian), dagger (conjugate transpose), and element-wise allclose comparison; a base container for the quantum operator verification workflow.
Public Functions
-
inline bool is_Hermitian(double tol = epsilon) const¶
Hermiticity check (tolerance tol).
-
inline bool allclose(const DenseMatrix<Ty> &other, double tol = epsilon) const¶
Element-wise approximate equality comparison (tolerance tol).
-
inline bool is_unitary(double tol = epsilon) const¶
Unitarity check: both AA^dagger and A^dagger*A are identity matrices (tolerance tol).
-
inline DenseMatrix<Ty> dagger() const¶
Conjugate transpose (dagger).
Public Static Functions
-
static inline DenseMatrix<Ty> from_eigen(const Eigen::MatrixX<Ty> &mat)¶
Construct from an Eigen dense matrix.
-
inline bool is_Hermitian(double tol = epsilon) const¶
-
template<typename Ty>
struct DenseVector¶ Dense vector (one-dimensional storage).
Provides Eigen conversion, element-wise allclose, and the basic operations needed for linear equation solving; used together with DenseMatrix.
Public Functions
-
inline bool allclose(const DenseVector<Ty> &other, double tol = epsilon) const¶
Element-wise approximate equality comparison (tolerance tol).
Public Static Functions
-
static inline DenseVector<Ty> from_eigen(const EigenVec<Ty> &vec)¶
Construct from an Eigen vector.
-
inline bool allclose(const DenseVector<Ty> &other, double tol = epsilon) const¶
随机引擎¶
-
struct random_engine¶
Global random engine singleton (MT19937-64).
The whole library shares one random source: QRAM memory generation, input sampling, and output sampling are all driven by this engine; after set_seed the entire simulation pipeline is reproducible (default seed 10101).
Public Functions
-
inline engine_t &_get_engine()¶
Reference to the engine (instance method).
-
inline const engine_t &_get_engine() const¶
Const reference to the engine (instance method).
-
inline double _rng()¶
Generate one U(0,1) random number (instance method).
-
inline double _uniform01()¶
Generate one U(0,1) random number (alias of _rng).
-
inline double _uniform(double a, double b)¶
Generate one U(a,b) random number (instance method).
-
inline int _randint(int a, int b)¶
Generate one random integer in [a,b] (instance method).
-
inline void _set_seed(seed_t _seed)¶
Set the seed (instance method).
-
inline seed_t reseed()¶
Reset the seed from the current random number and return the new seed.
-
inline seed_t _get_seed()¶
Return the current seed (instance method).
Public Static Functions
-
static inline random_engine &get_instance()¶
Get the process-wide unique instance.
-
static inline engine_t &get_engine()¶
Reference to the global engine.
-
static inline double rng()¶
Generate one U(0,1) random number.
-
static inline double uniform01()¶
Generate one U(0,1) random number (alias of rng).
-
static inline double uniform(double a, double b)¶
Generate one U(a,b) random number.
-
static inline int randint(int a, int b)¶
Generate one random integer in [a,b].
-
static inline void set_seed(seed_t _seed)¶
Set the seed of the global random engine.
-
static inline seed_t get_seed()¶
Return the current seed of the global random engine.
-
static inline seed_t time_seed()¶
Set the seed from the current system time and return that seed.
-
inline engine_t &_get_engine()¶
日志与剖析¶
-
struct Logger¶
File log singleton.
On the first instance() call a timestamped log file (log-*.txt) is created automatically; provides info / error level writing, a stack of timers, and flush.
Public Functions
-
inline void timer_start()¶
Push a new timer.
-
inline double timer_end(double unit = sec)¶
Pop the top timer and return the elapsed time (converted by unit; defaults to seconds).
Public Static Functions
-
static inline Logger &instance()¶
Get the Logger singleton (the first call automatically creates the log file and enables writing).
-
static inline std::string autofilename(std::string prefix, std::string postfix)¶
Generate an automatic file name of the form "prefix + timestamp + postfix".
-
inline void timer_start()¶
-
struct profiler¶
RAII function profiler: starts timing on construction, stops on destruction, aggregated by function name.
Used together with the FunctionProfiler macro (declare at function entry
volatile profiler _profilehelper_(__FUNCTION__);); print_profiler outputs the call count and accumulated time of each function.
-
template<typename Ty>
struct Statistic¶ Online statistics: accumulates mean / variance / standard deviation while recording.
- 模板参数:
Ty -- Type of the recorded values (must be convertible to double)
-
struct Outputter¶
Experiment result outputter: generates a .py result file from a Python class template.
Fills the template string with the experiment name / variables / results / time / profiler info, and outputs an Experiment-*.py file that can be imported directly on the Python side for analysis.
迭代工具¶
-
class range¶
Python-style integer range iterator.
Supports range(stop) and range(start, stop[, step]); usable in range-based for loops:
for (size_t i : range(4)).Public Functions
-
inline range(size_t stop)¶
Construct the interval [0, stop).
-
inline range(size_t start, size_t stop, size_t step = 1)¶
Construct the interval [start, stop) with step size step.
-
class iterator¶
Iterator: advances by the step size, bounded by stop.
-
inline range(size_t stop)¶
-
template<typename ...Containers>
class product¶ Cartesian product iterator over any number of containers.
Similar to Python's itertools.product: traverses all combinations with the last container varying fastest; each dereference yields a tuple of the current elements of all containers. Usage:
for (auto [i, j] : product(vecA, vecB)).Public Functions
-
inline product(const Containers&... cs)¶
Construct a Cartesian product view from several containers.
-
inline product(const Containers&... cs)¶