Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ Integrates quantum computing into classical machine learning to improve efficien
Solves key problems in physical modeling and engineering simulation (e.g., eigenvalues, linear equations, matrix decomposition).
- **QSVD (Quantum Variational Singular Value Decomposition)**
Extracts matrix singular values/vectors under a variational framework (for dimensionality reduction and recommendation systems).
- **VQLS (Variational Quantum Linear Solver)**
Solves power-of-two linear systems with a variational state ansatz, a scale-invariant global VQLS cost, SPSA optimization, and residual-aware reconstruction of the classical solution magnitude. Custom state functions can bridge PyQPanda3 simulators or hardware backends.

### 4. General Tools & Basic Components
Provides underlying tools for quantum computing workflows.
Expand Down
138 changes: 138 additions & 0 deletions docs/QEC-three-qubit-repetition.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# QEC: three-qubit repetition codes

`pyqpanda_alg.QEC` adds the canonical three-qubit repetition code in two
complementary forms:

- **bit-flip code**: corrects one Pauli-X error;
- **phase-flip code**: applies the same repetition logic in the Hadamard basis
and corrects one Pauli-Z error.

These are intentionally small, inspectable quantum error-correction building
blocks. They demonstrate encoding, syndrome formation and coherent recovery
without claiming a general fault-tolerant stack.

## Qubit contract

The public circuit functions receive exactly three distinct qubits:

```text
q_code = [q0, q1, q2]
```

Before encoding, `q0` contains the arbitrary logical state
`alpha|0> + beta|1>` and `q1=q2=|0>`.

After recovery, the decoded logical state is again on `q0`. The two former
ancillas retain a deterministic syndrome in `(q1, q2)`:

| error | syndrome `q1 q2` | syndrome integer `q1 + 2*q2` |
| --- | --- | ---: |
| none | `00` | 0 |
| on `q0` | `11` | 3 |
| on `q1` | `10` | 1 |
| on `q2` | `01` | 2 |

No measurement or reset is assumed by the recovery circuit; the syndrome stays
coherently encoded in the ancillas.

## Bit-flip code

Encoding uses two CNOTs:

```text
alpha|000> + beta|100> --encode--> alpha|000> + beta|111>
```

where the ket ordering in the equation is conceptual `(q0,q1,q2)` ordering.
The circuit API itself uses the supplied qubit objects directly and does not
rely on a state-vector bitstring display convention.

Recovery applies:

```text
CNOT(q0, q1)
CNOT(q0, q2)
TOFFOLI(q1, q2, q0)
```

For any one X error, this returns the original logical state to `q0` and leaves
the corresponding syndrome in `q1,q2`.

```python
from pyqpanda_alg.QEC import bit_flip_encode, bit_flip_recover

q = [0, 1, 2]
encode = bit_flip_encode(q)
recover = bit_flip_recover(q)
```

## Phase-flip code

The phase-flip encoder first creates the ordinary repetition code and then
applies `H` to all three code qubits. A Z error in that basis is mapped to an X
error by another layer of Hadamards during recovery, after which the bit-flip
recovery circuit is reused.

```python
from pyqpanda_alg.QEC import phase_flip_encode, phase_flip_recover

q = [0, 1, 2]
encode = phase_flip_encode(q)
recover = phase_flip_recover(q)
```

## Independent NumPy reference

`reference_repetition_recovery()` performs exact three-qubit state-vector
evolution without importing PyQPanda3. It is intended as an independent small
problem oracle for tests and examples.

```python
import numpy as np
from pyqpanda_alg.QEC import reference_repetition_recovery

logical = np.array([1, 1j], dtype=complex) / np.sqrt(2)
result = reference_repetition_recovery(
"phase_flip",
logical_state=logical,
error_qubit=2,
)

print(result["logical_fidelity"]) # ~1.0
print(result["syndrome_probabilities"]) # [0, 0, 1, 0]
```

The reference exposes:

- the reduced density matrix of decoded `q0`;
- pure-state logical fidelity;
- syndrome probabilities;
- optional final three-qubit state vector;
- explicit `X`/`Z` override so callers can demonstrate the error-model
boundary rather than accidentally imply broader correction.

## Capability boundary

A three-qubit repetition code has distance three only for the selected error
basis:

- the bit-flip code corrects one **X** error but does not generally correct Z;
- the phase-flip code corrects one **Z** error but does not generally correct X.

This module does **not** claim to correct an arbitrary single-qubit Pauli error.
A construction such as the nine-qubit Shor code combines both mechanisms for a
broader error model; that construction is outside this module's scope.

## Gate cost

Ignoring error injection itself:

| operation | CNOT | TOFFOLI | H |
| --- | ---: | ---: | ---: |
| bit-flip encode | 2 | 0 | 0 |
| bit-flip recover | 2 | 1 | 0 |
| phase-flip encode | 2 | 0 | 3 |
| phase-flip recover | 2 | 1 | 3 |

Backend-native cost for the Toffoli depends on backend decomposition and
transpilation.
75 changes: 75 additions & 0 deletions docs/QWalk-discrete-time-cycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# QWalk: discrete-time coined quantum walk on a cycle

`pyqpanda_alg.QWalk` adds a reusable circuit implementation of a discrete-time
coined quantum walk on a cyclic position register of size `N = 2^n`.

## Step operator

The state space is a coin qubit times an `n`-qubit position register. One step
is

```text
U = S (H_coin ⊗ I_position)
```

by default. The conditional shift is

```text
S |0, x> = |0, x-1 mod N>
S |1, x> = |1, x+1 mod N>.
```

The circuit does not allocate shift ancillas. Modular increment/decrement is
synthesized from multi-controlled `X` gates. `q_position[0]` is explicitly the
least-significant position bit, so an integer position has one unambiguous
mapping to the register.

A custom coin gate/circuit can be supplied to `walk_step()` or
`coined_walk_cycle()`. The exact NumPy reference accepts a 2x2 unitary
`coin_matrix` for independent small-instance verification.

## Quick start

```python
from pyqpanda_alg.QWalk import CoinedQuantumWalkCycle

walk = CoinedQuantumWalkCycle(
num_position_qubits=3,
steps=4,
initial_position=0,
initial_coin=0,
)

expected = walk.reference() # NumPy-only independent evolution
observed = walk.run_exact() # exact PyQPanda3 StateVector evolution
```

For one Hadamard step from `|coin=0, position=0>` on an 8-cycle, the position
probability is exactly `1/2` at position 7 and `1/2` at position 1. After two
steps it is `1/4` at 6, `1/2` at 0, and `1/4` at 2, exposing the interference
that distinguishes the walk from a classical random walk.

## Lower-level composition

The module also exports:

- `controlled_increment_cycle` / `controlled_decrement_cycle`: reversible
controlled modular arithmetic with no ancilla;
- `conditional_cycle_shift`: the coin-conditioned left/right shift;
- `walk_step`: one customizable coin-and-shift step;
- `coined_walk_cycle`: complete basis-state preparation plus repeated steps;
- `reference_walk_cycle`: independent exact NumPy evolution;
- `principal_displacement_moments`: explicit principal-branch mean/variance for
wrapped position distributions.

## Complexity and scope

For `n` position qubits, each shift uses `2n` controlled `X` operations plus two
coin flips for selecting the coin-0 decrement branch. A `t`-step walk therefore
uses `O(t n)` logical controlled operations. A multi-controlled `X` may itself
be decomposed by the backend, so hardware-native gate cost depends on the target
backend and transpilation strategy.

This contribution implements the canonical one-dimensional coined walk on a
power-of-two cycle. It does not claim arbitrary graph compilation, decoherence
models, or asymptotic quantum speedup for a particular application.
23 changes: 23 additions & 0 deletions pyqpanda-algorithm/example/QAlgBase/testeg_QEC_repetition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""Three-qubit repetition-code reference example."""

import numpy as np

from pyqpanda_alg.QEC import reference_repetition_recovery


logical = np.array([1.0, 1.0j], dtype=complex) / np.sqrt(2.0)

for code in ("bit_flip", "phase_flip"):
print(f"{code}:")
for error_qubit in (None, 0, 1, 2):
result = reference_repetition_recovery(
code,
logical_state=logical,
error_qubit=error_qubit,
)
syndrome = int(np.argmax(result["syndrome_probabilities"]))
print(
f" error={error_qubit!r} "
f"fidelity={result['logical_fidelity']:.12f} "
f"syndrome={syndrome}"
)
15 changes: 15 additions & 0 deletions pyqpanda-algorithm/example/QAlgBase/testeg_QOracleLearning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"""Deutsch-Jozsa and Bernstein-Vazirani example."""

from pyqpanda_alg import QOracleLearning


if __name__ == "__main__":
secret = "1011" # q0-first
recovered, probabilities = QOracleLearning.run_bernstein_vazirani(secret)
print("Bernstein-Vazirani secret:", recovered)
print("peak probability:", max(probabilities))

balanced_oracle = QOracleLearning.affine_truth_table("101")
classification, probabilities = QOracleLearning.run_deutsch_jozsa(balanced_oracle)
print("Deutsch-Jozsa:", classification)
print("P(0...0):", probabilities[0])
22 changes: 22 additions & 0 deletions pyqpanda-algorithm/example/QAlgBase/testeg_QWalk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Small discrete-time coined quantum-walk example."""

from pyqpanda_alg.QWalk import CoinedQuantumWalkCycle


walk = CoinedQuantumWalkCycle(
num_position_qubits=3,
steps=4,
initial_position=0,
initial_coin=0,
)

print("Independent exact reference distribution:")
for position, probability in enumerate(walk.reference()):
if probability > 1e-12:
print(f" position {position}: {probability:.6f}")

# Requires PyQPanda3, like the other circuit examples in this repository.
print("PyQPanda3 exact circuit distribution:")
for position, probability in enumerate(walk.run_exact()):
if probability > 1e-12:
print(f" position {position}: {probability:.6f}")
35 changes: 35 additions & 0 deletions pyqpanda-algorithm/example/VQLS/demo_vqls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Minimal Variational Quantum Linear Solver example."""

import numpy as np

from pyqpanda_alg.VQLS import VQLS


def main():
matrix = np.array(
[
[1.0, -1.0 / 3.0],
[-1.0 / 3.0, 1.0],
]
)
vector = np.array([1.0, 0.0])

solver = VQLS(
matrix,
vector,
layers=2,
max_iterations=400,
tolerance=1e-7,
learning_rate=0.35,
perturbation=0.15,
seed=7,
)
result = solver.solve()

print("cost:", result.cost)
print("residual norm:", result.residual_norm)
print("solution:", np.real_if_close(result.solution))


if __name__ == "__main__":
main()
29 changes: 29 additions & 0 deletions pyqpanda-algorithm/pyqpanda_alg/QEC/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Three-qubit repetition quantum error-correction codes."""

from .repetition_code import (
ThreeQubitRepetitionCode,
bit_flip_encode,
bit_flip_recover,
expected_syndrome,
inject_single_pauli_error,
logical_density_matrix,
logical_fidelity,
phase_flip_encode,
phase_flip_recover,
reference_repetition_recovery,
syndrome_probabilities,
)

__all__ = [
"ThreeQubitRepetitionCode",
"bit_flip_encode",
"bit_flip_recover",
"expected_syndrome",
"inject_single_pauli_error",
"logical_density_matrix",
"logical_fidelity",
"phase_flip_encode",
"phase_flip_recover",
"reference_repetition_recovery",
"syndrome_probabilities",
]
Loading