Skip to content

Commit 6743ea9

Browse files
committed
update
1 parent 017a2e3 commit 6743ea9

File tree

2 files changed

+169
-0
lines changed

2 files changed

+169
-0
lines changed

doc/Programs/VQEcodes/Simple44.txt

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
2+
Uses a random 4×4 Hermitian matrix as the Hamiltonian
3+
Maps this matrix to a 2-qubit operator (since 2^2 = 4)
4+
Implements VQE using:

5+
A TwoLocal ansatz
6+
The statevector simulator
7+
A classical optimizer (COBYLA)
8+
9+
Estimates the ground state energy of the matrix via VQE
10+
Compares the result to the exact lowest eigenvalue from NumPy
11+
12+
13+
14+
import numpy as np
15+
from qiskit import Aer
16+
from qiskit.opflow import MatrixOp
17+
from qiskit.circuit.library import TwoLocal
18+
from qiskit.algorithms import VQE
19+
from qiskit.algorithms.optimizers import COBYLA
20+
from qiskit.utils import QuantumInstance
21+
22+
# Set random seed for reproducibility
23+
np.random.seed(42)
24+
25+
# Step 1: Generate a random 4x4 Hermitian matrix
26+
A = np.random.randn(4, 4) + 1j * np.random.randn(4, 4)
27+
H_np = (A + A.conj().T) / 2 # Hermitian
28+
29+
# Step 2: Wrap it as a Qiskit MatrixOp (2 qubits)
30+
hamiltonian = MatrixOp(H_np)
31+
32+
# Step 3: Define a 2-qubit variational ansatz
33+
ansatz = TwoLocal(num_qubits=2, rotation_blocks=['ry', 'rz'],
34+
entanglement_blocks='cz', reps=1)
35+
36+
# Step 4: Set up the VQE algorithm
37+
optimizer = COBYLA(maxiter=200)
38+
backend = Aer.get_backend('aer_simulator_statevector')
39+
vqe = VQE(ansatz=ansatz,
40+
optimizer=optimizer,
41+
quantum_instance=QuantumInstance(backend))
42+
43+
# Step 5: Run VQE
44+
result = vqe.compute_minimum_eigenvalue(operator=hamiltonian)
45+
vqe_energy = np.real(result.eigenvalue)
46+
47+
# Step 6: Compute exact eigenvalues for comparison
48+
true_eigenvalues = np.linalg.eigvalsh(H_np)
49+
exact_ground_energy = np.min(true_eigenvalues)
50+
51+
# Step 7: Print results
52+
print("\n=== VQE Result ===")
53+
print(f"VQE estimated ground state energy: {vqe_energy:.6f}")
54+
print(f"Exact ground state energy : {exact_ground_energy:.6f}")
55+
print("Full spectrum:", np.round(true_eigenvalues, 6))
56+
57+
58+
59+
60+
61+
=== VQE Result ===
62+
VQE estimated ground state energy: -4.152306
63+
Exact ground state energy : -4.152306
64+
Full spectrum: [-4.152306 -1.431249 0.566301 3.657211]
65+
66+
67+
68+
69+
70+
MatrixOp lets you plug in any matrix (like a Hermitian Hamiltonian) without constructing a Pauli decomposition.
71+
Only 2 qubits are needed since the matrix is 4×4.
72+
This example is useful for testing VQE convergence on arbitrary problem Hamiltonians.
73+
74+
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
2+
Uses a random 8×8 Hermitian matrix (for 3 qubits)
3+
Decomposes it into Pauli terms
4+
Runs VQE using a TwoLocal ansatz
5+
Uses the statevector simulator
6+
Visualizes:

7+
The convergence of VQE (energy vs iteration)
8+
The circuit structure of the ansatz
9+
10+
11+
12+
13+
14+
import numpy as np
15+
import matplotlib.pyplot as plt
16+
from qiskit import Aer
17+
from qiskit.opflow import PauliSumOp, MatrixOp
18+
from qiskit.quantum_info import Operator
19+
from qiskit.circuit.library import TwoLocal
20+
from qiskit.algorithms import VQE
21+
from qiskit.algorithms.optimizers import COBYLA
22+
from qiskit.utils import QuantumInstance, algorithm_globals
23+
24+
# --- Parameters ---
25+
n_qubits = 3
26+
dim = 2**n_qubits
27+
np.random.seed(42)
28+
algorithm_globals.random_seed = 42
29+
30+
# --- Generate a random Hermitian matrix ---
31+
A = np.random.randn(dim, dim) + 1j * np.random.randn(dim, dim)
32+
H_np = (A + A.conj().T) / 2
33+
34+
# --- Convert to Pauli decomposition ---
35+
H_op = MatrixOp(H_np)
36+
H_pauli = PauliSumOp.from_operator(Operator(H_op))
37+
38+
# --- Exact eigenvalues for comparison ---
39+
eigvals = np.linalg.eigvalsh(H_np)
40+
exact_energy = np.min(eigvals)
41+
42+
# --- Ansatz circuit ---
43+
ansatz = TwoLocal(n_qubits, rotation_blocks=['ry', 'rz'],
44+
entanglement_blocks='cz', entanglement='full', reps=2)
45+
print("\nAnsatz circuit:")
46+
print(ansatz.decompose().draw())
47+
48+
# --- Track convergence ---
49+
energy_log = []
50+
51+
def store_intermediate_result(eval_count, params, energy, stddev):
52+
energy_log.append(energy)
53+
54+
# --- Optimizer and simulator ---
55+
optimizer = COBYLA(maxiter=200)
56+
backend = Aer.get_backend('aer_simulator_statevector')
57+
quantum_instance = QuantumInstance(backend)
58+
59+
# --- Run VQE ---
60+
vqe = VQE(ansatz=ansatz,
61+
optimizer=optimizer,
62+
quantum_instance=quantum_instance,
63+
callback=store_intermediate_result)
64+
65+
result = vqe.compute_minimum_eigenvalue(operator=H_pauli)
66+
vqe_energy = np.real(result.eigenvalue)
67+
68+
# --- Output results ---
69+
print("\n=== Results ===")
70+
print(f"Exact ground energy: {exact_energy:.6f}")
71+
print(f"VQE estimated ground energy: {vqe_energy:.6f}")
72+
print("Full spectrum:", np.round(eigvals, 6))
73+
74+
# --- Plot convergence ---
75+
plt.figure(figsize=(6,4))
76+
plt.plot(energy_log, marker='o')
77+
plt.xlabel("VQE iteration")
78+
plt.ylabel("Energy estimate")
79+
plt.title("VQE Convergence on Random 8×8 Hermitian Hamiltonian")
80+
plt.grid(True)
81+
plt.tight_layout()
82+
plt.show()
83+
84+
85+
Random Hermitian matrix: size 8 \times 8 → 3 qubits
86+
Pauli decomposition: PauliSumOp.from_operator() converts the dense matrix to a sum of Pauli strings
87+
TwoLocal ansatz: ry, rz, and cz with 2 layers
88+
Callback tracking: logs energy per iteration
89+
Plots:

90+
Convergence of VQE
91+
Circuit diagram of the ansatz
92+
93+
94+
95+

0 commit comments

Comments
 (0)