Example #1
0
def test_add_cast_include_subtypes():

    e = cirq.Extensions()
    e.add_cast(desired_type=Cousin,
               actual_type=Child,
               conversion=lambda _: 'boo',
               also_add_inherited_conversions=True)
    e2 = cirq.Extensions()
    e2.add_cast(desired_type=Cousin,
                actual_type=Child,
                conversion=lambda _: 'boo',
                also_add_inherited_conversions=False)

    c = Child()
    assert e.try_cast(Child, c) is c
    assert e.try_cast(Parent, c) is c
    assert e.try_cast(Grandparent, c) is c
    assert e.try_cast(object, c) is c
    assert e.try_cast(Aunt, c) == 'boo'
    assert e.try_cast(Cousin, c) == 'boo'

    assert e2.try_cast(Child, c) is c
    assert e2.try_cast(Parent, c) is c
    assert e2.try_cast(Grandparent, c) is c
    assert e2.try_cast(object, c) is c
    assert e2.try_cast(Aunt, c) is None
    assert e2.try_cast(Cousin, c) == 'boo'
def test_supports_extensions():

    class DummyGate(cirq.Gate):
        pass

    ext = cirq.Extensions()
    ext.add_cast(cirq.BoundedEffect, DummyGate, lambda e: cirq.Z**0.00001)
    big_ext = cirq.Extensions()
    big_ext.add_cast(cirq.BoundedEffect, DummyGate, lambda e: cirq.Z**0.75)
    with_ext = cirq.DropNegligible(tolerance=0.001, extensions=ext)
    with_big_ext = cirq.DropNegligible(tolerance=0.001, extensions=big_ext)
    without_ext = cirq.DropNegligible(tolerance=0.001)

    a = cirq.NamedQubit('a')
    circuit = cirq.Circuit.from_ops(DummyGate().on(a))
    cleared = cirq.Circuit([cirq.Moment()])
    assert_optimizes(without_ext,
                     initial_circuit=circuit,
                     expected_circuit=circuit)
    assert_optimizes(with_ext,
                     initial_circuit=circuit,
                     expected_circuit=cleared)
    assert_optimizes(with_big_ext,
                     initial_circuit=circuit,
                     expected_circuit=circuit)
Example #3
0
def test_add_cast_redundant_including_subtypes():
    o1 = Cousin()
    o2 = Cousin()
    o3 = Cousin()

    e = cirq.Extensions()
    e.add_cast(desired_type=Aunt,
               actual_type=Child,
               conversion=lambda _: o1,
               also_add_inherited_conversions=True,
               overwrite_existing=False)
    with pytest.raises(ValueError):
        e.add_cast(desired_type=Cousin,
                   actual_type=Child,
                   conversion=lambda _: o2,
                   also_add_inherited_conversions=True,
                   overwrite_existing=False)
    assert e.try_cast(Aunt, Child()) is o1
    assert e.try_cast(Cousin, Child()) is None
    e.add_cast(desired_type=Cousin,
               actual_type=Child,
               conversion=lambda _: o3,
               also_add_inherited_conversions=True,
               overwrite_existing=True)
    assert e.try_cast(Aunt, Child()) is o3
    assert e.try_cast(Cousin, Child()) is o3
Example #4
0
def test_runtime_types_of_rot_gates():
    for gate_type in [
            cirq.Rot11Gate, cirq.RotXGate, cirq.RotYGate, cirq.RotZGate
    ]:
        ext = cirq.Extensions()

        p = gate_type(half_turns=Symbol('a'))
        assert p.try_cast_to(cirq.KnownMatrix, ext) is None
        assert p.try_cast_to(cirq.ExtrapolatableEffect, ext) is None
        assert p.try_cast_to(cirq.ReversibleEffect, ext) is None
        assert p.try_cast_to(cirq.BoundedEffect, ext) is p
        with pytest.raises(ValueError):
            _ = p.matrix()
        with pytest.raises(ValueError):
            _ = p.extrapolate_effect(2)
        with pytest.raises(ValueError):
            _ = p.inverse()

        c = gate_type(half_turns=0.5)
        assert c.try_cast_to(cirq.KnownMatrix, ext) is c
        assert c.try_cast_to(cirq.ExtrapolatableEffect, ext) is c
        assert c.try_cast_to(cirq.ReversibleEffect, ext) is c
        assert c.try_cast_to(cirq.BoundedEffect, ext) is c
        assert c.matrix() is not None
        assert c.extrapolate_effect(2) is not None
        assert c.inverse() is not None
Example #5
0
def test_try_cast_to():
    ext = cirq.Extensions()

    # Already of the given type.
    assert CRestricted.try_cast_to(cirq.Gate, ext) is not None
    assert CRestricted.try_cast_to(cirq.ControlledGate, ext) is not None
    assert CY.try_cast_to(cirq.Gate, ext) is not None
    assert CY.try_cast_to(cirq.ControlledGate, ext) is not None

    # Unsupported sub features.
    assert CCH.try_cast_to(cirq.CompositeGate, ext) is None
    assert CCH.try_cast_to(cirq.EigenGate, ext) is None
    assert CY.try_cast_to(cirq.CompositeGate, ext) is None
    assert CY.try_cast_to(cirq.EigenGate, ext) is None
    assert CRestricted.try_cast_to(cirq.EigenGate, ext) is None
    assert CRestricted.try_cast_to(cirq.CompositeGate, ext) is None

    # Supported sub features that are not present on sub gate.
    assert CRestricted.try_cast_to(cirq.ReversibleEffect, ext) is None
    assert CRestricted.try_cast_to(cirq.ExtrapolatableEffect, ext) is None
    assert CRestricted.try_cast_to(cirq.TextDiagrammable, ext) is None
    assert CRestricted.try_cast_to(cirq.BoundedEffect, ext) is None
    assert CRestricted.try_cast_to(cirq.ParameterizableEffect, ext) is None

    # Supported sub features that are present on sub gate.
    assert CY.try_cast_to(cirq.ReversibleEffect, ext) is not None
    assert CY.try_cast_to(cirq.ExtrapolatableEffect, ext) is not None
    assert CY.try_cast_to(cirq.TextDiagrammable, ext) is not None
    assert CY.try_cast_to(cirq.BoundedEffect, ext) is not None
    assert CY.try_cast_to(cirq.ParameterizableEffect, ext) is not None
Example #6
0
def test_init():
    ext = cirq.Extensions()
    gate = cirq.ControlledGate(cirq.Z, ext)
    assert gate.default_extensions is ext
    assert gate.sub_gate is cirq.Z

    assert cirq.ControlledGate(cirq.X).default_extensions is None
Example #7
0
def test_try_cast_to():
    ext = cirq.Extensions()

    # Already of the given type.
    assert CRestricted.try_cast_to(cirq.Gate, ext) is not None
    assert CRestricted.try_cast_to(cirq.ControlledGate, ext) is not None
    assert CY.try_cast_to(cirq.Gate, ext) is not None
    assert CY.try_cast_to(cirq.ControlledGate, ext) is not None

    # Unsupported sub features.
    assert CCH.try_cast_to(cirq.CompositeGate, ext) is None
    assert CCH.try_cast_to(cirq.EigenGate, ext) is None
    assert CY.try_cast_to(cirq.CompositeGate, ext) is None
    assert CY.try_cast_to(cirq.EigenGate, ext) is None
    assert CRestricted.try_cast_to(cirq.EigenGate, ext) is None
    assert CRestricted.try_cast_to(cirq.CompositeGate, ext) is None

    # Supported sub features that are not present on sub gate.
    assert cirq.inverse(CRestricted, None) is None
    assert cirq.inverse(CY) == CY**-1 == CY
    assert CRestricted.try_cast_to(cirq.ExtrapolatableEffect, ext) is None
    assert CRestricted.try_cast_to(cirq.BoundedEffect, ext) is None

    # Supported sub features that are present on sub gate.
    assert cirq.inverse(CY, None) is not None
    assert CY.try_cast_to(cirq.ExtrapolatableEffect, ext) is not None
    assert CY.try_cast_to(cirq.BoundedEffect, ext) is not None
Example #8
0
def test_wrap():
    e = cirq.Extensions({DesiredType: {OtherType: WrapType}})
    o = OtherType()
    w = e.cast(DesiredType, o)
    assert w.make() == 'wrap'
    assert isinstance(w, WrapType)
    assert w.other is o
Example #9
0
def test_add_cast():
    e = cirq.Extensions()
    d = DesiredType()

    assert e.try_cast(DesiredType, UnrelatedType()) is None
    e.add_cast(desired_type=DesiredType,
               actual_type=UnrelatedType,
               conversion=lambda _: d)
    assert e.try_cast(DesiredType, UnrelatedType()) is d
Example #10
0
def test_partial_reflection_as_self_inverse():
    ex = cirq.Extensions()

    h0 = DummyGate(half_turns=0)
    h1 = DummyGate(half_turns=1)
    ha = DummyGate(half_turns=cirq.Symbol('a'))
    assert ex.try_cast(cirq.ReversibleEffect, h0) is h0
    assert ex.try_cast(cirq.ReversibleEffect, h1) is h1
    assert ex.try_cast(cirq.ReversibleEffect, ha) is None
Example #11
0
def test_try_cast_to():
    class Dummy: pass
    op = PauliStringPhasor(cirq.PauliString({}))
    ext = cirq.Extensions()
    assert not op.try_cast_to(cirq.CompositeOperation, ext) is None
    assert not op.try_cast_to(cirq.BoundedEffect, ext) is None
    assert not op.try_cast_to(cirq.ExtrapolatableEffect, ext) is None
    assert not op.try_cast_to(cirq.ReversibleEffect, ext) is None
    assert op.try_cast_to(Dummy, ext) is None

    op = PauliStringPhasor(cirq.PauliString({}),
                           half_turns=cirq.Symbol('a'))
    ext = cirq.Extensions()
    assert not op.try_cast_to(cirq.CompositeOperation, ext) is None
    assert not op.try_cast_to(cirq.BoundedEffect, ext) is None
    assert op.try_cast_to(cirq.ExtrapolatableEffect, ext) is None
    assert op.try_cast_to(cirq.ReversibleEffect, ext) is None
    assert op.try_cast_to(Dummy, ext) is None
Example #12
0
def test_parameterizable_via_extension():
    ext = cirq.Extensions()
    ext.add_cast(cirq.ParameterizableEffect, RestrictedGate, lambda _: cirq.S)
    without_ext = cirq.ControlledGate(RestrictedGate())
    with_ext = cirq.ControlledGate(RestrictedGate(), ext)

    with pytest.raises(TypeError):
        _ = without_ext.is_parameterized()

    assert not with_ext.is_parameterized()
Example #13
0
def test_text_diagrammable_via_extension():
    ext = cirq.Extensions()
    ext.add_cast(cirq.TextDiagrammableGate, RestrictedGate, lambda _: cirq.S)
    without_ext = cirq.ControlledGate(RestrictedGate())
    with_ext = cirq.ControlledGate(RestrictedGate(), ext)

    with pytest.raises(TypeError):
        _ = without_ext.text_diagram_exponent()

    assert with_ext.text_diagram_exponent() == 0.5
Example #14
0
def test_bounded_effect_via_extension():
    ext = cirq.Extensions()
    ext.add_cast(cirq.BoundedEffect, RestrictedGate, lambda _: cirq.Y)
    without_ext = cirq.ControlledGate(RestrictedGate())
    with_ext = cirq.ControlledGate(RestrictedGate(), ext)

    with pytest.raises(TypeError):
        _ = without_ext.trace_distance_bound()

    assert with_ext.trace_distance_bound() < 100
def test_partial_reflection_as_self_inverse():
    ex = cirq.Extensions()
    h0 = DummyGate(half_turns=0)
    h1 = DummyGate(half_turns=1)

    assert ex.try_cast(h1, cirq.SelfInverseGate) is h1
    assert ex.try_cast(h0, cirq.SelfInverseGate) is h0
    assert ex.try_cast(DummyGate(half_turns=0.5), cirq.SelfInverseGate) is None
    assert ex.try_cast(DummyGate(half_turns=-0.5),
                       cirq.SelfInverseGate) is None
Example #16
0
def test_reversible_via_extension():
    ext = cirq.Extensions()
    ext.add_cast(cirq.ReversibleEffect, RestrictedGate, lambda _: cirq.S)
    without_ext = cirq.ControlledGate(RestrictedGate())
    with_ext = cirq.ControlledGate(RestrictedGate(), ext)

    with pytest.raises(TypeError):
        _ = without_ext.inverse()

    assert with_ext.inverse() == cirq.ControlledGate(cirq.S.inverse())
Example #17
0
def test_override_order():
    e = cirq.Extensions({
        DesiredType: {
            object: lambda _, _2: 'obj',
            UnrelatedType: lambda _, _2: 'unrelated',
        }
    })
    assert e.cast(DesiredType, '') == 'obj'
    assert e.cast(DesiredType, None) == 'obj'
    assert e.cast(DesiredType, UnrelatedType()) == 'unrelated'
    assert e.cast(DesiredType, ChildType()) == 'obj'
Example #18
0
def test_add_potential_cast():
    a = Aunt()
    c1 = Child()
    c2 = Child()

    e = cirq.Extensions()
    e.add_cast(desired_type=Aunt,
               actual_type=Child,
               conversion=lambda e: a if e is c1 else None)

    assert e.try_cast(Aunt, c1) is a
    assert e.try_cast(Aunt, c2) is None
def test_composite_extension_overrides():
    q0, q1 = QubitId(), QubitId()
    cnot = CNOT(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(cnot)
    ext = cirq.Extensions()
    ext.add_cast(cirq.CompositeGate, cirq.CNotGate, lambda _: OtherCNot())
    opt = cirq.ExpandComposite(composite_gate_extension=ext)
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit()
    expected.append([Z(q0), Y(q1) ** -0.5, CZ(q0, q1), Y(q1) ** 0.5, Z(q0)])
    assert_equal_mod_empty(expected, circuit)
Example #20
0
def test_text_diagrammable_via_extension():
    ext = cirq.Extensions()
    ext.add_cast(cirq.TextDiagrammable, RestrictedGate, lambda _: cirq.Y**0.5)
    without_ext = cirq.ControlledGate(RestrictedGate())
    with_ext = cirq.ControlledGate(RestrictedGate(), ext)

    args = cirq.TextDiagramInfoArgs.UNINFORMED_DEFAULT
    with pytest.raises(TypeError):
        _ = without_ext.text_diagram_info(args)

    assert with_ext.text_diagram_info(args) == cirq.TextDiagramInfo(
        wire_symbols=('@', 'Y'), exponent=0.5)
Example #21
0
def test_add_recursive_cast():
    cousin = Cousin()
    child = Child()

    e = cirq.Extensions()
    e.add_cast(desired_type=Cousin,
               actual_type=Child,
               conversion=lambda _: cousin)
    e.add_recursive_cast(
        desired_type=Cousin,
        actual_type=Grandparent,
        conversion=lambda ext, _: ext.try_cast(Cousin, child))

    assert e.try_cast(Cousin, Grandparent()) is cousin
Example #22
0
def test_try_cast_hit_vs_miss():
    e = cirq.Extensions({DesiredType: {OtherType: WrapType}})
    o = OtherType()
    c = ChildType()
    u = UnrelatedType()

    assert e.try_cast(DesiredType, None) is None
    assert e.try_cast(DesiredType, u) is None
    assert e.try_cast(DesiredType, c) is c
    assert e.try_cast(DesiredType, o) is not o

    assert e.try_cast(UnrelatedType, None) is None
    assert e.try_cast(UnrelatedType, u) is u
    assert e.try_cast(UnrelatedType, c) is None
    assert e.try_cast(UnrelatedType, o) is None
def test_recursive_composite_extension_overrides():
    q0, q1 = QubitId(), QubitId()
    swap = SWAP(q0, q1)
    circuit = cirq.Circuit()
    circuit.append(swap)
    ext = cirq.Extensions()
    ext.add_cast(cirq.CompositeGate, cirq.CNotGate, lambda _: OtherCNot())
    opt = cirq.ExpandComposite(composite_gate_extension=ext)
    opt.optimize_circuit(circuit)
    expected = cirq.Circuit()
    expected.append([Z(q0), Y(q1) ** -0.5, CZ(q0, q1), Y(q1) ** 0.5, Z(q0)])
    expected.append([Z(q1), Y(q0) ** -0.5, CZ(q1, q0), Y(q0) ** 0.5, Z(q1)],
                    strategy=cirq.InsertStrategy.INLINE)
    expected.append([Z(q0), Y(q1) ** -0.5, CZ(q0, q1), Y(q1) ** 0.5, Z(q0)],
                    strategy=cirq.InsertStrategy.INLINE)
    assert_equal_mod_empty(expected, circuit)
Example #24
0
def test_try_cast_to():
    ext = cirq.Extensions()

    h = CExpZinGate(2)
    assert h.try_cast_to(cirq.ExtrapolatableEffect, ext) is h
    assert h.try_cast_to(cirq.SingleQubitGate, ext) is None
    assert cirq.inverse(h, None) is not None

    p = CExpZinGate(0.1)
    assert p.try_cast_to(cirq.ExtrapolatableEffect, ext) is p
    assert p.try_cast_to(cirq.SingleQubitGate, ext) is None
    assert cirq.inverse(p) is not None

    s = CExpZinGate(cirq.Symbol('a'))
    assert s.try_cast_to(cirq.ExtrapolatableEffect, ext) is None
    assert s.try_cast_to(cirq.SingleQubitGate, ext) is None
    assert cirq.inverse(s, None) is None
Example #25
0
def test_supports_extensions_for_parameter_resolving():
    class DummyGate(cirq.Gate):
        pass

    ext = cirq.Extensions()
    ext.add_cast(cirq.ParameterizableEffect, DummyGate,
                 lambda _: cg.ExpWGate(half_turns=cirq.Symbol('x')))

    a = cirq.NamedQubit('a')
    circuit = cirq.Circuit.from_ops(DummyGate().on(a),
                                    cg.XmonMeasurementGate('a').on(a))
    results = cirq.google.XmonSimulator().run(
        circuit=circuit,
        param_resolver=cirq.ParamResolver({'x': 1}),
        extensions=ext)

    assert str(results) == 'a=1'
Example #26
0
def test_matrix_via_extension():
    ext = cirq.Extensions()
    ext.add_cast(cirq.KnownMatrix, RestrictedGate, lambda _: cirq.X)
    without_ext = cirq.ControlledGate(RestrictedGate())
    with_ext = cirq.ControlledGate(RestrictedGate(), ext)

    with pytest.raises(TypeError):
        _ = without_ext.matrix()

    np.testing.assert_allclose(with_ext.matrix(),
                               np.array([
                                   [1, 0, 0, 0],
                                   [0, 1, 0, 0],
                                   [0, 0, 0, 1],
                                   [0, 0, 1, 0],
                               ]),
                               atol=1e-8)
Example #27
0
def test_empty():
    e = cirq.Extensions()
    o = OtherType()
    c = ChildType()
    u = UnrelatedType()

    with pytest.raises(TypeError):
        _ = e.cast(DesiredType, u)
    assert e.cast(DesiredType, c) is c
    with pytest.raises(TypeError):
        _ = e.cast(DesiredType, o)

    assert e.cast(UnrelatedType, u) is u
    with pytest.raises(TypeError):
        _ = e.cast(UnrelatedType, c)
    with pytest.raises(TypeError):
        _ = e.cast(UnrelatedType, o)
Example #28
0
def test_extension():
    class DummyGate(cirq.Gate):
        pass

    ext = cirq.Extensions()
    ext.add_cast(
        cirq.KnownMatrix, DummyGate,
        lambda _: cirq.SingleQubitMatrixGate(np.array([[0, 1], [1, 0]])))
    optimizer = cirq.google.MergeRotations(extensions=ext)

    q = cirq.QubitId()
    c = cirq.Circuit([
        cirq.Moment([DummyGate().on(q)]),
    ])
    assert_optimizes(before=c,
                     after=cirq.Circuit([cirq.Moment([cirq.X(q)])]),
                     optimizer=optimizer)
Example #29
0
def test_try_cast_potential_implementation():

    class PotentialOther(cirq.PotentialImplementation):
        def __init__(self, is_other):
            self.is_other = is_other

        def try_cast_to(self, desired_type, extensions):
            if desired_type is OtherType and self.is_other:
                return OtherType()
            return None

    e = cirq.Extensions()
    o = PotentialOther(is_other=False)
    u = PotentialOther(is_other=False)

    assert e.try_cast(OtherType, o) is None
    assert e.try_cast(OtherType, u) is None
Example #30
0
def test_extrapolatable_via_extension():
    ext = cirq.Extensions()
    ext.add_cast(cirq.ExtrapolatableEffect, RestrictedGate, lambda _: cirq.X)
    without_ext = cirq.ControlledGate(RestrictedGate())
    with_ext = cirq.ControlledGate(RestrictedGate(), ext)

    with pytest.raises(TypeError):
        _ = without_ext.extrapolate_effect(0.5)
    with pytest.raises(TypeError):
        _ = without_ext**0.5
    with pytest.raises(TypeError):
        _ = without_ext.inverse()

    assert (with_ext.extrapolate_effect(0.5) == cirq.ControlledGate(
        cirq.X.extrapolate_effect(0.5)))
    assert with_ext.inverse() == cirq.ControlledGate(cirq.X)
    assert with_ext**0.5 == cirq.ControlledGate(cirq.X.extrapolate_effect(0.5))