task_id
stringlengths
17
19
prompt
stringlengths
122
728
canonical_solution
stringlengths
97
1.53k
test
stringlengths
192
1.54k
entry_point
stringlengths
3
50
difficulty_scale
stringclasses
3 values
qiskitHumanEval/100
Create a pass manager to decompose the single qubit gates into gates of the dense subset ['t', 'tdg', 'h'] in the given circuit. You must implement this using a function named `sol_kit_decomp` with the following arguments: circuit.
from qiskit.transpiler.passes import SolovayKitaev from qiskit.transpiler import PassManager from qiskit.circuit import QuantumCircuit def sol_kit_decomp(circuit): pm = PassManager([SolovayKitaev()]) circ_dec = pm.run(circuit) return circ_dec
from qiskit.transpiler.passes import SolovayKitaev from qiskit.transpiler import PassManager from qiskit.circuit import QuantumCircuit def check(candidate): import numpy as np from qiskit.circuit.library import EfficientSU2 from qiskit.quantum_info import Operator circ = EfficientSU2(3).decompose() circ = circ.assign_parameters(np.random.random(circ.num_parameters)) circ_can = candidate(circ) op_or = Operator(circ) op_can = Operator(circ_can) assert Operator.equiv(op_or, op_can, rtol=0.1, atol=0.1), "Operators are not the same" assert isinstance(circ_can, QuantumCircuit), "Not a quantum circuit" for instruction in circ_can.data: instr, qargs, cargs = instruction.operation, instruction.qubits, instruction.clbits if instr.num_qubits == 1 and instr.name not in {"h", "tdg", "t"}: raise AssertionError("Circuit contains gates outside the given dense subset") check(sol_kit_decomp)
sol_kit_decomp
basic
qiskitHumanEval/101
Return the circuit for the graph state of the coupling map of the Fake Kyoto backend. Hint: Use the networkx library to convert the coupling map to a dense adjacency matrix. You must implement this using a function named `get_graph_state` with no arguments.
from qiskit_ibm_runtime.fake_provider import FakeKyoto from qiskit.circuit.library import GraphState import networkx as nx from qiskit.circuit import QuantumCircuit def get_graph_state(): backend = FakeKyoto() coupling_map = backend.coupling_map G = nx.Graph() G.add_edges_from(coupling_map) adj_matrix = nx.adjacency_matrix(G).todense() gr_state_circ = GraphState(adjacency_matrix=adj_matrix) return gr_state_circ
from qiskit_ibm_runtime.fake_provider import FakeKyoto from qiskit.circuit.library import GraphState import networkx as nx from qiskit.circuit import QuantumCircuit def check(candidate): from collections import OrderedDict from qiskit.transpiler.passes import UnitarySynthesis from qiskit.transpiler import PassManager gr_state_circ_can = candidate() assert isinstance(gr_state_circ_can, QuantumCircuit) gr_state_circ_exp_ops = OrderedDict([("cz", 144), ("h", 127)]) basis_gates = ["cz", "h"] pm = PassManager([UnitarySynthesis(basis_gates)]) gr_state_circ_can_ops = pm.run(gr_state_circ_can.decompose()).count_ops() assert gr_state_circ_can_ops == gr_state_circ_exp_ops check(get_graph_state)
get_graph_state
intermediate
qiskitHumanEval/102
Transpile the circuit for the phi plus bell state for FakeKyoto, FakeKyiv and FakeAuckland using the level 1 preset pass manager and return the backend name with the lowest number of instructions. You must implement this using a function named `backend_with_least_instructions` with no arguments.
from qiskit.circuit import QuantumCircuit from qiskit_ibm_runtime.fake_provider import FakeKyoto, FakeKyiv, FakeAuckland from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager def backend_with_least_instructions(): qc = QuantumCircuit(2) qc.h(0) qc.cx(0, 1) backends = [FakeKyiv(), FakeKyoto(), FakeAuckland()] qc_isa_num_intruc = {} for backend in backends: pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc_isa_num_intruc[backend.name] = len(pm.run(qc).data) return min(qc_isa_num_intruc, key=qc_isa_num_intruc.get)
from qiskit.circuit import QuantumCircuit from qiskit_ibm_runtime.fake_provider import FakeKyoto, FakeKyiv, FakeAuckland from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager def check(candidate): backend_can = candidate() assert backend_can in "fake_auckland" or "auckland" in backend_can check(backend_with_least_instructions)
backend_with_least_instructions
basic
qiskitHumanEval/103
Return the list of names of all the fake providers of type FakeBackendV2 which contains ecr gates in its available operations. You must implement this using a function named `fake_providers_v2_with_ecr` with no arguments.
import importlib import inspect from qiskit_ibm_runtime.fake_provider import fake_backend def fake_providers_v2_with_ecr(): fake_provider_module = importlib.import_module("qiskit_ibm_runtime.fake_provider") fake_providers = {} for name, obj in inspect.getmembers(fake_provider_module): if inspect.isclass(obj) and issubclass(obj, fake_backend.FakeBackendV2): fake_providers[name] = obj fake_providers_ecr = [] for name, provider in fake_providers.items(): backend = provider() if "ecr" in backend.operation_names: fake_providers_ecr.append(name) return fake_providers_ecr
import importlib import inspect from qiskit_ibm_runtime.fake_provider import fake_backend def check(candidate): providers_can = candidate() providers_exp = [ "FakeCusco", "FakeKawasaki", "FakeKyiv", "FakeKyoto", "FakeOsaka", "FakePeekskill", "FakeQuebec", "FakeSherbrooke", "FakeBrisbane", "FakeCairoV2", ] for providers in providers_can: assert providers in providers_exp for providers in providers_exp: assert providers in providers_can check(fake_providers_v2_with_ecr)
fake_providers_v2_with_ecr
basic
qiskitHumanEval/104
Transpile the 4-qubit QFT circuit using preset passmanager with optimization level 3 and seed transpiler = 1234 in FakeOsaka, FakeSherbrooke and FakeBrisbane. Compute the cost of the instructions by penalizing the two qubit gate with a cost of 5, rz gates with a cost 1 and other gates with a cost 2 and return the value of the highest cost among these backends. You must implement this using a function named `backend_with_lowest_complexity` with no arguments.
from qiskit_ibm_runtime.fake_provider import FakeOsaka, FakeSherbrooke, FakeBrisbane from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.circuit.library import QFT def backend_with_lowest_complexity(): qc = QFT(4) backends = [FakeOsaka(), FakeSherbrooke(), FakeBrisbane()] complexity_dict = {} for backend in backends: pm = generate_preset_pass_manager( optimization_level=3, seed_transpiler=1234, backend=backend ) data = pm.run(qc).data complexity = 0 for instruc in data: if instruc.operation.num_qubits == 2: complexity += 5 elif instruc.operation.name == "rz": complexity += 1 else: complexity += 2 complexity_dict[backend.name] = complexity return complexity_dict[max(complexity_dict, key=complexity_dict.get)]
from qiskit_ibm_runtime.fake_provider import FakeOsaka, FakeSherbrooke, FakeBrisbane from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.circuit.library import QFT def check(candidate): complexity_can = candidate() complexity_exp = 194 assert complexity_can == complexity_exp check(backend_with_lowest_complexity)
backend_with_lowest_complexity
intermediate
qiskitHumanEval/105
Initialize a CNOTDihedral element from a QuantumCircuit consist of 2-qubits with cx gate on qubit 0 and 1 and t gate on qubit 0 and return. You must implement this using a function named `initialize_cnot_dihedral` with no arguments.
from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral def initialize_cnot_dihedral(): circ = QuantumCircuit(2) # Apply gates circ.cx(0, 1) circ.t(0) elem = CNOTDihedral(circ) return elem
from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral def check(candidate): result = candidate() assert isinstance(result, CNOTDihedral), f'Expected result to be CNOTDihedral, but got {type(result)}' assert result.linear.tolist() == [[1, 0], [1, 1]] assert str(result.poly) == "0 + x_0" assert result.shift.tolist() == [0, 0] check(initialize_cnot_dihedral)
initialize_cnot_dihedral
basic
qiskitHumanEval/106
Create two Quantum Circuits of 2 qubits. First quantum circuit should have a cx gate on qubits 0 and 1 and a T gate on qubit 0. The second one is the same but with an additional X gate on qubit 1. Convert the two quantum circuits into CNOTDihedral elements and return the composed circuit. You must implement this using a function named `compose_cnot_dihedral` with no arguments.
from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral def compose_cnot_dihedral(): circ1 = QuantumCircuit(2) # Apply gates circ1.cx(0, 1) circ1.t(0) elem1 = CNOTDihedral(circ1) circ2 = circ1.copy() circ2.x(1) elem2 = CNOTDihedral(circ2) composed_elem = elem1.compose(elem2) return composed_elem
from qiskit import QuantumCircuit from qiskit.quantum_info import CNOTDihedral def check(candidate): result = candidate() assert isinstance(result, CNOTDihedral), f'Expected result to be CNOTDihedral, but got {type(result)}' assert result.linear.tolist() == [[1, 0], [0, 1]] assert str(result.poly) == "0 + 2*x_0" assert list(result.shift) == [0, 1] check(compose_cnot_dihedral)
compose_cnot_dihedral
intermediate
qiskitHumanEval/107
Create two ScalarOp objects with dimension 2 and coefficient 2, compose them together, and return the resulting ScalarOp. You must implement this using a function named `compose_scalar_ops` with no arguments.
from qiskit.quantum_info import ScalarOp def compose_scalar_ops(): op1 = ScalarOp(2, 2) op2 = ScalarOp(2, 2) composed_op = op1.compose(op2) return composed_op
from qiskit.quantum_info import ScalarOp def check(candidate): result = candidate() assert isinstance(result, ScalarOp), f'Expected result to be ScalarOp, but got {type(result)}' assert result.coeff == 4 assert result.input_dims() == (2,) check(compose_scalar_ops)
compose_scalar_ops
basic
qiskitHumanEval/108
Initialize Choi matrices for the given data1 and data2 as inputs. Compute data1 adjoint, and then return the data1 Choi matrix, its adjoint and the composed choi matrices in order. You must implement this using a function named `initialize_adjoint_and_compose` with the following arguments: data1, data2.
from qiskit.quantum_info import Choi import numpy as np def initialize_adjoint_and_compose(data1, data2): choi1 = Choi(data1) choi2 = Choi(data2) adjoint_choi1 = choi1.adjoint() composed_choi = choi1.compose(choi2) return choi1, adjoint_choi1, composed_choi
from qiskit.quantum_info import Choi import numpy as np def check(candidate): data = np.eye(4) choi, adjoint_choi, composed_choi = candidate(data, data) assert isinstance(choi, Choi), f'Expected choi to be Choi, but got {type(choi)}' assert choi.dim == (2, 2), f'Expected dimensions to be (2, 2), but got {choi.dim}' assert isinstance(adjoint_choi, Choi), f'Expected adjoint_choi to be Choi, but got {type(adjoint_choi)}' assert isinstance(composed_choi, Choi), f'Expected composed_choi to be Choi, but got {type(composed_choi)}' expected_adjoint_data = data.conj().T assert np.allclose(adjoint_choi.data, expected_adjoint_data), f'Expected adjoint data to be {expected_adjoint_data}, but got {adjoint_choi.data}' check(initialize_adjoint_and_compose)
initialize_adjoint_and_compose
basic
qiskitHumanEval/109
Create a parameterized quantum circuit using minimum resources whose statevector output cover the equatorial plane of the surface of the bloch sphere. You must implement this using a function named `circuit` with no arguments.
from qiskit.circuit import QuantumCircuit, Parameter def circuit(): qc = QuantumCircuit(1) qc.h(0) theta = Parameter('th') qc.rz(theta,0) return qc
from qiskit.circuit import QuantumCircuit, Parameter def check(candidate): import numpy as np from qiskit.quantum_info import Statevector def statevector_to_bloch_angles(state_vector): alpha = state_vector[0] beta = state_vector[1] norm = np.sqrt(np.abs(alpha)**2 + np.abs(beta)**2) alpha = alpha / norm beta = beta / norm theta = 2 * np.arccos(np.abs(alpha)) phi = np.angle(beta) - np.angle(alpha) phi = (phi + 2 * np.pi) % (2 * np.pi) return theta, phi error = 0.000001 for i in range(1000): qc = candidate() num_params = qc.num_parameters qc.assign_parameters(np.random.randn(num_params), inplace=True) sv = Statevector(qc) theta, phi = statevector_to_bloch_angles(sv) assert np.pi/2 - error <= theta <= np.pi/2 + error check(circuit)
circuit
intermediate
qiskitHumanEval/110
Given a clifford circuit return a list of n random clifford circuits which are equivalent to the given circuit up to a relative and absolute tolerance of 0.4. You must implement this using a function named `equivalent_clifford_circuit` with the following arguments: circuit, n.
from qiskit import QuantumCircuit from qiskit.quantum_info import random_clifford, Operator def equivalent_clifford_circuit(circuit, n): op_or = Operator(circuit) num_qubits = circuit.num_qubits qc_list = [] counter = 0 while counter< n: qc = random_clifford(num_qubits).to_circuit() op_qc = Operator(qc) if op_qc.equiv(op_or, rtol = 0.4, atol = 0.4) == True: counter += 1 qc_list.append(qc) return qc_list
from qiskit import QuantumCircuit from qiskit.quantum_info import random_clifford, Operator def check(candidate): from qiskit.quantum_info import Clifford qc_comp = random_clifford(5).to_circuit() op_comp = Operator(qc_comp) can_circ_list = candidate(qc_comp, 10) for item in can_circ_list: assert Operator(item).equiv(op_comp, rtol = 0.4, atol = 0.4) try: Clifford(item) except Exception as err: raise AssertionError("The circuit is not a Clifford circuit.") from err check(equivalent_clifford_circuit)
equivalent_clifford_circuit
intermediate
qiskitHumanEval/111
Return an ansatz to create a quantum dataset of pure states distributed equally across the bloch sphere. Use minimum number of gates in the ansatz. You must implement this using a function named `circuit` with no arguments.
from qiskit.circuit import QuantumCircuit, Parameter def circuit(): qc = QuantumCircuit(1) p1 = Parameter("p1") p2 = Parameter("p2") qc.rx(p1,0) qc.ry(p2,0) return qc
from qiskit.circuit import QuantumCircuit, Parameter def check(candidate): assert candidate().num_parameters >= 2 , "The circuit doesn't cover the bloch sphere." assert candidate().num_parameters <= 5 , "The circuit is too long" check(circuit)
circuit
intermediate
qiskitHumanEval/112
Create a quantum circuit using LieTrotter for a list of Pauli strings and times. Each Pauli string is associated with a corresponding time in the 'times' list. The function should return the resulting QuantumCircuit. You must implement this using a function named `create_product_formula_circuit` with the following arguments: pauli_strings, times, order, reps.
from qiskit.quantum_info import Operator from qiskit.circuit.library import PauliEvolutionGate from qiskit.synthesis import LieTrotter from qiskit import QuantumCircuit from qiskit.quantum_info import Pauli, SparsePauliOp def create_product_formula_circuit(pauli_strings, times, order, reps): qc = QuantumCircuit(len(pauli_strings[0])) synthesizer = LieTrotter(reps=reps) for pauli_string, time in zip(pauli_strings, times): pauli = Pauli(pauli_string) hamiltonian = SparsePauliOp(pauli) evolution_gate = PauliEvolutionGate(hamiltonian, time) synthesized_circuit = synthesizer.synthesize(evolution_gate) qc.append(synthesized_circuit.to_gate(), range(len(pauli_string))) return qc
from qiskit.quantum_info import Operator from qiskit.circuit.library import PauliEvolutionGate from qiskit.synthesis import LieTrotter from qiskit import QuantumCircuit from qiskit.quantum_info import Pauli, SparsePauliOp def check(candidate): pauli_strings = ["X", "Y", "Z"] times = [1.0, 2.0, 3.0] order = 2 reps = 1 def create_solution_circuit(pauli_strings, times, order, reps): qc = QuantumCircuit(len(pauli_strings[0])) synthesizer = LieTrotter(reps=reps) for pauli_string, time in zip(pauli_strings, times): pauli = Pauli(pauli_string) hamiltonian = SparsePauliOp(pauli) evolution_gate = PauliEvolutionGate(hamiltonian, time) synthesized_circuit = synthesizer.synthesize(evolution_gate) qc.append(synthesized_circuit.to_gate(), range(len(pauli_string))) return qc solution_circuit = create_solution_circuit(pauli_strings, times, order, reps) candidate_circuit = candidate(pauli_strings, times, order, reps) assert Operator(solution_circuit) == Operator(candidate_circuit), "The candidate circuit does not match the expected solution." assert isinstance(candidate_circuit, QuantumCircuit), "The returned object is not a QuantumCircuit." check(create_product_formula_circuit)
create_product_formula_circuit
intermediate
qiskitHumanEval/113
Remove barriers from the given quantum circuit and calculate the depth before and after removal. Return a PropertySet with 'depth_before', 'depth_after', and 'width' properties. The function should only remove barriers and not perform any other optimizations. You must implement this using a function named `calculate_depth_after_barrier_removal` with the following arguments: qc.
from qiskit import QuantumCircuit from qiskit.transpiler import PassManager, PropertySet from qiskit.transpiler.passes import RemoveBarriers def calculate_depth_after_barrier_removal(qc): property_set = PropertySet() property_set["depth_before"] = qc.depth() property_set["width"] = qc.width() pass_manager = PassManager(RemoveBarriers()) optimized_qc = pass_manager.run(qc) property_set['depth_after'] = optimized_qc.depth() return property_set
from qiskit import QuantumCircuit from qiskit.transpiler import PassManager, PropertySet from qiskit.transpiler.passes import RemoveBarriers def check(candidate): qc = QuantumCircuit(3) qc.h(0) qc.barrier() qc.cx(0, 1) qc.barrier() qc.cx(1, 2) qc.measure_all() property_set = candidate(qc) assert property_set["depth_before"] == qc.depth(), "'depth_before' should match the original circuit depth" assert property_set["width"] == qc.width(), "'width' should match the circuit width" optimized_qc = PassManager(RemoveBarriers()).run(qc) assert property_set["depth_after"] == optimized_qc.depth(), "'depth_after' should match the depth of a barrier-free circuit" check(calculate_depth_after_barrier_removal)
calculate_depth_after_barrier_removal
intermediate
qiskitHumanEval/114
Create a CouplingMap with a specific coupling list, then modify it by adding an edge and a physical qubit. The initial coupling list is [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]]. Add an edge (5, 6), and add a physical qubit "7". You must implement this using a function named `create_and_modify_coupling_map` with no arguments.
from qiskit.transpiler import CouplingMap def create_and_modify_coupling_map(): coupling_list = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5]] cmap = CouplingMap(couplinglist=coupling_list) cmap.add_edge(5, 6) cmap.add_physical_qubit(7) return cmap
from qiskit.transpiler import CouplingMap def check(candidate): cmap = candidate() edges = set(cmap.get_edges()) assert edges == { (0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5,6) } assert len(cmap.physical_qubits) == 8 check(create_and_modify_coupling_map)
create_and_modify_coupling_map
intermediate
qiskitHumanEval/115
Create a Target object for a 2-qubit system and add UGate and CXGate instructions with specific properties. - Add UGate for both qubits (0 and 1) with parameters 'theta', 'phi', and 'lambda'. - Add CXGate for qubit pairs (0,1) and (1,0). - All instructions should have nonzero 'duration' and 'error' properties set. You must implement this using a function named `create_target` with no arguments.
from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, CXGate from qiskit.circuit import Parameter def create_target(): gmap = Target() theta, phi, lam = [Parameter(p) for p in ("theta", "phi", "lambda")] u_props = { (0,): InstructionProperties(duration=5.23e-8, error=0.00038115), (1,): InstructionProperties(duration=4.52e-8, error=0.00032115), } gmap.add_instruction(UGate(theta, phi, lam), u_props) cx_props = { (0,1): InstructionProperties(duration=5.23e-7, error=0.00098115), (1,0): InstructionProperties(duration=4.52e-7, error=0.00132115), } gmap.add_instruction(CXGate(), cx_props) return gmap
from qiskit.transpiler import Target, InstructionProperties from qiskit.circuit.library import UGate, CXGate from qiskit.circuit import Parameter def check(candidate): target = candidate() assert isinstance(target, Target) instructions = target.instructions u_gate_instructions = [inst for inst in instructions if inst[0].name == "u"] cx_gate_instructions = [inst for inst in instructions if inst[0].name == 'cx'] assert len(u_gate_instructions) == 2 assert len(cx_gate_instructions) == 2 for inst in u_gate_instructions + cx_gate_instructions: props = target[inst[0].name][inst[1]] assert isinstance(props, InstructionProperties) assert props.duration > 0 assert props.error >= 0 assert set(inst[1] for inst in u_gate_instructions) == {(0,), (1,)} assert set(inst[1] for inst in cx_gate_instructions) == {(0, 1), (1, 0)} check(create_target)
create_target
intermediate
qiskitHumanEval/116
Synthesize an evolution gate using MatrixExponential for a given Pauli string and time. The Pauli string can be any combination of 'I', 'X', 'Y', and 'Z'. Return the resulting QuantumCircuit. You must implement this using a function named `synthesize_evolution_gate` with the following arguments: pauli_string, time.
from qiskit.circuit.library import PauliEvolutionGate from qiskit.synthesis import MatrixExponential from qiskit import QuantumCircuit from qiskit.quantum_info import Pauli, Operator import numpy as np def synthesize_evolution_gate(pauli_string, time): pauli = Pauli(pauli_string) evolution_gate = PauliEvolutionGate(pauli, time) synthesizer = MatrixExponential() qc = synthesizer.synthesize(evolution_gate) return qc
from qiskit.circuit.library import PauliEvolutionGate from qiskit.synthesis import MatrixExponential from qiskit import QuantumCircuit from qiskit.quantum_info import Pauli, Operator import numpy as np def check(candidate): pauli_string = "X" time = 1.0 qc = candidate(pauli_string, time) assert isinstance(qc, QuantumCircuit), "The function should return a QuantumCircuit" assert qc.size() > 0, "The circuit should not be empty" ideal_solution = QuantumCircuit(1) ideal_solution.rx(2 * time, 0) assert np.allclose(Operator(qc), Operator(ideal_solution)), "The synthesized circuit does not match the expected evolution" check(synthesize_evolution_gate)
synthesize_evolution_gate
intermediate
qiskitHumanEval/117
Decompose a 4x4 unitary using the TwoQubitBasisDecomposer with CXGate as the basis gate. Return the resulting QuantumCircuit. You must implement this using a function named `decompose_unitary` with the following arguments: unitary.
from qiskit.synthesis import TwoQubitBasisDecomposer from qiskit.quantum_info import Operator, random_unitary from qiskit.circuit.library import CXGate from qiskit import QuantumCircuit import numpy as np def decompose_unitary(unitary): decomposer = TwoQubitBasisDecomposer(CXGate()) return decomposer(unitary)
from qiskit.synthesis import TwoQubitBasisDecomposer from qiskit.quantum_info import Operator, random_unitary from qiskit.circuit.library import CXGate from qiskit import QuantumCircuit import numpy as np def check(candidate): unitary = random_unitary(4) try: qc = candidate(unitary) assert isinstance(qc, QuantumCircuit) assert qc.num_qubits == 2 assert qc.size() > 0 cx_count = sum(1 for inst in qc.data if inst.operation.name == "cx") assert cx_count > 0 except (ValueError, np.linalg.LinAlgError) as e: raise e check(decompose_unitary)
decompose_unitary
intermediate
qiskitHumanEval/118
Create a QuantumCircuit with a C3SXGate applied to the first four qubits. You must implement this using a function named `create_c3sx_circuit` with no arguments.
from qiskit import QuantumCircuit from qiskit.circuit.library import C3SXGate def create_c3sx_circuit(): qc = QuantumCircuit(4) c3sx_gate = C3SXGate() qc.append(c3sx_gate, [0, 1, 2, 3]) return qc
from qiskit import QuantumCircuit from qiskit.circuit.library import C3SXGate def check(candidate): qc = candidate() assert isinstance(qc, QuantumCircuit) c3sx_instructions = [inst for inst in qc.data if isinstance(inst.operation, C3SXGate)] assert len(c3sx_instructions) == 1 assert c3sx_instructions[0].qubits == tuple([qc.qubits[i] for i in range(4)]) check(create_c3sx_circuit)
create_c3sx_circuit
intermediate
qiskitHumanEval/119
Create a QuantumCircuit with a CDKMRippleCarryAdder applied to the qubits. The kind of adder can be 'full', 'half', or 'fixed'. You must implement this using a function named `create_ripple_carry_adder_circuit` with the following arguments: num_state_qubits, kind.
from qiskit.circuit.library import CDKMRippleCarryAdder from qiskit import QuantumCircuit from qiskit.quantum_info import Operator def create_ripple_carry_adder_circuit(num_state_qubits, kind): adder = CDKMRippleCarryAdder(num_state_qubits, kind) qc = QuantumCircuit(adder.num_qubits) qc.append(adder.to_instruction(), range(adder.num_qubits)) return qc
from qiskit.circuit.library import CDKMRippleCarryAdder from qiskit import QuantumCircuit from qiskit.quantum_info import Operator def check(candidate): qc_full = candidate(3, "full") assert isinstance(qc_full, QuantumCircuit), "The function should return a QuantumCircuit" op_full = Operator(qc_full) expected_full = Operator(CDKMRippleCarryAdder(3, "full")) assert op_full.equiv(expected_full), "The circuit does not match the expected CDKMRippleCarryAdder for full kind" qc_fixed = candidate(3, "fixed") assert isinstance(qc_fixed, QuantumCircuit), "The function should return a QuantumCircuit" op_fixed = Operator(qc_fixed) expected_fixed = Operator(CDKMRippleCarryAdder(3, "fixed")) assert op_fixed.equiv(expected_fixed), "The circuit does not match the expected CDKMRippleCarryAdder for fixed kind" check(create_ripple_carry_adder_circuit)
create_ripple_carry_adder_circuit
intermediate
qiskitHumanEval/120
Create a QuantumCircuit with a Diagonal gate applied to the qubits. The diagonal elements are provided in the list 'diag'. You must implement this using a function named `create_diagonal_circuit` with the following arguments: diag.
from qiskit.circuit.library import Diagonal from qiskit import QuantumCircuit from qiskit.quantum_info import Operator def create_diagonal_circuit(diag): diagonal_gate = Diagonal(diag) qc = QuantumCircuit(diagonal_gate.num_qubits) qc.append(diagonal_gate.to_instruction(), range(diagonal_gate.num_qubits)) return qc
from qiskit.circuit.library import Diagonal from qiskit import QuantumCircuit from qiskit.quantum_info import Operator def check(candidate): diag = [1, 1j, -1, -1j] qc = candidate(diag) assert isinstance(qc, QuantumCircuit), "The function should return a QuantumCircuit" op_circuit = Operator(qc) expected_diagonal = Diagonal(diag) op_expected = Operator(expected_diagonal) assert op_circuit.equiv(op_expected), "The circuit does not match the expected Diagonal gate" check(create_diagonal_circuit)
create_diagonal_circuit
intermediate
qiskitHumanEval/121
Create a quantum circuit with one qubit and two classical bits. The qubit's operation depends on its measurement outcome: if it measures to 1 (|1> state), it flips the qubit's state back to |0> using an X gate. The qubit's initial state is randomized using a Hadamard gate. When building the quantum circuit make sure the classical registers is named 'c'. You must implement this using a function named `conditional_two_qubit_circuit` with no arguments.
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister def conditional_two_qubit_circuit(): qr = QuantumRegister(1) cr = ClassicalRegister(2, 'c') qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.measure(qr[0], cr[0]) with qc.if_test((cr[0], 1)): qc.x(qr[0]) qc.measure(qr[0], cr[1]) return qc
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister def check(candidate): from qiskit_aer import AerSimulator from qiskit_ibm_runtime import Sampler from qiskit_ibm_runtime.options import SamplerOptions qc = candidate() assert isinstance(qc, QuantumCircuit) assert qc.num_qubits == 1 assert qc.num_clbits == 2 ops = dict(qc.count_ops()) assert "h" in ops and "if_else" in ops backend = AerSimulator() options = SamplerOptions() options.simulator.seed_simulator=42 sampler = Sampler(mode=backend, options=options) result = sampler.run([qc]).result() counts = result[0].data.c.get_counts() assert "10" not in counts and "11" not in counts check(conditional_two_qubit_circuit)
conditional_two_qubit_circuit
basic
qiskitHumanEval/122
Generate an EfficientSU2 circuit with the given number of qubits, 1 reps and make entanglement circular. Then use the Qiskit Transpiler service with the AI flag turned on, use the ibm_brisbane backend and an optimization level of 3 and transpile the generated circuit. You must implement this using a function named `ai_transpiling` with the following arguments: num_qubits.
from qiskit.circuit.library import EfficientSU2 from qiskit_ibm_transpiler.transpiler_service import TranspilerService def ai_transpiling(num_qubits): circuit = EfficientSU2(num_qubits, entanglement="circular", reps=1) transpiler_ai_true = TranspilerService( backend_name="ibm_brisbane", ai=True, optimization_level=3 ) transpiled_circuit = transpiler_ai_true.run(circuit) return transpiled_circuit
from qiskit.circuit.library import EfficientSU2 from qiskit_ibm_transpiler.transpiler_service import TranspilerService def check(candidate): import qiskit num_qubits = 3 backend_name = "ibm_brisbane" ai_flag = True optimization_level = 3 og_circuit = EfficientSU2(num_qubits, entanglement="circular", reps=1) gen_transpiled_circuit = candidate(num_qubits) assert isinstance(gen_transpiled_circuit, qiskit.circuit.QuantumCircuit) transpiler_service = TranspilerService( backend_name=backend_name, ai=ai_flag, optimization_level=optimization_level ) expected_transpiled_circuit = transpiler_service.run(og_circuit) # We can add the following check once we have the random_state/seed feature in the transpiler service # assert gen_transpiled_circuit == expected_transpiled_circuit check(ai_transpiling)
ai_transpiling
basic
qiskitHumanEval/123
Instantiate a FakeBelemV2 backend and return the plot of its error_map. You must implement this using a function named `backend_error_map` with no arguments.
from qiskit.visualization import plot_error_map from qiskit_ibm_runtime.fake_provider import FakeBelemV2 def backend_error_map(): backend = FakeBelemV2() return plot_error_map(backend)
from qiskit.visualization import plot_error_map from qiskit_ibm_runtime.fake_provider import FakeBelemV2 def check(candidate): from matplotlib.figure import Figure result = candidate() assert type(result) == Figure assert len(result.axes) == 5 assert result.get_suptitle() == "fake_belem Error Map" check(backend_error_map)
backend_error_map
basic
qiskitHumanEval/124
Generate a noise model from the Fake Cairo V2 backend. You must implement this using a function named `gen_noise_model` with no arguments.
from qiskit_ibm_runtime.fake_provider import FakeCairoV2 from qiskit_aer.noise import NoiseModel def gen_noise_model(): backend = FakeCairoV2() noise_model = NoiseModel.from_backend(backend) return noise_model
from qiskit_ibm_runtime.fake_provider import FakeCairoV2 from qiskit_aer.noise import NoiseModel def check(candidate): backend = FakeCairoV2() expected_nm = NoiseModel.from_backend(backend) noise_model = candidate() assert type(noise_model) == NoiseModel assert noise_model == expected_nm check(gen_noise_model)
gen_noise_model
basic
qiskitHumanEval/125
Given a QuantumCircuit, convert it into a gate equivalent to the action of the input circuit and return it. You must implement this using a function named `circ_to_gate` with the following arguments: circ.
from qiskit.converters import circuit_to_gate def circ_to_gate(circ): circ_gate = circuit_to_gate(circ) return circ_gate
from qiskit.converters import circuit_to_gate def check(candidate): from qiskit import QuantumCircuit, QuantumRegister from qiskit.circuit.gate import Gate from qiskit.quantum_info import Operator from qiskit.circuit.library import ZGate q = QuantumRegister(3, "q") circ = QuantumCircuit(q) circ.h(q[0]) circ.cx(q[0], q[1]) custom_gate = candidate(circ) assert type(custom_gate) == Gate assert custom_gate.num_qubits == 3 assert custom_gate.num_clbits == 0 q = QuantumRegister(1, "q") circ = QuantumCircuit(q) circ.h(q) circ.x(q) circ.h(q) hxh_gate = circ_to_gate(circ) hxh_op = Operator(hxh_gate) z_op = Operator(ZGate()) assert hxh_op.equiv(z_op) check(circ_to_gate)
circ_to_gate
basic
qiskitHumanEval/126
Create two quantum operators using Hadamard gate that differ only by a global phase. Calculate the process fidelity between these two operators and return the process fidelity value. You must implement this using a function named `calculate_phase_difference_fidelity` with no arguments.
from qiskit.circuit.library import HGate from qiskit.quantum_info import Operator, process_fidelity import numpy as np def calculate_phase_difference_fidelity(): op_a = Operator(HGate()) op_b = np.exp(1j * 0.5) * Operator(HGate()) fidelity = process_fidelity(op_a, op_b) return fidelity
from qiskit.circuit.library import HGate from qiskit.quantum_info import Operator, process_fidelity import numpy as np def check(candidate): result = candidate() assert isinstance(result, float) assert abs(result - 1.0) < 1e-6 check(calculate_phase_difference_fidelity)
calculate_phase_difference_fidelity
basic
qiskitHumanEval/127
Using qiskit's random_circuit function, generate a circuit with 4 qubits and a depth of 3 that measures all qubits at the end. Use the seed value 17 and return the generated circuit. You must implement this using a function named `random_circuit_depth` with no arguments.
from qiskit.circuit.random import random_circuit from qiskit import QuantumCircuit def random_circuit_depth(): circuit = random_circuit(4, 3, measure=True, seed = 17) return circuit
from qiskit.circuit.random import random_circuit from qiskit import QuantumCircuit def check(candidate): from qiskit.circuit.random import random_circuit from qiskit import QuantumCircuit # Run the candidate function result = candidate() # Check if the output is a QuantumCircuit assert isinstance(result, QuantumCircuit), "Output should be a QuantumCircuit" # Generate the expected circuit using the same parameters expected_qc = random_circuit(4, 3, measure=True, seed=17) # Ensure the circuit has 4 qubits assert result.num_qubits == 4, f"Expected 4 qubits, but got {result.num_qubits}" # Ensure the circuit depth is within an acceptable range (allowing small variations) expected_depth = expected_qc.depth() assert abs(result.depth() - expected_depth) <= 1, f"Expected depth around {expected_depth}, but got {result.depth()}" # Check if all qubits are measured at the end measured_qubits = [op for op, qargs, _ in result.data if op.name == "measure"] assert len(measured_qubits) == 4, "All qubits should be measured at the end" # Ensure the generated circuit matches the expected circuit structure assert result == expected_qc, "Generated circuit does not match expected circuit" check(random_circuit_depth)
random_circuit_depth
basic
qiskitHumanEval/128
Create a quantum circuit with 4 qubits and 4 classical bits. Apply Hadamard gates to the first three qubits, measure them with three classical registers, and conditionally apply an X gate to the fourth qubit based on the XOR of the three classical bits. Finally, measure the fourth qubit into another classical register. You must implement this using a function named `conditional_quantum_circuit` with no arguments.
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.classical import expr def conditional_quantum_circuit(): qr = QuantumRegister(4, "q") cr = ClassicalRegister(4, "c") circ = QuantumCircuit(qr, cr) circ.h(qr[0:3]) circ.measure(qr[0:3], cr[0:3]) _condition = expr.bit_xor(expr.bit_xor(cr[0], cr[1]), cr[2]) with circ.if_test(_condition): circ.x(qr[3]) circ.measure(qr[3], cr[3]) return circ
from qiskit.circuit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit.circuit.classical import expr def check(candidate): from qiskit_aer import AerSimulator from qiskit_ibm_runtime import Sampler, SamplerOptions from qiskit_ibm_runtime.options import SamplerOptions circ_res = candidate() assert type(circ_res) == QuantumCircuit assert circ_res.num_qubits == 4 assert circ_res.num_clbits == 4 assert any(instr.operation.name == "if_else" and instr.operation.num_qubits == 1 and instr.operation.num_clbits == 3 for instr in circ_res.data) sim = AerSimulator() options = SamplerOptions() options.simulator.seed_simulator=17 sampler = Sampler(mode=sim, options=options) counts = sampler.run([circ_res], shots=1024).result()[0].data.c.get_counts() for outcome, _ in counts.items(): qubit_states = outcome[::-1] q3_state = int(qubit_states[3]) q0 = int(qubit_states[0]) q1 = int(qubit_states[1]) q2 = int(qubit_states[2]) expected_q3_state = (q0 ^ q1 ^ q2) assert q3_state == expected_q3_state check(conditional_quantum_circuit)
conditional_quantum_circuit
basic
qiskitHumanEval/129
Given the name of a quantum backend, retrieve the properties of the specified backend and identify the qubit pair with the highest error rate among its RZ gates. Return this qubit pair along with the corresponding error rate as a tuple. If the backend doesn't support the RZ gate, return None. You must implement this using a function named `find_highest_rz_error_rate` with the following arguments: backend_name.
from qiskit_ibm_runtime import QiskitRuntimeService def find_highest_rz_error_rate(backend_name): service = QiskitRuntimeService(channel="ibm_quantum") backend = service.backend(backend_name) backend_properties = backend.properties() try: rz_props = backend_properties.gate_property("rz") except: return None qubit_pair = max(rz_props, key=lambda x: rz_props[x]["gate_error"][0]) max_rz_error = rz_props[qubit_pair]["gate_error"][0] return (qubit_pair, max_rz_error)
from qiskit_ibm_runtime import QiskitRuntimeService def check(candidate): service = QiskitRuntimeService(channel="ibm_quantum") backend = service.least_busy(filters=lambda b : ("rz" in b.basis_gates)) max_rz_error_pair, max_rz_error_rate = candidate(backend.name) assert isinstance(max_rz_error_pair, (tuple, list)) assert len(max_rz_error_pair) == 1 assert all(isinstance(qubit, int) for qubit in max_rz_error_pair) assert max_rz_error_rate >= 0 and max_rz_error_rate <= 1 backend_properties = backend.properties() rz_props = backend_properties.gate_property("rz") expected_max_rz_error_pair = max(rz_props, key=lambda x: rz_props[x]["gate_error"][0]) expected_max_rz_error_rate = rz_props[expected_max_rz_error_pair]["gate_error"][0] assert (expected_max_rz_error_pair, expected_max_rz_error_rate) == (max_rz_error_pair, max_rz_error_rate) check(find_highest_rz_error_rate)
find_highest_rz_error_rate
intermediate
qiskitHumanEval/130
Create a quantum circuit with 'n' qubits. Apply Hadamard gates to the second and third qubits. Then apply CNOT gates between the second and fourth qubits, and between the third and fifth qubits. Finally give the inverse of the quantum circuit. You must implement this using a function named `inv_circuit` with the following arguments: n.
from qiskit.circuit import QuantumCircuit def inv_circuit(n): qc = QuantumCircuit(n) for i in range(2): qc.h(i+1) for i in range(2): qc.cx(i+1, i+2+1) return qc.inverse()
from qiskit.circuit import QuantumCircuit def check(candidate): n = 5 qc_inv = candidate(n) expected_qc = QuantumCircuit(n) for i in range(2): expected_qc.h(i+1) for i in range(2): expected_qc.cx(i+1, i+2+1) expected_qc_inv = expected_qc.inverse() assert qc_inv, QuantumCircuit assert qc_inv == expected_qc_inv check(inv_circuit)
inv_circuit
basic
qiskitHumanEval/131
Given the fake backend name, retrieve information about the backend's number of qubits, coupling map, and supported instructions using the Qiskit Runtime Fake Provider, and create a dictionary containing the info. The dictionary must have the following keys: 'num_qubits' (the number of qubits), 'coupling_map' (the coupling map of the backend), and 'supported_instructions' (the supported instructions of the backend). You must implement this using a function named `backend_info` with the following arguments: backend_name.
from qiskit_ibm_runtime.fake_provider import FakeCairoV2 def backend_info(backend_name): backend = FakeCairoV2() config = backend.configuration() dict_result = {"num_qubits": config.num_qubits, "coupling_map": config.coupling_map, "supported_instructions": config.supported_instructions} return dict_result
from qiskit_ibm_runtime.fake_provider import FakeCairoV2 def check(candidate): backend = FakeCairoV2() binfo_dict = candidate(backend.name) backend_config = backend.configuration() assert isinstance(binfo_dict, dict) assert binfo_dict["num_qubits"] == backend_config.num_qubits assert binfo_dict["coupling_map"] == backend_config.coupling_map assert binfo_dict["supported_instructions"] == backend_config.supported_instructions check(backend_info)
backend_info
basic
qiskitHumanEval/132
Generate 6 random quantum circuits, each with 3 qubits, depth of 2 and measure set to True; using the random_circuit Qiskit function, with seed 17. Then use a preset pass manager to optimize these circuits with an optimization level of 1, the backend for the pass manager should be FakeManilaV2, and set the seed value to 1. Partition these optimized circuits into batches of 3 circuits each, and execute these batches using Qiskit Runtime's Batch mode, and return a list containing the measurement outcome for each batch. For the execution of each batch set the seed to 42 for the sampler primitive. You must implement this using a function named `run_batched_random_circuits` with no arguments.
from qiskit.circuit.random import random_circuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import Batch, Sampler from qiskit_ibm_runtime.fake_provider import FakeManilaV2 def run_batched_random_circuits(): fake_manila = FakeManilaV2() pm = generate_preset_pass_manager(backend=fake_manila, optimization_level=1, seed_transpiler = 1) circuits = [pm.run(random_circuit(3, 2, measure=True, seed=17)) for _ in range(6)] batch_size = 3 partitions = [circuits[i : i + batch_size] for i in range(0, len(circuits), batch_size)] sampler_options = {"simulator": {"seed_simulator": 42}} with Batch(backend=fake_manila): sampler = Sampler(mode=fake_manila, options=sampler_options) results = [] for partition in partitions: job = sampler.run(partition) results.append(job.result()[0].data.c.get_counts()) return results
from qiskit.circuit.random import random_circuit from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit_ibm_runtime import Batch, Sampler from qiskit_ibm_runtime.fake_provider import FakeManilaV2 def check(candidate): result = candidate() assert isinstance(result, list) assert len(result) == 2 for counts in result: assert isinstance(counts, dict) assert counts == {"110": 423, "100": 474, "000": 58, "010": 52, "101": 8, "111": 8, "011": 1} check(run_batched_random_circuits)
run_batched_random_circuits
basic
qiskitHumanEval/133
Find and return jobs submitted in the last three months using QiskitRuntimeService. You must implement this using a function named `find_recent_jobs` with no arguments.
import datetime from qiskit_ibm_runtime import QiskitRuntimeService def find_recent_jobs(): three_months_ago = datetime.datetime.now() - datetime.timedelta(days=90) service = QiskitRuntimeService() jobs_in_last_three_months = service.jobs(created_after=three_months_ago) return jobs_in_last_three_months
import datetime from qiskit_ibm_runtime import QiskitRuntimeService def check(candidate): result = candidate() assert isinstance(result, list) for job in result: assert hasattr(job, "job_id") assert hasattr(job, "creation_date") assert job.creation_date.replace(tzinfo=None) >= (datetime.datetime.now() - datetime.timedelta(days=90)).replace(tzinfo=None) check(find_recent_jobs)
find_recent_jobs
basic
qiskitHumanEval/134
Using the QiskitRuntimeService, retrieve the backends that meet the following criteria: they are real quantum devices, they are operational, and they have a minimum of 20 qubits. Then, return a list of dictionaries, each containing the backend's name, number of qubits, and the list of supported instruction names. Ensure that the list of dictionaries is sorted by the backend name. You must implement this using a function named `backend_info` with no arguments.
from qiskit_ibm_runtime import QiskitRuntimeService def backend_info(): service = QiskitRuntimeService() backends = service.backends(simulator=False, operational=True, min_num_qubits=20) backend_info = [] for b in backends: backend_info.append({"backend_name": b.name, "num_qubits": b.num_qubits, "instructions": b.operation_names}) sorted_backend_info = sorted(backend_info, key=lambda x: x["backend_name"]) return sorted_backend_info
from qiskit_ibm_runtime import QiskitRuntimeService def check(candidate): result = candidate() assert isinstance(result, list) service = QiskitRuntimeService() backends = service.backends(simulator=False, operational=True, min_num_qubits=20) backend_info = [] for b in backends: backend_info.append({"backend_name": b.name, "num_qubits": b.num_qubits, "instructions": b.operation_names}) sorted_backend_info_expected = sorted(backend_info, key=lambda x: x["backend_name"]) assert sorted_backend_info_expected == result check(backend_info)
backend_info
basic
qiskitHumanEval/135
Construct a noise model with specific readout error properties for different qubits. For qubit 0, a readout of 1 has a 20% probability of being erroneously read as 0, and a readout of 0 has a 30% probability of being erroneously read as 1. For all other qubits, a readout of 1 has a 3% probability of being erroneously read as 0, and a readout of 0 has a 2% probability of being erroneously read as 1. You must implement this using a function named `noise_model_with_readouterror` with no arguments.
from qiskit_aer.noise import NoiseModel, ReadoutError def noise_model_with_readouterror(): noise_model = NoiseModel() p0given1_other = 0.03 p1given0_other = 0.02 readout_error_other = ReadoutError( [ [1 - p1given0_other, p1given0_other], [p0given1_other, 1 - p0given1_other], ] ) noise_model.add_all_qubit_readout_error(readout_error_other) p0given1_q0 = 0.2 p1given0_q0 = 0.3 readout_error_q0 = ReadoutError( [ [1 - p1given0_q0, p1given0_q0], [p0given1_q0, 1 - p0given1_q0], ] ) noise_model.add_readout_error(readout_error_q0, [0]) return noise_model
from qiskit_aer.noise import NoiseModel, ReadoutError def check(candidate): result = candidate() assert isinstance(result, NoiseModel), "Result should be a NoiseModel instance" global_error = result.to_dict()["errors"][0]['probabilities'] assert global_error == [[0.98, 0.02], [0.03, 0.97]] qubit0_error = result.to_dict()["errors"][1] assert qubit0_error["gate_qubits"][0][0] == 0 assert qubit0_error["probabilities"] == [[0.7, 0.3], [0.2, 0.8]] assert len(result.to_dict()["errors"]) == 2 check(noise_model_with_readouterror)
noise_model_with_readouterror
intermediate
qiskitHumanEval/136
Return a list of ten density matrices which are pure up to a tolerance of ε. You must implement this using a function named `pure_states` with the following arguments: ε.
from qiskit.quantum_info import entropy, random_density_matrix, DensityMatrix def pure_states(ε): entropy_list = [] while len(entropy_list) <= 9: density_matrix = random_density_matrix(dims = 2) if entropy(density_matrix) < ε: entropy_list.append(density_matrix) return entropy_list
from qiskit.quantum_info import entropy, random_density_matrix, DensityMatrix def check(candidate): tol = 0.01 list_can = candidate(tol) assert len(list_can) == 10," Length of the list is not 10" for _, item in enumerate(list_can): assert isinstance(item, DensityMatrix), "The list doesn't contain density matrices" assert entropy(item) < tol, "Entropy of density matrix is not within tolerance" check(pure_states)
pure_states
intermediate
qiskitHumanEval/137
Return a dataset of density matrices whose 2-qubit entanglement of formation is within given tolerance. You must implement this using a function named `entanglement_dataset` with the following arguments: ε.
from qiskit.quantum_info import random_density_matrix, entanglement_of_formation def entanglement_dataset(ε): entanglement_data = [] while len(entanglement_data) <= 9: density_matrix = random_density_matrix(dims = 4) if entanglement_of_formation(density_matrix)>=ε: entanglement_data.append(density_matrix) return entanglement_data
from qiskit.quantum_info import random_density_matrix, entanglement_of_formation def check(candidate): from qiskit.quantum_info import DensityMatrix tol = 0.1 can_list = candidate(tol) assert len(can_list) == 10, "Length of list is not 10" for _, item in enumerate(can_list): assert isinstance(item, DensityMatrix), "The list doesn't contain density matrices" assert entanglement_of_formation(item) >= tol , " The entanglement of formation is not within tolerance" check(entanglement_dataset)
entanglement_dataset
intermediate
qiskitHumanEval/138
Return a list of density matrices whose mutual information is greater than the given tolerance. You must implement this using a function named `mutual_information_dataset` with the following arguments: ε.
from qiskit.quantum_info import mutual_information, random_density_matrix def mutual_information_dataset(ε): mutual_information_list = [] while len(mutual_information_list)<= 9: density_matrix = random_density_matrix(dims = 4) if mutual_information(density_matrix) >= ε: mutual_information_list.append(density_matrix) return mutual_information_list
from qiskit.quantum_info import mutual_information, random_density_matrix def check(candidate): from qiskit.quantum_info import mutual_information, DensityMatrix, random_density_matrix import numpy as np tolerances = [0.1, 0.5, 1.0] # Different values of ε to test num_matrices = 10 for tol in tolerances: can_list = candidate(tol) # Check output type assert isinstance(can_list, list), "Output should be a list" assert len(can_list) == num_matrices, f"Expected {num_matrices} density matrices, but got {len(can_list)}" for i, item in enumerate(can_list): # Check if each item is a DensityMatrix assert isinstance(item, DensityMatrix), f"Item {i} is not a DensityMatrix" # Ensure mutual information is above ε assert mutual_information(item) >= tol, f"Mutual information of matrix {i} is less than {tol}" # Validate that the density matrix is properly normalized (trace = 1) assert np.isclose(item.trace(), 1, atol=1e-3), f"Density matrix {i} trace is not 1" # Ensure the density matrix is Hermitian assert np.allclose(item.data, item.data.conj().T), f"Density matrix {i} is not Hermitian" # Ensure the density matrix is positive semidefinite eigenvalues = np.linalg.eigvalsh(item.data) assert np.all(eigenvalues >= -1e-10), f"Density matrix {i} has negative eigenvalues (not positive semidefinite)" check(mutual_information_dataset)
mutual_information_dataset
intermediate
qiskitHumanEval/139
Return the schmidt decomposition coefficients and the subsystem vectors for the given density matrix and partition. You must implement this using a function named `schmidt_test` with the following arguments: data, qargs_B.
from qiskit.quantum_info import schmidt_decomposition def schmidt_test(data, qargs_B): return schmidt_decomposition(data, qargs_B)
from qiskit.quantum_info import schmidt_decomposition def check(candidate): from qiskit.quantum_info import random_statevector rs = random_statevector(dims = 16) qargs = [0,1] schmidt_decomp = candidate(rs, qargs) for _, item in enumerate(schmidt_decomp): assert item[0]>=0, "Schmidt coefficients must be real" assert item[1].dims() == (2,2), "The dimension of the first subsystem doesn't match" assert item[2].dims() == (2,2), "The dimension of the second subsystem doesn't match" check(schmidt_test)
schmidt_test
basic
qiskitHumanEval/140
Return a list of ten probability vectors each of length 16 whose shannon entropy is greater than a given value. You must implement this using a function named `shannon_entropy_data` with the following arguments: ε.
from qiskit.quantum_info import shannon_entropy import numpy as np def shannon_entropy_data(ε): shannon_data = [] while len(shannon_data) <= 9: rand_prob = np.random.randn(16) if shannon_entropy(rand_prob) >= ε: shannon_data.append(rand_prob) return shannon_data
from qiskit.quantum_info import shannon_entropy import numpy as np def check(candidate): tol = 1 can_list = candidate(tol) assert len(can_list) == 10, " The length of the list is not 10" for _, item in enumerate(can_list): assert shannon_entropy(item)>= tol, "Shannon entropy not greater than given value" assert len(item) == 16, "The length of the probability vector is not 16" check(shannon_entropy_data)
shannon_entropy_data
basic
qiskitHumanEval/141
Return a list of ten anticommutators for the given pauli. You must implement this using a function named `anticommutators` with the following arguments: pauli.
from qiskit.quantum_info import anti_commutator, SparsePauliOp from qiskit.quantum_info import random_pauli import numpy as np def anticommutators(pauli): def is_multiple_of_identity(matrix): identity_matrix = np.eye(matrix.shape[0]) scalar = matrix[0,0] return np.allclose(matrix, scalar*identity_matrix) num_qubits = pauli.num_qubits anticommutator_list = [] while len(anticommutator_list) <= 9: random_pauli_value = SparsePauliOp(random_pauli(num_qubits)) anti_commutator_value = anti_commutator(pauli, random_pauli_value) if is_multiple_of_identity(anti_commutator_value.to_matrix()): anticommutator_list.append(random_pauli_value) return anticommutator_list
from qiskit.quantum_info import anti_commutator, SparsePauliOp from qiskit.quantum_info import random_pauli import numpy as np def check(candidate): def is_multiple_of_identity(matrix): if matrix.shape[0] != matrix.shape[1]: return False # Not a square matrix identity_matrix = np.eye(matrix.shape[0]) scalar = matrix[0,0] return np.allclose(matrix, scalar*identity_matrix) test_pauli = SparsePauliOp(["XI"]) can_anticommutators = candidate(test_pauli) assert len(can_anticommutators) == 10, "The number of anticommutators is not 10" for _,item in enumerate(can_anticommutators): assert is_multiple_of_identity(anti_commutator(item, test_pauli).to_matrix()), "The operator doesn't anticommute with the given pauli operator" check(anticommutators)
anticommutators
intermediate
qiskitHumanEval/142
Return a list of 10 single qubit density matrices whose purity is greater than 0.5. You must implement this using a function named `purity_dataset` with no arguments.
from qiskit.quantum_info import random_density_matrix, purity, DensityMatrix import numpy as np def purity_dataset(): purity_dataset_list = [] while len(purity_dataset_list)<=9: rand_density_matrix = random_density_matrix(dims=2) if np.abs(purity(rand_density_matrix))>=0.5: purity_dataset_list.append(rand_density_matrix) return purity_dataset_list
from qiskit.quantum_info import random_density_matrix, purity, DensityMatrix import numpy as np def check(candidate): can_list = candidate() assert len(can_list) == 10, "Number of density matrices is not 10" for _, item in enumerate(can_list): assert isinstance(item, DensityMatrix) assert np.abs(purity(item))>=0.5, "Purity of the denisty matrices is not less than 0.5" check(purity_dataset)
purity_dataset
intermediate
qiskitHumanEval/143
Return a list of ten pairs of one qubit state vectors whose state fidelity is greater than 0.9. You must implement this using a function named `fidelity_dataset` with no arguments.
from qiskit.quantum_info import random_statevector, state_fidelity, Statevector def fidelity_dataset(): fidelity_dataset_list = [] while len(fidelity_dataset_list)<=9: sv_1 = random_statevector(2) sv_2 = random_statevector(2) if state_fidelity(sv_1, sv_2) >= 0.9: fidelity_dataset_list.append((sv_1,sv_2)) return fidelity_dataset_list
from qiskit.quantum_info import random_statevector, state_fidelity, Statevector def check(candidate): can_list = candidate() assert len(can_list) == 10, "Length of returned list is not 10" for _, item in enumerate(can_list): assert isinstance(item[0], Statevector) assert isinstance(item[1], Statevector) assert(state_fidelity(item[0], item[1]))>=0.9, "State fidelity of the returned pairs is less than 0.9" check(fidelity_dataset)
fidelity_dataset
intermediate
qiskitHumanEval/144
Return a list of 10 density matrices whose concurrence is 0. You must implement this using a function named `concurrence_dataset` with no arguments.
from qiskit.quantum_info import random_density_matrix, concurrence, DensityMatrix def concurrence_dataset(): concurrence_dataset_list = [] while len(concurrence_dataset_list) <= 9: rand_mat = random_density_matrix(dims = 4) if concurrence(rand_mat) == 0: concurrence_dataset_list.append(rand_mat) return concurrence_dataset_list
from qiskit.quantum_info import random_density_matrix, concurrence, DensityMatrix def check(candidate): can_mat_list = candidate() assert len(can_mat_list) == 10, "The list doesn't contain 10 elements" for _, item in enumerate(can_mat_list): assert isinstance(item, DensityMatrix) assert concurrence(item) == 0, "The concurrence of the density matrix is not 0" check(concurrence_dataset)
concurrence_dataset
intermediate
qiskitHumanEval/145
Return the inverse qft circuit for n qubits. You must implement this using a function named `qft_inverse` with the following arguments: n.
from qiskit.circuit.library import QFT from qiskit import QuantumCircuit from qiskit.quantum_info import Operator def qft_inverse(n): return QFT(num_qubits=n, approximation_degree=0, inverse=True)
from qiskit.circuit.library import QFT from qiskit import QuantumCircuit from qiskit.quantum_info import Operator def check(candidate): from qiskit.circuit.library import QFT from qiskit import QuantumCircuit from qiskit.quantum_info import Operator # Test multiple values of n for n in [1, 2, 3, 5, 8, 10]: candidate_circ = candidate(n) # Ensure the result is a QuantumCircuit assert isinstance(candidate_circ, QuantumCircuit), "Returned object is not a QuantumCircuit" # Ensure the circuit has the correct number of qubits assert candidate_circ.num_qubits == n, f"Expected {n} qubits, but got {candidate_circ.num_qubits}" # Verify that the returned circuit is equivalent to the expected inverse QFT circuit candidate_op = Operator(candidate_circ) test_circ = QFT(n, approximation_degree=0, inverse=True) test_op = Operator(test_circ) assert test_op.equiv(candidate_op), "The circuit doesn't match the expected inverse QFT circuit" # Edge case: n=0 (should raise an error or return an empty circuit) try: candidate_circ = candidate(0) assert candidate_circ.num_qubits == 0, "For n=0, circuit should have 0 qubits" except Exception: pass # Allow exception if function correctly handles invalid input check(qft_inverse)
qft_inverse
intermediate
qiskitHumanEval/146
Generate Qiskit code that sets up a StagedPassManager with a trivial layout using PassManager for the least busy backend available. You must implement this using a function named `trivial_layout` with no arguments.
from qiskit.transpiler import PassManager, StagedPassManager from qiskit_ibm_runtime import QiskitRuntimeService from qiskit.transpiler.passes.layout.trivial_layout import TrivialLayout def trivial_layout(): pm_opt = StagedPassManager() pm_opt.layout = PassManager() backend = QiskitRuntimeService().least_busy() cm = backend.coupling_map pm_opt.layout += TrivialLayout(cm) return pm_opt
from qiskit.transpiler import PassManager, StagedPassManager from qiskit_ibm_runtime import QiskitRuntimeService from qiskit.transpiler.passes.layout.trivial_layout import TrivialLayout def check(candidate): from qiskit.transpiler import PassManager, StagedPassManager from qiskit.transpiler.passes.layout.trivial_layout import TrivialLayout from qiskit_ibm_runtime import QiskitRuntimeService # Run the candidate function pm_opt = candidate() # Check if the result is a StagedPassManager assert isinstance(pm_opt, StagedPassManager), "Output should be a StagedPassManager" # Check if the layout attribute exists and is an instance of PassManager assert hasattr(pm_opt, "layout"), "pm_opt should have a layout attribute" assert isinstance(pm_opt.layout, PassManager), "layout should be an instance of PassManager" # Ensure the first task in layout uses TrivialLayout assert len(pm_opt.layout._tasks) > 0, "PassManager should have tasks" assert isinstance(pm_opt.layout._tasks[0][0], TrivialLayout), "First task should be a TrivialLayout" # Verify backend is retrieved service = QiskitRuntimeService() backend = service.least_busy() assert backend is not None, "A valid backend should be retrieved" # Ensure coupling map is used in the layout cm = backend.coupling_map assert cm is not None, "Coupling map should be retrieved from the backend" check(trivial_layout)
trivial_layout
basic
qiskitHumanEval/147
Add a multi-controlled-Y operation to qubit 4, controlled by qubits 0-3. You must implement this using a function named `mcy` with the following arguments: qc.
from qiskit import QuantumCircuit from qiskit.circuit.library import YGate def mcy(qc): mcy_gate = YGate().control(num_ctrl_qubits=4) qc.append(mcy_gate, range(5)) return qc
from qiskit import QuantumCircuit from qiskit.circuit.library import YGate from qiskit.quantum_info import Operator def check(candidate): expected = QuantumCircuit(6) expected.h([0, 4, 5]) mcy_gate = YGate().control(num_ctrl_qubits=4) expected.append(mcy_gate, range(5)) solution = QuantumCircuit(6) solution.h([0, 4, 5]) solution = candidate(solution) assert Operator(solution) == Operator(expected) check(mcy)
mcy
intermediate
qiskitHumanEval/148
Add SWAPs to route `qc` for the `backend` object's coupling map, but don't transform any gates. You must implement this using a function named `swap_map` with the following arguments: qc, backend.
from qiskit import QuantumCircuit from qiskit.transpiler.passes import BasicSwap from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit_ibm_runtime import IBMBackend def swap_map(qc, backend): swap_pass = BasicSwap(coupling_map=backend.coupling_map) dag = circuit_to_dag(qc) mapped_dag = swap_pass.run(dag) return dag_to_circuit(mapped_dag)
from qiskit import QuantumCircuit from qiskit.transpiler.passes import BasicSwap from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit_ibm_runtime import IBMBackend def check(candidate): from qiskit_ibm_runtime.fake_provider import FakeKyiv from qiskit.circuit.random import random_circuit from qiskit.transpiler.passes import CheckMap backend = FakeKyiv() for _ in range(3): qc = random_circuit(5,5) original_ops = qc.count_ops() original_ops.pop("swap", None) mapped_qc = candidate(qc, backend) check_map = CheckMap(coupling_map=backend.coupling_map) dag = circuit_to_dag(mapped_qc) check_map.run(dag) assert check_map.property_set["is_swap_mapped"] mapped_ops = mapped_qc.count_ops() mapped_ops.pop("swap", None) # We convert to set for comparison to ignore dictionary ordering assert set(original_ops.items()) == set(mapped_ops.items()) check(swap_map)
swap_map
intermediate
qiskitHumanEval/149
Return the most common result as a string of `1`s and `0`s. You must implement this using a function named `most_common_result` with the following arguments: bits.
from statistics import mode from qiskit.primitives import BitArray def most_common_result(bits): return mode(bits.get_bitstrings())
from statistics import mode from qiskit.primitives import BitArray def check(candidate): test_inputs = [ {"001": 50, "101": 3}, {"1": 1}, {"01101": 302, "10010": 10, "101": 209}, ] for counts in test_inputs: bit_array = BitArray.from_counts(counts) expected = max(counts.items(), key=lambda x: x[1])[0] assert candidate(bit_array) == expected check(most_common_result)
most_common_result
intermediate
qiskitHumanEval/150
Add a sub-circuit to the quantum circuit `qc` that applies a series of operations for `n` iterations using the `for_loop`. In each iteration `i`, perform the following: 1. Apply a `RY` rotation on qubit 0 with an angle of `pi/n * i`. 2. Apply a Hadamard gate to qubit 0 and a CNOT gate between qubits 0 and 1 to create a phi plus Bell state. 3. Measure qubit 0 and store the result in the corresponding classical register. 4. Break the loop if the classical register for qubit 0 measures the value 1. Use the `for_loop` control flow structure to implement the loop and include conditional breaking based on the measurement. You must implement this using a function named `for_loop_circuit` with the following arguments: qc, n.
from qiskit import QuantumCircuit from numpy import pi def for_loop_circuit(qc, n): with qc.for_loop(range(n)) as i: qc.ry(pi/n*i, 0) qc.h(0) qc.cx(0, 1) qc.measure(0, 0) with qc.if_test((qc.clbits[0], 1)): qc.break_loop() return qc
from qiskit import QuantumCircuit from numpy import pi def check(candidate): from qiskit.circuit.library import RYGate, HGate, CXGate, Measure from qiskit.circuit.controlflow import IfElseOp from qiskit.circuit import CircuitInstruction qc = QuantumCircuit(2,1) solution = candidate(qc, 2) assert len(solution.data) > 0, "Circuit should have operations added" op = solution.data[0].operation assert op.name == "for_loop" assert op.num_qubits == 2 and op.num_clbits == 1 indexset, loop_param, sub_qc = op.params assert indexset == range(2) # Test sub circuit data = sub_qc.data qr = qc.qregs[0] cr = qc.cregs[0] assert data[0] == CircuitInstruction(RYGate(pi/2*loop_param), [qr[0]], []) assert data[1] == CircuitInstruction(HGate(), [qr[0]], []) assert data[2] == CircuitInstruction(CXGate(), [qr[0], qr[1]], []) assert data[3] == CircuitInstruction(Measure(), [qr[0]],[cr[0]]) assert isinstance(data[4].operation, IfElseOp) assert set(data[4].qubits) == {qr[0], qr[1]} or set(data[4].qubits) == {qr[1], qr[0]} assert [bit._index for bit in data[4].clbits] == [0] check(for_loop_circuit)
for_loop_circuit
difficult