Beispiel #1
0
def test_pauli_measure_in_bad_qubits_error():
    n = 5
    pauli = PauliString(spec="X" * n)
    circuit = cirq.Circuit(cirq.H.on_each(cirq.LineQubit.range(n - 1)))

    with pytest.raises(ValueError, match="Qubit mismatch."):
        pauli.measure_in(circuit)
Beispiel #2
0
def test_observable_expectation_from_measurements_two_pauli_strings():
    obs = Observable(PauliString(spec="Z", coeff=2.5), PauliString(spec="X"))

    bits = MeasurementResult([[0], [0], [0], [0], [0], [0], [0], [0], [0],
                              [0]])
    expectation = obs._expectation_from_measurements([bits, bits])
    assert np.isclose(expectation, 3.5)
Beispiel #3
0
def test_can_be_measured_with_single_qubit():
    pauli = PauliString(spec="Z")

    assert pauli.can_be_measured_with(PauliString(spec="I"))
    assert not pauli.can_be_measured_with(PauliString(spec="X"))
    assert not pauli.can_be_measured_with(PauliString(spec="Y"))
    assert pauli.can_be_measured_with(PauliString(spec="Z", coeff=-0.5))
    assert pauli.can_be_measured_with(pauli)
Beispiel #4
0
def test_weight():
    assert PauliString(spec="I").weight() == 0
    assert PauliString(spec="Z").weight() == 1

    n = 4
    assert PauliString(spec="X" * n).weight() == n
    assert PauliString(spec="IX" * n).weight() == n
    assert PauliString(spec="ZX" * n).weight() == 2 * n
Beispiel #5
0
def test_observable_partition_one_set():
    pauli1 = PauliString(spec="ZI")
    pauli2 = PauliString(spec="IZ")
    pauli3 = PauliString(spec="ZZ")
    obs = Observable(pauli1, pauli2, pauli3)
    assert obs.nterms == 3

    assert obs.ngroups == 1
    assert obs.groups[0] == PauliStringCollection(pauli1, pauli2, pauli3)
Beispiel #6
0
def test_pstring_collection_len():
    x = PauliString(spec="X", support=(0,))
    y = PauliString(spec="Y", support=(1,))
    z = PauliString(spec="Z", support=(2,))
    assert len(PauliStringCollection(x, y, z)) == 3
    assert len(PauliStringCollection(x, x, x)) == 3
    assert len(PauliStringCollection(x, y)) == 2
    assert len(PauliStringCollection(x)) == 1
    assert len(PauliStringCollection()) == 0
Beispiel #7
0
def test_pstring_collection_str():
    x = PauliString(spec="X")
    iz = PauliString(spec="IZ")
    pcol = PauliStringCollection(x, iz)
    assert str(pcol) == "X(0) + Z(1)"

    xz = PauliString(spec="XZ", coeff=-2.4)
    pcol.add(xz)
    assert str(pcol) == "X(0) + Z(1) + (-2.4+0j)*X(0)*Z(1)"
Beispiel #8
0
def test_observable_expectation_two_circuits(n, executor):
    executor = functools.partial(executor, noise_level=(0, ))

    obs = Observable(PauliString(spec="X" * n, coeff=-2.0),
                     PauliString(spec="Z" * n))
    qubits = cirq.LineQubit.range(n)
    circuit = cirq.Circuit(cirq.H.on_each(qubits))

    expectation = obs.expectation(circuit, executor)
    assert np.isclose(expectation, -2.0, atol=1e-1)
Beispiel #9
0
def test_pauli_matrix_include_qubits():
    pauli = PauliString(spec="X")

    assert np.allclose(pauli.matrix(), xmat)
    assert np.allclose(pauli.matrix(qubit_indices_to_include=[0, 1]),
                       np.kron(xmat, imat))
    assert np.allclose(
        pauli.matrix(qubit_indices_to_include=[0, 1, 2]),
        np.kron(np.kron(xmat, imat), imat),
    )
Beispiel #10
0
def test_pstring_collection_eq():
    x = PauliString(spec="X")
    z = PauliString(spec="IZ")
    xz = PauliString(spec="XZ")
    xzz = PauliString(spec="IIIXZZ")

    assert PauliStringCollection(x, xzz) == PauliStringCollection(xzz, x)
    assert PauliStringCollection(x, z) != PauliStringCollection(x, xz)
    assert PauliStringCollection(x, z, xz) == PauliStringCollection(z, xz, x)
    assert PauliStringCollection() == PauliStringCollection()
Beispiel #11
0
def test_pstringcollection_expectation_from_measurements_qubit_indices():
    measurements = MeasurementResult([[0, 0], [0, 0], [0, 1], [0, 1]],
                                     qubit_indices=(1, 5))
    pset = PauliStringCollection(
        PauliString(spec="Z", coeff=-2.0, support=(1, )))
    assert np.isclose(pset._expectation_from_measurements(measurements), -2.0)

    pset = PauliStringCollection(
        PauliString(spec="Z", coeff=-2.0, support=(5, )))
    assert np.isclose(pset._expectation_from_measurements(measurements), 0.0)
Beispiel #12
0
def test_pstringcollection_expectation_from_measurements():
    measurements = MeasurementResult([[0, 0], [0, 0], [0, 1], [0, 1]])
    pset = PauliStringCollection(PauliString(spec="ZI", coeff=-2.0),
                                 PauliString(spec="IZ", coeff=5.0))
    assert np.isclose(pset._expectation_from_measurements(measurements), -2.0)

    measurements = MeasurementResult([[1, 0], [1, 0], [0, 1], [0, 1]])
    pset = PauliStringCollection(PauliString(spec="ZI", coeff=-2.0),
                                 PauliString(spec="IZ", coeff=5.0))
    assert np.isclose(pset._expectation_from_measurements(measurements), 0.0)
Beispiel #13
0
def test_expectation_from_measurements_identity(seed, nqubits):
    """For P = cI, asserts ⟨P⟩ = c."""
    rng = np.random.RandomState(seed)
    coeff = rng.random()
    pauli = PauliString(spec="I", coeff=coeff)

    measurements = MeasurementResult(
        rng.randint(low=0, high=1 + 1, size=(100, nqubits)).tolist())
    assert np.isclose(
        pauli._expectation_from_measurements(measurements),
        coeff,
    )
Beispiel #14
0
def test_observable_from_pauli_string_collections():
    z = PauliString("Z")
    zz = PauliString("ZZ")
    pcol1 = PauliStringCollection(z, zz)
    x = PauliString("X")
    xx = PauliString("XX")
    pcol2 = PauliStringCollection(x, xx)

    obs = Observable.from_pauli_string_collections(pcol1, pcol2)
    assert obs.ngroups == 2
    assert obs.groups[0] == pcol1
    assert obs.groups[1] == pcol2
    assert obs.nterms == 4
Beispiel #15
0
def test_observable():
    pauli1 = PauliString(spec="XI", coeff=-1.0)
    pauli2 = PauliString(spec="IZ", coeff=2.0)
    obs = Observable(pauli1, pauli2)

    assert obs.nqubits == 2
    assert obs.qubit_indices == [0, 1]
    assert obs.nterms == 2
    assert obs.ngroups == 1

    assert str(obs) == "-X(0) + (2+0j)*Z(1)"

    correct_matrix = -1.0 * np.kron(xmat, imat) + 2.0 * np.kron(imat, zmat)
    assert np.allclose(obs.matrix(), correct_matrix)
Beispiel #16
0
def test_observable_partition_single_qubit_paulis():
    x = PauliString(spec="X")
    y = PauliString(spec="Y")
    z = PauliString(spec="Z")
    obs = Observable(x, y, z)
    assert obs.nterms == 3

    obs.partition(seed=2)
    expected_groups = [
        PauliStringCollection(x),
        PauliStringCollection(y),
        PauliStringCollection(z),
    ]
    assert obs.groups == expected_groups
Beispiel #17
0
def test_pauli_init_with_support():
    support = (2, 37)
    pauli = PauliString(spec="XZ", support=support)

    assert pauli._pauli == cirq.PauliString(cirq.X(cirq.LineQubit(support[0])),
                                            cirq.Z(cirq.LineQubit(support[1])))
    assert str(pauli) == f"X({support[0]})*Z({support[1]})"
Beispiel #18
0
def test_pauli_init():
    pauli = PauliString(spec="IZXYI", coeff=1.0)
    a, b, c = cirq.LineQubit.range(1, 4)
    assert pauli._pauli == cirq.PauliString(
        1.0, cirq.Z(a), cirq.X(b), cirq.Y(c)
    )
    assert str(pauli) == "Z(1)*X(2)*Y(3)"
Beispiel #19
0
def test_pstringcollection():
    x = PauliString(spec="X")
    iz = PauliString(spec="IZ")
    xz = PauliString(spec="XZ")
    xzixx = PauliString(spec="XZIXX")
    pauli_collection = PauliStringCollection(x, iz, xz, xzixx)

    assert pauli_collection.elements == [x, iz, xz, xzixx]
    assert pauli_collection.elements_by_weight == {
        1: Counter((x, iz)),
        2: Counter((xz,)),
        4: Counter((xzixx,)),
    }
    assert pauli_collection.min_weight() == 1
    assert pauli_collection.max_weight() == 4
    assert pauli_collection.support() == {0, 1, 3, 4}
    assert len(pauli_collection) == 4
Beispiel #20
0
def test_observable_expectation_supported_qubits(executor):
    executor = functools.partial(executor, noise_level=(0, ))

    a, b, c = cirq.LineQubit.range(3)
    circuit = cirq.Circuit(cirq.I(a), cirq.X.on(b), cirq.H.on(c))

    # <Z0> = 1.
    obs = Observable(PauliString(spec="Z", support=(0, )))
    assert np.isclose(obs.expectation(circuit, executor), 1.0)

    # <Z1> = -1.
    obs = Observable(PauliString(spec="Z", support=(1, )))
    assert np.isclose(obs.expectation(circuit, executor), -1.0)

    # <Z2> = 0.
    obs = Observable(PauliString(spec="Z", support=(2, )))
    assert np.isclose(obs.expectation(circuit, executor), 0.0, atol=5e-2)
Beispiel #21
0
def test_observable_expectation_one_circuit(n, executor):
    executor = functools.partial(executor, noise_level=(0, ))

    qubits = cirq.LineQubit.range(n)
    obs = Observable(PauliString(spec="X" * n))
    circuit = cirq.Circuit(cirq.H.on_each(qubits))

    expectation = obs.expectation(circuit, executor)
    assert np.isclose(expectation, 1.0)
Beispiel #22
0
def test_observable_measure_in_needs_one_circuit_x():
    pauli1 = PauliString(spec="XI")
    pauli2 = PauliString(spec="IX")
    pauli3 = PauliString(spec="XX")
    obs = Observable(pauli1, pauli2, pauli3)

    qubits = cirq.LineQubit.range(2)
    circuit = cirq.testing.random_circuit(qubits, 3, 1, random_state=1)

    measures_obs_circuits = obs.measure_in(circuit)
    assert len(measures_obs_circuits) == 1

    expected = circuit + xrotation.on_each(*qubits) + cirq.measure(*qubits)
    assert _equal(
        measures_obs_circuits[0],
        expected,
        require_qubit_equality=True,
        require_measurement_equality=True,
    )
Beispiel #23
0
def test_observable_measure_in_needs_two_circuits():
    obs = Observable(PauliString(spec="X"), PauliString(spec="Z"))

    q = cirq.LineQubit(0)
    circuit = cirq.Circuit(cirq.H.on(q))

    measures_obs_circuits = sorted(obs.measure_in(circuit), key=len)
    assert len(measures_obs_circuits) == 2

    expected_circuits = [
        circuit + cirq.measure(q),
        circuit + xrotation.on(q) + cirq.measure(q),
    ]
    for expected, measured in zip(expected_circuits, measures_obs_circuits):
        assert _equal(
            measured,
            expected,
            require_qubit_equality=True,
            require_measurement_equality=True,
        )
Beispiel #24
0
def test_pstring_collection_add():
    pcol = PauliStringCollection()

    a = PauliString(spec="ZZ")
    assert pcol.can_add(a)
    pcol.add(a)
    assert pcol.elements == [a]

    b = PauliString(spec="ZIXZ")
    assert pcol.can_add(b)
    pcol.add(b)
    assert pcol.elements == [a, b]

    assert pcol.can_add(a)
    pcol.add(a)
    assert pcol.elements == [a, a, b]

    c = PauliString(spec="YY")
    assert not pcol.can_add(c)
    with pytest.raises(ValueError, match="Cannot add PauliString"):
        pcol.add(c)
Beispiel #25
0
def test_pauli_measure_in_circuit(support, circuit_type):
    pauli = PauliString(spec="XYZ", support=support, coeff=-0.5)

    names = ("0th", "1st", "2nd", "3rd", "4th", "5th")
    qreg = [cirq.NamedQubit(name) for name in names]
    base_circuit = cirq.Circuit(cirq.H.on_each(qreg))

    if circuit_type == "cirq":

        def convert(circ):
            return circ

    elif circuit_type == "qiskit":
        convert = mitiq_qiskit.to_qiskit
    elif circuit_type == "pyquil":
        convert = mitiq_pyquil.to_pyquil

    circuit = convert(base_circuit)
    measured = pauli.measure_in(circuit)

    qreg = [cirq.NamedQubit(name) for name in names]
    expected = cirq.Circuit(
        # Original circuit.
        base_circuit.all_operations(),
        # Basis rotations.
        xrotation.on(qreg[support[0]]),
        yrotation.on(qreg[support[1]]),
        # Measurements.
        cirq.measure(*[qreg[s] for s in support]),
    )
    if circuit_type == "cirq":
        assert _equal(measured, expected, require_qubit_equality=True)
    else:
        expected = convert(expected)
        if circuit_type == "pyquil":  # Special case with basis rotation order.
            assert set(measured) == set(expected)
        else:
            assert measured == expected
Beispiel #26
0
def test_observable_expectation_from_measurements_one_pauli_string():
    obs = Observable(PauliString(spec="Z"))

    measurements = MeasurementResult([[0], [0], [0], [0], [0], [0], [0], [0],
                                      [0], [0]])
    expectation = obs._expectation_from_measurements([measurements])
    assert np.isclose(expectation, 1.0)

    measurements = MeasurementResult([[1], [1], [1], [1], [1], [1], [1], [1],
                                      [1], [1]])
    expectation = obs._expectation_from_measurements([measurements])
    assert np.isclose(expectation, -1.0)

    measurements = MeasurementResult([[0], [1], [0], [1], [0], [1], [0], [1],
                                      [0], [1]])
    expectation = obs._expectation_from_measurements([measurements])
    assert np.isclose(expectation, 0.0)
Beispiel #27
0
def test_observable_partition_can_be_measured_with():
    n = 10
    nterms = 50
    rng = np.random.RandomState(seed=1)
    obs = Observable(*[
        PauliString(spec=rng.choice(
            ("I", "X", "Y", "Z"),
            size=n,
            replace=True,
            p=(0.7, 0.1, 0.1, 0.1),
        )) for _ in range(nterms)
    ])

    assert obs.nqubits == n
    assert obs.nterms == nterms
    assert obs.ngroups <= nterms

    for pset in obs.groups:
        pauli_list = list(pset.elements)
        for i in range(len(pauli_list) - 1):
            for j in range(i, len(pauli_list)):
                assert pauli_list[i].can_be_measured_with(pauli_list[j])
Beispiel #28
0
def test_matrix():
    assert np.allclose(PauliString(spec="X").matrix(), xmat)
    assert np.allclose(PauliString(spec="Z", coeff=-0.5).matrix(), -0.5 * zmat)
    assert np.allclose(PauliString(spec="ZZ").matrix(), np.kron(zmat, zmat))
    assert np.allclose(PauliString(spec="XZ").matrix(), np.kron(xmat, zmat))
Beispiel #29
0
def test_pauli_eq():
    assert PauliString(spec="Z") == PauliString(spec="Z")
    assert PauliString(spec="X") != PauliString(spec="Z")
    assert PauliString(spec="Z") != PauliString(spec="Z", coeff=-1.0)

    assert PauliString(spec="Z", support=(0,)) != PauliString(
        spec="Z", support=(1,)
    )
    assert PauliString(spec="IZ") == PauliString(spec="Z", support=(1,))
    assert PauliString(spec="XY") == PauliString(spec="YX", support=(1, 0))

    assert {PauliString(spec="Z"), PauliString(spec="Z")} == {
        PauliString(spec="Z")
    }
Beispiel #30
0
def test_pauli_init_empty():
    pauli = PauliString()
    assert pauli.support() == set()
    assert pauli.weight() == 0
    assert np.allclose(pauli.matrix(), [[1]])