Skip to content

Commit ea83f4e

Browse files
authored
Add example: Qiskit BackendEstimatorV2 with MQSS adapter (#27)
* Add example: Qiskit BackendEstimatorV2 with MQSS adapter * Apply pre-commit fixes * Apply pre-commit fixes * remove the transpilation * remove the transpilation
1 parent 62f13fa commit ea83f4e

2 files changed

Lines changed: 1582 additions & 654 deletions

File tree

examples/backend_estimator.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import math
2+
import sys
3+
from qiskit import QuantumCircuit
4+
from mqss.qiskit_adapter import MQSSQiskitAdapter
5+
from qiskit.quantum_info import SparsePauliOp, Statevector
6+
from qiskit.primitives import BackendEstimatorV2
7+
8+
adapter = MQSSQiskitAdapter(token="<api-token>")
9+
[backend] = adapter.backends(name="<resource-name>")
10+
11+
12+
def estimate_required_shots(precision, variance=1.0):
13+
if precision <= 0:
14+
raise ValueError("precision must be > 0")
15+
return math.ceil(variance / (precision**2))
16+
17+
18+
# State-preparation circuit
19+
qc = QuantumCircuit(2)
20+
qc.h(0)
21+
qc.cx(0, 1)
22+
23+
# Define a simple Hamiltonian
24+
H = SparsePauliOp.from_list(
25+
[
26+
("ZI", 1.0),
27+
("IZ", 1.0),
28+
("ZZ", 1.0),
29+
]
30+
)
31+
32+
# Compute the ideal expectation for comparisons
33+
sv_logical = Statevector.from_instruction(qc)
34+
ev_ideal = sv_logical.expectation_value(H)
35+
ev_ideal_val = float(ev_ideal.real)
36+
37+
# Run the Estimator grouping commuting observables
38+
estimator = BackendEstimatorV2(backend=backend)
39+
estimator.options.abelian_grouping = True
40+
precision = 0.01
41+
42+
estimated_num_shots = estimate_required_shots(precision=precision, variance=1.0)
43+
print(f"Requested precision = {precision}")
44+
print(f"Estimated shots (placeholder worst-case) ≈ {estimated_num_shots}")
45+
46+
if estimated_num_shots > 20000:
47+
print("Error: estimated shot count is too high.")
48+
print("Consider using a looser precision (e.g. precision=0.05).")
49+
sys.exit(1)
50+
51+
job = estimator.run([(qc, H)], precision=precision)
52+
result = job.result()
53+
pub_result = result[0]
54+
55+
ev_backend_val = float(pub_result.data.evs)
56+
print("Ideal Estimator expectation value =", ev_ideal_val)
57+
print("Backend Estimator expectation value =", ev_backend_val)
58+
print("Absolute error |backend - ideal| =", abs(ev_backend_val - ev_ideal_val))

0 commit comments

Comments
 (0)