qpandalite.algorithmics.circuits package#

可复用量子电路构建块。

Submodules#

qpandalite.algorithmics.circuits.qft module#

Quantum Fourier Transform (QFT) circuit.

qpandalite.algorithmics.circuits.qft.qft_circuit(circuit, qubits=None, swaps=True)[源代码]

Apply the Quantum Fourier Transform (QFT) to the given qubits.

The QFT maps the computational basis state \(|j\rangle\) to:

\[\frac{1}{\sqrt{N}} \sum_{k=0}^{N-1} e^{2\pi i\, jk/N} |k\rangle\]

where \(N = 2^n\) and n is the number of qubits.

The circuit applies, for each qubit j (from most-significant to least-significant):

  1. A Hadamard gate on qubit j.

  2. Controlled phase rotations \(R_k\) from every later qubit k > j with angle \(\pi / 2^{k-j}\).

If swaps is True (the default), a layer of SWAP gates is appended to reverse the qubit order so that the output follows the standard big-endian convention.

To obtain the inverse QFT, use circuit.dagger() on a copy of the QFT sub-circuit, or apply qft_circuit and then call circuit.dagger() on the relevant gates.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices to apply QFT on. None means all qubits of circuit (list(range(circuit.qubit_num))).

  • swaps (bool) -- Whether to append SWAP gates to reverse qubit order. Defaults to True.

抛出:

ValueError -- Fewer than 1 qubit is specified.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import qft_circuit
>>> c = Circuit(3)
>>> qft_circuit(c, qubits=[0, 1, 2])

qpandalite.algorithmics.circuits.deutsch_jozsa module#

Deutsch-Jozsa algorithm circuit and oracle builder.

qpandalite.algorithmics.circuits.deutsch_jozsa.deutsch_jozsa_circuit(circuit, oracle, qubits, ancilla=None)[源代码]

Apply the Deutsch-Jozsa algorithm to the circuit.

The Deutsch-Jozsa algorithm determines whether a function \(f: \{0,1\}^n \to \{0,1\}\) is constant or balanced using a single quantum query.

Circuit steps:

  1. Initialise data qubits to \(|+\rangle\) and ancilla to \(|-\rangle\) (via X then H).

  2. Apply the oracle.

  3. Apply Hadamard on all data qubits.

  4. Measure data qubits: all-zeros → constant, otherwise → balanced.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • oracle (Circuit) -- Oracle sub-circuit to embed. Must operate on len(qubits) + 1 qubits (data + ancilla), or be empty (constant-zero oracle).

  • qubits (List[int]) -- Data-qubit indices (explicit list, no default).

  • ancilla (int | None) -- Ancilla qubit index. None means max(qubits) + 1.

抛出:
  • TypeError -- qubits is not a list.

  • ValueError -- qubits is empty, or oracle qubit count mismatches.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import (
...     deutsch_jozsa_circuit, deutsch_jozsa_oracle,
... )
>>> n = 3
>>> oracle = deutsch_jozsa_oracle(qubits=list(range(n)), balanced=True)
>>> c = Circuit()
>>> deutsch_jozsa_circuit(c, oracle, qubits=list(range(n)), ancilla=n)
qpandalite.algorithmics.circuits.deutsch_jozsa.deutsch_jozsa_oracle(qubits, balanced=True, target_bits=None)[源代码]

Build a Deutsch-Jozsa oracle circuit.

Generates either a constant oracle (maps all inputs to 0 or all to 1) or a balanced oracle (maps half the inputs to 0 and half to 1).

  • Constant oracle: does nothing (output = 0) or flips the ancilla (output = 1). Here we implement the identity (output always 0).

  • Balanced oracle: applies CNOT from each target_bit to the ancilla. If target_bits is None, all data qubits are used. This yields a balanced function because the ancilla flips exactly when an odd number of target bits are set.

The oracle acts on the data qubits in qubits plus one ancilla qubit at max(qubits) + 1.

参数:
  • qubits (List[int]) -- Data-qubit indices (explicit list, no default).

  • balanced (bool) -- If True, build a balanced oracle; otherwise constant.

  • target_bits (List[int] | None) -- Data-qubit indices (positions within qubits) that control the ancilla flip. Only used when balanced is True. None means all data qubits.

返回:

A new Circuit containing the oracle gates.

抛出:
  • TypeError -- qubits is not a list.

  • ValueError -- qubits is empty, or target_bits contains invalid indices.

返回类型:

Circuit

示例

>>> oracle = deutsch_jozsa_oracle(qubits=[0, 1, 2], balanced=True)
>>> oracle.qubit_num  # 3 data + 1 ancilla
4

qpandalite.algorithmics.circuits.amplitude_estimation module#

Quantum Amplitude Estimation (QAE) circuit.

qpandalite.algorithmics.circuits.amplitude_estimation.amplitude_estimation_circuit(circuit, oracle, qubits, eval_qubits)[源代码]

Apply Quantum Amplitude Estimation (QAE).

Estimates the probability a that a measurement of the state prepared by A|0⟩ yields a "good" outcome (as defined by the oracle).

Uses the canonical QPE-based construction:

  1. Prepare evaluation register in uniform superposition (H^{⊗m}).

  2. For each evaluation qubit at position i (LSB-first), apply 2^i controlled-Grover iterations on the search register.

  3. Apply inverse QFT on the evaluation register.

  4. Measure the evaluation register.

The search register is initialised with H^{⊗n} (uniform superposition) before the controlled-Grover operations.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • oracle (Circuit) -- Oracle circuit implementing the phase flip on marked states.

  • qubits (List[int]) -- Qubit indices for the search register.

  • eval_qubits (List[int]) -- Qubit indices for the evaluation (precision) register, in LSB-first order (eval_qubits[0] controls 2^0 = 1 Grover iteration, eval_qubits[1] controls 2^1 = 2, …).

抛出:

ValueError -- Invalid parameters.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import amplitude_estimation_circuit
>>> oracle = Circuit()
>>> oracle.z(0)
>>> c = Circuit()
>>> amplitude_estimation_circuit(
...     c, oracle, qubits=[3, 4], eval_qubits=[0, 1, 2]
... )
qpandalite.algorithmics.circuits.amplitude_estimation.amplitude_estimation_result(counts, n_eval_qubits)[源代码]

Estimate probability a from QAE measurement results.

Converts the most-frequent measurement outcome to an angle θ and computes a = sin²(θ).

The QAE phase relation is theta = pi * m / 2^(M+1) where m is the integer outcome and M = n_eval_qubits. The extra factor of two compared to the bare QPE formula comes from the fact that the Grover operator's eigenphase is 2 theta rather than theta.

参数:
  • counts (dict) -- Dictionary mapping measurement outcomes (bit-strings or integers) to frequencies/counts.

  • n_eval_qubits (int) -- Number of evaluation qubits used in QAE.

返回:

Estimated probability a ∈ [0, 1].

返回类型:

float

qpandalite.algorithmics.circuits.amplitude_estimation.grover_operator(circuit, oracle, qubits)[源代码]

Apply one Grover iteration G = A · S₀ · A† · S_f.

Where: - S_f is the oracle (phase flip on marked states) - A† is the inverse of the state preparation - S₀ is the reflection about |0⟩ - A is the state preparation

In the standard QAE formulation, A = H^{⊗n} (uniform superposition), and S_f is provided by the oracle circuit.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • oracle (Circuit) -- Oracle circuit implementing phase flip on target states. Must use the same qubit indices as qubits.

  • qubits (List[int]) -- Qubit indices for the search register.

返回类型:

None

qpandalite.algorithmics.circuits.dicke_state module#

Dicke state preparation circuit using the SCUC algorithm.

Reference:

Bärtschi & Eidenbenz, "Deterministic Preparation of Dicke States", FCT 2019, arXiv:1904.07358.

qpandalite.algorithmics.circuits.dicke_state.dicke_state_circuit(circuit, k, qubits=None)[源代码]

Prepare the Dicke state \(|D(n,k)\rangle\).

The Dicke state \(|D(n,k)\rangle\) is the equal superposition of all \(\binom{n}{k}\) computational basis states with exactly k qubits in \(|1\rangle\):

\[|D(n,k)\rangle = \frac{1}{\sqrt{\binom{n}{k}}} \sum_{x\,\in\,\{0,1\}^n,\;|x|=k} |x\rangle\]

This implementation uses the SCUC (Sequential Conditional Unitary Cascade) algorithm from Bärtschi & Eidenbenz (2019), built from CNOT, CRY, and Toffoli gates in \(O(nk)\) depth.

Algorithm outline:
  1. Initialize the last k qubits to \(|1\rangle\) (X gates).

  2. first_block: for l = n, n-1, …, k+1 apply SCS_{l,k} on the first l qubits.

  3. second_block: for l = k, k-1, …, 2 apply SCS_{l,l-1} on the first l qubits.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • k (int) -- Number of excitations (1``s) in the target Dicke state. Must satisfy ``1 <= k <= n.

  • qubits (List[int] | None) -- Qubit indices to use. None means all qubits of circuit (list(range(circuit.qubit_num))). Must contain at least k qubits.

抛出:

ValueError -- If k is not in [1, n].

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import dicke_state_circuit
>>> c = Circuit()
>>> dicke_state_circuit(c, k=2, qubits=[0, 1, 2, 3])

qpandalite.algorithmics.circuits.entangled_states module#

Entangled state preparation circuits: GHZ, W, and Cluster states.

qpandalite.algorithmics.circuits.entangled_states.cluster_state(circuit, qubits=None, edges=None)[源代码]

Prepare a cluster state (graph state).

A cluster state is prepared by:

  1. Applying Hadamard to all qubits: \(H^{\otimes n}\)

  2. Applying CZ (controlled-Z) on each edge of the graph

The resulting state is:

\[\frac{1}{\sqrt{2^n}} \sum_{x \in \{0,1\}^n} (-1)^{\sum_{(i,j) \in E} x_i x_j} |x\rangle\]
参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

  • edges (List[Tuple[int, int]] | None) -- List of (source, target) pairs defining the entanglement graph. Indices refer to positions in qubits. None uses a linear nearest-neighbor chain: (0,1), (1,2), (2,3), ....

抛出:

ValueError -- Fewer than 1 qubit.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import cluster_state
>>> c = Circuit(4)
>>> cluster_state(c)  # linear chain
>>> # Custom graph (square)
>>> c2 = Circuit(4)
>>> cluster_state(c2, edges=[(0,1), (1,2), (2,3), (3,0)])
qpandalite.algorithmics.circuits.entangled_states.ghz_state(circuit, qubits=None)[源代码]

Prepare a GHZ (Greenberger–Horne–Zeilinger) state.

Produces the state:

\[\frac{1}{\sqrt{2}}(|00\ldots0\rangle + |11\ldots1\rangle)\]

Implementation:

  1. Hadamard on the first qubit: \(\frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)\)

  2. Chain of CNOT gates: CNOT(q[0], q[1]), CNOT(q[1], q[2]), ...

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

抛出:

ValueError -- Fewer than 2 qubits.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import ghz_state
>>> c = Circuit(3)
>>> ghz_state(c)
qpandalite.algorithmics.circuits.entangled_states.w_state(circuit, qubits=None)[源代码]

Prepare a W state.

Produces the state:

\[\frac{1}{\sqrt{n}}(|10\ldots0\rangle + |01\ldots0\rangle + \ldots + |00\ldots1\rangle)\]

Implemented as a Dicke state \(|D(n,1)\rangle\) (equal superposition of all single-excitation computational basis states) via dicke_state_circuit() with k=1.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

抛出:

ValueError -- Fewer than 2 qubits.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import w_state
>>> c = Circuit(4)
>>> w_state(c)

qpandalite.algorithmics.circuits.grover_oracle module#

Grover oracle and diffusion operator construction.

Provides reusable building blocks for Grover's quantum search algorithm:

  • grover_oracle() — phase-flip oracle for a marked computational basis state.

  • grover_diffusion() — Grover diffusion (amplitude amplification) operator.

Both functions operate on a Circuit object passed in by the caller, following the standard circuit-building convention of qpandalite.algorithmics.circuits.

引用

Grover, L. K. (1996). "A fast quantum mechanical algorithm for database search." STOC '96. https://arxiv.org/abs/quant-ph/9605043

qpandalite.algorithmics.circuits.grover_oracle.grover_diffusion(circuit, qubits=None, ancilla=None)[源代码]

Construct the Grover diffusion (amplitude amplification) operator.

The diffusion operator is:

\[D = 2|s\rangle\langle s| - I\]

where \(|s\rangle = H^{\otimes n}|0\rangle^{\otimes n}\) is the uniform superposition. It is equivalent to:

\[D = H^{\otimes n} \cdot \bigl(2|0\rangle\langle 0| - I\bigr) \cdot H^{\otimes n}\]

The 2|0⟩⟨0| - I part is implemented as X gates followed by a multi-controlled Z and X gates again.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Data qubit indices. None means [0, 1] (2 qubits).

  • ancilla (int | None) -- Deprecated and unused. The current implementation derives the MCZ target directly from qubits[-1], so this argument has no effect regardless of its value. It is retained for API compatibility only and will be removed in a future release.

抛出:

ValueError -- Fewer than 1 qubit specified.

返回类型:

None

qpandalite.algorithmics.circuits.grover_oracle.grover_oracle(circuit, marked_state, qubits=None, ancilla=None)[源代码]

Construct a phase-flip oracle for a marked basis state.

The oracle flips the phase of the computational basis state whose integer encoding is marked_state, leaving all other states unchanged:

\[U_f |x\rangle = (-1)^{[x = \text{marked}]} |x\rangle\]

The implementation uses an ancilla qubit prepared in \(|-\rangle\) and a multi-controlled Z gate. X gates are applied before and after the MCZ to match the bit pattern of marked_state.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • marked_state (int) -- Non-negative integer encoding the marked basis state.

  • qubits (List[int] | None) -- Data qubit indices. None means list(range(n_bits)) where n_bits is the number of bits needed to represent marked_state (at least 1).

  • ancilla (int | None) -- Ancilla qubit index for the MCZ target. None means max(qubits) + 1 (auto-allocated).

返回:

The ancilla qubit index that was used.

抛出:

ValueError -- marked_state is negative or exceeds the addressable space of qubits.

返回类型:

int

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import grover_oracle
>>> c = Circuit()
>>> for i in range(3):
...     c.h(i)          # uniform superposition
>>> anc = grover_oracle(c, marked_state=5, qubits=[0, 1, 2])

qpandalite.algorithmics.circuits.thermal_state module#

Thermal state preparation circuit.

qpandalite.algorithmics.circuits.thermal_state.thermal_state_circuit(circuit, beta, qubits=None)[源代码]

Prepare a thermal state via single-qubit rotations.

For the transverse-field-free Hamiltonian \(H = \sum_i Z_i\), the thermal (Gibbs) state at inverse temperature \(\beta\) factorises into a product of single-qubit states. Each qubit is prepared in

\[\sqrt{p_0}\,|0\rangle + \sqrt{p_1}\,|1\rangle\]

where

\[p_0 = \frac{e^{\beta}}{e^{\beta}+e^{-\beta}}, \qquad p_1 = 1 - p_0.\]

This is achieved by applying \(R_y(\theta)\) with \(\theta = 2\arccos(\sqrt{p_0})\) to every qubit independently.

This is a lightweight, circuit-only counterpart of state_preparation.thermal_state for the default Hamiltonian case.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • beta (float) -- Inverse temperature (\(\beta > 0\)). Larger values bias the state towards \(|0\rangle\).

  • qubits (List[int] | None) -- Qubit indices to use. None means all qubits of circuit (list(range(circuit.qubit_num))).

抛出:

ValueError -- beta is negative.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import thermal_state_circuit
>>> c = Circuit(3)
>>> thermal_state_circuit(c, beta=1.0)

qpandalite.algorithmics.circuits.vqd module#

Variational Quantum Deflation (VQD) circuit components.

qpandalite.algorithmics.circuits.vqd.vqd_circuit(circuit, ansatz_params, prev_states, qubits=None, penalty=10.0, n_layers=2)[源代码]

Apply a VQD ansatz circuit to circuit.

Variational Quantum Deflation (VQD) is a hybrid algorithm for finding excited states of a Hamiltonian one at a time. It minimises the cost function

\[C(\boldsymbol{\theta}) = \langle\psi(\boldsymbol{\theta})|H|\psi(\boldsymbol{\theta})\rangle + \sum_i \beta_i\,|\langle\psi(\boldsymbol{\theta})|\phi_i\rangle|^2\]

where \(|\phi_i\rangle\) are previously found lower-energy states and \(\beta_i\) are penalty coefficients.

This function only constructs the parameterised ansatz on the circuit. The overlap penalty terms are evaluated separately (see vqd_overlap_circuit()) and combined by a classical optimiser.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • ansatz_params (List[float]) -- Parameters for the HEA ansatz.

  • prev_states (List[ndarray]) -- List of previously found state vectors (used by the classical optimiser, not directly in this circuit).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

  • penalty (float) -- Penalty coefficient \(\beta\) (used by the caller).

  • n_layers (int) -- Number of HEA layers.

抛出:

ValueError -- If prev_states is empty (use VQE for the ground state).

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> import numpy as np
>>> c = Circuit(2)
>>> gs = np.array([1, 0, 0, 0], dtype=complex)
>>> vqd_circuit(c, [0.1]*4, prev_states=[gs], n_layers=2)
qpandalite.algorithmics.circuits.vqd.vqd_overlap_circuit(prev_state, ansatz_params, n_layers=2, qubits=None)[源代码]

Build a circuit to compute \(|\langle\psi(\boldsymbol{\theta})|\phi\rangle|^2\).

Uses the swap test: an ancilla qubit controls SWAPs between the ansatz register and a register prepared in prev_state. Measuring the ancilla in the computational basis gives an estimate of the overlap.

Circuit layout (2 data qubits):

ancilla: ──H──●──────●──●──────●── Measure
               |      |  |      |
data_A:  ──[ansatz]──SWAP──[ansatz]──SWAP──
               |      |  |      |
data_B:  ──[prev]──SWAP──[prev]──SWAP──
参数:
  • prev_state (ndarray) -- State vector \(|\phi\rangle\) of dimension \(2^n\).

  • ansatz_params (List[float]) -- Parameters for the HEA ansatz.

  • n_layers (int) -- Number of HEA layers.

  • qubits (List[int] | None) -- Data qubit indices for the ansatz register. None means [0, 1, …, n-1] where n is inferred from prev_state.

返回:

A new Circuit containing the swap-test circuit with the ancilla measured.

抛出:

ValueError -- prev_state is not a power-of-2 length.

返回类型:

Circuit

示例

>>> import numpy as np
>>> gs = np.array([1, 0, 0, 0], dtype=complex)
>>> circ = vqd_overlap_circuit(gs, [0.1]*4, n_layers=2)

Module contents#

Circuits module — reusable quantum circuit building blocks.

qpandalite.algorithmics.circuits.amplitude_estimation_circuit(circuit, oracle, qubits, eval_qubits)[源代码]

Apply Quantum Amplitude Estimation (QAE).

Estimates the probability a that a measurement of the state prepared by A|0⟩ yields a "good" outcome (as defined by the oracle).

Uses the canonical QPE-based construction:

  1. Prepare evaluation register in uniform superposition (H^{⊗m}).

  2. For each evaluation qubit at position i (LSB-first), apply 2^i controlled-Grover iterations on the search register.

  3. Apply inverse QFT on the evaluation register.

  4. Measure the evaluation register.

The search register is initialised with H^{⊗n} (uniform superposition) before the controlled-Grover operations.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • oracle (Circuit) -- Oracle circuit implementing the phase flip on marked states.

  • qubits (List[int]) -- Qubit indices for the search register.

  • eval_qubits (List[int]) -- Qubit indices for the evaluation (precision) register, in LSB-first order (eval_qubits[0] controls 2^0 = 1 Grover iteration, eval_qubits[1] controls 2^1 = 2, …).

抛出:

ValueError -- Invalid parameters.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import amplitude_estimation_circuit
>>> oracle = Circuit()
>>> oracle.z(0)
>>> c = Circuit()
>>> amplitude_estimation_circuit(
...     c, oracle, qubits=[3, 4], eval_qubits=[0, 1, 2]
... )
qpandalite.algorithmics.circuits.amplitude_estimation_result(counts, n_eval_qubits)[源代码]

Estimate probability a from QAE measurement results.

Converts the most-frequent measurement outcome to an angle θ and computes a = sin²(θ).

The QAE phase relation is theta = pi * m / 2^(M+1) where m is the integer outcome and M = n_eval_qubits. The extra factor of two compared to the bare QPE formula comes from the fact that the Grover operator's eigenphase is 2 theta rather than theta.

参数:
  • counts (dict) -- Dictionary mapping measurement outcomes (bit-strings or integers) to frequencies/counts.

  • n_eval_qubits (int) -- Number of evaluation qubits used in QAE.

返回:

Estimated probability a ∈ [0, 1].

返回类型:

float

qpandalite.algorithmics.circuits.cluster_state(circuit, qubits=None, edges=None)[源代码]

Prepare a cluster state (graph state).

A cluster state is prepared by:

  1. Applying Hadamard to all qubits: \(H^{\otimes n}\)

  2. Applying CZ (controlled-Z) on each edge of the graph

The resulting state is:

\[\frac{1}{\sqrt{2^n}} \sum_{x \in \{0,1\}^n} (-1)^{\sum_{(i,j) \in E} x_i x_j} |x\rangle\]
参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

  • edges (List[Tuple[int, int]] | None) -- List of (source, target) pairs defining the entanglement graph. Indices refer to positions in qubits. None uses a linear nearest-neighbor chain: (0,1), (1,2), (2,3), ....

抛出:

ValueError -- Fewer than 1 qubit.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import cluster_state
>>> c = Circuit(4)
>>> cluster_state(c)  # linear chain
>>> # Custom graph (square)
>>> c2 = Circuit(4)
>>> cluster_state(c2, edges=[(0,1), (1,2), (2,3), (3,0)])
qpandalite.algorithmics.circuits.deutsch_jozsa_circuit(circuit, oracle, qubits, ancilla=None)[源代码]

Apply the Deutsch-Jozsa algorithm to the circuit.

The Deutsch-Jozsa algorithm determines whether a function \(f: \{0,1\}^n \to \{0,1\}\) is constant or balanced using a single quantum query.

Circuit steps:

  1. Initialise data qubits to \(|+\rangle\) and ancilla to \(|-\rangle\) (via X then H).

  2. Apply the oracle.

  3. Apply Hadamard on all data qubits.

  4. Measure data qubits: all-zeros → constant, otherwise → balanced.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • oracle (Circuit) -- Oracle sub-circuit to embed. Must operate on len(qubits) + 1 qubits (data + ancilla), or be empty (constant-zero oracle).

  • qubits (List[int]) -- Data-qubit indices (explicit list, no default).

  • ancilla (int | None) -- Ancilla qubit index. None means max(qubits) + 1.

抛出:
  • TypeError -- qubits is not a list.

  • ValueError -- qubits is empty, or oracle qubit count mismatches.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import (
...     deutsch_jozsa_circuit, deutsch_jozsa_oracle,
... )
>>> n = 3
>>> oracle = deutsch_jozsa_oracle(qubits=list(range(n)), balanced=True)
>>> c = Circuit()
>>> deutsch_jozsa_circuit(c, oracle, qubits=list(range(n)), ancilla=n)
qpandalite.algorithmics.circuits.deutsch_jozsa_oracle(qubits, balanced=True, target_bits=None)[源代码]

Build a Deutsch-Jozsa oracle circuit.

Generates either a constant oracle (maps all inputs to 0 or all to 1) or a balanced oracle (maps half the inputs to 0 and half to 1).

  • Constant oracle: does nothing (output = 0) or flips the ancilla (output = 1). Here we implement the identity (output always 0).

  • Balanced oracle: applies CNOT from each target_bit to the ancilla. If target_bits is None, all data qubits are used. This yields a balanced function because the ancilla flips exactly when an odd number of target bits are set.

The oracle acts on the data qubits in qubits plus one ancilla qubit at max(qubits) + 1.

参数:
  • qubits (List[int]) -- Data-qubit indices (explicit list, no default).

  • balanced (bool) -- If True, build a balanced oracle; otherwise constant.

  • target_bits (List[int] | None) -- Data-qubit indices (positions within qubits) that control the ancilla flip. Only used when balanced is True. None means all data qubits.

返回:

A new Circuit containing the oracle gates.

抛出:
  • TypeError -- qubits is not a list.

  • ValueError -- qubits is empty, or target_bits contains invalid indices.

返回类型:

Circuit

示例

>>> oracle = deutsch_jozsa_oracle(qubits=[0, 1, 2], balanced=True)
>>> oracle.qubit_num  # 3 data + 1 ancilla
4
qpandalite.algorithmics.circuits.dicke_state_circuit(circuit, k, qubits=None)[源代码]

Prepare the Dicke state \(|D(n,k)\rangle\).

The Dicke state \(|D(n,k)\rangle\) is the equal superposition of all \(\binom{n}{k}\) computational basis states with exactly k qubits in \(|1\rangle\):

\[|D(n,k)\rangle = \frac{1}{\sqrt{\binom{n}{k}}} \sum_{x\,\in\,\{0,1\}^n,\;|x|=k} |x\rangle\]

This implementation uses the SCUC (Sequential Conditional Unitary Cascade) algorithm from Bärtschi & Eidenbenz (2019), built from CNOT, CRY, and Toffoli gates in \(O(nk)\) depth.

Algorithm outline:
  1. Initialize the last k qubits to \(|1\rangle\) (X gates).

  2. first_block: for l = n, n-1, …, k+1 apply SCS_{l,k} on the first l qubits.

  3. second_block: for l = k, k-1, …, 2 apply SCS_{l,l-1} on the first l qubits.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • k (int) -- Number of excitations (1``s) in the target Dicke state. Must satisfy ``1 <= k <= n.

  • qubits (List[int] | None) -- Qubit indices to use. None means all qubits of circuit (list(range(circuit.qubit_num))). Must contain at least k qubits.

抛出:

ValueError -- If k is not in [1, n].

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import dicke_state_circuit
>>> c = Circuit()
>>> dicke_state_circuit(c, k=2, qubits=[0, 1, 2, 3])
qpandalite.algorithmics.circuits.ghz_state(circuit, qubits=None)[源代码]

Prepare a GHZ (Greenberger–Horne–Zeilinger) state.

Produces the state:

\[\frac{1}{\sqrt{2}}(|00\ldots0\rangle + |11\ldots1\rangle)\]

Implementation:

  1. Hadamard on the first qubit: \(\frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)\)

  2. Chain of CNOT gates: CNOT(q[0], q[1]), CNOT(q[1], q[2]), ...

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

抛出:

ValueError -- Fewer than 2 qubits.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import ghz_state
>>> c = Circuit(3)
>>> ghz_state(c)
qpandalite.algorithmics.circuits.grover_diffusion(circuit, qubits=None, ancilla=None)[源代码]

Construct the Grover diffusion (amplitude amplification) operator.

The diffusion operator is:

\[D = 2|s\rangle\langle s| - I\]

where \(|s\rangle = H^{\otimes n}|0\rangle^{\otimes n}\) is the uniform superposition. It is equivalent to:

\[D = H^{\otimes n} \cdot \bigl(2|0\rangle\langle 0| - I\bigr) \cdot H^{\otimes n}\]

The 2|0⟩⟨0| - I part is implemented as X gates followed by a multi-controlled Z and X gates again.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Data qubit indices. None means [0, 1] (2 qubits).

  • ancilla (int | None) -- Deprecated and unused. The current implementation derives the MCZ target directly from qubits[-1], so this argument has no effect regardless of its value. It is retained for API compatibility only and will be removed in a future release.

抛出:

ValueError -- Fewer than 1 qubit specified.

返回类型:

None

qpandalite.algorithmics.circuits.grover_operator(circuit, oracle, qubits)[源代码]

Apply one Grover iteration G = A · S₀ · A† · S_f.

Where: - S_f is the oracle (phase flip on marked states) - A† is the inverse of the state preparation - S₀ is the reflection about |0⟩ - A is the state preparation

In the standard QAE formulation, A = H^{⊗n} (uniform superposition), and S_f is provided by the oracle circuit.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • oracle (Circuit) -- Oracle circuit implementing phase flip on target states. Must use the same qubit indices as qubits.

  • qubits (List[int]) -- Qubit indices for the search register.

返回类型:

None

qpandalite.algorithmics.circuits.grover_oracle(circuit, marked_state, qubits=None, ancilla=None)[源代码]

Construct a phase-flip oracle for a marked basis state.

The oracle flips the phase of the computational basis state whose integer encoding is marked_state, leaving all other states unchanged:

\[U_f |x\rangle = (-1)^{[x = \text{marked}]} |x\rangle\]

The implementation uses an ancilla qubit prepared in \(|-\rangle\) and a multi-controlled Z gate. X gates are applied before and after the MCZ to match the bit pattern of marked_state.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • marked_state (int) -- Non-negative integer encoding the marked basis state.

  • qubits (List[int] | None) -- Data qubit indices. None means list(range(n_bits)) where n_bits is the number of bits needed to represent marked_state (at least 1).

  • ancilla (int | None) -- Ancilla qubit index for the MCZ target. None means max(qubits) + 1 (auto-allocated).

返回:

The ancilla qubit index that was used.

抛出:

ValueError -- marked_state is negative or exceeds the addressable space of qubits.

返回类型:

int

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import grover_oracle
>>> c = Circuit()
>>> for i in range(3):
...     c.h(i)          # uniform superposition
>>> anc = grover_oracle(c, marked_state=5, qubits=[0, 1, 2])
qpandalite.algorithmics.circuits.qft_circuit(circuit, qubits=None, swaps=True)[源代码]

Apply the Quantum Fourier Transform (QFT) to the given qubits.

The QFT maps the computational basis state \(|j\rangle\) to:

\[\frac{1}{\sqrt{N}} \sum_{k=0}^{N-1} e^{2\pi i\, jk/N} |k\rangle\]

where \(N = 2^n\) and n is the number of qubits.

The circuit applies, for each qubit j (from most-significant to least-significant):

  1. A Hadamard gate on qubit j.

  2. Controlled phase rotations \(R_k\) from every later qubit k > j with angle \(\pi / 2^{k-j}\).

If swaps is True (the default), a layer of SWAP gates is appended to reverse the qubit order so that the output follows the standard big-endian convention.

To obtain the inverse QFT, use circuit.dagger() on a copy of the QFT sub-circuit, or apply qft_circuit and then call circuit.dagger() on the relevant gates.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices to apply QFT on. None means all qubits of circuit (list(range(circuit.qubit_num))).

  • swaps (bool) -- Whether to append SWAP gates to reverse qubit order. Defaults to True.

抛出:

ValueError -- Fewer than 1 qubit is specified.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import qft_circuit
>>> c = Circuit(3)
>>> qft_circuit(c, qubits=[0, 1, 2])
qpandalite.algorithmics.circuits.thermal_state_circuit(circuit, beta, qubits=None)[源代码]

Prepare a thermal state via single-qubit rotations.

For the transverse-field-free Hamiltonian \(H = \sum_i Z_i\), the thermal (Gibbs) state at inverse temperature \(\beta\) factorises into a product of single-qubit states. Each qubit is prepared in

\[\sqrt{p_0}\,|0\rangle + \sqrt{p_1}\,|1\rangle\]

where

\[p_0 = \frac{e^{\beta}}{e^{\beta}+e^{-\beta}}, \qquad p_1 = 1 - p_0.\]

This is achieved by applying \(R_y(\theta)\) with \(\theta = 2\arccos(\sqrt{p_0})\) to every qubit independently.

This is a lightweight, circuit-only counterpart of state_preparation.thermal_state for the default Hamiltonian case.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • beta (float) -- Inverse temperature (\(\beta > 0\)). Larger values bias the state towards \(|0\rangle\).

  • qubits (List[int] | None) -- Qubit indices to use. None means all qubits of circuit (list(range(circuit.qubit_num))).

抛出:

ValueError -- beta is negative.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import thermal_state_circuit
>>> c = Circuit(3)
>>> thermal_state_circuit(c, beta=1.0)
qpandalite.algorithmics.circuits.vqd_circuit(circuit, ansatz_params, prev_states, qubits=None, penalty=10.0, n_layers=2)[源代码]

Apply a VQD ansatz circuit to circuit.

Variational Quantum Deflation (VQD) is a hybrid algorithm for finding excited states of a Hamiltonian one at a time. It minimises the cost function

\[C(\boldsymbol{\theta}) = \langle\psi(\boldsymbol{\theta})|H|\psi(\boldsymbol{\theta})\rangle + \sum_i \beta_i\,|\langle\psi(\boldsymbol{\theta})|\phi_i\rangle|^2\]

where \(|\phi_i\rangle\) are previously found lower-energy states and \(\beta_i\) are penalty coefficients.

This function only constructs the parameterised ansatz on the circuit. The overlap penalty terms are evaluated separately (see vqd_overlap_circuit()) and combined by a classical optimiser.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • ansatz_params (List[float]) -- Parameters for the HEA ansatz.

  • prev_states (List[ndarray]) -- List of previously found state vectors (used by the classical optimiser, not directly in this circuit).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

  • penalty (float) -- Penalty coefficient \(\beta\) (used by the caller).

  • n_layers (int) -- Number of HEA layers.

抛出:

ValueError -- If prev_states is empty (use VQE for the ground state).

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> import numpy as np
>>> c = Circuit(2)
>>> gs = np.array([1, 0, 0, 0], dtype=complex)
>>> vqd_circuit(c, [0.1]*4, prev_states=[gs], n_layers=2)
qpandalite.algorithmics.circuits.vqd_overlap_circuit(prev_state, ansatz_params, n_layers=2, qubits=None)[源代码]

Build a circuit to compute \(|\langle\psi(\boldsymbol{\theta})|\phi\rangle|^2\).

Uses the swap test: an ancilla qubit controls SWAPs between the ansatz register and a register prepared in prev_state. Measuring the ancilla in the computational basis gives an estimate of the overlap.

Circuit layout (2 data qubits):

ancilla: ──H──●──────●──●──────●── Measure
               |      |  |      |
data_A:  ──[ansatz]──SWAP──[ansatz]──SWAP──
               |      |  |      |
data_B:  ──[prev]──SWAP──[prev]──SWAP──
参数:
  • prev_state (ndarray) -- State vector \(|\phi\rangle\) of dimension \(2^n\).

  • ansatz_params (List[float]) -- Parameters for the HEA ansatz.

  • n_layers (int) -- Number of HEA layers.

  • qubits (List[int] | None) -- Data qubit indices for the ansatz register. None means [0, 1, …, n-1] where n is inferred from prev_state.

返回:

A new Circuit containing the swap-test circuit with the ancilla measured.

抛出:

ValueError -- prev_state is not a power-of-2 length.

返回类型:

Circuit

示例

>>> import numpy as np
>>> gs = np.array([1, 0, 0, 0], dtype=complex)
>>> circ = vqd_overlap_circuit(gs, [0.1]*4, n_layers=2)
qpandalite.algorithmics.circuits.w_state(circuit, qubits=None)[源代码]

Prepare a W state.

Produces the state:

\[\frac{1}{\sqrt{n}}(|10\ldots0\rangle + |01\ldots0\rangle + \ldots + |00\ldots1\rangle)\]

Implemented as a Dicke state \(|D(n,1)\rangle\) (equal superposition of all single-excitation computational basis states) via dicke_state_circuit() with k=1.

参数:
  • circuit (Circuit) -- Quantum circuit to operate on (mutated in-place).

  • qubits (List[int] | None) -- Qubit indices. None means all qubits of circuit.

抛出:

ValueError -- Fewer than 2 qubits.

返回类型:

None

示例

>>> from qpandalite.circuit_builder import Circuit
>>> from qpandalite.algorithmics.circuits import w_state
>>> c = Circuit(4)
>>> w_state(c)