예제 #1
0
def test_rowsum():
    # Note: rowsum should not apply on two rows that anti-commute each other.
    t = cirq.CliffordTableau(num_qubits=2)
    # XI * IX ==> XX
    t._rowsum(0, 1)
    assert t.destabilizers()[0] == cirq.DensePauliString('XX', coefficient=1)

    # IX * ZI ==> ZX
    t._rowsum(1, 2)
    assert t.destabilizers()[1] == cirq.DensePauliString('ZX', coefficient=1)

    # ZI * IZ ==> ZZ
    t._rowsum(2, 3)
    assert t.stabilizers()[0] == cirq.DensePauliString('ZZ', coefficient=1)

    t = cirq.CliffordTableau(num_qubits=2)
    _S(t, 0)  # Table now are [YI, IX, ZI, IZ]
    _CNOT(t, 0, 1)  # Table now are [YX, IX, ZI, ZZ]

    # YX * ZZ ==> XY
    t._rowsum(0, 3)
    assert t.destabilizers()[0] == cirq.DensePauliString('XY', coefficient=1)

    # ZZ * XY ==> YX
    t._rowsum(3, 0)
    assert t.stabilizers()[1] == cirq.DensePauliString('YX', coefficient=1)
예제 #2
0
def test_destabilizers():
    # Note: Like stablizers, the destabilizers are not unique for one state, too.
    # We just use the one produced by the tableau algorithm.
    # Under the clifford tableau algorithm, there are several properties that the
    # destablizers have to satisfy:
    #    1. destablizers[i] anti-commutes with stablizers[i]
    #    2. destablizers[i] commutes with destablizers[j] for j!= i
    #    3. destablizers[i] commutes with stablizers[j] for j!= i

    # 1. Final state is |1>: Stabalized by -Z.
    t = cirq.CliffordTableau(num_qubits=1, initial_state=1)
    destabilizers = t.destabilizers()
    assert len(destabilizers) == 1
    assert destabilizers[0] == cirq.DensePauliString('X', coefficient=1)

    # 2. EPR pair -- Final state is |00> + |11>: Stabalized by XX and ZZ.
    t = cirq.CliffordTableau(num_qubits=2)
    _H(t, 0)
    _CNOT(t, 0, 1)
    destabilizers = t.destabilizers()
    assert len(destabilizers) == 2
    assert destabilizers[0] == cirq.DensePauliString('ZI', coefficient=1)
    assert destabilizers[1] == cirq.DensePauliString('IX', coefficient=1)

    # 3. Uniform distribution: Stablized by XI and IX.
    t = cirq.CliffordTableau(num_qubits=2)
    _H(t, 0)
    _H(t, 1)
    destabilizers = t.destabilizers()
    assert len(destabilizers) == 2
    assert destabilizers[0] == cirq.DensePauliString('ZI', coefficient=1)
    assert destabilizers[1] == cirq.DensePauliString('IZ', coefficient=1)
예제 #3
0
def test_stabilizers():
    # Note: the stabilizers are not unique for one state. We just use the one
    # produced by the tableau algorithm.
    # 1. Final state is |1>: Stabalized by -Z.
    t = cirq.CliffordTableau(num_qubits=1, initial_state=1)
    stabilizers = t.stabilizers()
    assert len(stabilizers) == 1
    assert stabilizers[0] == cirq.DensePauliString('Z', coefficient=-1)

    # 2. EPR pair -- Final state is |00> + |11>: Stabalized by XX and ZZ.
    t = cirq.CliffordTableau(num_qubits=2)
    _H(t, 0)
    _CNOT(t, 0, 1)
    stabilizers = t.stabilizers()
    assert len(stabilizers) == 2
    assert stabilizers[0] == cirq.DensePauliString('XX', coefficient=1)
    assert stabilizers[1] == cirq.DensePauliString('ZZ', coefficient=1)

    # 3. Uniform distribution: Stablized by XI and IX.
    t = cirq.CliffordTableau(num_qubits=2)
    _H(t, 0)
    _H(t, 1)
    stabilizers = t.stabilizers()
    assert len(stabilizers) == 2
    assert stabilizers[0] == cirq.DensePauliString('XI', coefficient=1)
    assert stabilizers[1] == cirq.DensePauliString('IX', coefficient=1)
def test_bad_observable_raises():
    with pytest.raises(ValueError, match='Pauli observable .* is empty'):
        _ = cirq.PauliMeasurementGate([])

    with pytest.raises(ValueError, match=r'Pauli observable .* must be Iterable\[`cirq.Pauli`\]'):
        _ = cirq.PauliMeasurementGate([cirq.I, cirq.X, cirq.Y])

    with pytest.raises(ValueError, match=r'Pauli observable .* must be Iterable\[`cirq.Pauli`\]'):
        _ = cirq.PauliMeasurementGate(cirq.DensePauliString('XYZI'))

    with pytest.raises(ValueError, match=r'must have coefficient \+1/-1.'):
        _ = cirq.PauliMeasurementGate(cirq.DensePauliString('XYZ', coefficient=1j))
예제 #5
0
def test_gate_on_operation_besides_gate_operation():
    a, b = cirq.LineQubit.range(2)

    op = -1j * cirq.X(a) * cirq.Y(b)
    assert isinstance(op.gate, cirq.DensePauliString)
    assert op.gate == -1j * cirq.DensePauliString('XY')
    assert not isinstance(op.gate, cirq.XPowGate)
def test_init(observable, key):
    g = cirq.PauliMeasurementGate(observable, key)
    assert g.num_qubits() == len(observable)
    assert g.key == 'a'
    assert g.mkey == cirq.MeasurementKey('a')
    assert g._observable == cirq.DensePauliString(observable)
    assert cirq.qid_shape(g) == (2,) * len(observable)
def test_gate_eq_ne_hash():
    eq = cirq.testing.EqualsTester()
    dps_xyx = cirq.DensePauliString('XYX')
    eq.make_equality_group(
        lambda: cirq.PauliStringPhasorGate(dps_empty, exponent_neg=0.5),
        lambda: cirq.PauliStringPhasorGate(dps_empty, exponent_neg=-1.5),
        lambda: cirq.PauliStringPhasorGate(dps_empty, exponent_neg=2.5),
    )
    eq.make_equality_group(
        lambda: cirq.PauliStringPhasorGate(-dps_empty, exponent_neg=-0.5))
    eq.add_equality_group(cirq.PauliStringPhasorGate(dps_xyz),
                          cirq.PauliStringPhasorGate(dps_xyz, exponent_neg=1))
    eq.add_equality_group(cirq.PauliStringPhasorGate(-dps_xyz, exponent_neg=1))
    eq.add_equality_group(cirq.PauliStringPhasorGate(dps_xyx),
                          cirq.PauliStringPhasorGate(dps_xyx, exponent_neg=1))
    eq.add_equality_group(cirq.PauliStringPhasorGate(dps_xy),
                          cirq.PauliStringPhasorGate(dps_xy, exponent_neg=1))
    eq.add_equality_group(cirq.PauliStringPhasorGate(dps_yx),
                          cirq.PauliStringPhasorGate(dps_yx, exponent_neg=1))
    eq.add_equality_group(cirq.PauliStringPhasorGate(-dps_xyx, exponent_neg=1))
    eq.add_equality_group(cirq.PauliStringPhasorGate(dps_xyx,
                                                     exponent_neg=0.5))
    eq.add_equality_group(
        cirq.PauliStringPhasorGate(-dps_xyx, exponent_neg=-0.5))
    eq.add_equality_group(
        cirq.PauliStringPhasorGate(dps_xyz, exponent_neg=sympy.Symbol('a')))
예제 #8
0
def test_cz_act_on_tableau():
    with pytest.raises(TypeError, match="Failed to act"):
        cirq.act_on(cirq.CZ, DummyActOnArgs(), qubits=())
    original_tableau = cirq.CliffordTableau(num_qubits=5, initial_state=31)

    args = cirq.ActOnCliffordTableauArgs(
        tableau=original_tableau.copy(),
        qubits=cirq.LineQubit.range(5),
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )

    cirq.act_on(cirq.CZ, args, cirq.LineQubit.range(2), allow_decompose=False)
    assert args.log_of_measurement_results == {}
    assert args.tableau.stabilizers() == [
        cirq.DensePauliString('ZIIII', coefficient=-1),
        cirq.DensePauliString('IZIII', coefficient=-1),
        cirq.DensePauliString('IIZII', coefficient=-1),
        cirq.DensePauliString('IIIZI', coefficient=-1),
        cirq.DensePauliString('IIIIZ', coefficient=-1),
    ]
    assert args.tableau.destabilizers() == [
        cirq.DensePauliString('XZIII', coefficient=1),
        cirq.DensePauliString('ZXIII', coefficient=1),
        cirq.DensePauliString('IIXII', coefficient=1),
        cirq.DensePauliString('IIIXI', coefficient=1),
        cirq.DensePauliString('IIIIX', coefficient=1),
    ]

    cirq.act_on(cirq.CZ, args, cirq.LineQubit.range(2), allow_decompose=False)
    assert args.log_of_measurement_results == {}
    assert args.tableau == original_tableau

    cirq.act_on(cirq.CZ**4,
                args,
                cirq.LineQubit.range(2),
                allow_decompose=False)
    assert args.log_of_measurement_results == {}
    assert args.tableau == original_tableau

    foo = sympy.Symbol('foo')
    with pytest.raises(TypeError, match="Failed to act action on state"):
        cirq.act_on(cirq.CZ**foo, args, cirq.LineQubit.range(2))

    with pytest.raises(TypeError, match="Failed to act action on state"):
        cirq.act_on(cirq.CZ**1.5, args, cirq.LineQubit.range(2))
예제 #9
0
def test_parameterizable(resolve_fn):
    t = sympy.Symbol('t')
    x = cirq.DensePauliString('X')
    assert not cirq.is_parameterized(x)
    assert not cirq.is_parameterized(x * 2)
    assert cirq.is_parameterized(x * t)
    assert resolve_fn(x * t, {'t': 2}) == x * 2
    assert resolve_fn(x * 3, {'t': 2}) == x * 3
예제 #10
0
def test_more_unitary_gate_conversions():
    for p in [1, 1j, -1, -1j]:
        assert_unitary_gate_converts_correctly(p *
                                               cirq.DensePauliString("IXYZ"))
        assert_unitary_gate_converts_correctly(
            (p * cirq.DensePauliString("IXYZ")).controlled(1))

    a, b = cirq.LineQubit.range(2)
    c, _ = cirq_circuit_to_stim_data(
        cirq.Circuit(cirq.H(a), cirq.CNOT(a, b), cirq.measure(a, b),
                     cirq.reset(a)))
    assert (str(c).strip() == """
H 0
CX 0 1
M 0 1
R 0
    """.strip())
예제 #11
0
def test_init():
    mask = np.array([0, 3, 1, 2], dtype=np.uint8)
    p = cirq.DensePauliString(coefficient=2, pauli_mask=mask)
    m = cirq.MutableDensePauliString(coefficient=3, pauli_mask=mask)
    assert p.coefficient == 2
    assert m.coefficient == 3
    np.testing.assert_allclose(p.pauli_mask, [0, 3, 1, 2])
    np.testing.assert_allclose(m.pauli_mask, [0, 3, 1, 2])

    # The non-mutable initializer makes a copy.
    assert m.pauli_mask is mask
    assert p.pauli_mask is not mask
    mask[:] = 0
    assert m.pauli_mask[2] == 0
    assert p.pauli_mask[2] == 1

    # Copies and converts non-uint8 arrays.
    p2 = cirq.DensePauliString(coefficient=2, pauli_mask=[1, 2, 3])
    m2 = cirq.DensePauliString(coefficient=2, pauli_mask=[1, 2, 3])
    assert p2.pauli_mask.dtype == m2.pauli_mask.dtype == np.uint8
    assert list(p2.pauli_mask) == list(m2.pauli_mask) == [1, 2, 3]

    # Mixed types.
    assert cirq.DensePauliString([1, 'X',
                                  cirq.X]) == cirq.DensePauliString('XXX')
    assert list(cirq.DensePauliString('XXX')) == [cirq.X, cirq.X, cirq.X]
    with pytest.raises(TypeError, match='Expected a cirq.PAULI_GATE_LIKE'):
        _ = cirq.DensePauliString([object()])
예제 #12
0
def test_setters_deprecated():
    gate = cirq.DensePauliString('X')
    mask = np.array([0, 3, 1, 2], dtype=np.uint8)
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.pauli_mask = mask
    assert gate.pauli_mask is mask
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.coefficient = -1
    assert gate.coefficient == -1
예제 #13
0
def test_symbolic():
    t = sympy.Symbol('t')
    r = sympy.Symbol('r')
    p = cirq.MutableDensePauliString('XYZ', coefficient=t)
    assert p * r == cirq.DensePauliString('XYZ', coefficient=t * r)
    p *= r
    assert p == cirq.MutableDensePauliString('XYZ', coefficient=t * r)
    p /= r
    assert p == cirq.MutableDensePauliString('XYZ', coefficient=t)
예제 #14
0
def test_cx_act_on():
    with pytest.raises(TypeError, match="Failed to act"):
        cirq.act_on(cirq.Y, object())
    original_tableau = cirq.CliffordTableau(num_qubits=5, initial_state=31)

    args = cirq.ActOnCliffordTableauArgs(
        tableau=original_tableau.copy(),
        axes=[0, 1],
        prng=np.random.RandomState(),
        log_of_measurement_results={},
    )

    cirq.act_on(cirq.CX, args, allow_decompose=False)
    assert args.log_of_measurement_results == {}
    assert (args.tableau.stabilizers() == [
        cirq.DensePauliString('ZIIII', coefficient=-1),
        cirq.DensePauliString('ZZIII', coefficient=-1),
        cirq.DensePauliString('IIZII', coefficient=-1),
        cirq.DensePauliString('IIIZI', coefficient=-1),
        cirq.DensePauliString('IIIIZ', coefficient=-1)
    ])
    assert (args.tableau.destabilizers() == [
        cirq.DensePauliString('XXIII', coefficient=1),
        cirq.DensePauliString('IXIII', coefficient=1),
        cirq.DensePauliString('IIXII', coefficient=1),
        cirq.DensePauliString('IIIXI', coefficient=1),
        cirq.DensePauliString('IIIIX', coefficient=1)
    ])

    cirq.act_on(cirq.CX, args, allow_decompose=False)
    assert args.log_of_measurement_results == {}
    assert args.tableau == original_tableau

    cirq.act_on(cirq.CX**4, args, allow_decompose=False)
    assert args.log_of_measurement_results == {}
    assert args.tableau == original_tableau

    foo = sympy.Symbol('foo')
    with pytest.raises(TypeError, match="Failed to act action on state"):
        cirq.act_on(cirq.CX**foo, args)

    with pytest.raises(TypeError, match="Failed to act action on state"):
        cirq.act_on(cirq.CX**1.5, args)
예제 #15
0
def test_sparse():
    a, b, c = cirq.LineQubit.range(3)
    p = -cirq.DensePauliString('XYZ')
    assert p.sparse() == cirq.PauliString(-1, cirq.X(a), cirq.Y(b), cirq.Z(c))
    assert p.sparse([c, b, a]) == cirq.PauliString(-1, cirq.X(c), cirq.Y(b),
                                                   cirq.Z(a))
    with pytest.raises(ValueError, match='number of qubits'):
        _ = p.sparse([])
    with pytest.raises(ValueError, match='number of qubits'):
        _ = p.sparse(cirq.GridQubit.rect(2, 2))
예제 #16
0
def test_json_dict():
    t = cirq.CliffordTableau._from_json_dict_(n=1, rs=[0, 0], xs=[[1], [0]], zs=[[0], [1]])
    assert t.destabilizers()[0] == cirq.DensePauliString('X', coefficient=1)
    assert t.stabilizers()[0] == cirq.DensePauliString('Z', coefficient=1)
    json_dict = t._json_dict_()
    except_json_dict = {
        'cirq_type': 'CliffordTableau',
        'n': 1,
        'rs': [False, False],
        'xs': [[True], [False]],
        'zs': [[False], [True]],
    }
    assert list(json_dict.keys()) == list(except_json_dict.keys())
    for k, v in except_json_dict.items():
        assert k in json_dict
        if isinstance(v, list):
            assert all(json_dict[k] == v)
        else:
            assert json_dict[k] == v
예제 #17
0
def test_item_immutable():
    p = -cirq.DensePauliString('XYIZ')
    assert p[-1] == cirq.Z
    assert p[0] == cirq.X
    assert p[1] == cirq.Y
    assert p[2] == cirq.I
    assert p[3] == cirq.Z

    with pytest.raises(TypeError):
        _ = p["test"]
    with pytest.raises(IndexError):
        _ = p[4]
    with pytest.raises(TypeError):
        p[2] = cirq.X
    with pytest.raises(TypeError):
        p[:] = p

    assert p[:] == abs(p)
    assert p[1:] == cirq.DensePauliString('YIZ')
    assert p[::2] == cirq.DensePauliString('XI')
예제 #18
0
def test_gate_on_operation_besides_gate_operation():
    a, b = cirq.LineQubit.range(2)

    assert cirq.op_gate_of_type(
        -1j * cirq.X(a) * cirq.Y(b),
        cirq.DensePauliString) == -1j * cirq.DensePauliString('XY')

    assert cirq.op_gate_isinstance(-1j * cirq.X(a) * cirq.Y(b),
                                   cirq.DensePauliString)

    assert not cirq.op_gate_isinstance(-1j * cirq.X(a) * cirq.Y(b),
                                       cirq.XPowGate)
예제 #19
0
def test_copy():
    p = -cirq.DensePauliString('XYZ')
    m = cirq.MutableDensePauliString('XYZ', coefficient=-1)

    # Immutable copies.
    assert p.copy() is p
    assert p.frozen() is p
    assert p.mutable_copy() is not p
    assert p.mutable_copy() == m

    # Mutable copies.
    assert m.copy() is not m
    assert m.copy() == m
    assert m.frozen() == p
    assert m.mutable_copy() is not m
    assert m.mutable_copy() == m

    # Copy immutable with modifications.
    assert p.copy(coefficient=-1) is p
    assert p.copy(coefficient=-2) is not p
    assert p.copy(coefficient=-2) == -2 * cirq.DensePauliString('XYZ')
    assert p.copy(coefficient=-2,
                  pauli_mask=[3]) == -2 * cirq.DensePauliString('Z')

    # Copy mutable with modifications.
    assert m.copy(coefficient=-1) is not m
    assert m.copy(coefficient=-2) is not m
    assert m.copy(coefficient=-2) == cirq.MutableDensePauliString(
        'XYZ', coefficient=-2)
    assert m.copy(coefficient=-2,
                  pauli_mask=[2]) == cirq.MutableDensePauliString(
                      'Y', coefficient=-2)

    # Aliasing of the mask attribute when copying with modifications.
    mask = np.array([1, 2, 3], dtype=np.uint8)
    assert cirq.MutableDensePauliString(mask).copy().pauli_mask is not mask
    assert cirq.MutableDensePauliString(mask).copy(
        pauli_mask=mask).pauli_mask is mask
    assert cirq.MutableDensePauliString('XYZ').copy(
        pauli_mask=mask).pauli_mask is mask
def test_gate_str():
    gate = cirq.PauliStringPhasorGate(
        cirq.DensePauliString('ZYX', coefficient=+1))**0.5
    assert str(gate) == '(+ZYX)**0.5'

    gate = cirq.PauliStringPhasorGate(
        cirq.DensePauliString('ZYX', coefficient=+1))**-0.5
    assert str(gate) == '(+ZYX)**-0.5'

    gate = cirq.PauliStringPhasorGate(
        cirq.DensePauliString('ZYX', coefficient=-1))**-0.5
    assert str(gate) == '(+ZYX)**0.5'

    gate = cirq.PauliStringPhasorGate(cirq.DensePauliString('ZYX'),
                                      exponent_pos=0.5,
                                      exponent_neg=-0.5)
    assert str(gate) == 'exp(iπ0.5*+ZYX)'

    gate = (cirq.PauliStringPhasorGate(cirq.DensePauliString('ZYX'),
                                       exponent_pos=0.5,
                                       exponent_neg=-0.5)**-0.5)
    assert str(gate) == 'exp(-iπ0.25*+ZYX)'
예제 #21
0
def test_parameterizable(resolve_fn):
    t = sympy.Symbol('t')
    x = cirq.DensePauliString('X')
    xt = x * t
    x2 = x * 2
    q = cirq.LineQubit(0)
    assert not cirq.is_parameterized(x)
    assert not cirq.is_parameterized(x * 2)
    assert cirq.is_parameterized(x * t)
    assert resolve_fn(xt, {'t': 2}) == x2
    assert resolve_fn(x * 3, {'t': 2}) == x * 3
    assert resolve_fn(xt(q), {'t': 2}).gate == x2
    assert resolve_fn(xt(q).gate, {'t': 2}) == x2
예제 #22
0
def test_setters_deprecated():
    gate = cirq.PauliMeasurementGate(cirq.DensePauliString("Z", coefficient=+1), key='m')
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.key = 'n'
    assert gate.key == 'n'
    assert gate.mkey == cirq.MeasurementKey('n')
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.key = cirq.MeasurementKey('o')
    assert gate.key == 'o'
    assert gate.mkey == cirq.MeasurementKey('o')
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.mkey = cirq.MeasurementKey('p')
    assert gate.key == 'p'
    assert gate.mkey == cirq.MeasurementKey('p')
예제 #23
0
def test_immutable_eq():
    eq = cirq.testing.EqualsTester()

    # Immutables
    eq.make_equality_group(
        lambda: cirq.DensePauliString(coefficient=2, pauli_mask=[1]))
    eq.add_equality_group(
        lambda: cirq.DensePauliString(coefficient=3, pauli_mask=[1]))
    eq.make_equality_group(
        lambda: cirq.DensePauliString(coefficient=2, pauli_mask=[]))
    eq.add_equality_group(
        lambda: cirq.DensePauliString(coefficient=2, pauli_mask=[0]))
    eq.make_equality_group(
        lambda: cirq.DensePauliString(coefficient=2, pauli_mask=[2]))

    # Mutables
    eq.make_equality_group(
        lambda: cirq.MutableDensePauliString(coefficient=2, pauli_mask=[1]))
    eq.add_equality_group(
        lambda: cirq.MutableDensePauliString(coefficient=3, pauli_mask=[1]))
    eq.make_equality_group(
        lambda: cirq.MutableDensePauliString(coefficient=2, pauli_mask=[]))
    eq.make_equality_group(
        lambda: cirq.MutableDensePauliString(coefficient=2, pauli_mask=[2]))
def test_gate_init():
    a = cirq.LineQubit(0)
    with pytest.raises(ValueError, match='eigenvalues'):
        _ = cirq.PauliStringPhasorGate(1j * cirq.X(a))

    v1 = cirq.PauliStringPhasorGate(cirq.DensePauliString('X', coefficient=-1),
                                    exponent_neg=0.25,
                                    exponent_pos=-0.5)
    assert v1.dense_pauli_string == dps_x
    assert v1.exponent_neg == -0.5
    assert v1.exponent_pos == 0.25

    v2 = cirq.PauliStringPhasorGate(dps_x,
                                    exponent_neg=0.75,
                                    exponent_pos=-0.125)
    assert v2.dense_pauli_string == dps_x
    assert v2.exponent_neg == 0.75
    assert v2.exponent_pos == -0.125
예제 #25
0
def test_pauli():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(
        cirq.PauliMeasurementGate(cirq.DensePauliString('Y'), key='a').on(q0),
        cirq.X(q1).with_classical_controls('a'),
        cirq.measure(q1, key='b'),
    )
    deferred = cirq.defer_measurements(circuit)
    q_ma = _MeasurementQid('a', q0)
    cirq.testing.assert_same_circuits(
        cirq.unroll_circuit_op(deferred),
        cirq.Circuit(
            cirq.SingleQubitCliffordGate.X_sqrt(q0),
            cirq.CX(q0, q_ma),
            (cirq.SingleQubitCliffordGate.X_sqrt(q0)**-1),
            cirq.Moment(cirq.CX(q_ma, q1)),
            cirq.measure(q_ma, key='a'),
            cirq.measure(q1, key='b'),
        ),
    )
예제 #26
0
    def _row_to_dense_pauli(self, i: int) -> DensePauliString:
        """
        Args:
            i: index of the row in the tableau.
        Returns:
            A DensePauliString representing the row. The length of the string
            is equal to the total number of qubits and each character
            represents the effective single Pauli operator on that qubit. The
            overall phase is captured in the coefficient.
        """
        coefficient = -1 if self.rs[i] else 1
        pauli_mask = ""

        for k in range(self.n):
            if self.xs[i, k] & (not self.zs[i, k]):
                pauli_mask += "X"
            elif (not self.xs[i, k]) & self.zs[i, k]:
                pauli_mask += "Z"
            elif self.xs[i, k] & self.zs[i, k]:
                pauli_mask += "Y"
            else:
                pauli_mask += "I"
        return cirq.DensePauliString(pauli_mask, coefficient=coefficient)
def test_gate_on():
    q = cirq.LineQubit(0)
    g1 = cirq.PauliStringPhasorGate(cirq.DensePauliString('X', coefficient=-1),
                                    exponent_neg=0.25,
                                    exponent_pos=-0.5)

    op1 = g1.on(q)
    assert isinstance(op1, cirq.PauliStringPhasor)
    assert op1.qubits == (q, )
    assert op1.gate == g1
    assert op1.pauli_string == dps_x.on(q)
    assert op1.exponent_neg == -0.5
    assert op1.exponent_pos == 0.25

    g2 = cirq.PauliStringPhasorGate(dps_x,
                                    exponent_neg=0.75,
                                    exponent_pos=-0.125)
    op2 = g2.on(q)
    assert isinstance(op2, cirq.PauliStringPhasor)
    assert op2.qubits == (q, )
    assert op2.gate == g2
    assert op2.pauli_string == dps_x.on(q)
    assert op2.exponent_neg == 0.75
    assert op2.exponent_pos == -0.125
예제 #28
0
def test_protocols():
    t = sympy.Symbol('t')

    cirq.testing.assert_implements_consistent_protocols(
        cirq.DensePauliString('Y'))
    cirq.testing.assert_implements_consistent_protocols(
        -cirq.DensePauliString('Z'))
    cirq.testing.assert_implements_consistent_protocols(
        1j * cirq.DensePauliString('X'))
    cirq.testing.assert_implements_consistent_protocols(
        2 * cirq.DensePauliString('X'))
    cirq.testing.assert_implements_consistent_protocols(
        t * cirq.DensePauliString('XYIZ'))
    cirq.testing.assert_implements_consistent_protocols(
        cirq.DensePauliString('XYIZ', coefficient=t + 2))
    cirq.testing.assert_implements_consistent_protocols(
        -cirq.DensePauliString('XYIZ'))
    cirq.testing.assert_implements_consistent_protocols(
        cirq.MutableDensePauliString('XYIZ', coefficient=-1))

    # Unitarity and shape.
    assert cirq.has_unitary(1j * cirq.DensePauliString('X'))
    assert not cirq.has_unitary(2j * cirq.DensePauliString('X'))
    assert not cirq.has_unitary(cirq.DensePauliString('X') * t)
    p = -cirq.DensePauliString('XYIZ')
    assert cirq.num_qubits(p) == len(p) == 4

    # Parameterization.
    x = cirq.DensePauliString('X')
    assert not cirq.is_parameterized(x)
    assert not cirq.is_parameterized(x * 2)
    assert cirq.is_parameterized(x * t)
    assert cirq.resolve_parameters(x * t, {'t': 2}) == x * 2
    assert cirq.resolve_parameters(x * 3, {'t': 2}) == x * 3
예제 #29
0
def test_pos_neg():
    p = 1j * cirq.DensePauliString('XYZ')
    assert +p == p
    assert -p == -1 * p
예제 #30
0
@pytest.mark.parametrize(
    'key',
    ['q0_1_0', cirq.MeasurementKey(name='q0_1_0'), cirq.MeasurementKey(path=('a', 'b'), name='c')],
)
def test_eval_repr(key):
    # Basic safeguard against repr-inequality.
    op = cirq.GateOperation(
        gate=cirq.PauliMeasurementGate([cirq.X, cirq.Y], key),
        qubits=[cirq.GridQubit(0, 1), cirq.GridQubit(1, 1)],
    )
    cirq.testing.assert_equivalent_repr(op)
    assert cirq.is_measurement(op)
    assert cirq.measurement_key_name(op) == str(key)


@pytest.mark.parametrize('observable', [[cirq.X], [cirq.Y, cirq.Z], cirq.DensePauliString('XYZ')])
@pytest.mark.parametrize('key', ['a', cirq.MeasurementKey('a')])
def test_init(observable, key):
    g = cirq.PauliMeasurementGate(observable, key)
    assert g.num_qubits() == len(observable)
    assert g.key == 'a'
    assert g.mkey == cirq.MeasurementKey('a')
    assert g._observable == cirq.DensePauliString(observable)
    assert cirq.qid_shape(g) == (2,) * len(observable)


def test_measurement_has_unitary_returns_false():
    gate = cirq.PauliMeasurementGate([cirq.X], 'a')
    assert not cirq.has_unitary(gate)