task_id
stringlengths 17
19
| prompt
stringlengths 129
898
| canonical_solution
stringlengths 30
1.05k
| test
stringlengths 72
1.05k
| entry_point
stringlengths 3
50
| difficulty_scale
stringclasses 3
values |
---|---|---|---|---|---|
qiskitHumanEval/0 | from qiskit import QuantumCircuit
def create_quantum_circuit(n_qubits):
""" Generate a Quantum Circuit for the given int 'n_qubits' and return it.
""" |
return QuantumCircuit(n_qubits)
| def check(candidate):
result = candidate(3)
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 3
| create_quantum_circuit | basic |
qiskitHumanEval/1 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def run_bell_state_simulator():
""" Define a phi plus bell state using Qiskit, transpile the circuit using pass manager with optimization level as 1, run it using Qiskit Sampler with the Aer simulator as backend and return the counts dictionary.
""" |
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
backend = AerSimulator()
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pass_manager.run(bell)
sampler = Sampler(mode=backend)
result = sampler.run([isa_circuit], shots=1000).result()
return result[0].data.meas.get_counts()
| def check(candidate):
result = candidate()
assert isinstance(result, dict)
assert result.keys() == {"00", "11"}
assert 0.4 < (result["00"] / sum(result.values())) < 0.6
| run_bell_state_simulator | basic |
qiskitHumanEval/2 | from qiskit.quantum_info import Statevector
from math import sqrt
def create_bell_statevector() -> Statevector:
""" Return a phi+ Bell statevector.
""" |
return (Statevector.from_label("00") + Statevector.from_label("11")) / sqrt(2)
| def check(candidate):
result = candidate()
solution = (Statevector.from_label("00") + Statevector.from_label("11")) / sqrt(2)
assert result.equiv(solution)
| create_bell_statevector | basic |
qiskitHumanEval/3 | from qiskit import QuantumCircuit
def create_ghz(drawing=False):
""" Generate a QuantumCircuit for a 3 qubit GHZ State and measure it. If `drawing` is True, return both the circuit object and the Matplotlib drawing of the circuit, otherwise return just the circuit object.
""" |
ghz = QuantumCircuit(3)
ghz.h(0)
ghz.cx(0, 1)
ghz.cx(0, 2)
ghz.measure_all()
if drawing:
return ghz, ghz.draw(output="mpl")
return ghz | def check(candidate):
from qiskit.quantum_info import Statevector
import math
import matplotlib
def check_circuit(circuit):
assert circuit.data[-1].operation.name == "measure"
circuit.remove_final_measurements()
ghz_statevector = (
Statevector.from_label("000") + Statevector.from_label("111")
) / math.sqrt(2)
assert Statevector.from_instruction(circuit).equiv(ghz_statevector)
circuit = candidate()
check_circuit(circuit)
circuit, drawing = candidate(drawing=True)
check_circuit(circuit)
assert isinstance(drawing, matplotlib.figure.Figure)
| create_ghz | basic |
qiskitHumanEval/4 | from qiskit import QuantumCircuit
def create_unitary_from_matrix():
""" Write the function that converts the matrix [[0, 0, 0, 1],[0, 0, 1, 0],[1, 0, 0, 0],[0, 1, 0, 0]] into a unitary gate and apply it to a Quantum Circuit. Then return the circuit.
""" |
matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]]
circuit = QuantumCircuit(2)
circuit.unitary(matrix, [0, 1])
return circuit
| def check(candidate):
from qiskit.quantum_info import Operator
matrix = [[0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0]]
solution = QuantumCircuit(2)
solution.unitary(matrix, [0, 1])
assert Operator(solution).equiv(Operator(candidate()))
| create_unitary_from_matrix | basic |
qiskitHumanEval/5 | from qiskit import QuantumCircuit
def create_state_prep():
""" Return a QuantumCircuit that prepares the binary state 1.
""" |
qc = QuantumCircuit(2)
qc.prepare_state("01")
return qc
| def check(candidate):
from qiskit.quantum_info import Statevector
candidate_circuit = candidate()
assert isinstance(candidate_circuit, QuantumCircuit)
candidate_sv = Statevector.from_instruction(candidate())
refrence_sv = Statevector.from_label("1".zfill(candidate_sv.num_qubits))
assert candidate_sv.equiv(refrence_sv)
| create_state_prep | basic |
qiskitHumanEval/6 | from qiskit import QuantumCircuit
def create_state_prep(num_qubits):
""" Return a QuantumCircuit that prepares the state |1> on an n-qubit register.
""" |
qc = QuantumCircuit(num_qubits)
qc.prepare_state(1)
return qc
| def check(candidate):
from qiskit.quantum_info import Statevector
candidate_circuit = candidate(num_qubits=5)
assert isinstance(candidate_circuit, QuantumCircuit)
assert candidate_circuit.num_qubits == 5
candidate_sv = Statevector.from_instruction(candidate_circuit)
refrence_sv = Statevector.from_label("1".zfill(candidate_sv.num_qubits))
assert candidate_sv.equiv(refrence_sv)
| create_state_prep | basic |
qiskitHumanEval/7 | from qiskit.circuit import QuantumCircuit, Parameter
def create_parametrized_gate():
""" Generate a 1 qubit QuantumCircuit with a parametrized Rx gate with parameter "theta".
""" |
theta = Parameter("theta")
quantum_circuit = QuantumCircuit(1)
quantum_circuit.rx(theta, 0)
return quantum_circuit
| def check(candidate):
circuit = candidate()
assert circuit.num_qubits == 1
assert circuit.data[0].operation.name == "rx"
assert circuit.data[0].operation.params[0].name == "theta"
| create_parametrized_gate | basic |
qiskitHumanEval/8 | from qiskit.circuit import QuantumCircuit, Parameter
def rx_gate(value=None):
""" Return a 1-qubit QuantumCircuit with a parametrized Rx gate and parameter "theta". If value is not None, return the circuit with value assigned to theta.
""" |
theta = Parameter("theta")
quantum_circuit = QuantumCircuit(1)
quantum_circuit.rx(theta, 0)
if value is not None:
return quantum_circuit.assign_parameters({theta: value})
return quantum_circuit
| def check(candidate):
from qiskit.quantum_info import Operator
import math
circuit = candidate()
assert circuit.num_qubits == 1
assert circuit.data[0].operation.name == "rx"
assert circuit.data[0].operation.params[0].name == "theta"
candidate_circuit = candidate(value=math.pi * 3 / 4)
solution_circuit = QuantumCircuit(1)
solution_circuit.rx((math.pi * 3 / 4), 0)
assert Operator(solution_circuit).equiv(Operator(candidate_circuit))
| rx_gate | basic |
qiskitHumanEval/9 | from qiskit.circuit.library import EfficientSU2
def create_efficientSU2():
""" Generate an EfficientSU2 circuit with 3 qubits, 1 reps and make insert_barriers true.
""" |
circuit = EfficientSU2(num_qubits=3, reps=1, insert_barriers=True)
return circuit
| def check(candidate):
result = candidate()
solution = EfficientSU2(num_qubits=3, reps=1, insert_barriers=True)
assert isinstance(solution, EfficientSU2)
assert solution.reps == result.reps
assert solution.num_qubits == result.num_qubits
| create_efficientSU2 | basic |
qiskitHumanEval/10 | from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def create_operator() -> QuantumCircuit:
""" Create a Qiskit circuit with the following unitary [[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]], consisting of only single-qubit gates and CX gates, then transpile the circuit using pass manager with optimization level as 1.
""" |
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
circ = QuantumCircuit(2, 2)
circ.append(XX, [0, 1])
pass_manager = generate_preset_pass_manager(optimization_level=1, basis_gates=["u", "cx"])
return pass_manager.run(circ)
| def check(candidate):
result = candidate()
XX = Operator([[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
assert XX.equiv(Operator(result))
for inst in result.data:
if inst.operation.num_qubits > 1:
assert inst.operation.name in ["cx", "barrier"]
| create_operator | basic |
qiskitHumanEval/11 | from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
def get_statevector(circuit: QuantumCircuit) -> Statevector:
""" Return the statevector from a circuit.
""" |
sv = Statevector.from_instruction(circuit)
return sv
| def check(candidate):
test_circuit = QuantumCircuit(2)
test_circuit.u(0.39702, 0.238798, 0.298374, 0)
test_circuit.cx(0, 1)
result = candidate(test_circuit)
assert isinstance(result, Statevector)
assert Statevector.from_instruction(test_circuit).equiv(result)
| get_statevector | basic |
qiskitHumanEval/12 | from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
def get_unitary() -> Operator:
""" Get unitary matrix for a phi plus bell circuit and return it.
""" |
circ = QuantumCircuit(2)
circ.h(0)
circ.cx(0, 1)
return Operator.from_circuit(circ).to_matrix() | def check(candidate):
result = candidate()
solution = QuantumCircuit(2)
solution.h(0)
solution.cx(0, 1)
assert Operator(solution).equiv(result)
| get_unitary | basic |
qiskitHumanEval/13 | from qiskit import QuantumCircuit
import numpy as np
def custom_rotation_gate() -> QuantumCircuit:
""" Create a quantum circuit that carries out a custom single-qubit rotation gate (U gate) with angles theta, phi and lambda all equal to pi/2.
""" |
circuit = QuantumCircuit(1)
circuit.u(np.pi / 2, np.pi / 2, np.pi / 2, 0)
return circuit
| def check(candidate):
from qiskit.quantum_info import Operator
result = candidate()
assert isinstance(result, QuantumCircuit)
solution = QuantumCircuit(1)
solution.u(np.pi / 2, np.pi / 2, np.pi / 2, 0)
assert Operator(solution).equiv(Operator(result))
| custom_rotation_gate | basic |
qiskitHumanEval/14 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def bell_each_shot() -> list[str]:
""" Run a phi plus Bell circuit using Qiskit Sampler with the Aer simulator as backend for 10 shots and return measurement results for each shots. To do so, transpile the circuit using a pass manager with optimization level as 1.
""" |
bell = QuantumCircuit(2)
# Apply gates
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
# choose simulator backend
backend = AerSimulator()
# Transpile for simulator
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
bell_circ = pass_manager.run(bell)
sampler = Sampler(mode=backend)
result = sampler.run([bell_circ],shots=10).result()
memory = result[0].data.meas.get_bitstrings()
return memory
| def check(candidate):
result = candidate()
assert isinstance(result, list)
assert len(result) > 0
assert set(result) == {"00", "11"}
| bell_each_shot | basic |
qiskitHumanEval/15 | from qiskit_ibm_runtime.fake_provider import FakeBelemV2
from qiskit_ibm_runtime import Sampler
from qiskit_aer import AerSimulator
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def noisy_bell():
""" Transpile a bell circuit using pass manager with optimization level as 1, run it using Qiskit Sampler with the Aer simulator as backend and get the execution counts.
""" |
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
bell.measure_all()
device_backend = FakeBelemV2()
simulator = AerSimulator.from_backend(device_backend)
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=simulator)
bell_circ = pass_manager.run(bell)
sampler = Sampler(mode=simulator)
result = sampler.run([bell_circ], shots=1000).result()
counts = result[0].data.meas.get_counts()
return counts
| def check(candidate):
result = candidate()
assert isinstance(result, dict)
assert (result["00"] + result["11"]) != sum(result.values())
| noisy_bell | basic |
qiskitHumanEval/16 | from qiskit_ibm_runtime.fake_provider import FakeCairoV2
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def transpile_circuit(circuit: QuantumCircuit) -> QuantumCircuit:
""" For the given Quantum Circuit, return the transpiled circuit for the Fake Cairo V2 backend using pass manager with optimization level as 1.
""" |
backend = FakeCairoV2()
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
return pass_manager.run(circuit)
| def check(candidate):
backend = FakeCairoV2()
circuit = QuantumCircuit(4, 3)
circuit.cx([0, 1, 2, 3], [1, 2, 3, 0])
t_circuit = candidate(circuit)
assert t_circuit.num_qubits == backend.num_qubits
for inst in t_circuit.data:
assert inst.operation.name in backend.configuration().basis_gates
| transpile_circuit | basic |
qiskitHumanEval/17 | from qiskit import QuantumCircuit
from qiskit.circuit.library.standard_gates.equivalence_library import ( StandardEquivalenceLibrary as std_eqlib, )
from qiskit.transpiler.passes import BasisTranslator
from qiskit.transpiler import PassManager
import numpy as np
def unroll_circuit(circuit: QuantumCircuit) -> QuantumCircuit:
""" Unroll circuit for the gateset: CX, ID, RZ, SX, X, U.
""" |
pass_ = BasisTranslator(std_eqlib, ["cx", "id", "rz", "sx", "x", "u"])
pm = PassManager(pass_)
return pm.run(circuit)
| def check(candidate):
from qiskit.quantum_info import Operator
trial_circuit = QuantumCircuit(2)
trial_circuit.h(0)
trial_circuit.u(0.3, 0.1, 0.1, 1)
trial_circuit.cp(np.pi / 4, 0, 1)
trial_circuit.h(0)
output = candidate(trial_circuit)
assert Operator(output).equiv(Operator(trial_circuit))
for inst in output.data:
assert inst.operation.name in ["cx", "id", "rz", "sx", "x", "u"]
| unroll_circuit | basic |
qiskitHumanEval/18 | from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeSydneyV2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def transpile_circuit_noopt() -> QuantumCircuit:
""" Transpile a 10-qubit GHZ circuit for the Fake Sydney V2 backend using pass manager with no optimization.
""" |
backend = FakeSydneyV2()
ghz = QuantumCircuit(10)
ghz.h(0)
ghz.cx(0, range(1, 10))
ghz.measure_all()
pass_manager = generate_preset_pass_manager(optimization_level=0, backend=backend)
return pass_manager.run(ghz)
| def check(candidate):
result = candidate()
backend = FakeSydneyV2()
# Optimization level 0 should use trivial qubit mapping
# i.e. circuit qubit 'i' => device qubit 'i'.
# This is very unlikely with higher optimization levels
assert result.layout.initial_index_layout() == list(range(backend.num_qubits))
| transpile_circuit_noopt | basic |
qiskitHumanEval/19 | from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeTorontoV2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def transpile_circuit_maxopt() -> QuantumCircuit:
""" Transpile and map an 11-qubit GHZ circuit for the Fake Toronto V2 backend using pass manager with maximum transpiler optimization.
""" |
backend = FakeTorontoV2()
ghz = QuantumCircuit(11, 11)
ghz.h(0)
ghz.cx(0, range(1, 11))
ghz.barrier()
pass_manager = generate_preset_pass_manager(optimization_level=3, backend=backend)
return pass_manager.run(ghz)
| def check(candidate):
result = candidate()
result.remove_final_measurements()
backend = FakeTorontoV2()
# Check initial layout is not the trivial layout (this is very unlikely
# if transpiled with optimization level 3)
assert result.layout.initial_index_layout() != list(range(backend.num_qubits))
# Optimization level 3 should easily find circuits with depth < 200
assert result.depth() < 150
| transpile_circuit_maxopt | intermediate |
qiskitHumanEval/20 | from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakePerth
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def transpile_ghz_customlayout() -> QuantumCircuit:
""" Using a pass manager with optimization level as 1, transpile and map a three-qubit GHZ circuit for the Fake Perth backend using custom initial layout: [2,4,6].
""" |
backend = FakePerth()
ghz = QuantumCircuit(3)
ghz.h(0)
ghz.cx(0, [1, 2])
ghz.barrier()
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend, initial_layout=[2, 4, 6])
return pass_manager.run(ghz)
| def check(candidate):
result = candidate()
result.remove_final_measurements()
backend = FakePerth()
assert result.num_qubits == backend.num_qubits
assert result.layout.initial_index_layout()[:3] == [2, 4, 6]
| transpile_ghz_customlayout | intermediate |
qiskitHumanEval/21 | from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeOslo
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def transpile_circuit_dense() -> QuantumCircuit:
""" Using a pass manager with optimization level as 1 and dense layout method, transpile and map a bell circuit for the Fake Oslo backend.
""" |
backend = FakeOslo()
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend, layout_method="dense")
solution_circ = pass_manager.run(bell)
return solution_circ
| def check(candidate):
result = candidate()
backend = FakeOslo()
assert result.num_qubits == backend.num_qubits
| transpile_circuit_dense | basic |
qiskitHumanEval/22 | from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeAuckland
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def transpile_circuit_alap() -> QuantumCircuit:
""" Using a pass manager with optimization level as 1 and as-late-as-possible scheduling method, transpile and map a bell circuit for the Fake Auckland backend. Return the circuit.
""" |
backend = FakeAuckland()
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0, 1)
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend, scheduling_method="alap")
return pass_manager.run(bell)
| def check(candidate):
result = candidate()
backend = FakeAuckland()
assert result.num_qubits == backend.num_qubits
| transpile_circuit_alap | basic |
qiskitHumanEval/23 | from qiskit import QuantumCircuit
def dj_constant_oracle() -> QuantumCircuit:
""" Create a constant oracle for use in a Deutsch-Jozsa experiment. The oracle takes two input bits (qubits 0 and 1) and writes to one output bit (qubit 2).
""" |
oracle = QuantumCircuit(3)
oracle.x(2)
return oracle
| def check(candidate):
from qiskit.quantum_info import Operator
qc = QuantumCircuit(3)
constant_0_oracle = Operator(qc)
qc.x(2)
constant_1_oracle = Operator(qc)
result = Operator(candidate())
assert result.equiv(constant_0_oracle) or result.equiv(constant_1_oracle)
| dj_constant_oracle | basic |
qiskitHumanEval/24 | from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
from numpy import isclose
def dj_algorithm(oracle: QuantumCircuit) -> bool:
""" Given a Deutsch-Jozsa oracle in which the final qubit is the "output" qubit, return True if the oracle is constant or False otherwise.
""" |
n = oracle.num_qubits
qc = QuantumCircuit(n, n - 1)
qc.x(n - 1)
qc.h(range(n))
qc.compose(oracle, inplace=True)
qc.h(range(n))
qc.measure(range(n - 1), range(n - 1))
counts = StatevectorSampler().run([qc]).result()[0].data.c.get_counts()
return isclose(counts.get('00000000', 0), 1024)
| def check(candidate):
balanced = QuantumCircuit(5)
balanced.cx(3, 4)
assert candidate(balanced) == False
constant = QuantumCircuit(9)
constant.x(8)
assert candidate(constant) == True
| dj_algorithm | intermediate |
qiskitHumanEval/25 | from qiskit import QuantumCircuit
from qiskit.transpiler import CouplingMap
from qiskit.transpiler.passes import LookaheadSwap
from qiskit.transpiler.passmanager import PassManager
def passmanager_Lookahead(coupling) -> QuantumCircuit:
""" Transpile a 7-qubit GHZ circuit using LookaheadSwap pass and an input custom coupling map [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]].
""" |
ghz = QuantumCircuit(7)
ghz.h(0)
ghz.cx(0, range(1, 7))
coupling_map = CouplingMap(couplinglist=coupling)
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(ghz)
return lookahead_circ
| def check(candidate):
from qiskit.quantum_info import Statevector
from qiskit.transpiler.passes import CheckMap
from qiskit.converters import circuit_to_dag
coupling = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
coupling_map = CouplingMap(couplinglist=coupling)
result = candidate(coupling)
chkmp = CheckMap(coupling_map)
chkmp.run(circuit_to_dag(result))
assert chkmp.property_set["is_swap_mapped"] == True
solution = QuantumCircuit(7)
solution.h(0)
solution.cx(0, range(1, 7))
ls = LookaheadSwap(coupling_map=coupling_map)
pass_manager = PassManager(ls)
lookahead_circ = pass_manager.run(solution)
assert Statevector.from_instruction(lookahead_circ).equiv(Statevector.from_instruction(result))
| passmanager_Lookahead | intermediate |
qiskitHumanEval/26 | from qiskit.dagcircuit import DAGCircuit
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.converters import circuit_to_dag
def bell_dag() -> DAGCircuit:
""" Construct a DAG circuit for a 3-qubit Quantum Circuit with the bell state applied on qubit 0 and 1. Finally return the DAG Circuit object.
""" |
q = QuantumRegister(3, 'q')
c = ClassicalRegister(3, 'c')
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.measure(q[0], c[0])
dag = circuit_to_dag(circ)
return dag
| def check(candidate):
result = candidate()
assert type(result) == DAGCircuit
assert result.num_qubits() == 3
assert result.depth() == 3
assert dict(result.count_ops()) == {'h': 1, 'cx': 1, 'measure':1}
| bell_dag | basic |
qiskitHumanEval/27 | from qiskit.dagcircuit import DAGCircuit
from qiskit.converters import circuit_to_dag
from qiskit.circuit.library import HGate
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def apply_op_back() -> DAGCircuit:
""" Generate a DAG circuit for 3-qubit Quantum Circuit which consists of H gate on qubit 0 and CX gate on qubit 0 and 1. After converting the circuit to DAG, apply a Hadamard operation to the back of qubit 0 and return the DAGCircuit.
""" |
q = QuantumRegister(3, "q")
c = ClassicalRegister(3, "c")
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
dag = circuit_to_dag(circ)
dag.apply_operation_back(HGate(), qargs=[q[0]])
return dag
| def check(candidate):
from qiskit.quantum_info import Statevector
from qiskit.converters import dag_to_circuit
result = candidate()
assert type(result) == DAGCircuit
assert result.num_qubits() == 3
last_node = result.op_nodes()[-1]
assert last_node.name == "h"
assert len(result.descendants(last_node)) == 1
q = QuantumRegister(3, "q")
c = ClassicalRegister(3, "c")
circ = QuantumCircuit(q, c)
circ.h(q[0])
circ.cx(q[0], q[1])
circ.h(0)
candidate_circ = dag_to_circuit(result)
assert Statevector.from_instruction(circ).equiv(Statevector.from_instruction(candidate_circ))
| apply_op_back | intermediate |
qiskitHumanEval/28 | from matplotlib.figure import Figure
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit.visualization import plot_histogram
def visualize_bell_states()->Figure:
""" Prepare phi plus and phi minus bell states and visualize their results in a histogram and return the histogram.
""" |
phi_plus = QuantumCircuit(2)
phi_minus = QuantumCircuit(2)
phi_plus.h(0)
phi_plus.cx(0,1)
phi_minus.x(0)
phi_minus.h(0)
phi_minus.cx(0,1)
phi_plus.measure_all()
phi_minus.measure_all()
backend = AerSimulator()
sampler = Sampler(mode=backend)
result_phi_plus = sampler.run([phi_plus], shots=1000).result()
result_phi_minus = sampler.run([phi_minus], shots=1000).result()
phi_plus_counts = result_phi_plus[0].data.meas.get_counts()
phi_minus_counts = result_phi_minus[0].data.meas.get_counts()
return plot_histogram([phi_plus_counts, phi_minus_counts], legend = ['|Φ+⟩ Count', '|Φ-⟩ Count'])
| def check(candidate):
from matplotlib.patches import Rectangle
result = candidate()
assert isinstance(result, Figure)
gca = result.gca()
assert {xlabel.get_text() for xlabel in gca.get_xticklabels()} == {"00", "11"}
objs = gca.findobj(Rectangle)
assert len(objs) >= 4
counts = [obj.get_height() for obj in objs[:4]]
shots = counts[0] + counts[1]
for i in range(4):
assert round(counts[i]/shots, 1) == 0.5
| visualize_bell_states | basic |
qiskitHumanEval/29 | from matplotlib.figure import Figure
from qiskit.visualization import plot_circuit_layout
from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeAthensV2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def plot_circuit_layout_bell() -> Figure:
""" Plot a circuit layout visualization for a transpiled bell circuit using a pass manager with optimization level as 1 for the Fake Athens V2 backend.
""" |
backend = FakeAthensV2()
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0,1)
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
brisbane_bell = pass_manager.run(bell)
return (plot_circuit_layout(brisbane_bell, backend))
| def check(candidate):
result = candidate()
assert type(result) == Figure
| plot_circuit_layout_bell | intermediate |
qiskitHumanEval/30 | from qiskit import QuantumCircuit
from matplotlib.figure import Figure
from qiskit.visualization import plot_state_city
from qiskit.quantum_info import Statevector
def plot_circuit_layout_bell() -> Figure:
""" Plot a city_state for a bell circuit.
""" |
bell = QuantumCircuit(2)
bell.h(0)
bell.cx(0,1)
bell_state = Statevector(bell)
plot_state_city(bell_state)
return plot_state_city(bell_state)
| def check(candidate):
result = candidate()
assert type(result) == Figure
assert len(result.axes) == 2
| plot_circuit_layout_bell | basic |
qiskitHumanEval/31 | from typing import Dict
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit_ibm_runtime.options import SamplerOptions
def sampler_qiskit() -> Dict:
""" Run a Bell circuit on Qiskit Sampler and run the circuit on the Aer simulator with the seed set as 42. Return the resulting counts dictionary.
""" |
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
qc.measure_all()
options = SamplerOptions()
options.simulator.seed_simulator=42
sampler = Sampler(mode=AerSimulator(), options=options)
job = sampler.run([qc])
result = job.result()[0].data.meas.get_counts()
return result
| def check(candidate):
result = candidate()
assert result == {"00": 521, "11": 503}
| sampler_qiskit | intermediate |
qiskitHumanEval/32 | from numpy import float64
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Estimator
from qiskit.quantum_info import SparsePauliOp
def estimator_qiskit() -> float64:
""" Run a Bell circuit on Qiskit Estimator and return expectation values for the bases II, XX, YY, ZZ.
""" |
observable = SparsePauliOp(["II","XX","YY","ZZ"], coeffs=[1, 1, -1, 1])
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
estimator = Estimator(mode=AerSimulator())
job = estimator.run([(qc, observable)])
result = job.result()[0].data.evs.item()
return result
| def check(candidate):
result = candidate()
assert result == 4.0
| estimator_qiskit | intermediate |
qiskitHumanEval/33 | from typing import List
from qiskit.circuit.random import random_circuit
from qiskit_ibm_runtime import Sampler, SamplerOptions
from qiskit_aer import AerSimulator
def run_multiple_sampler() -> List:
""" Generate two random quantum circuits, each with 2 qubits and a depth of 2, using seed values of 0 and 1 respectively. Run the circuits using the Sampler on the Aer simulator with the seed set as 42 and return the counts for both circuits.
""" |
circuits = (
random_circuit(2, 2, seed=0, measure=True).decompose(reps=1),
random_circuit(2, 2, seed=1, measure=True).decompose(reps=1),
)
options = SamplerOptions()
options.simulator.seed_simulator=42
sampler = Sampler(mode=AerSimulator(), options=options)
job = sampler.run(circuits)
results = job.result()
statevectors = [result.data.c.get_counts() for result in results]
return statevectors
| def check(candidate):
result = candidate()
assert isinstance(result, list)
assert result == [{"01": 1024}, {"00": 552, "01": 472}]
| run_multiple_sampler | intermediate |
qiskitHumanEval/34 | from typing import Dict, Optional, Tuple
from qiskit_ibm_runtime import Batch, Sampler
from qiskit.primitives.primitive_job import PrimitiveJob
from qiskit_ibm_runtime.fake_provider import FakeCairoV2
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def run_jobs_on_batch() -> Tuple[Dict[str, PrimitiveJob], Optional[str]]:
""" Generate all four Bell states and execute them on the Fake Cairo V2 backend using SamplerV2 with batch mode. Each Bell state circuit will be transpiled with an optimization level of 3, with the seed 123 for the transpiler.
Returns a dictionary where the keys are the Bell state names ['phi_plus', 'phi_minus', 'psi_plus', 'psi_minus'] and the values are the corresponding RuntimeJob objects and the batch id.
""" |
def create_bell_circuit(state):
"Helper function to create bell state"
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
if state == "phi_minus":
qc.z(0)
elif state == "psi_plus":
qc.x(1)
elif state == "psi_minus'":
qc.x(1)
qc.z(0)
qc.measure_all()
return qc
# Create bell states
bell_states = ["phi_plus", "phi_minus", "psi_plus", "psi_minus"]
circuits = [create_bell_circuit(state) for state in bell_states]
# Setting backend and pass managers
backend = FakeCairoV2()
pm = generate_preset_pass_manager(optimization_level = 3, backend=backend, seed_transpiler=123)
# Running jobs using batch
with Batch(backend=backend) as batch:
jobs = {}
sampler = Sampler(mode=batch)
for bell_state, bell_circuit in zip(bell_states, circuits):
isa_bell_circuit = pm.run(bell_circuit)
jobs[bell_state] = sampler.run([(isa_bell_circuit)])
return jobs
| def check(candidate):
from numpy import isclose
jobs = candidate()
reference_data = {
'phi_plus': {'00': 0.10, '11': 0.10},
'phi_minus': {'00': 0.10, '11': 0.10},
'psi_plus': {'01': 0.10, '10': 0.10},
'psi_minus': {'01': 0.001, '10': 0.002}
}
assert isinstance(jobs, dict)
assert set(jobs.keys()) == set(reference_data.keys())
for state, job in jobs.items():
assert isinstance(job, PrimitiveJob)
assert job.job_id() is not None
counts = job.result()[0].data.meas.get_counts()
shots = 4096
normalized_counts = {k: v/shots for k, v in counts.items()}
for key, value in reference_data[state].items():
assert isclose(normalized_counts[key], value, atol=1e-01)
| run_jobs_on_batch | difficult |
qiskitHumanEval/35 | from qiskit.circuit.library import EfficientSU2
from qiskit.quantum_info import SparsePauliOp
import numpy as np
from qiskit_ibm_runtime import QiskitRuntimeService, Estimator, EstimatorOptions
from qiskit.primitives.primitive_job import PrimitiveJob
from qiskit_ibm_runtime.fake_provider import FakeCairoV2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def run_circuit_with_dd_trex() -> PrimitiveJob:
"""
Run an EfficientSU2 circuit with 5 qubits, 2 repetitions, and pairwise entanglement on the Fake Cairo V2 backend.
The circuit should be transpiled with an optimization level of 1 and a transpiler seed of 789. Use 1*Z_-1 observable to calculate the expectation value.
""" |
n_qubits = 5
reps = 2
circuit = EfficientSU2(n_qubits, entanglement="pairwise", reps=reps)
observable = SparsePauliOp.from_sparse_list([("Z", [-1], 1.0)], num_qubits=n_qubits)
# Generate random parameters
rng = np.random.default_rng(1234)
params = rng.uniform(-np.pi, np.pi, size=circuit.num_parameters)
backend = FakeCairoV2()
pm = generate_preset_pass_manager(optimization_level = 1, backend=backend, seed_transpiler=789)
isa_circuit = pm.run(circuit)
isa_observable = observable.apply_layout(isa_circuit.layout)
options = EstimatorOptions()
options.environment.job_tags = ["run_circ_dd_trex"]
estimator = Estimator(mode=backend, options=options)
job = estimator.run([(isa_circuit, isa_observable, params)])
return job
| def check(candidate):
from numpy import isclose
job = candidate()
assert isinstance(job, PrimitiveJob)
assert job.job_id() is not None
result = job.result()
assert isclose(result[0].data.evs.item(), 0.33, atol=0.06)
| run_circuit_with_dd_trex | difficult |
qiskitHumanEval/36 | from qiskit import QuantumCircuit
def bv_function(s: str) -> QuantumCircuit:
""" Write a function to design a Bernstein-Vazirani oracle from a bitstring and return it.
""" |
n = len(s)
qc = QuantumCircuit(n + 1)
for index, bit in enumerate(reversed(s)):
if bit == "1":
qc.cx(index, n)
return qc
| def check(candidate):
from qiskit.quantum_info.operators import Operator
s = "1111"
result = candidate(s)
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 5
solution = QuantumCircuit(5)
for i in range(4):
solution.cx(i, 4)
assert Operator(result).equiv(Operator(solution))
| bv_function | intermediate |
qiskitHumanEval/37 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit.primitives.containers.primitive_result import PrimitiveResult
def bv_algorithm(s: str) -> [list, PrimitiveResult]:
""" Illustrate a Bernstein-Vazirani algorithm routine on Qiskit and run it using Qiskit Sampler with Aer simulator as backend for a string of 0s and 1s. Return the bit strings of the result and the result itself.
""" |
qc = QuantumCircuit(len(s) + 1)
for index, bit in enumerate(reversed(s)):
if bit == "1":
qc.cx(index, len(s))
qc.measure_all()
backend = AerSimulator()
sampler = Sampler(mode=backend)
result= sampler.run([qc], shots=1).result()
bitstrings = result[0].data.meas.get_bitstrings()
return [bitstrings, result]
| def check(candidate):
s = "1111"
result = candidate(s)
assert (type(result[0]) == list)
assert (len(result[0]) == result[1][0].data.meas.num_shots)
assert (type(result[1]) == PrimitiveResult)
| bv_algorithm | intermediate |
qiskitHumanEval/38 | from qiskit import QuantumCircuit
def create_quantum_circuit_based_h0_crz01_h1_cry10(theta):
""" Build a 2-qubit Quantum Circuit composed by H gate in Quantum register 0, Controlled-RZ gate in quantum register 0 1 with given input theta value, H gate in quantum register 1 and Controlled-RY gate in quantum register 1 0 with given input theta value.
""" |
qc = QuantumCircuit(2)
qc.h(0)
qc.crz(theta,0,1)
qc.h(1)
qc.cry(theta,1,0)
return qc
| def check(candidate):
from qiskit import QuantumRegister
from qiskit.circuit import CircuitInstruction
from math import pi
from qiskit.circuit.library import HGate, CRZGate, CRYGate
qr = QuantumRegister(2, name="q")
theta = pi/2
data = candidate(theta).data
assert data[0]==CircuitInstruction(HGate(), [qr[0]], [])
assert data[1]==CircuitInstruction(CRZGate(theta), [qr[0], qr[1]], [])
assert data[2]==CircuitInstruction(HGate(), [qr[1]], [])
assert data[3]==CircuitInstruction(CRYGate(theta), [qr[1], qr[0]], [])
| create_quantum_circuit_based_h0_crz01_h1_cry10 | basic |
qiskitHumanEval/39 | from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
def create_uniform_superposition(n: int) -> QuantumCircuit:
""" Initialize a uniform superposition on n qubits and return statevector.
""" |
qc = QuantumCircuit(n)
qc.h(range(n))
return Statevector(qc)
| def check(candidate):
from qiskit.quantum_info import state_fidelity
from math import sqrt
assert round(state_fidelity(candidate(1), [1/sqrt(2)]*2),3)==1
assert round(state_fidelity(candidate(2), [0.5]*4),3)==1
assert round(state_fidelity(candidate(3), [1/sqrt(8)]*8),3)==1
| create_uniform_superposition | basic |
qiskitHumanEval/40 | from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit_ibm_runtime.options import SamplerOptions
def init_random_3qubit(desired_vector: [complex])-> dict:
""" Initialize a non-trivial 3-qubit state for a given desired vector state and return counts after running it using Qiskit Sampler with the Aer simulator as backend and ser=t seed as 42.
""" |
qc = QuantumCircuit(3)
qc.initialize(desired_vector, range(3))
qc.measure_all()
backend = AerSimulator()
options = SamplerOptions()
options.simulator.seed_simulator=42
sampler = Sampler(mode=backend,options=options)
result = sampler.run([qc]).result()
return result[0].data.meas.get_counts()
| def check(candidate):
from math import sqrt
from qiskit.quantum_info import state_fidelity
desired_vector = [0.25j, 1 /sqrt(8)+0j, 0.25+0.25j, 0, 0,1 / sqrt(8) * (1+2j), 0.25+0j, 0]
result = candidate(desired_vector)
assert isinstance(result, dict)
assert result == {"101": 665, "010": 118, "000": 49, "110": 51, "001": 141}
| init_random_3qubit | basic |
qiskitHumanEval/41 | from qiskit.quantum_info.operators import Operator, Pauli
import numpy as np
def compose_op() -> Operator:
""" Compose XZ with a 3-qubit identity operator using the Operator and the Pauli 'YX' class in Qiskit. Return the operator instance.
""" |
op = Operator(np.eye(2 ** 3))
YX = Operator(Pauli('YX'))
op.compose(YX, qargs=[0, 2], front=True)
return op
| def check(candidate):
result = candidate()
op = Operator(np.eye(2 ** 3))
YX = Operator(Pauli('YX'))
op.compose(YX, qargs=[0, 2], front=True)
assert(result == op)
| compose_op | basic |
qiskitHumanEval/42 | from qiskit.quantum_info.operators import Operator, Pauli
def combine_op() -> Operator:
""" Combine the following three operators XX YY ZZ as: 0.5 * (XX + YY - 3 * ZZ).
""" |
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY - 3 * ZZ)
return op
| def check(candidate):
result = candidate()
XX = Operator(Pauli('XX'))
YY = Operator(Pauli('YY'))
ZZ = Operator(Pauli('ZZ'))
op = 0.5 * (XX + YY - 3 * ZZ)
assert (result == op)
| combine_op | basic |
qiskitHumanEval/43 | from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import QiskitRuntimeService
from qiskit import QuantumCircuit
def generate_pass_manager_obj()-> QuantumCircuit:
""" Instantiate a preset_passmanager using Qiskit using the least busy device available and optimzation level 3. Return the resulting passmanager instance.
""" |
provider = QiskitRuntimeService()
backend = provider.least_busy()
pass_manager = generate_preset_pass_manager(optimization_level=3, backend=backend)
return pass_manager
| def check(candidate):
from qiskit.transpiler.passmanager import StagedPassManager
result = candidate()
assert(type(result) == StagedPassManager)
| generate_pass_manager_obj | basic |
qiskitHumanEval/44 | from qiskit import QuantumCircuit
def tensor_circuits() -> QuantumCircuit:
""" Write an example using Qiskit that performs tensor operation on a 1-qubit quantum circuit with an X gate and a 2-qubit quantum circuit with a CRY gate, where the CRY gate has an angle of 0.2 radians and is controlled by qubit 0.
""" |
top = QuantumCircuit(1)
top.x(0)
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1)
tensored = bottom.tensor(top)
return tensored
| def check(candidate):
from qiskit.quantum_info import Statevector
result = candidate()
top = QuantumCircuit(1)
top.x(0);
bottom = QuantumCircuit(2)
bottom.cry(0.2, 0, 1)
tensored = bottom.tensor(top)
assert Statevector.from_instruction(result).equiv(Statevector.from_instruction(tensored))
| tensor_circuits | basic |
qiskitHumanEval/45 | from qiskit.quantum_info.random import random_clifford
def get_random_clifford(n_qubits):
""" Generate a random clifford circuit using the input n_qubit as number of qubits.
""" |
return random_clifford(num_qubits=n_qubits)
| def check(candidate):
from qiskit.quantum_info import Clifford
result = candidate(3)
assert result.num_qubits == 3
assert isinstance(result, Clifford)
| get_random_clifford | basic |
qiskitHumanEval/46 | from qiskit.circuit.library import LinearFunction
from qiskit.synthesis.linear.linear_matrix_utils import random_invertible_binary_matrix
def get_random_linear_function(n_qubits, seed):
""" Generate a random linear function circuit using the input parameters n_qubits and seed, and the random_invertible_binary_matrix method.
""" |
return LinearFunction(random_invertible_binary_matrix(num_qubits=n_qubits, seed=seed))
| def check(candidate):
result = candidate(3,3)
assert result.num_qubits == 3
assert isinstance(result, LinearFunction)
| get_random_linear_function | basic |
qiskitHumanEval/47 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def random_coin_flip(samples: int)->dict:
""" Design a Quantum Circuit that simulates random coin flips for the given samples using Qiskit Sampler with the Aer simulator as backend and outputs the count of heads and tails in a dictionary. The heads should be stored in the dict as 'Heads' and tails as 'Tails'. For example
random_coin_flip(10) == {'Heads' : 5, 'Tails : 5}
random_coin_flip(20) == {'Heads' : 9, 'Tails : 11}.
""" |
circuit = QuantumCircuit(1,1)
circuit.h(0)
circuit.measure_all()
backend = AerSimulator()
sampler = Sampler(mode=backend)
result = sampler.run([circuit], shots=samples).result()
counts = result[0].data.meas.get_counts()
return {'Heads' : counts['0'], 'Tails': counts['1']}
| def check(candidate):
samples = 2000
result = candidate(samples)
assert result.keys() == {'Heads', 'Tails'}
assert round(result['Heads']/samples, 1) == 0.5
assert round(result['Tails']/samples, 1) == 0.5
| random_coin_flip | intermediate |
qiskitHumanEval/48 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def random_number_generator_unsigned_8bit(n: int)->[int]:
""" Write a function that generates n number of random 8-bit unsigned integers using a Quantum Circuit and outputs a list of integers.
""" |
circuit = QuantumCircuit(8)
circuit.h(range(8))
circuit.measure_all()
backend = AerSimulator()
sampler = Sampler(mode=backend)
result = sampler.run([circuit], shots=n).result()
samples = result[0].data.meas.get_bitstrings()
return [int(sample, 2) for sample in samples]
| def check(candidate):
result = candidate(10)
assert isinstance(result, list)
assert len(result) == 10
for i in range(10):
assert result[i] >= 0 and result[i] < 256
| random_number_generator_unsigned_8bit | intermediate |
qiskitHumanEval/49 | from qiskit import QuantumCircuit
def simple_elitzur_vaidman()->QuantumCircuit:
""" Return a simple Elitzur Vaidman bomb tester circuit.
""" |
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0,1)
circuit.h(0)
return circuit
| def check(candidate):
from qiskit.quantum_info import Statevector
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 2
circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0,1)
circuit.h(0)
assert Statevector.from_instruction(result).equiv(Statevector.from_instruction(circuit))
| simple_elitzur_vaidman | intermediate |
qiskitHumanEval/50 | from qiskit import QuantumCircuit
def remove_gate_in_position(circuit: QuantumCircuit, position: int):
""" Remove the gate in the input position for the given Quantum Circuit.
""" |
del circuit.data[position]
return circuit
| def check(candidate):
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.h(1)
qc.h(0)
expected_qc = QuantumCircuit(2)
expected_qc.cx(0, 1)
expected_qc.h(1)
expected_qc.h(0)
assert candidate(qc, 0)==expected_qc
| remove_gate_in_position | basic |
qiskitHumanEval/51 | from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Instruction
def quantum_teleportation_circuit(data: [Instruction])->QuantumCircuit:
""" Write a function to build a quantum teleportation circuit that takes a list of instructions as an argument to transfer the data from the sender to the receiver while taking advantage of dynamic circuits.
""" |
sender = QuantumRegister(1, "sender")
receiver = QuantumRegister(1, "receiver")
ancillary = QuantumRegister(1, "ancillary")
c_sender = ClassicalRegister(1, "c_sender")
c_receiver = ClassicalRegister(1, "c_receiver")
c_ancillary = ClassicalRegister(1, "c_ancillary")
circuit = QuantumCircuit(sender, ancillary, receiver, c_sender, c_ancillary, c_receiver)
for gate in data:
circuit.append(gate, [0])
circuit.barrier()
circuit.h(ancillary)
circuit.cx(ancillary, receiver)
circuit.barrier()
circuit.cx(sender, ancillary)
circuit.h(sender)
circuit.measure(sender, c_sender)
circuit.measure(ancillary, c_ancillary)
circuit.barrier()
with circuit.if_test((c_ancillary, 1)):
circuit.x(receiver)
with circuit.if_test((c_sender, 1)):
circuit.z(receiver)
circuit.barrier()
circuit.measure(receiver, c_receiver)
return circuit
| def check(candidate):
from qiskit.circuit.library import XGate, HGate
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit.result import marginal_distribution
result_x = candidate([XGate()])
backend = AerSimulator()
sampler = Sampler(mode=backend)
assert isinstance(result_x, QuantumCircuit)
assert result_x.num_qubits == 3
assert result_x.count_ops()['x'] == 1 and result_x.count_ops()['if_else'] == 2
assert marginal_distribution(sampler.run([result_x]).result()[0].data.c_receiver.get_counts()) == {'1': 1024}
result_h = candidate([HGate()])
assert result_h.count_ops()['h'] == 3 and result_h.count_ops()['if_else'] == 2
assert round(marginal_distribution(sampler.run([result_h]).result()[0].data.c_receiver.get_counts())['0']/1024, 1) == 0.5
| quantum_teleportation_circuit | intermediate |
qiskitHumanEval/52 | from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
def send_bits(bitstring: str)->QuantumCircuit:
""" Provide a quantum circuit that enables the transmission of two classical bits from the sender to the receiver through a single qubit of quantum communication, given that the sender and receiver have access to entangled qubits.
""" |
sender = QuantumRegister(1, "sender")
receiver = QuantumRegister(1, "receiver")
measure = ClassicalRegister(2, "measure")
circuit = QuantumCircuit(sender, receiver, measure)
# Prepare ebit used for superdense coding
circuit.h(sender)
circuit.cx(sender, receiver)
circuit.barrier()
# sender's operations
if bitstring[1] == "1":
circuit.z(sender)
if bitstring[0] == "1":
circuit.x(sender)
circuit.barrier()
# receiver's actions
circuit.cx(sender, receiver)
circuit.h(sender)
circuit.measure(sender, measure[0])
circuit.measure(receiver, measure[1])
return circuit
| def check(candidate):
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
result_1 = candidate("10")
backend = AerSimulator()
sampler = Sampler(mode=backend)
assert isinstance(result_1, QuantumCircuit)
assert result_1.num_qubits == 2
assert result_1.count_ops()["x"] == 1
assert sampler.run([result_1]).result()[0].data.measure.get_counts() == {"10": 1024}
result_2 = candidate("01")
assert result_2.depth() == 6
assert result_2.count_ops()["z"] == 1
assert sampler.run([result_2]).result()[0].data.measure.get_counts() == {"01": 1024}
| send_bits | intermediate |
qiskitHumanEval/53 | from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from qiskit.circuit.library import XOR
def xor_gate(a: int, b: int)->dict:
""" Given two 8-bit integers a and b design a Quantum Circuit that acts as a classical XOR gate. Simulate the circuit using Qiskit Sampler with the Aer simulator as backend and return the counts of the result.
""" |
circuit = XOR(8, a).compose(XOR(8, b))
circuit.measure_all()
backend = AerSimulator()
sampler = Sampler(mode=backend)
result = sampler.run([circuit.decompose()]).result()
return result[0].data.meas.get_counts()
| def check(candidate):
assert candidate(10, 20) == {"00011110": 1024}
assert candidate(61, 9) == {"00110100": 1024}
assert candidate(47, 8) == {"00100111": 1024}
| xor_gate | intermediate |
qiskitHumanEval/54 | from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def and_gate(a: int, b: int)->dict:
""" Given two 3-bit integers a and b, design a quantum circuit that acts as a classical AND gate. Simulate the circuit on using Qiskit Sampler with the Aer simulator as backend and return the counts of the result.
""" |
qr_a = QuantumRegister(3, "qr_a")
qr_b = QuantumRegister(3, "qr_b")
ancillary = QuantumRegister(3, "ancillary")
measure = ClassicalRegister(3, "measure")
circuit = QuantumCircuit(qr_a, qr_b, ancillary, measure)
a = format(a, '03b')
b = format(b, '03b')
for i in range(3):
if a[2-i] == '1':
circuit.x(qr_a[i])
if b[2-i] == '1':
circuit.x(qr_b[i])
for i in range(3):
circuit.ccx(qr_a[i], qr_b[i], ancillary[i])
circuit.measure(ancillary, measure)
backend = AerSimulator()
sampler = Sampler(mode=backend)
result = sampler.run([circuit]).result()
return result[0].data.measure.get_counts()
| def check(candidate):
assert candidate(1, 2) == {'000': 1024}
assert candidate(6, 7) == {'110': 1024}
assert candidate(3, 5) == {'001': 1024}
| and_gate | intermediate |
qiskitHumanEval/55 | from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def or_gate(a: int, b: int)->dict:
""" Given two 3-bit integers a and b, design a quantum circuit that acts as a classical OR gate. Simulate the circuit using Qiskit Sampler with the Aer simulator as backend and return the counts of the result.
""" |
qr_a = QuantumRegister(3, "qr_a")
qr_b = QuantumRegister(3, "qr_b")
ancillary = QuantumRegister(3, "ancillary")
measure = ClassicalRegister(3, "measure")
circuit = QuantumCircuit(qr_a, qr_b, ancillary, measure)
a = format(a, '03b')
b = format(b, '03b')
for i in range(3):
if a[2-i] == '0':
circuit.x(qr_a[i])
if b[2-i] == '0':
circuit.x(qr_b[i])
for i in range(3):
circuit.ccx(qr_a[i], qr_b[i], ancillary[i])
circuit.x(ancillary)
circuit.measure(ancillary, measure)
backend = AerSimulator()
sampler = Sampler(mode=backend)
result = sampler.run([circuit]).result()
return result[0].data.measure.get_counts()
| def check(candidate):
assert candidate(1, 2) == {"011": 1024}
assert candidate(6, 7) == {"111": 1024}
assert candidate(0, 5) == {"101": 1024}
| or_gate | intermediate |
qiskitHumanEval/56 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
def not_gate(a: int)->dict:
""" Given two 8-bit integers, design a quantum circuit that acts as a classical NOT gate. Simulate the circuit Qiskit Sampler with the Aer simulator as backend and return the counts of the result.
""" |
circuit = QuantumCircuit(8)
a = format(a, "08b")
for i in range(8):
if a[7-i] == "0":
circuit.x(i)
circuit.measure_all()
backend = AerSimulator()
sampler = Sampler(mode=backend)
result = sampler.run([circuit]).result()
return result[0].data.meas.get_counts()
| def check(candidate):
assert candidate(0) == {"11111111": 1024}
assert candidate(238) == {"00010001": 1024}
assert candidate(59) == {"11000100": 1024}
| not_gate | intermediate |
qiskitHumanEval/57 | from qiskit import QuantumCircuit
def create_swap_gate()->QuantumCircuit:
""" Design a SWAP gate using only CX gates.
""" |
circuit = QuantumCircuit(2)
circuit.cx(0,1)
circuit.cx(1,0)
circuit.cx(0,1)
return circuit
| def check(candidate):
from qiskit.circuit.library import SwapGate
from qiskit.quantum_info.operators import Operator
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 2
assert dict(result.count_ops()) == {'cx': 3}
assert Operator(result) == Operator(SwapGate())
| create_swap_gate | intermediate |
qiskitHumanEval/58 | from qiskit import QuantumCircuit
from numpy import pi
def create_ch_gate()->QuantumCircuit:
""" Design a CH gate using CX and RY gates.
""" |
circuit = QuantumCircuit(2)
circuit.ry(pi/4, 1)
circuit.cx(0,1)
circuit.ry(-pi/4, 1)
return circuit
| def check(candidate):
from qiskit.circuit.library import CHGate
from qiskit.quantum_info.operators import Operator
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 2
assert dict(result.count_ops()) == {'ry': 2, 'cx': 1}
assert Operator(result) == Operator(CHGate())
| create_ch_gate | intermediate |
qiskitHumanEval/59 | from qiskit import QuantumCircuit
def create_cz_gate()->QuantumCircuit:
""" Design a CZ gate using only H and CNOT gates and return the quantum circuit.
""" |
circuit = QuantumCircuit(2)
circuit.h(1)
circuit.cx(0,1)
circuit.h(1)
return circuit
| def check(candidate):
from qiskit.circuit.library import CZGate
from qiskit.quantum_info.operators import Operator
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 2
assert dict(result.count_ops()) == {'h': 2, 'cx': 1}
assert Operator(result) == Operator(CZGate())
| create_cz_gate | intermediate |
qiskitHumanEval/60 | from qiskit import QuantumCircuit
def create_cy_gate()->QuantumCircuit:
""" Design a CY gate using only one CX gate and any other single qubit gates.
""" |
circuit = QuantumCircuit(2)
circuit.sdg(1)
circuit.cx(0,1)
circuit.s(1)
return circuit
| def check(candidate):
from qiskit.circuit.library import CYGate
from qiskit.quantum_info.operators import Operator
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 2
assert 'cx' in result.count_ops()
for gate in result.data:
op = gate.operation
assert op.num_qubits == 1 or op.name == 'cx' or op.name == 'barrier'
assert Operator(result) == Operator(CYGate())
| create_cy_gate | intermediate |
qiskitHumanEval/61 | from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister
def create_quantum_circuit_with_one_qubit_and_measure():
""" Build a Quantum Circuit by first creating one Quantum Register and one Classical Register and then perform measurement on it.
""" |
q = QuantumRegister(1, 'q')
c = ClassicalRegister(1, 'c')
qc = QuantumCircuit(q, c)
qc.measure(q, c)
return qc
| def check(candidate):
result = candidate()
assert result.depth() == 1
assert result.width() == 2
assert dict(result.count_ops()) == {'measure': 1}
| create_quantum_circuit_with_one_qubit_and_measure | basic |
qiskitHumanEval/62 | from qiskit import QuantumCircuit
def bb84_senders_circuit(state: [int], basis: [int])->QuantumCircuit:
""" Construct a BB84 protocol circuit for the sender, inputting both the states and the measured bases.
""" |
num_qubits = len(state)
circuit = QuantumCircuit(num_qubits)
for i in range(len(basis)):
if state[i] == 1:
circuit.x(i)
if basis[i] == 1:
circuit.h(i)
return circuit
| def check(candidate):
from qiskit.quantum_info import Statevector
from numpy.random import randint, seed
seed(12345)
qubits = 5
state = randint(2, size=qubits)
basis = randint(2, size=qubits)
result = candidate(state, basis)
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == qubits
assert result.count_ops()['h'] == sum(basis)
assert result.count_ops()['x'] == sum(state)
solution = QuantumCircuit(5)
solution.x([1,2,3])
solution.h([0,3])
assert Statevector.from_instruction(result).equiv(Statevector.from_instruction(solution))
| bb84_senders_circuit | intermediate |
qiskitHumanEval/63 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from numpy.random import randint
def bb84_circuit_generate_key(senders_basis: [int], circuit: QuantumCircuit)->str:
""" Write a function to generate the key from the circuit and the sender's basis generated by the sender using BB84 protocol.
""" |
n = len(senders_basis)
receivers_basis = randint(2, size=n)
for i in range(n):
if receivers_basis[i]:
circuit.h(i)
circuit.measure_all()
backend = AerSimulator()
sampler = Sampler(mode=backend)
result = sampler.run([circuit.reverse_bits()], shots=1).result()
count= result[0].data.meas.get_counts()
key = next(iter(count))
encryption_key = ''
for i in range(n):
if senders_basis[i] == receivers_basis[i]:
encryption_key += str(key[i])
return encryption_key
| def check(candidate):
from numpy.random import seed
seed(12345)
basis = [1, 0, 0, 1, 1]
circuit = QuantumCircuit(5)
circuit.x([3, 4])
circuit.h([0, 3, 4])
result = candidate(basis, circuit)
assert result == "1"
| bb84_circuit_generate_key | difficult |
qiskitHumanEval/64 | from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
def simons_algorithm(s: str)->QuantumCircuit:
""" Write a function that takes the bitstring 's' as the input and builds a Quantum Circuit such that the output when xor-ed with the input 's' is same as the 's'. When building the quantum circuit make sure the classical registers is named 'c'.
""" |
n = len(s)
s = s[::-1]
q_reg1 = QuantumRegister(n,"reg1")
q_reg2 = QuantumRegister(n,"reg2")
c_reg = ClassicalRegister(n, "c")
circuit = QuantumCircuit (q_reg1, q_reg2, c_reg)
circuit.h(q_reg1)
circuit.barrier()
circuit.cx(q_reg1, q_reg2)
if "1" in s:
i = s.find("1")
for j in range(n):
if s[j] == "1":
circuit.cx(i, q_reg2[j])
circuit.barrier()
circuit.h(q_reg1)
circuit.measure(q_reg1, c_reg)
return circuit
| def check(candidate):
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
result = candidate('1010')
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 8
def dpm2(vec1, vec2):
return sum(int(a) * int(b) for a, b in zip(vec1, vec2)) % 2
backend = AerSimulator()
sampler = Sampler(mode=backend)
job = sampler.run([result]).result()
data = job[0].data
counts= data.c.get_counts()
for key in counts:
assert dpm2(key, "1010") == 0
| simons_algorithm | intermediate |
qiskitHumanEval/65 | from qiskit import QuantumCircuit
from numpy import pi
def QFT(n: int)->QuantumCircuit:
""" Design a Quantum Fourier Transform circuit for n qubits using basic Quantum gates.
""" |
circuit = QuantumCircuit(n)
def swap_registers(circuit, n):
for qubit in range(n//2):
circuit.swap(qubit, n-qubit-1)
return circuit
def qft_rotations(circuit, n):
"""Performs qft on the first n qubits in circuit (without swaps)"""
if n == 0:
return circuit
n -= 1
circuit.h(n)
for qubit in range(n):
circuit.cp(pi/2**(n-qubit), qubit, n)
qft_rotations(circuit, n)
qft_rotations(circuit, n)
swap_registers(circuit, n)
return circuit
| def check(candidate):
from qiskit.circuit.library import QFT as QiskitQFT
from qiskit.quantum_info.operators import Operator
result = candidate(3)
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 3
for gate in result.data:
op = gate.operation
assert op.num_qubits <= 2 or op.name == 'barrier'
solution = QiskitQFT(3)
assert Operator(result).equiv(Operator(solution))
| QFT | intermediate |
qiskitHumanEval/66 | from qiskit import QuantumCircuit
from numpy import arccos, sqrt
def w_state()->QuantumCircuit:
""" Generate a Quantum Circuit for a W state and measure it.
""" |
circuit = QuantumCircuit(3)
circuit.ry(2*arccos(1/sqrt(3)), 0)
circuit.ch(0,1)
circuit.cx(1,2)
circuit.cx(0,1)
circuit.x(0)
circuit.measure_all()
return circuit
| def check(candidate):
from qiskit_aer import AerSimulator
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
from qiskit_ibm_runtime import Sampler
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 3
backend = AerSimulator()
sampler = Sampler(mode=backend)
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pass_manager.run(result)
job = sampler.run([isa_circuit]).result()
counts= job[0].data.meas.get_counts()
assert counts.keys() == {'001', '010' , '100'}
assert counts['001'] >= 300 and counts['001'] <= 400
assert counts['010'] >= 300 and counts['010'] <= 400
assert counts['100'] >= 300 and counts['100'] <= 400
assert counts['001'] + counts['010'] + counts['100'] == 1024
| w_state | intermediate |
qiskitHumanEval/67 | from qiskit import QuantumCircuit
from numpy import pi
def chsh_circuit(alice: int, bob: int)->QuantumCircuit:
""" Design a CHSH circuit that takes bits of Alice and Bob as input and return the Quantum Circuit after measuring.
""" |
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.barrier()
if alice == 0:
qc.ry(0, 0)
else:
qc.ry(-pi / 2, 0)
qc.measure(0, 0)
if bob == 0:
qc.ry(-pi / 4, 1)
else:
qc.ry(pi / 4, 1)
qc.measure(1, 1)
return qc
| def check(candidate):
result = candidate(0,1)
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 2
assert result.width() == 4
assert result.depth() == 4
assert set({'ry': 2, 'measure': 2, 'h': 1, 'cx': 1}.items()).issubset(set(result.count_ops().items()))
| chsh_circuit | intermediate |
qiskitHumanEval/68 | from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
from numpy import pi
def zeno_elitzur_vaidman_bomb_tester(bomb_live: bool)->(float, float, float):
""" Design a Zeno Elitzur Vaidman Bomb Tester circuit which takes the boolean if the bomb is live and outputs the percentage of successful live bomb predictions, dud bomb predictions and bombs that detonated. Use 25 cycles to increase the efficiency of the circuit.
""" |
live_predictions = dud_predictions = detonations = 0
shots = 1024
cycles = 25
e = pi/cycles
measurements = cycles + 1 if bomb_live else 1
circuit = QuantumCircuit(1, measurements)
for i in range(cycles):
circuit.ry(e, 0)
if bomb_live:
circuit.measure(0, i)
circuit.measure(0, measurements - 1)
backend = AerSimulator()
sampler = Sampler(mode=backend)
job = sampler.run([circuit],shots=shots).result()
counts= job[0].data.c.get_counts()
if bomb_live:
for key, value in counts.items():
if key[0] == '1':
detonations += value
elif '1' in key[1:]:
dud_predictions += value
else:
live_predictions += value
else:
live_predictions = counts['0'] if '0' in counts else 0
dud_predictions = counts['1']
detonations = 0
return (live_predictions/shots, dud_predictions/shots, detonations/shots)
| def check(candidate):
result = candidate(True)
assert isinstance(result, tuple) and len(result) == 3
assert result[0] >= 0.85 and result[1] <= 0.03 and result[2] <= 0.12
assert candidate(False) == (0.0, 1.0, 0.0)
| zeno_elitzur_vaidman_bomb_tester | difficult |
qiskitHumanEval/69 | from qiskit import QuantumCircuit
def create_quantum_circuit_based_h0_cs01_h1_csdg10():
""" Build a Quantum Circuit composed by the gates H in Quantum register 0, Controlled-S gate in quantum register 0 1, H gate in quantum register 1 and Controlled-S dagger gate in quantum register 1 0.
""" |
qc = QuantumCircuit(2)
qc.h(0)
qc.cs(0,1)
qc.h(1)
qc.csdg(1,0)
return qc
| def check(candidate):
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 2
assert result.depth() == 4
assert dict(result.count_ops()) == {'h': 2, 'cs': 1, 'csdg': 1}
| create_quantum_circuit_based_h0_cs01_h1_csdg10 | basic |
qiskitHumanEval/70 | from qiskit import QuantumCircuit
def create_quantum_circuit_based_h0_cswap012_h1_csdg10():
""" Build a Quantum Circuit composed by the gates H in Quantum register 0, Controlled-SWAP gate, also known as the Fredkin gate in quantum register 0 1 2, H gate in quantum register 1 and Controlled-S dagger gate in quantum register 1 0.
""" |
qc = QuantumCircuit(3)
qc.h(0)
qc.cswap(0,1,2)
qc.h(1)
qc.csdg(1,0)
return qc
| def check(candidate):
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 3
assert result.depth() == 4
assert dict(result.count_ops()) == {"h": 2, "cswap": 1, "csdg": 1}
| create_quantum_circuit_based_h0_cswap012_h1_csdg10 | basic |
qiskitHumanEval/71 | from qiskit import QuantumCircuit
def create_quantum_circuit_based_h0_csx01_h1():
""" Build a Quantum Circuit composed by the gates H in Quantum register 0, Controlled-√X gate in quantum register 0 1, and H gate in quantum register 1.
""" |
qc = QuantumCircuit(3)
qc.h(0)
qc.csx(0,1)
qc.h(1)
return qc
| def check(candidate):
result = candidate()
assert isinstance(result, QuantumCircuit)
assert result.num_qubits == 3
assert result.depth() == 3
assert dict(result.count_ops()) == {"h": 2, "csx": 1}
| create_quantum_circuit_based_h0_csx01_h1 | basic |
qiskitHumanEval/72 | import contextlib
from qiskit import QuantumCircuit
from qiskit.circuit import Gate
def gate_if_clbits(
circuit: QuantumCircuit, gate: Gate, qubits: list[int], condition_clbits: list[int]
) -> None:
""" Apply `gate` to qubits with indices `qubits`, conditioned on all `condition_clbits` being 1.
""" |
with contextlib.ExitStack() as stack:
for index in condition_clbits:
stack.enter_context(circuit.if_test((index, 1)))
circuit.append(gate, qubits)
| def check(candidate):
from qiskit.circuit.library import CXGate
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
qc = QuantumCircuit(2, 3)
qc.x(0)
candidate(qc, CXGate(), [0, 1], [0, 2])
qc.measure_all()
sampler = Sampler(mode=AerSimulator())
result = sampler.run([qc]).result()[0].data.meas.get_counts()
assert result.get("01") == 1024
qc = QuantumCircuit(2, 3)
qc.x([0, 1])
qc.measure([0, 1], [0, 2])
qc.x(1)
candidate(qc, CXGate(), [0, 1], [0, 2])
qc.measure_all()
result = sampler.run([qc]).result()[0].data.meas.get_counts()
assert result.get("11") == 1024
| gate_if_clbits | intermediate |
qiskitHumanEval/73 | from qiskit import QuantumCircuit
def x_measurement(circuit: QuantumCircuit, qubit: int, clbit: int) -> None:
""" Add an X-basis measurement on qubit at index `qubit`, storing the result to classical bit `clbit`.
""" |
circuit.h(qubit)
circuit.measure(qubit, clbit)
| def check(candidate):
from qiskit.primitives import StatevectorSampler
qc = QuantumCircuit(3, 2)
qc.x(1)
qc.h(1)
candidate(qc, 1, 0)
result = StatevectorSampler().run([qc]).result()[0].data.c.get_counts()
assert result.get('01') == 1024
| x_measurement | basic |
qiskitHumanEval/74 | from qiskit import QuantumCircuit
from qiskit.circuit.library import Barrier
def split_circuit_at_barriers(circuit: QuantumCircuit) -> list[QuantumCircuit]:
""" Split `circuit` at each barrier operation. Do not include barriers in the output circuits.
""" |
output = []
new_circuit = circuit.copy_empty_like()
for inst in circuit.data:
if isinstance(inst.operation, Barrier):
output.append(new_circuit)
new_circuit = circuit.copy_empty_like()
continue
new_circuit.data.append(inst)
output.append(new_circuit)
return output
| def check(candidate):
qc = QuantumCircuit(3)
qc.x(0)
qc.barrier()
qc.cx(0, 1)
qc.h([0, 1])
qc.z(1)
qc.barrier()
qc.barrier()
qc.tdg(0)
circuits = candidate(qc)
assert len(circuits) == 4
for circuit, expected_length in zip(circuits, [1, 4, 0, 1]):
assert len(circuit.data) == expected_length
| split_circuit_at_barriers | intermediate |
qiskitHumanEval/75 | from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
def circuit_to_bools(circuit: QuantumCircuit) -> list[bool]:
""" Given a QuantumCircuit, sample it once and convert the measurement result to a list of bools, where the 0th bool is the result of the 0th classical bit.
""" |
result = StatevectorSampler().run([circuit], shots=1).result()[0].data.meas.get_counts()
measurement_int = int(list(result.keys())[0], 2)
output = []
for bit_index in range(circuit.num_clbits):
# Use bit-masking to get bits from `int`
bit = bool(2 ** (bit_index) & measurement_int)
output.append(bit)
return output
| def check(candidate):
# 101
qc = QuantumCircuit(3)
qc.x([0, 2])
qc.measure_all()
assert candidate(qc) == [True, False, True]
# 00011
qc = QuantumCircuit(5)
qc.x([3, 4])
qc.measure_all()
assert candidate(qc) == [False] * 3 + [True] * 2
# 111011111
qc = QuantumCircuit(9)
qc.x(range(9))
qc.x(3)
qc.measure_all()
assert candidate(qc) == [True] * 3 + [False] + [True] * 5
| circuit_to_bools | intermediate |
qiskitHumanEval/76 | from qiskit import QuantumRegister
from qiskit.transpiler.basepasses import TransformationPass
from qiskit.dagcircuit import DAGCircuit
from qiskit.circuit.library import ZGate, HGate, XGate
def create_hxh_pass() -> TransformationPass:
""" Return a transpiler pass that replaces all non-controlled Z-gates with H-X-H-gate sequences.
""" |
class HXHPass(TransformationPass):
def run(
self,
dag: DAGCircuit,
) -> DAGCircuit:
for node in dag.op_nodes():
if not isinstance(node.op, ZGate):
continue
# Create HXH gate sequence
hxh_dag = DAGCircuit()
register = QuantumRegister(1)
hxh_dag.add_qreg(register)
hxh_dag.apply_operation_back(HGate(), [register[0]])
hxh_dag.apply_operation_back(XGate(), [register[0]])
hxh_dag.apply_operation_back(HGate(), [register[0]])
dag.substitute_node_with_dag(node, hxh_dag)
return dag
return HXHPass()
| def check(candidate):
from qiskit.transpiler import PassManager
from qiskit import QuantumCircuit
hxh_pass = candidate()
# Be lenient and accept both class and instance of class
if not isinstance(hxh_pass, TransformationPass):
hxh_pass = hxh_pass()
assert isinstance(hxh_pass, TransformationPass)
passmanager = PassManager(hxh_pass)
qc = QuantumCircuit(1)
qc.x(0)
qc.z(0)
result = passmanager.run(qc)
result_op_strings = list(
map(lambda circuit_inst: circuit_inst.operation.name, result.data)
)
assert result_op_strings == ["x", "h", "x", "h"]
qc = QuantumCircuit(3)
qc.h(1)
qc.z(1)
qc.cz(0, 1)
qc.cx(1, 2)
result = passmanager.run(qc)
result_op_strings = list(
map(lambda circuit_inst: circuit_inst.operation.name, result.data)
)
assert result_op_strings == ["h", "h", "x", "h", "cz", "cx"]
| create_hxh_pass | intermediate |
qiskitHumanEval/77 | import math
from qiskit import QuantumCircuit
def circuit_from_probability_dist(probability_dist: dict[int, float]) -> QuantumCircuit:
""" Given a distribution as a dictionary of the form { measurement: probability }, return a quantum circuit that produces that distribution.
""" |
num_qubits = math.ceil(math.log2(max(probability_dist.keys()) + 1)) or 1
amplitudes = []
for basis_state in range(2**num_qubits):
prob = probability_dist.get(basis_state, 0)
amplitudes.append(math.sqrt(prob))
qc = QuantumCircuit(num_qubits)
qc.prepare_state(amplitudes, range(num_qubits))
return qc
| def check(candidate):
from qiskit.quantum_info import Statevector
def _check(input_dist):
circuit = candidate(input_dist)
# allow circuits with or without final measurements
circuit.remove_final_measurements()
probability_dist = Statevector(circuit).probabilities()
for basis_state, target_probability in input_dist.items():
assert math.isclose(
target_probability, probability_dist[basis_state], abs_tol=0.05
)
for input_dist in [
{0: 1},
{0: 0.1, 1: 0.1, 2: 0.7, 3: 0.1},
{0: 0.5, 3: 0.5},
{1: 0.5, 2: 0.5},
]:
_check(input_dist)
| circuit_from_probability_dist | intermediate |
qiskitHumanEval/78 | from qiskit import QuantumCircuit
from qiskit.circuit.library import QFT
def qft_no_swaps(num_qubits: int) -> QuantumCircuit:
""" Return an inverse quantum Fourier transform circuit without the swap gates.
""" |
qft = QFT(num_qubits=num_qubits, do_swaps=False, inverse=True)
return qft
| def check(candidate):
from qiskit.quantum_info import Operator
for num_qubits in [1, 3, 8]:
qft = QFT(num_qubits=num_qubits, do_swaps=False, inverse=True)
response = candidate(num_qubits)
assert Operator(qft) == Operator(response)
| qft_no_swaps | intermediate |
qiskitHumanEval/79 | from qiskit import QuantumCircuit
def count_instructions(circuit: QuantumCircuit) -> int:
""" Return the total number of instructions in the circuit.
""" |
return len(circuit.data)
| def check(candidate):
qc = QuantumCircuit(4)
qc.x(0)
assert candidate(qc) == 1
qc.cx(0, [1, 2])
assert candidate(qc) == 3
qc.measure_all()
assert candidate(qc) == 8
| count_instructions | basic |
qiskitHumanEval/80 | from qiskit import QuantumCircuit
from qiskit.circuit import Gate
def count_gates(circuit: QuantumCircuit) -> int:
""" Return the total number of unitary gates in the circuit.
""" |
count = 0
for inst in circuit.data:
if isinstance(inst.operation, Gate):
count += 1
return count
| def check(candidate):
qc = QuantumCircuit(4)
qc.reset(0)
qc.tdg(0)
assert candidate(qc) == 1
qc.cx(0, [1, 2])
assert candidate(qc) == 3
qc.measure_all()
assert candidate(qc) == 3
| count_gates | basic |
qiskitHumanEval/81 | from qiskit import QuantumCircuit
def convert_qasm_string_to_quantum_circuit() -> QuantumCircuit:
""" Generate a QASM 2 string representing a Phi plus Bell state quantum circuit. Then, convert this QASM 2 string into a Quantum Circuit object and return the resulting circuit.
""" |
qasm_string="""OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];"""
qc = QuantumCircuit.from_qasm_str(qasm_string)
return qc
| def check(candidate):
from qiskit.quantum_info import Statevector
from math import sqrt
data = candidate()
bell_state = (Statevector.from_label("11") + Statevector.from_label("00"))/sqrt(2)
assert Statevector.from_instruction(data) == bell_state
| convert_qasm_string_to_quantum_circuit | basic |
qiskitHumanEval/82 | from qiskit import QuantumCircuit
from qiskit import qpy
def create_binary_serialization():
""" Create a file containing the binary serialization of a Phi plus Bell state quantum circuit and write it as 'bell.qpy' in binary mode.
""" |
qc = QuantumCircuit(2, name='Bell', metadata={'test': True})
qc.h(0)
qc.cx(0, 1)
with open('bell.qpy', 'wb') as fd:
qpy.dump(qc, fd)
| def check(candidate):
from qiskit.quantum_info import Statevector
from math import sqrt
candidate()
with open('bell.qpy', 'rb') as fd:
data = qpy.load(fd)[0]
bell_state = (Statevector.from_label("11") + Statevector.from_label("00"))/sqrt(2)
assert Statevector.from_instruction(data) == bell_state
| create_binary_serialization | basic |
qiskitHumanEval/83 | from qiskit import QuantumCircuit
from qiskit.quantum_info import DensityMatrix, concurrence
def calculate_bell_state_properties():
""" Construct a Phi plus Bell state quantum circuit, compute its Density Matrix and Concurrence, and return these results in a tuple in the same order.
""" |
qc = QuantumCircuit(2, name='Bell')
qc.h(0)
qc.cx(0, 1)
rho = DensityMatrix.from_instruction(qc)
concur = concurrence(rho)
return rho, concur
| def check(candidate):
import numpy as np
DensityMatrix, concurrence = candidate()
assert round(concurrence,1) == 1
expected_rho = np.array([[0.5, 0, 0, 0.5], [0, 0, 0, 0], [0, 0, 0, 0], [0.5, 0, 0, 0.5]])
np.testing.assert_array_almost_equal(DensityMatrix, expected_rho, decimal=5, err_msg='Density matrix does not match the expected Bell state density matrix')
| calculate_bell_state_properties | basic |
qiskitHumanEval/84 | from qiskit import pulse
from qiskit_ibm_runtime.fake_provider import FakeBelemV2
from qiskit.pulse import DriveChannel, Gaussian
def define_gaussian_pulse_schedule():
""" Using Qiskit Pulse, create a Gaussian pulse schedule on drive channel 0 with a duration of 128 and name this schedule 'gaussian_pulse_schedule'. Configure it for the FakeBelem backend and return the resulting pulse schedule.
""" |
backend = FakeBelemV2()
gaussian_pulse = Gaussian(duration=128, amp=0.1, sigma=16)
d0 = DriveChannel(0)
with pulse.build(backend=backend, name='gaussian_pulse_schedule') as gaussian_pulse_schedule:
pulse.play(gaussian_pulse, d0)
return gaussian_pulse_schedule
| def check(candidate):
gaussian_pulse_schedule = candidate()
assert gaussian_pulse_schedule.name == 'gaussian_pulse_schedule'
assert gaussian_pulse_schedule.duration == 128
| define_gaussian_pulse_schedule | intermediate |
qiskitHumanEval/85 | from qiskit import QuantumCircuit
import qiskit.qasm2
def convert_quantum_circuit_to_qasm_string(circuit: QuantumCircuit) -> str:
""" Given a QuantumCircuit, convert it into qasm2 string and return it.
""" |
qasm_str = qiskit.qasm2.dumps(circuit)
return qasm_str
| def check(candidate):
from qiskit.quantum_info import Statevector
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0,1)
qasm_str = candidate(qc)
circuit = QuantumCircuit.from_qasm_str(qasm_str)
assert Statevector.from_instruction(circuit) == Statevector.from_instruction(qc)
| convert_quantum_circuit_to_qasm_string | basic |
qiskitHumanEval/86 | from qiskit import pulse
from qiskit_ibm_runtime.fake_provider import FakeBelemV2
from qiskit.pulse import DriveChannel, Constant, Play, Delay
def pulse_schedule_with_constant_and_delay():
""" Using Qiskit Pulse, create a schedule with a constant pulse on drive channel 0, featuring a duration of 160 and an amplitude of 0.1 and name this schedule "pulse_schedule_with_constant_and_delay". Use the FakeBelem backend for configuration. After creating the pulse, add a delay of 400 to the schedule, then replay the same pulse. Return the completed pulse schedule.
""" |
backend = FakeBelemV2()
constant_pulse = Constant(duration=160, amp=0.1)
drive_chan = DriveChannel(0)
with pulse.build(backend=backend, name="pulse_schedule_with_constant_and_delay") as pulse_sched:
pulse.play(constant_pulse, drive_chan)
pulse.delay(400, drive_chan)
pulse.play(constant_pulse, drive_chan)
return pulse_sched
| def check(candidate):
pulse_sched = candidate()
constant_pulses = 0
delays = 0
for _, inst in pulse_sched.instructions:
if isinstance(inst, Play):
if isinstance(inst.pulse, Constant):
constant_pulses += 1
elif isinstance(inst, Delay):
delays += 1
assert constant_pulses == 2, "Schedule should contain exactly two Constant pulses."
assert delays == 1, "Schedule should contain exactly one Delay instruction."
assert pulse_sched.name == "pulse_schedule_with_constant_and_delay"
| pulse_schedule_with_constant_and_delay | intermediate |
qiskitHumanEval/87 | from qiskit import QuantumCircuit
def quantum_circuit_with_delay():
""" Create a one-qubit quantum circuit, apply hadamard gate, then add a delay of 100 and then again apply hadamard gate and return the circuit.
""" |
qc = QuantumCircuit(1)
qc.h(0)
delay_duration = 100
qc.delay(delay_duration, 0, unit="dt")
qc.h(0)
return qc
| def check(candidate):
from qiskit import QuantumRegister
from qiskit.circuit import CircuitInstruction
from qiskit.circuit.library import HGate
from qiskit.circuit import Delay
qr = QuantumRegister(1, name="q")
data = candidate().data
assert data[0]==CircuitInstruction(HGate(), [qr[0]], [])
assert data[1]==CircuitInstruction(Delay(100), [qr[0]], [])
assert data[2]==CircuitInstruction(HGate(), [qr[0]], [])
| quantum_circuit_with_delay | intermediate |
qiskitHumanEval/88 | from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit import IfElseOp
def create_conditional_circuit():
""" Create a one-qubit quantum circuit, apply a Hadamard gate, and then measure it. Based on the classical output, use an IfElseOp operation: if the output is 1, append a one-qubit quantum circuit with a Z gate; if the output is 0, append a one-qubit quantum circuit with an X gate. Finally, add a measurement to the appended circuit and return the complete quantum circuit.
""" |
qr = QuantumRegister(1, 'q')
cr = ClassicalRegister(1, 'c')
circuit = QuantumCircuit(qr, cr)
circuit.h(qr[0])
circuit.measure(qr[0], cr[0])
true_body = QuantumCircuit(qr, cr)
true_body.z(qr[0])
false_body = QuantumCircuit(qr, cr)
false_body.x(qr[0])
if_else_gate = IfElseOp((cr, 1), true_body, false_body)
circuit.append(if_else_gate, [qr[0]], [cr[0]])
circuit.measure(qr[0], cr[0])
return circuit
| def check(candidate):
from qiskit import QuantumRegister
from qiskit.circuit import CircuitInstruction
from qiskit.circuit.library import HGate
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import Sampler
qr = QuantumRegister(1, name="q")
circuit = candidate()
data = circuit.data
assert data[0]==CircuitInstruction(HGate(), [qr[0]], [])
assert data[2].operation.name == "if_else"
backend = AerSimulator()
sampler = Sampler(mode=backend)
results = sampler.run([circuit],shots=1024).result()
counts= results[0].data.c.get_counts()
assert counts == {'1': 1024}
assert sum(counts.values()) == 1024
| create_conditional_circuit | intermediate |
qiskitHumanEval/89 | from qiskit.circuit.library import HGate
from qiskit import QuantumCircuit, QuantumRegister
def create_controlled_hgate()->QuantumCircuit:
""" Construct a quantum circuit with a three-qubit controlled-Hadamard gate, using qubit 0 and qubit 1 as the control bits and qubit 2 as the target bit. Return the circuit.
""" |
qr = QuantumRegister(3)
qc = QuantumCircuit(qr)
c3h_gate = HGate().control(2)
qc.append(c3h_gate, qr)
return qc
| def check(candidate):
from qiskit.quantum_info import Operator
solution_register = QuantumRegister(3)
solution_circuit = QuantumCircuit(solution_register)
c3h_gate = HGate().control(2)
solution_circuit.append(c3h_gate, solution_register)
qc = candidate()
assert Operator(qc).equiv(solution_circuit)
| create_controlled_hgate | basic |
qiskitHumanEval/90 | from qiskit import QuantumCircuit
def create_custom_controlled()-> QuantumCircuit:
""" Create a custom 2-qubit gate with an X gate on qubit 0 and an H gate on qubit 1. Then, add two control qubits to this gate. Apply this controlled gate to a 4-qubit circuit, using qubits 0 and 3 as controls and qubits 1 and 2 as targets. Return the final circuit.
""" |
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
return qc2
| def check(candidate):
from qiskit.quantum_info import Operator
qc1 = QuantumCircuit(2)
qc1.x(0)
qc1.h(1)
custom = qc1.to_gate().control(2)
qc2 = QuantumCircuit(4)
qc2.append(custom, [0, 3, 1, 2])
candidate_circuit = candidate()
assert Operator(qc2).equiv(candidate_circuit)
| create_custom_controlled | basic |
qiskitHumanEval/91 | from qiskit import QuantumCircuit
from qiskit.converters import circuit_to_instruction
def convert_circuit_to_instruction():
""" Create a circuit that produces a phi plus bell state with name bell_instruction and convert it into a quantum instruction.
""" |
circ = QuantumCircuit(2, 2, name="bell_instruction")
circ.h(0)
circ.cx(0,1)
circ.measure([0, 1], [0, 1])
instruction = circuit_to_instruction(circ)
return instruction
| def check(candidate):
instruction = candidate()
assert instruction.name == "bell_instruction"
assert instruction.num_qubits == 2
circ = QuantumCircuit(2, 2)
circ.h(0)
circ.cx(0,1)
circ.measure([0, 1], [0, 1])
assert instruction.definition == circ
| convert_circuit_to_instruction | basic |
qiskitHumanEval/92 | from qiskit import QuantumCircuit
from qiskit.quantum_info import StabilizerState
def calculate_stabilizer_state_info():
""" Construct a Phi plus Bell state quantum circuit, compute its stabilizer state, and return both the stabilizer state and a dictionary of the stabilizer state measurement probabilities.
""" |
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
stab = StabilizerState(qc)
probabilities_dict = stab.probabilities_dict()
return stab, probabilities_dict
| def check(candidate):
stab, probabilities_dict = candidate()
assert isinstance(stab, StabilizerState)
assert isinstance(probabilities_dict, dict)
assert probabilities_dict == {"00": 0.5, "11": 0.5}
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
new_stab = StabilizerState(qc)
assert stab.equiv(new_stab)
| calculate_stabilizer_state_info | basic |
qiskitHumanEval/93 | from qiskit.synthesis import synth_clifford_full
from qiskit.quantum_info.random import random_clifford
def synthesize_clifford_circuit(n_qubits:int):
""" Create a random clifford circuit using the random_clifford function for a given n qubits with seed 1234 and synthesize it using synth_clifford_full method and return.
""" |
qc = random_clifford(n_qubits, seed=1234)
synthesized_qc = synth_clifford_full(qc)
return synthesized_qc
| def check(candidate):
from qiskit.quantum_info import Operator
n_qubits = 6
synthesized_qc = candidate(n_qubits)
qc = random_clifford(n_qubits)
synthesized_qc = synth_clifford_full(qc)
assert Operator(synthesized_qc) == Operator(qc)
| synthesize_clifford_circuit | basic |
qiskitHumanEval/94 | from qiskit import QuantumCircuit
import qiskit.qasm3
def convert_quantum_circuit_to_qasm_string(circuit: QuantumCircuit) -> str:
""" Given a Quantum Circuit as the argument, convert it into qasm3 string and return it.
""" |
qasm_str = qiskit.qasm3.dumps(circuit)
return qasm_str
| def check(candidate):
from qiskit.quantum_info import Operator
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0,1)
qasm_str = candidate(qc)
circuit = qiskit.qasm3.loads(qasm_str)
assert Operator(circuit).equiv(Operator(qc)), "Loaded QASM does not match circuit"
| convert_quantum_circuit_to_qasm_string | basic |
qiskitHumanEval/95 | from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
def remove_barrier(circuit: QuantumCircuit):
""" For a given Quantum Circuit remove all the barriers from it and return.
""" |
return RemoveBarriers()(circuit)
| def check(candidate):
from qiskit.quantum_info import Operator
circuit = QuantumCircuit(1)
circuit.h(0)
circuit.barrier()
circuit.x(0)
candidate_circuit = candidate(circuit)
for inst in candidate_circuit.data:
assert inst.operation.name != 'barrier'
assert Operator(circuit).equiv(candidate_circuit)
| remove_barrier | basic |
qiskitHumanEval/96 | from qiskit_ibm_runtime.fake_provider import FakeKyoto
from qiskit.circuit import QuantumCircuit
from qiskit_ibm_runtime import Sampler
from qiskit_ibm_runtime.options import SamplerOptions
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def bell_state_noisy() -> dict:
""" Create the phi+ Bell state, run it in the FakeKyoto backend and return the counts. Use seed 42 for the sampler.
""" |
backend = FakeKyoto()
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pass_manager.run(qc)
options = SamplerOptions()
options.simulator.seed_simulator=42
sampler = Sampler(backend, options=options)
result = sampler.run([isa_circuit]).result()
counts = result[0].data.meas.get_counts()
return counts
| def check(candidate):
from qiskit.quantum_info import hellinger_fidelity
counts_can = candidate()
backend = FakeKyoto()
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
qc.measure_all()
pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend)
isa_circuit = pass_manager.run(qc)
sampler = Sampler(backend)
result = sampler.run([isa_circuit]).result()
counts_exp = result[0].data.meas.get_counts()
assert isinstance(counts_can, dict), "Return the counts"
assert 0.7 < hellinger_fidelity(counts_can, counts_exp) < 1, "Output doesn't match with the results from Fake Kyoto"
| bell_state_noisy | basic |
qiskitHumanEval/97 | from qiskit_ibm_runtime.fake_provider.fake_backend import FakeBackendV2
from qiskit_ibm_runtime import IBMBackend
from typing import Union
def two_qubit_conections(
backend: Union[FakeBackendV2, IBMBackend]
) -> list:
""" Return the two qubit connections for any input backend of type FakeBackendV2, IBMBackend.
""" |
if isinstance(backend, FakeBackendV2):
return backend.coupling_map
return backend.configuration().coupling_map
| def check(candidate):
from qiskit_ibm_runtime.fake_provider import FakeKyoto
from qiskit_ibm_runtime import QiskitRuntimeService
backend_v2 = FakeKyoto()
backend_ser = QiskitRuntimeService().least_busy()
connections_can_v2 = candidate(backend_v2)
connections_exp_v2 = backend_v2.coupling_map
assert connections_exp_v2 == connections_can_v2, "The list of connections doesn't match the two qubit connections from the backend"
connections_can_ser = candidate(backend_ser)
connections_exp_ser = backend_ser.configuration().coupling_map
assert connections_exp_ser == connections_can_ser, "The list of connections doesn't match the two qubit connections from the backend"
| two_qubit_conections | intermediate |
qiskitHumanEval/98 | import numpy as np
from typing import Union
from qiskit_ibm_runtime.fake_provider.fake_backend import FakeBackendV2
from qiskit_ibm_runtime import IBMBackend
def qubit_with_least_readout_error(backend: Union[IBMBackend, FakeBackendV2])-> float:
""" Return the minimum readout error of any input backend of type FakeBackendV2, IBMBackend.
""" |
error_list = []
if issubclass(type(backend), FakeBackendV2):
for qubits in range(backend.num_qubits):
error_list.append(backend.target["measure"][(qubits,)].error)
else:
for qubits in range(backend.configuration().num_qubits):
error_list.append(backend.properties().readout_error(qubits))
return np.min(error_list)
| def check(candidate):
from qiskit_ibm_runtime.fake_provider import FakeKyoto
from qiskit_ibm_runtime import QiskitRuntimeService
backend_v2 = FakeKyoto()
error_can_v2 = candidate(backend_v2)
error_list_v2 = []
for qubits in range(backend_v2.num_qubits):
error_list_v2.append(backend_v2.target["measure"][(qubits,)].error)
error_exp_v2 = np.min(error_list_v2)
assert error_can_v2 == error_exp_v2, "The qubit returned doesn't have the least readout error"
backend_ser = QiskitRuntimeService().least_busy()
error_can_ser = candidate(backend_ser)
error_list_ser = []
for qubits in range(backend_ser.configuration().num_qubits):
error_list_ser.append(backend_ser.properties().readout_error(qubits))
error_exp_ser = np.min(error_list_ser)
assert error_can_ser == error_exp_ser, "The qubit returned doesn't have the least readout error"
| qubit_with_least_readout_error | basic |
qiskitHumanEval/99 | from qiskit.circuit import Parameter, QuantumCircuit
def remove_unassigned_parameterized_gates(circuit: QuantumCircuit) -> QuantumCircuit:
""" Remove all the gates with unassigned parameters from the given circuit.
""" |
circuit_data = circuit.data.copy()
circuit_without_params = QuantumCircuit(circuit.num_qubits, circuit.num_clbits)
#for instr, qargs, cargs in circuit_data:
for instruction in circuit_data:
instr, qargs, cargs = instruction.operation, instruction.qubits, instruction.clbits
if not (isinstance(instr.params, Parameter) or
isinstance(instr.params[0], Parameter)):
circuit_without_params.append(instr, qargs, cargs)
return circuit_without_params
| def check(candidate):
from qiskit.circuit.library import RXGate, RZGate
circ = QuantumCircuit(2)
theta = Parameter("θ")
circ.rx(0.1, 1)
circ.ry(theta, 1)
circ.rx(theta, 0)
circ.cp(theta, 0, 1)
circ.rz(0.4, 0)
circ_can = candidate(circ)
assert isinstance(circ_can, QuantumCircuit), "Not a quantum circuit"
assert len(circ_can.parameters) == 0, "Circuit consists of gates with unassigned parameters."
has_rx = False
has_rz = False
for instruction in circ_can:
instr, qargs, cargs = instruction.operation, instruction.qubits, instruction.clbits
if isinstance(instr, RXGate):
has_rx = True
if isinstance(instr, RZGate):
has_rz = True
assert has_rx is True, "Removed rx gates with assigned parameters from the circuit"
assert has_rz is True, "Removed rz gates with assigned parameters from the circuit"
| remove_unassigned_parameterized_gates | basic |