Qiskit/qiskit_humaneval_hard huggingface dataset:
Create a 2-qubit quantum circuit where you define a custom 1-qubit unitary gate (e.g., U3) and apply it as a controlled gate with qubit 0 as control and qubit 1 as target. Return the final circuit.
You must implement this using a function named `controlled_custom_unitary_circuit` with no arguments.

Solution:
from qiskit import QuantumCircuit
from qiskit.circuit.library import U3Gate

def controlled_custom_unitary_circuit():
    qc = QuantumCircuit(2)
    custom_gate = U3Gate(0.3, 0.2, 0.1).control()
    qc.append(custom_gate, [0, 1])
    return qc


Test:
from qiskit import QuantumCircuit
from qiskit.circuit.library import U3Gate
def check(candidate):
    qc = candidate()
    assert isinstance(qc, QuantumCircuit)
    assert qc.num_qubits == 2
    assert any(instr[0].name.startswith('cu3') or 'u3' in instr[0].name for instr in qc.data)

check(controlled_custom_unitary_circuit)
Given a QuantumCircuit, convert it into qasm2 string and return it.
You must implement this using a function named `convert_quantum_circuit_to_qasm_string` with the following arguments: circuit.

Solution:
from qiskit import QuantumCircuit
import qiskit.qasm2

def convert_quantum_circuit_to_qasm_string(circuit):
    qasm_str = qiskit.qasm2.dumps(circuit)
    return qasm_str


Test:
from qiskit import QuantumCircuit
import qiskit.qasm2
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)

check(convert_quantum_circuit_to_qasm_string)
Create a 5-qubit quantum circuit with a chain of CX gates and apply Qiskit's CollectLinearFunctions transpiler pass. Return two circuits:
1. One with no block width restriction.
2. One with a max_block_width of 3.
Use PassManager to apply the pass and return both circuits.
You must implement this using a function named `collect_linear_blocks_with_and_without_limit` with no arguments.

Solution:
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import CollectLinearFunctions
from qiskit.transpiler import PassManager

def collect_linear_blocks_with_and_without_limit():
    qc = QuantumCircuit(5)
    qc.h(0)
    qc.cx(0, 1)
    qc.cx(1, 2)
    qc.cx(2, 3)
    qc.cx(3, 4)
    pm_full = PassManager([CollectLinearFunctions()])
    full_block = pm_full.run(qc)
    pm_limited = PassManager([CollectLinearFunctions(max_block_width=3)])
    limited_block = pm_limited.run(qc)
    return full_block, limited_block


Test:
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import CollectLinearFunctions
from qiskit.transpiler import PassManager
def check(candidate):
    from qiskit.circuit.library import LinearFunction
    full, limited = candidate()
    full_linear_count = sum(1 for instr in full.data if isinstance(instr.operation, LinearFunction))
    limited_linear_count = sum(1 for instr in limited.data if isinstance(instr.operation, LinearFunction))
    assert full_linear_count == 1
    assert limited_linear_count > 1

check(collect_linear_blocks_with_and_without_limit)
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.
You must implement this using a function named `quantum_circuit_with_delay` with no arguments.

Solution:
from qiskit import QuantumCircuit

def quantum_circuit_with_delay():
    qc = QuantumCircuit(1)
    qc.h(0)
    delay_duration = 100
    qc.delay(delay_duration, 0, unit="dt")
    qc.h(0)
    return qc


Test:
from qiskit import QuantumCircuit
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]], [])

check(quantum_circuit_with_delay)
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.
You must implement this using a function named `create_conditional_circuit` with no arguments.

Solution:
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit import IfElseOp

def create_conditional_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


Test:
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit.circuit import IfElseOp
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

check(create_conditional_circuit)
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.
You must implement this using a function named `create_controlled_hgate` with no arguments.

Solution:
from qiskit.circuit.library import HGate
from qiskit import QuantumCircuit, QuantumRegister

def create_controlled_hgate():
    qr = QuantumRegister(3)
    qc = QuantumCircuit(qr)
    c3h_gate = HGate().control(2)
    qc.append(c3h_gate, qr)
    return qc


Test:
from qiskit.circuit.library import HGate
from qiskit import QuantumCircuit, QuantumRegister
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)

check(create_controlled_hgate)
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.
You must implement this using a function named `create_custom_controlled` with no arguments.

Solution:
from qiskit import QuantumCircuit

def create_custom_controlled():
    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


Test:
from qiskit import QuantumCircuit
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)

check(create_custom_controlled)
Create a circuit that produces a phi plus bell state with name bell_instruction and convert it into a quantum instruction.
You must implement this using a function named `convert_circuit_to_instruction` with no arguments.

Solution:
from qiskit import QuantumCircuit
from qiskit.converters import circuit_to_instruction

def convert_circuit_to_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


Test:
from qiskit import QuantumCircuit
from qiskit.converters import circuit_to_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

check(convert_circuit_to_instruction)
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.
You must implement this using a function named `calculate_stabilizer_state_info` with no arguments.

Solution:
from qiskit import QuantumCircuit
from qiskit.quantum_info import StabilizerState

def calculate_stabilizer_state_info():
    qc = QuantumCircuit(2)
    qc.h(0)
    qc.cx(0, 1)
    stab = StabilizerState(qc)
    probabilities_dict = stab.probabilities_dict()
    return stab, probabilities_dict


Test:
from qiskit import QuantumCircuit
from qiskit.quantum_info import StabilizerState
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)

check(calculate_stabilizer_state_info)
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.
You must implement this using a function named `synthesize_clifford_circuit` with the following arguments: n_qubits.

Solution:
from qiskit.synthesis import synth_clifford_full
from qiskit.quantum_info.random import random_clifford

def synthesize_clifford_circuit(n_qubits):
    qc = random_clifford(n_qubits, seed=1234)
    synthesized_qc = synth_clifford_full(qc)
    return synthesized_qc


Test:
from qiskit.synthesis import synth_clifford_full
from qiskit.quantum_info.random import random_clifford
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)

check(synthesize_clifford_circuit)
Given a Quantum Circuit as the argument, convert it into qasm3 string and return it.
You must implement this using a function named `convert_quantum_circuit_to_qasm_string` with the following arguments: circuit.

Solution:
from qiskit import QuantumCircuit
import qiskit.qasm3

def convert_quantum_circuit_to_qasm_string(circuit):
    qasm_str = qiskit.qasm3.dumps(circuit)
    return qasm_str


Test:
from qiskit import QuantumCircuit
import qiskit.qasm3
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"

check(convert_quantum_circuit_to_qasm_string)
For a given Quantum Circuit remove all the barriers from it and return.
You must implement this using a function named `remove_barrier` with the following arguments: circuit.

Solution:
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers

def remove_barrier(circuit):
    return  RemoveBarriers()(circuit)


Test:
from qiskit import QuantumCircuit
from qiskit.transpiler.passes import RemoveBarriers
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)

check(remove_barrier)
Create the phi+ Bell state, run it in the FakeKyoto backend and return the counts. Use seed 42 for the sampler.
You must implement this using a function named `bell_state_noisy` with no arguments.

Solution:
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():
    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


Test:
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 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"
    
check(bell_state_noisy)
Return the two qubit connections for any input backend of type FakeBackendV2, IBMBackend.
You must implement this using a function named `two_qubit_conections` with the following arguments: backend.

Solution:
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):
    if isinstance(backend, FakeBackendV2):
        return backend.coupling_map
    return backend.configuration().coupling_map


Test:
from qiskit_ibm_runtime.fake_provider.fake_backend import FakeBackendV2
from qiskit_ibm_runtime import IBMBackend
from typing import Union
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"

check(two_qubit_conections)
Return the minimum readout error of any input backend of type FakeBackendV2, IBMBackend.
You must implement this using a function named `qubit_with_least_readout_error` with the following arguments: backend.

Solution:
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):
    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)


Test:
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 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"

check(qubit_with_least_readout_error)
Remove all the gates with unassigned parameters from the given circuit.
You must implement this using a function named `remove_unassigned_parameterized_gates` with the following arguments: circuit.

Solution:
from qiskit.circuit import Parameter, QuantumCircuit

def remove_unassigned_parameterized_gates(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


Test:
from qiskit.circuit import Parameter, QuantumCircuit
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"

check(remove_unassigned_parameterized_gates)
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.

Solution:
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


Test:
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)
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.

Solution:
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


Test:
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)
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.

Solution:
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)


Test:
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)