예제 #1
0
def test_add_cast_include_subtypes():

    e = extension.Extensions()
    e.add_cast(desired_type=Cousin,
               actual_type=Child,
               conversion=lambda _: 'boo',
               also_add_inherited_conversions=True)
    e2 = extension.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'
예제 #2
0
def test_add_cast_redundant_including_subtypes():
    o1 = Cousin()
    o2 = Cousin()
    o3 = Cousin()

    e = extension.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
예제 #3
0
def test_wrap():
    e = extension.Extensions({DesiredType: {OtherType: WrapType}})
    o = OtherType()
    w = e.cast(DesiredType, o)
    assert w.make() == 'wrap'
    assert isinstance(w, WrapType)
    assert w.other is o
예제 #4
0
def circuit_to_latex_using_qcircuit(
        circuit: circuits.Circuit,
        ext: extension.Extensions = None,
        qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT) -> str:
    """Returns a QCircuit-based latex diagram of the given circuit.

    Args:
        circuit: The circuit to represent in latex.
        ext: Extensions used when attempting to cast gates into
            QCircuitDiagrammableGate instances (before falling back to the
            default wrapping methods).
        qubit_order: Determines the order of qubit wires in the diagram.

    Returns:
        Latex code for the diagram.
    """
    if ext is None:
        ext = extension.Extensions()
    qcircuit = _wrap_circuit(circuit, ext)

    # Note: can't be a lambda because we need the type hint.
    def get_sub(q: _QCircuitQubit) -> ops.QubitId:
        return q.sub

    diagram = qcircuit.to_text_diagram_drawer(
        ext,
        qubit_name_suffix='',
        qubit_order=ops.QubitOrder.as_qubit_order(qubit_order).map(
            internalize=get_sub, externalize=_QCircuitQubit))
    return _render(diagram)
예제 #5
0
def test_add_cast():
    e = extension.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
예제 #6
0
def test_override_order():
    e = extension.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'
예제 #7
0
def test_override_order():
    e = extension.Extensions({
        DesiredType: {
            object: lambda _: 'obj',
            UnrelatedType: lambda _: 'unrelated',
        }
    })
    assert e.cast('', DesiredType) == 'obj'
    assert e.cast(None, DesiredType) == 'obj'
    assert e.cast(UnrelatedType(), DesiredType) == 'unrelated'
    assert e.cast(ChildType(), DesiredType) == 'obj'
예제 #8
0
def test_add_potential_cast():
    a = Aunt()
    c1 = Child()
    c2 = Child()

    e = extension.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
예제 #9
0
def test_add_recursive_cast():
    cousin = Cousin()
    child = Child()

    e = extension.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
예제 #10
0
파일: eject_z.py 프로젝트: YZNIU/Cirq
 def __init__(self,
              tolerance: float = 0.0,
              ext: extension.Extensions=None) -> None:
     """
     Args:
         tolerance: Maximum absolute error tolerance. The optimization is
              permitted to simply drop negligible combinations of Z gates,
              with a threshold determined by this tolerance.
         ext: Extensions object used for determining if gates are phaseable
             (i.e. if Z gates can pass through them).
     """
     self.tolerance = tolerance
     self.ext = ext or extension.Extensions()
예제 #11
0
    def __init__(self,
                 composite_gate_extension: extension.Extensions = None,
                 no_decomp: Callable[[ops.Operation], bool]=(lambda _: False)
                 ) -> None:
        """Construct the optimization pass.

        Args:
            composite_gate_extension: An extension that that can be used
                to supply or override a CompositeOperation decomposition.
            no_decomp: A predicate that determines whether an operation should
                be decomposed or not. Defaults to decomposing everything.
        """
        self.extension = composite_gate_extension or extension.Extensions()
        self.no_decomp = no_decomp
예제 #12
0
 def __init__(self,
              extensions: extension.Extensions = None,
              ignore_failures: bool = False,
              allow_partial_czs: bool = False) -> None:
     """
     Args:
         extensions: The extensions instance to use when trying to
             cast gates to known types.
         ignore_failures: If set, gates that fail to convert are forwarded
             unchanged. If not set, conversion failures raise a TypeError.
     """
     self.extensions = extensions or extension.Extensions()
     self.ignore_failures = ignore_failures
     self.allow_partial_czs = allow_partial_czs
예제 #13
0
def test_try_cast_hit_vs_miss():
    e = extension.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
예제 #14
0
def test_try_cast_hit_vs_miss():
    e = extension.Extensions({DesiredType: {OtherType: WrapType}})
    o = OtherType()
    c = ChildType()
    u = UnrelatedType()

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

    assert e.try_cast(None, UnrelatedType) is None
    assert e.try_cast(u, UnrelatedType) is u
    assert e.try_cast(c, UnrelatedType) is None
    assert e.try_cast(o, UnrelatedType) is None
예제 #15
0
def test_try_cast_potential_implementation():
    class PotentialOther(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 = extension.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
예제 #16
0
def test_empty():
    e = extension.Extensions()
    o = OtherType()
    c = ChildType()
    u = UnrelatedType()

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

    assert e.cast(u, UnrelatedType) is u
    with pytest.raises(TypeError):
        _ = e.cast(c, UnrelatedType)
    with pytest.raises(TypeError):
        _ = e.cast(o, UnrelatedType)
예제 #17
0
def test_empty():
    e = extension.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)
 def __init__(self,
              ignore_failures: bool = False,
              tolerance: float = 0,
              extensions: extension.Extensions = None) -> None:
     """
     Args:
         ignore_failures: If set, gates that fail to convert are forwarded
             unchanged. If not set, conversion failures raise a TypeError.
         tolerance: Maximum absolute error tolerance. The optimization is
             permitted to round angles with a threshold determined by this
             tolerance.
         extensions: The extensions instance to use when trying to
             cast gates to known types.
     """
     self.extensions = extensions or extension.Extensions()
     self.ignore_failures = ignore_failures
     self.tolerance = tolerance
예제 #19
0
def test_cast_hit_vs_miss():
    e = extension.Extensions({DesiredType: {OtherType: WrapType}})
    o = OtherType()
    c = ChildType()
    u = UnrelatedType()

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

    with pytest.raises(TypeError):
        _ = e.cast(None, UnrelatedType)
    assert e.cast(u, UnrelatedType) is u
    with pytest.raises(TypeError):
        _ = e.cast(c, UnrelatedType)
    with pytest.raises(TypeError):
        _ = e.cast(o, UnrelatedType)
예제 #20
0
def test_cast_hit_vs_miss():
    e = extension.Extensions({DesiredType: {OtherType: WrapType}})
    o = OtherType()
    c = ChildType()
    u = UnrelatedType()

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

    with pytest.raises(TypeError):
        _ = e.cast(UnrelatedType, None)
    assert e.cast(UnrelatedType, u) is u
    with pytest.raises(TypeError):
        _ = e.cast(UnrelatedType, c)
    with pytest.raises(TypeError):
        _ = e.cast(UnrelatedType, o)
 def __init__(self,
              ignore_failures: bool = False,
              keep_clifford: bool = False,
              tolerance: float = 0,
              extensions: extension.Extensions = None) -> None:
     """
     Args:
         ignore_failures: If set, gates that fail to convert are forwarded
             unchanged. If not set, conversion failures raise a TypeError.
         keep_clifford: If set, single qubit rotations in the Clifford group
             are converted to CliffordGates.
         tolerance: Maximum absolute error tolerance. The optimization is
             permitted to round angles with a threshold determined by this
             tolerance.
         extensions: The extensions instance to use when trying to
             cast gates to known types.
     """
     super().__init__()
     self.extensions = extensions or extension.Extensions()
     self.ignore_failures = ignore_failures
     self.keep_clifford = keep_clifford
     self.tolerance = tolerance
     self._tol = linalg.Tolerance(atol=tolerance)
예제 #22
0
def test_add_cast_redundant():
    o1 = Cousin()
    o2 = Cousin()
    o3 = Cousin()

    e = extension.Extensions()
    e.add_cast(desired_type=Cousin,
               actual_type=Child,
               conversion=lambda _: o1,
               also_add_inherited_conversions=False,
               overwrite_existing=False)
    with pytest.raises(ValueError):
        e.add_cast(desired_type=Cousin,
                   actual_type=Child,
                   conversion=lambda _: o2,
                   also_add_inherited_conversions=False,
                   overwrite_existing=False)
    assert e.try_cast(Child(), Cousin) is o1
    e.add_cast(desired_type=Cousin,
               actual_type=Child,
               conversion=lambda _: o3,
               also_add_inherited_conversions=False,
               overwrite_existing=True)
    assert e.try_cast(Child(), Cousin) is o3
예제 #23
0
    def __init__(self,
                 operations: ops.OP_TREE,
                 qubits: Tuple[ops.QubitId, ...],
                 header: str = '',
                 precision: int = 10,
                 version: str = '2.0',
                 ext: extension.Extensions = None) -> None:
        self.operations = tuple(ops.flatten_op_tree(operations))
        self.qubits = qubits
        self.header = header
        if ext is None:
            ext = extension.Extensions()
        self.ext = ext
        self.measurements = tuple(
            cast(ops.GateOperation, op) for op in self.operations
            if ops.MeasurementGate.is_measurement(op))

        meas_key_id_map, meas_comments = self._generate_measurement_ids()
        self.meas_comments = meas_comments
        qubit_id_map = self._generate_qubit_ids()
        self.args = ops.QasmOutputArgs(precision=precision,
                                       version=version,
                                       qubit_id_map=qubit_id_map,
                                       meas_key_id_map=meas_key_id_map)
예제 #24
0
def test_can_cast():
    e = extension.Extensions({DesiredType: {OtherType: WrapType}})
    c = ChildType()
    u = UnrelatedType()
    assert not e.can_cast(DesiredType, u)
    assert e.can_cast(DesiredType, c)
예제 #25
0
 def __init__(self):
     circuits.PointOptimizer.__init__(self)
     self.extension = extension.Extensions()
     self.no_decomp = lambda op: (not get_acquaintance_size(op) or (
         isinstance(op, ops.GateOperation) and isinstance(
             op.gate, AcquaintanceOpportunityGate)))
예제 #26
0
 def __init__(self, extensions: extension.Extensions = None) -> None:
     super().__init__()
     self.extensions = extensions or extension.Extensions()
예제 #27
0
 def _cast_sub_gate(self, desired_type: Type[T_DESIRED]) -> T_DESIRED:
     ext = self.default_extensions or extension.Extensions()
     cast_sub_gate = ext.try_cast(desired_type, self.sub_gate)
     if cast_sub_gate is None:
         raise TypeError('sub_gate is not a {}', desired_type)
     return cast_sub_gate
예제 #28
0
 def __init__(self,
              tolerance: float = 1e-8,
              extensions: extension.Extensions = None) -> None:
     self.tolerance = tolerance
     self.extensions = extensions or extension.Extensions()