Ejemplo n.º 1
0
def test_dict():
    # Standard type tests.
    assert hash(Dict[int, float]) == hash(Dict[int, float])
    assert hash(Dict[int, float]) != hash(Tuple[int, str])
    assert hash(Dict[int, float]) != hash(Tuple[str, float])
    assert hash(Dict[Tuple[int], float]) == hash(Dict[Tuple[int], float])
    assert hash(Dict[Tuple[int], float]) != hash(Dict[Tuple[str], float])
    assert repr(Dict[int, float]) == f"Dict[{Type(int)!r}, {Type(float)!r}]"
    assert issubclass(Dict[int, float].get_types()[0], dict)
    assert not issubclass(Dict[int, float].get_types()[0], int)

    # Test instance check.
    assert isinstance({}, Dict[Union[object], Union[object]])
    assert isinstance({1: 2.0}, Dict[int, float])

    # Check tracking of parametric.
    assert Dict[int, float].parametric
    assert ptype(Dict[Tuple[int], float]).parametric
    assert ptype(Union[Dict[int, float]]).parametric
    promise = PromisedType()
    promise.deliver(Dict[int, float])
    assert promise.resolve().parametric

    # Check tracking of runtime `type_of`.
    assert Dict[int, float].runtime_type_of
    assert ptype(Dict[Tuple[int], float]).runtime_type_of
    assert ptype(Union[Dict[int, float]]).runtime_type_of
    promise = PromisedType()
    promise.deliver(Dict[int, float])
    assert promise.resolve().runtime_type_of

    # Test correctness.
    dispatch = Dispatcher()

    @dispatch
    def f(x):
        return "fallback"

    @dispatch
    def f(x: dict):
        return "dict"

    @dispatch
    def f(x: Dict[int, int]):
        return "int to int"

    @dispatch
    def f(x: Dict[str, int]):
        return "str to int"

    @dispatch
    def f(x: Dict[Union[int, str], int]):
        return "int or str to int"

    assert f(1) == "fallback"
    assert f({1: 1}) == "int to int"
    assert f({"1": 1}) == "str to int"
    assert f({"1": 1, 1: 1}) == "int or str to int"
    assert f({"1": "1", 1: 1}) == "dict"
Ejemplo n.º 2
0
def test_list():
    # Standard type tests.
    assert hash(List[int]) == hash(List[int])
    assert hash(List[int]) != hash(List[str])
    assert hash(List[List[int]]) == hash(List[List[int]])
    assert hash(List[List[int]]) != hash(List[List[str]])
    assert repr(List[int]) == f"List[{Type(int)!r}]"
    assert issubclass(List[int].get_types()[0], list)
    assert not issubclass(List[int].get_types()[0], int)
    assert not issubclass(List[int].get_types()[0], tuple)

    # Test instance check.
    assert isinstance([], List[Union[object]])
    assert isinstance([1, 2], List[Union[int]])

    # Check tracking of parametric.
    assert List[int].parametric
    assert ptype(List[List[int]]).parametric
    assert ptype(Union[List[int]]).parametric
    promise = PromisedType()
    promise.deliver(List[int])
    assert promise.resolve().parametric

    # Check tracking of runtime `type_of`.
    assert List[int].runtime_type_of
    assert ptype(List[List[int]]).runtime_type_of
    assert ptype(Union[List[int]]).runtime_type_of
    promise = PromisedType()
    promise.deliver(List[int])
    assert promise.resolve().runtime_type_of

    # Test correctness.
    dispatch = Dispatcher()

    @dispatch
    def f(x):
        return "fallback"

    @dispatch
    def f(x: list):
        return "list"

    @dispatch
    def f(x: List[int]):
        return "list of int"

    @dispatch
    def f(x: List[List[int]]):
        return "list of list of int"

    assert f([1]) == "list of int"
    assert f(1) == "fallback"
    assert f([1, 2]) == "list of int"
    assert f([1, 2, "3"]) == "list"
    assert f([[1]]) == "list of list of int"
    assert f([[1], [1]]) == "list of list of int"
    assert f([[1], [1, 2]]) == "list of list of int"
    assert f([[1], [1, 2, "3"]]) == "list"
Ejemplo n.º 3
0
def test_typetype():
    Promised = PromisedType()
    Promised.deliver(int)

    assert as_type(type(int)) <= TypeType
    assert as_type(type(Promised)) <= TypeType
    assert as_type(type({int})) <= TypeType
    assert as_type(type([int])) <= TypeType

    assert not (as_type(int) <= TypeType)
    assert not (as_type(Promised) <= TypeType)
    assert not (as_type({int}) <= TypeType)
def test_tupletype():
    # Standard type tests.
    assert hash(Tuple(int)) == hash(Tuple(int))
    assert hash(Tuple(int)) != hash(Tuple(str))
    assert hash(Tuple(Tuple(int))) == hash(Tuple(Tuple(int)))
    assert hash(Tuple(Tuple(int))) != hash(Tuple(Tuple(str)))
    assert repr(Tuple(int)) == 'TupleType({})'.format(repr(Type(int)))
    assert issubclass(Tuple(int).get_types()[0], tuple)
    assert not issubclass(Tuple(int).get_types()[0], int)
    assert not issubclass(Tuple(int).get_types()[0], list)

    # Test instance check.
    assert isinstance((), Tuple(Union()))
    assert isinstance((1, 2), Tuple(Union(int)))

    # Check tracking of parametric.
    assert Tuple(int).parametric
    assert as_type([Tuple(int)]).parametric
    assert as_type({Tuple(int)}).parametric
    promise = PromisedType()
    promise.deliver(Tuple(int))
    assert promise.resolve().parametric

    # Test correctness.
    dispatch = Dispatcher()

    @dispatch(object)
    def f(x):
        return 'fallback'

    @dispatch(tuple)
    def f(x):
        return 'tup'

    @dispatch(Tuple(int))
    def f(x):
        return 'tup of int'

    @dispatch(Tuple(Tuple(int)))
    def f(x):
        return 'tup of tup of int'

    assert f((1, )) == 'tup of int'
    assert f(1) == 'fallback'
    assert f((1, 2)) == 'tup of int'
    assert f((1, 2, '3')) == 'tup'
    assert f(((1, ), )) == 'tup of tup of int'
    assert f(((1, ), (1, ))) == 'tup of tup of int'
    assert f(((1, ), (1, 2))) == 'tup of tup of int'
    assert f(((1, ), (1, 2, '3'))) == 'tup'
def test_listtype():
    # Standard type tests.
    assert hash(List(int)) == hash(List(int))
    assert hash(List(int)) != hash(List(str))
    assert hash(List(List(int))) == hash(List(List(int)))
    assert hash(List(List(int))) != hash(List(List(str)))
    assert repr(List(int)) == 'ListType({})'.format(repr(Type(int)))
    assert issubclass(List(int).get_types()[0], list)
    assert not issubclass(List(int).get_types()[0], int)
    assert not issubclass(List(int).get_types()[0], tuple)

    # Test instance check.
    assert isinstance([], List(Union()))
    assert isinstance([1, 2], List(Union(int)))

    # Check tracking of parametric.
    assert List(int).parametric
    assert as_type([List(int)]).parametric
    assert as_type({List(int)}).parametric
    promise = PromisedType()
    promise.deliver(List(int))
    assert promise.resolve().parametric

    # Test correctness.
    dispatch = Dispatcher()

    @dispatch(object)
    def f(x):
        return 'fallback'

    @dispatch(list)
    def f(x):
        return 'list'

    @dispatch(List(int))
    def f(x):
        return 'list of int'

    @dispatch(List(List(int)))
    def f(x):
        return 'list of list of int'

    assert f([1]) == 'list of int'
    assert f(1) == 'fallback'
    assert f([1, 2]) == 'list of int'
    assert f([1, 2, '3']) == 'list'
    assert f([[1]]) == 'list of list of int'
    assert f([[1], [1]]) == 'list of list of int'
    assert f([[1], [1, 2]]) == 'list of list of int'
    assert f([[1], [1, 2, '3']]) == 'list'
Ejemplo n.º 6
0
def test_promisedtype():
    t = PromisedType()
    with pytest.raises(ResolutionError):
        hash(t)
    with pytest.raises(ResolutionError):
        repr(t)
    with pytest.raises(ResolutionError):
        t.get_types()

    t.deliver(Type(int))
    assert hash(t) == hash(Type(int))
    assert repr(t) == repr(Type(int))
    assert t.get_types() == Type(int).get_types()
    assert not t.parametric
Ejemplo n.º 7
0
    def __div__(self, other):
        return self * (1 / other)

    def __truediv__(self, other):
        return Random.__div__(self, other)


class RandomProcess(Random):
    """A random process."""


class RandomVector(Random):
    """A random vector."""


PromisedGP = PromisedType()


class Normal(RandomVector, At):
    """Normal random variable.

    A normal random variable also acts as an instance of `At`, which can be
    used to specify a process at particular points.

    Args:
        var (matrix): Variance of the distribution.
        mean (tensor, optional): Mean of the distribution. Defaults to zero.
    """

    _dispatch = Dispatcher(in_class=Self)
Ejemplo n.º 8
0
def test_sequence():
    # Standard type tests.
    assert hash(Sequence[int]) == hash(Sequence[int])
    assert hash(Sequence[int]) != hash(Sequence[str])
    assert hash(Sequence[int]) != hash(Sequence())
    assert hash(Sequence[Sequence[int]]) == hash(Sequence[Sequence[int]])
    assert hash(Sequence[Sequence[int]]) != hash(Sequence[Sequence[str]])
    assert repr(Sequence()) == "Sequence"
    assert repr(Sequence[int]) == f"Sequence[{Type(int)!r}]"

    # Test instance check.
    assert isinstance([], Sequence())
    assert isinstance([], Sequence[object])
    assert isinstance((1, 2.0), Sequence())
    assert isinstance((1, 2.0), Sequence[Union[int, float]])
    assert isinstance([1, 2], Sequence())
    assert isinstance([1, 2], Sequence[int])
    assert not isinstance((x for x in [1, 2]), Sequence())

    # Test subclass check.
    assert issubclass(ptype(list), Sequence())
    assert issubclass(List[int], Sequence())
    assert issubclass(List[int], Sequence[int])
    assert not issubclass(ptype(list), Sequence[int])
    assert issubclass(Sequence[int], Sequence[object])

    # Check tracking of parametric.
    assert Sequence[int].parametric
    assert ptype(Sequence[Sequence[int]]).parametric
    assert ptype(Union[Sequence[int]]).parametric
    promise = PromisedType()
    promise.deliver(Sequence[int])
    assert promise.resolve().parametric

    # Check tracking of runtime `type_of`.
    assert Sequence[int].runtime_type_of
    assert ptype(Sequence[Sequence[int]]).runtime_type_of
    assert ptype(Union[Sequence[int]]).runtime_type_of
    promise = PromisedType()
    promise.deliver(Sequence[int])
    assert promise.resolve().runtime_type_of

    assert not Sequence().runtime_type_of
    assert ptype(Sequence[Sequence()]).runtime_type_of
    assert not ptype(Union[Sequence()]).runtime_type_of
    promise = PromisedType()
    promise.deliver(Sequence())
    assert not promise.resolve().runtime_type_of

    # Test correctness.
    dispatch = Dispatcher()

    @parametric
    class A:
        def __init__(self, el_type):
            pass

        def __len__(self):
            pass

        def __getitem__(self, item):
            pass

    @parametric
    class B(A):
        @classmethod
        def __getitem_el_type__(cls):
            return cls.type_parameter

    @dispatch
    def f(x):
        return "fallback"

    @dispatch
    def f(x: Sequence()):
        return "seq"

    @dispatch
    def f(x: Sequence[int]):
        return "seq of int"

    @dispatch
    def f(x: Sequence[Sequence[object]]):
        return "seq of seq"

    assert f(1) == "fallback"
    assert f((x for x in [1, 2])) == "fallback"
    # Test various sequences:
    assert f(A(1)) == "seq"
    assert f(A(1.0)) == "seq"
    assert f(B(1)) == "seq of int"
    assert f(B(1.0)) == "seq"
    assert f([1]) == "seq of int"
    assert f([1.0]) == "seq"
    assert f({1: 1}) == "seq of int"
    assert f({1: 1.0}) == "seq"
    assert f((1, 1)) == "seq of int"
    assert f((1.0, 1)) == "seq"
    # Test nested sequences:
    assert f([[1]]) == "seq of seq"
    assert f(([1], [1, 2, "3"])) == "seq of seq"
Ejemplo n.º 9
0
def test_tuple():
    # Standard type tests.
    assert hash(Tuple[int]) == hash(Tuple[int])
    assert hash(Tuple[int]) != hash(Tuple[str])
    assert hash(Tuple[Tuple[int]]) == hash(Tuple[Tuple[int]])
    assert hash(Tuple[Tuple[int]]) != hash(Tuple[Tuple[str]])
    assert repr(Tuple[int]) == f"Tuple[{Type(int)!r}]"
    assert issubclass(Tuple[int].get_types()[0], tuple)
    assert not issubclass(Tuple[int].get_types()[0], int)
    assert not issubclass(Tuple[int].get_types()[0], list)

    # Test instance check.
    assert isinstance((), Tuple())
    assert isinstance((1, 2), Tuple[int, int])

    # Check tracking of parametric.
    assert Tuple[int].parametric
    assert ptype(List[Tuple[int]]).parametric
    assert ptype(Union[Tuple[int]]).parametric
    promise = PromisedType()
    promise.deliver(Tuple[int])
    assert promise.resolve().parametric

    # Check tracking of runtime `type_of`.
    assert Tuple[int].runtime_type_of
    assert ptype(List[Tuple[int]]).runtime_type_of
    assert ptype(Union[Tuple[int]]).runtime_type_of
    promise = PromisedType()
    promise.deliver(Tuple[int])
    assert promise.resolve().runtime_type_of

    # Test correctness.
    dispatch = Dispatcher()

    @dispatch
    def f(x):
        return "fallback"

    @dispatch
    def f(x: tuple):
        return "tup"

    @dispatch
    def f(x: Tuple[int]):
        return "tup of int"

    @dispatch
    def f(x: Tuple[int, int]):
        return "tup of double int"

    @dispatch
    def f(x: Tuple[Tuple[int]]):
        return "tup of tup of int"

    @dispatch
    def f(x: Tuple[Tuple[int], Tuple[int]]):
        return "tup of double tup of int"

    @dispatch
    def f(x: Tuple[int, Tuple[int, int]]):
        return "tup of int and tup of double int"

    assert f((1, )) == "tup of int"
    assert f(1) == "fallback"
    assert f((1, 2)) == "tup of double int"
    assert f((1, 2, "3")) == "tup"
    assert f(((1, ), )) == "tup of tup of int"
    assert f(((1, ), (1, ))) == "tup of double tup of int"
    assert f((1, (1, 2))) == "tup of int and tup of double int"
    assert f(((1, ), (1, 2))) == "tup"
Ejemplo n.º 10
0
from ._version import version as __version__  # noqa

# noinspection PyUnresolvedReferences
import matrix

# noinspection PyUnresolvedReferences
from mlkernels import *

# noinspection PyUnresolvedReferences
import lab as B

from plum import PromisedType, Dispatcher

PromisedFDD = PromisedType()
PromisedGP = PromisedType()
PromisedMeasure = PromisedType()

_dispatch = Dispatcher()


class BreakingChangeWarning(UserWarning):
    """A breaking change."""


from .lazy import *
from .model import *
from .mo import *
from .random import *
Ejemplo n.º 11
0
# noinspection PyUnresolvedReferences
import matrix
# noinspection PyUnresolvedReferences
from lab import B

from plum import PromisedType

PromisedFDD = PromisedType()
PromisedGP = PromisedType()

from .input import *
from .kernel import *
from .lazy import *
from .mean import *
from .measure import *
from .mokernel import *
from .momean import *
from .random import *
from .util import *

Ejemplo n.º 12
0

def var(x, power=1):
    """Polynomial consisting of just a single variable.

    Args:
        x (tensor): Constant.
        power (int, optional): Power. Defaults to one.

    Returns:
        :class:`.exppoly.Poly`: Resulting polynomial.
    """
    return Poly(Term(1, Factor(x, power)))


PromisedPoly = PromisedType()


class Factor:
    """Variable raised to some power.

    Args:
        name (str): Variable name.
        power (int, optional): Power. Defaults to one.
    """
    @_dispatch
    def __init__(self, name: str):
        Factor.__init__(self, name, 1)

    @_dispatch
    def __init__(self, name: str, power: int):
Ejemplo n.º 13
0
    def __add__(self, other):
        return 'unknown device'

    def __radd__(self, other):
        return other + self

    @_dispatch(object, ComputableObject)
    def compute(self, a, b):
        return 'a result'

    @_dispatch(ComputableObject, object)
    def compute(self, a, b):
        return 'another result'


PromisedCalculator = PromisedType()
PromisedHammer = PromisedType()


class Hammer(Device):
    _dispatch = Dispatcher(in_class=Self)

    @_dispatch(PromisedHammer)
    def __add__(self, other):
        return 'super hammer'

    @_dispatch(PromisedCalculator)
    def __add__(self, other):
        return 'destroyed calculator'