def test_cancellation_aer() -> None:
    b = AerBackend()
    c = circuit_gen(True)
    b.compile_circuit(c)
    h = b.process_circuit(c, 10)
    b.cancel(h)
    print(b.circuit_status(h))
def test_ibmq_emulator() -> None:
    b_emu = IBMQEmulatorBackend("ibmq_santiago",
                                hub="ibm-q",
                                group="open",
                                project="main")
    assert b_emu._noise_model is not None
    b_ibm = b_emu._ibmq
    b_aer = AerBackend()
    for ol in range(3):
        comp_pass = b_emu.default_compilation_pass(ol)
        c = Circuit(3, 3)
        c.H(0)
        c.CX(0, 1)
        c.CSWAP(1, 0, 2)
        c.ZZPhase(0.84, 2, 0)
        c_cop = c.copy()
        comp_pass.apply(c_cop)
        c.measure_all()
        for bac in (b_emu, b_ibm):
            assert all(pred.verify(c_cop) for pred in bac.required_predicates)

        c_cop_2 = c.copy()
        b_aer.compile_circuit(c_cop_2, ol)
        if ol == 0:
            assert not all(
                pred.verify(c_cop_2) for pred in b_emu.required_predicates)

    circ = Circuit(2, 2).H(0).CX(0, 1).measure_all()
    b_emu.compile_circuit(circ)
    b_noi = AerBackend(noise_model=b_emu._noise_model)
    emu_shots = b_emu.get_shots(circ, 10, seed=10)
    aer_shots = b_noi.get_shots(circ, 10, seed=10)
    assert np.array_equal(emu_shots, aer_shots)
def test_process_characterisation_no_noise_model() -> None:
    my_noise_model = NoiseModel()
    back = AerBackend(my_noise_model)
    assert back.characterisation is None

    c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0)
    back.compile_circuit(c)
    assert back.valid_circuit(c)
def test_mixed_circuit() -> None:
    c = Circuit()
    qr = c.add_q_register("q", 2)
    ar = c.add_c_register("a", 1)
    br = c.add_c_register("b", 1)
    c.H(qr[0])
    c.Measure(qr[0], ar[0])
    c.X(qr[1], condition=reg_eq(ar, 0))
    c.Measure(qr[1], br[0])
    backend = AerBackend()
    backend.compile_circuit(c)
    counts = backend.get_counts(c, 1024)
    for key in counts.keys():
        assert key in {(0, 1), (1, 0)}
def test_cache() -> None:
    b = AerBackend()
    c = circuit_gen()
    b.compile_circuit(c)
    h = b.process_circuits([c], 2)[0]
    b.get_result(h).get_shots()
    assert h in b._cache
    b.pop_result(h)
    assert h not in b._cache
    assert not b._cache

    b.get_counts(c, n_shots=2)
    b.get_counts(c.copy(), n_shots=2)
    b.empty_cache()
    assert not b._cache
def test_process_characterisation_incomplete_noise_model() -> None:

    my_noise_model = NoiseModel()

    my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"],
                                     [0, 1])
    my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [1])
    my_noise_model.add_quantum_error(depolarizing_error(0.1, 1), ["u3"], [3])
    my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Z", 0.65)]),
                                     ["u2"], [0])
    my_noise_model.add_quantum_error(pauli_error([("X", 0.35), ("Y", 0.65)]),
                                     ["u1"], [2])

    back = AerBackend(my_noise_model)
    char = cast(Dict[str, Any], back.characterisation)

    c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0).measure_all()
    back.compile_circuit(c)
    assert back.valid_circuit(c)

    dev = Device(
        char.get("NodeErrors", {}),
        char.get("EdgeErrors", {}),
        char.get("Architecture", Architecture([])),
    )
    nodes = dev.nodes
    assert set(dev.architecture.coupling) == set([
        (nodes[0], nodes[1]),
        (nodes[0], nodes[2]),
        (nodes[0], nodes[3]),
        (nodes[1], nodes[2]),
        (nodes[1], nodes[3]),
        (nodes[2], nodes[0]),
        (nodes[2], nodes[1]),
        (nodes[2], nodes[3]),
        (nodes[3], nodes[0]),
        (nodes[3], nodes[1]),
        (nodes[3], nodes[2]),
    ])
def test_noise() -> None:
    with open(os.path.join(sys.path[0], "ibmqx2_properties.pickle"),
              "rb") as f:
        properties = pickle.load(f)

    noise_model = NoiseModel.from_backend(properties)
    n_qbs = 5
    c = Circuit(n_qbs, n_qbs)
    x_qbs = [2, 0, 4]
    for i in x_qbs:
        c.X(i)
    c.measure_all()
    b = AerBackend(noise_model)
    n_shots = 50
    b.compile_circuit(c)
    shots = b.get_shots(c, n_shots, seed=4)
    zer_exp = []
    one_exp = []
    for i in range(n_qbs):
        expectation = np.sum(shots[:, i]) / n_shots
        if i in x_qbs:
            one_exp.append(expectation)
        else:
            zer_exp.append(expectation)

    assert min(one_exp) > max(zer_exp)

    c2 = (Circuit(4, 4).H(0).CX(0,
                                2).CX(3,
                                      1).T(2).CX(0,
                                                 1).CX(0,
                                                       3).CX(2,
                                                             1).measure_all())

    b.compile_circuit(c2)
    shots = b.get_shots(c2, 10, seed=5)
    assert shots.shape == (10, 4)
def test_circuit_compilation_complete_noise_model() -> None:
    my_noise_model = NoiseModel()
    my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"],
                                     [0, 1])
    my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"],
                                     [0, 2])
    my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"],
                                     [0, 3])
    my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"],
                                     [1, 2])
    my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"],
                                     [1, 3])
    my_noise_model.add_quantum_error(depolarizing_error(0.6, 2), ["cx"],
                                     [2, 3])
    my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [0])
    my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [1])
    my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [2])
    my_noise_model.add_quantum_error(depolarizing_error(0.5, 1), ["u3"], [3])

    back = AerBackend(my_noise_model)

    c = Circuit(4).CX(0, 1).H(2).CX(2, 1).H(3).CX(0, 3).H(1).X(0).measure_all()
    back.compile_circuit(c)
    assert back.valid_circuit(c)
from pytket.circuit import Circuit, Qubit
from pytket.pauli import Pauli, QubitPauliString
from pytket.utils import QubitPauliOperator
from pytket.utils.expectations import get_operator_expectation_value
from pytket.extensions.qiskit import AerBackend, AerStateBackend

# First, let's get some results on a toy circuit without using any measurement reduction:

shots_backend = AerBackend()
n_shots = 10000

c = Circuit(5)
c.H(4)
c.V(2)

shots_backend.compile_circuit(c)
op = QubitPauliOperator({
    QubitPauliString([Qubit(0)], [Pauli.Z]):
    0.1,
    QubitPauliString(
        [Qubit(0), Qubit(1), Qubit(2),
         Qubit(3), Qubit(4)],
        [Pauli.Y, Pauli.Z, Pauli.X, Pauli.X, Pauli.Y],
    ):
    0.4,
    QubitPauliString([Qubit(0), Qubit(1)], [Pauli.X, Pauli.X]):
    0.2,
})

shots_result = get_operator_expectation_value(c, op, shots_backend, n_shots)
print(shots_result)
示例#10
0
print("Number of calibration circuits: ", len(calibration_circuits))

sim_handles = pytket_noisy_sim_backend.process_circuits(
    calibration_circuits, n_shots)

# Count results from the simulator are then used to calculate the matrices used for SPAM correction for ```ibmq_santiago```.

sim_count_results = (pytket_noisy_sim_backend.get_result(handle).get_counts()
                     for handle in sim_handles)
santiago_spam.calculate_matrices(sim_count_results)

from pytket import Circuit

ghz_circuit = (Circuit(len(pytket_santiago_device.nodes)).H(0).CX(0, 1).CX(
    1, 2).measure_all())
pytket_noisy_sim_backend.compile_circuit(ghz_circuit)
ghz_noisy_counts = pytket_noisy_sim_backend.get_counts(ghz_circuit, n_shots)

# We also run a noiseless simulation so we can compare performance.

pytket_noiseless_sim_backend = AerBackend()
ghz_noiseless_counts = pytket_noiseless_sim_backend.get_counts(
    ghz_circuit, n_shots)

# Noisy simulator counts are corrected using the ```SpamCorrecter``` objects ```correct_counts``` method.
#
# To correctly amend counts, the ```correct_counts``` method requires the executed circuits qubit_readout, a map from qubit to its index in readouts from backends.

ghz_spam_corrected_counts = santiago_spam.correct_counts(
    ghz_noisy_counts, ghz_circuit.qubit_readout)
示例#11
0
from pytket.extensions.qiskit import AerBackend

# Connect to a simulator:

backend = AerBackend()

# Make a ZZ measurement of the Bell pair:

bell_test = es.copy()
bell_test.Measure(ava[0], data[0])
bell_test.Measure(charlie[0], data[1])

# Run the experiment:

backend.compile_circuit(bell_test)
from pytket.extensions.qiskit import tk_to_qiskit

print(tk_to_qiskit(bell_test))
handle = backend.process_circuit(bell_test, n_shots=2000)
counts = backend.get_result(handle).get_counts()

print(counts)

# This is good, we have got roughly 50/50 measurement results of 00 and 11 under the ZZ operator. But there are many other states beyond the Bell state that also generate this distribution, so to gain more confidence in our claim about the state we should make more measurements that also characterise it, i.e. perform state tomography.
#
# Here, we will demonstrate a naive approach to tomography that makes 3^n measurement circuits for an n-qubit state. More elaborate methods also exist.

from pytket.pauli import Pauli, QubitPauliString
from pytket.utils import append_pauli_measurement, probs_from_counts
from itertools import product
示例#12
0
# The preconditions and postconditions of all the elementary predicates are documented in their string representations:

PauliSimp()

# ## Backends and default passes

# A `pytket` `Backend` may have a default compilation pass, which will guarantee that the circuit can run on it. This is given by the `default_compilation_pass` property. For example, the default pass for Qiskit's `AerBackend` just converts all gates to U1, U2, U3 and CX:

from pytket.extensions.qiskit import AerBackend

b = AerBackend()
b.default_compilation_pass

# To compile a circuit using the default pass of a `Backend` we can simply use the `compile_circuit()` method:

circ = Circuit(2).X(0).Y(1).CRz(0.5, 1, 0)
circ1 = circ.copy()
b.compile_circuit(circ1)
print(tk_to_qiskit(circ1))

# Every `Backend` will have a certain set of requirements that must be met by any circuit in order to run. These are exposed via the `required_predicates` property:

b.required_predicates

# We can test whether a given circuit satisfies these requirements using the `valid_circuit()` method:

b.valid_circuit(circ)

b.valid_circuit(circ1)
示例#13
0
print(tk_to_qiskit(c))
print("Number of CX:", c.n_gates_of_type(OpType.CX))

# Contextual optimizations allow us to shave some gates from the beginning and end of the circuit. Those at the end get commuted through the Measure gates into a classical post-processing circuit, which we can then pass to `BackendResult` methods to have the postprocessing performed automatically.

# The `prepare_circuit()` method returns a pair of circuits, the first of which is what we actually run and the second of specifies the required postprocessing.

from pytket.utils import prepare_circuit

c0, ppcirc = prepare_circuit(c)
print(tk_to_qiskit(c0))
print("Number of CX:", c0.n_gates_of_type(OpType.CX))

# In this case, one CX has been shaved from the beginning of the circuit and two from the end.

# We can run the processed circuit on our backend:

from pytket.extensions.qiskit import AerBackend

b = AerBackend()
b.compile_circuit(c0)
h = b.process_circuit(c0, n_shots=10)
r = b.get_result(h)

# And finally get the counts or shots, accounting for the classical postprocessing:

counts = r.get_counts(ppcirc=ppcirc)
print(counts)

# See the [pytket user manual](https://cqcl.github.io/pytket/build/html/manual/manual_compiler.html#contextual-optimisations) for more details about contextual optimisations and how to apply them in TKET.
示例#14
0
from pytket import Circuit
from pytket.extensions.qiskit import AerBackend

# Define a circuit:

c = Circuit(3, 3)
c.Ry(0.7, 0)
c.CX(0, 1)
c.X(2)
c.measure_all()

# Run on the backend:

backend = AerBackend()
backend.compile_circuit(c)
handle = backend.process_circuit(c, n_shots=2000)
counts = backend.get_result(handle).get_counts()
print(counts)

# ## Statevector simulator usage

from pytket import Circuit
from pytket.extensions.qiskit import AerStateBackend

# Build a quantum state:

c = Circuit(3)
c.H(0).CX(0, 1)
c.Rz(0.3, 0)
c.Rz(-0.3, 1)