def test_aer_result_handle() -> None:
    c = Circuit(2, 2).H(0).CX(0, 1).measure_all()

    b = AerBackend()

    handles = b.process_circuits([c, c.copy()], n_shots=2)

    ids, indices = zip(*(han for han in handles))

    assert all(isinstance(idval, str) for idval in ids)
    assert indices == (0, 1)

    assert len(b.get_result(handles[0]).get_shots()) == 2

    with pytest.raises(TypeError) as errorinfo:
        _ = b.get_result(ResultHandle("43"))
    assert "ResultHandle('43',) does not match expected identifier types" in str(
        errorinfo.value)

    wronghandle = ResultHandle("asdf", 3)

    with pytest.raises(CircuitNotRunError) as errorinfoCirc:
        _ = b.get_result(wronghandle)
    assert "Circuit corresponding to {0!r} ".format(
        wronghandle) + "has not been run by this backend instance." in str(
            errorinfoCirc.value)
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_shots_bits_edgecases(n_shots: int, n_bits: int) -> None:
    c = Circuit(n_bits, n_bits)
    aer_backend = AerBackend()

    # TODO TKET-813 add more shot based backends and move to integration tests
    h = aer_backend.process_circuit(c, n_shots)
    res = aer_backend.get_result(h)

    correct_shots = np.zeros((n_shots, n_bits), dtype=int)
    correct_shape = (n_shots, n_bits)
    correct_counts = Counter({(0, ) * n_bits: n_shots})
    # BackendResult
    assert np.array_equal(res.get_shots(), correct_shots)
    assert res.get_shots().shape == correct_shape
    assert res.get_counts() == correct_counts

    # Direct
    assert np.array_equal(aer_backend.get_shots(c, n_shots), correct_shots)
    assert aer_backend.get_shots(c, n_shots).shape == correct_shape
    assert aer_backend.get_counts(c, n_shots) == correct_counts
Example #4
0
pytket_noisy_sim_backend = AerBackend(
    NoiseModel.from_backend(ibmq_santiago_backend))
santiago_spam = SpamCorrecter([santiago_node_subsets],
                              pytket_noisy_sim_backend)

# The SpamCorrecter uses these subsets of qubits to produce calibration circuits.

calibration_circuits = santiago_spam.calibration_circuits()
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)
Example #5
0
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
from scipy.linalg import lstsq, eigh
import numpy as np


def gen_tomography_circuits(state, qubits, bits):
Example #6
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.
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)
c.Ry(0.8, 2)