Qiskit/qiskit_humaneval_hard huggingface dataset:
Generate a Quantum Circuit for the given int 'n_qubits' and return it.
You must implement this using a function named `create_quantum_circuit` with the following arguments: n_qubits.

Solution:
from qiskit import QuantumCircuit

def create_quantum_circuit(n_qubits):
    return QuantumCircuit(n_qubits)


Test:
from qiskit import QuantumCircuit
def check(candidate):
    result = candidate(3)
    assert isinstance(result, QuantumCircuit)
    assert result.num_qubits == 3

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

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


Test:
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 check(candidate):
    result = candidate()
    assert isinstance(result, dict)
    assert result.keys() == {"00", "11"}
    assert 0.4 < (result["00"] / sum(result.values())) < 0.6

check(run_bell_state_simulator)
Return a phi+ Bell statevector.
You must implement this using a function named `create_bell_statevector` with no arguments.

Solution:
from qiskit.quantum_info import Statevector
from math import sqrt

def create_bell_statevector():
    return (Statevector.from_label("00") + Statevector.from_label("11")) / sqrt(2)


Test:
from qiskit.quantum_info import Statevector
from math import sqrt
def check(candidate):
    result = candidate()
    solution = (Statevector.from_label("00") + Statevector.from_label("11")) / sqrt(2)
    assert result.equiv(solution)

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

Solution:
from qiskit import QuantumCircuit

def create_ghz(drawing=False):
    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

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

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

Solution:
from qiskit import QuantumCircuit

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


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

check(create_unitary_from_matrix)
Return a QuantumCircuit that prepares the binary state 1.
You must implement this using a function named `create_state_prep` with no arguments.

Solution:
from qiskit import QuantumCircuit

def create_state_prep():
    qc = QuantumCircuit(2)
    qc.prepare_state("01")
    return qc


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

check(create_state_prep)
Return a QuantumCircuit that prepares the state |1> on an n-qubit register.
You must implement this using a function named `create_state_prep` with the following arguments: num_qubits.

Solution:
from qiskit import QuantumCircuit

def create_state_prep(num_qubits):
    qc = QuantumCircuit(num_qubits)
    qc.prepare_state(1)
    return qc


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

check(create_state_prep)
Generate a 1 qubit QuantumCircuit with a parametrized Rx gate with parameter "theta".
You must implement this using a function named `create_parametrized_gate` with no arguments.

Solution:
from qiskit.circuit import QuantumCircuit, Parameter

def create_parametrized_gate():
    theta = Parameter("theta")
    quantum_circuit = QuantumCircuit(1)
    quantum_circuit.rx(theta, 0)
    return quantum_circuit


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

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

Solution:
from qiskit.circuit import QuantumCircuit, Parameter

def rx_gate(value=None):
    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


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

check(rx_gate)
Generate an EfficientSU2 circuit with 3 qubits, 1 reps and make insert_barriers true.
You must implement this using a function named `create_efficientSU2` with no arguments.

Solution:
from qiskit.circuit.library import EfficientSU2

def create_efficientSU2():
    circuit = EfficientSU2(num_qubits=3, reps=1, insert_barriers=True)
    return circuit


Test:
from qiskit.circuit.library import EfficientSU2
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

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

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


Test:
from qiskit.circuit import QuantumCircuit
from qiskit.quantum_info.operators import Operator
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
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"]

check(create_operator)
Return the statevector from a circuit.
You must implement this using a function named `get_statevector` with the following arguments: circuit.

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

def get_statevector(circuit):
    sv = Statevector.from_instruction(circuit)
    return sv


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

check(get_statevector)
Get unitary matrix for a phi plus bell circuit and return it.
You must implement this using a function named `get_unitary` with no arguments.

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

def get_unitary():
    circ = QuantumCircuit(2)
    circ.h(0)
    circ.cx(0, 1)
    return Operator.from_circuit(circ).to_matrix()

Test:
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
def check(candidate):
    result = candidate()
    solution = QuantumCircuit(2)
    solution.h(0)
    solution.cx(0, 1)
    assert Operator(solution).equiv(result)

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

Solution:
from qiskit import QuantumCircuit
import numpy as np

def custom_rotation_gate():
    circuit = QuantumCircuit(1)
    circuit.u(np.pi / 2, np.pi / 2, np.pi / 2, 0)
    return circuit


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

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

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


Test:
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 check(candidate):
    result = candidate()
    assert isinstance(result, list)
    assert len(result) > 0
    assert set(result) == {"00", "11"}

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

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


Test:
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 check(candidate):
    result = candidate()
    assert isinstance(result, dict)
    assert (result["00"] + result["11"]) != sum(result.values())

check(noisy_bell)
For the given Quantum Circuit, return the transpiled circuit for the Fake Cairo V2 backend using pass manager with optimization level as 1.
You must implement this using a function named `transpile_circuit` with the following arguments: circuit.

Solution:
from qiskit_ibm_runtime.fake_provider import FakeCairoV2
from qiskit.transpiler import CouplingMap
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager

def transpile_circuit(circuit):
    backend = FakeCairoV2()
    coupling_map = CouplingMap(backend.configuration().coupling_map)
    pass_manager = generate_preset_pass_manager(optimization_level=1, backend=backend, coupling_map=coupling_map)
    return pass_manager.run(circuit)


Test:
from qiskit_ibm_runtime.fake_provider import FakeCairoV2
from qiskit.transpiler import CouplingMap
from qiskit import QuantumCircuit
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
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

check(transpile_circuit)
Unroll circuit for the gateset: CX, ID, RZ, SX, X, U.
You must implement this using a function named `unroll_circuit` with the following arguments: circuit.

Solution:
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):
    pass_ = BasisTranslator(std_eqlib, ["cx", "id", "rz", "sx", "x", "u"])
    pm = PassManager(pass_)
    return pm.run(circuit)


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

check(unroll_circuit)
Transpile a 10-qubit GHZ circuit for the Fake Sydney V2 backend using pass manager with no optimization.
You must implement this using a function named `transpile_circuit_noopt` with no arguments.

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


Test:
from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeSydneyV2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
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))

check(transpile_circuit_noopt)
Transpile and map an 11-qubit GHZ circuit for the Fake Toronto V2 backend using pass manager with maximum transpiler optimization.
You must implement this using a function named `transpile_circuit_maxopt` with no arguments.

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


Test:
from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeTorontoV2
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
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

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

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


Test:
from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakePerth
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
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]

check(transpile_ghz_customlayout)
Using a pass manager with optimization level as 1 and dense layout method, transpile and map a bell circuit for the Fake Oslo backend.
You must implement this using a function named `transpile_circuit_dense` with no arguments.

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


Test:
from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeOslo
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def check(candidate):
    result = candidate()
    backend = FakeOslo()
    assert result.num_qubits == backend.num_qubits

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

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


Test:
from qiskit import QuantumCircuit
from qiskit_ibm_runtime.fake_provider import FakeAuckland
from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager
def check(candidate):
    result = candidate()
    backend = FakeAuckland()
    assert result.num_qubits == backend.num_qubits

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

Solution:
from qiskit import QuantumCircuit

def dj_constant_oracle():
    oracle = QuantumCircuit(3)
    oracle.x(2)
    return oracle


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

check(dj_constant_oracle)