matricity module
Embedded domain-specific library for implicitly and explicitly encoding functions as matrices that operate on domains of one-hot vectors.
- class onehot(index: int, size: int)[source]
Bases:
objectData structure for an individual one-hot vector.
>>> v = onehot(7, 16) >>> int(v) 7 >>> list(v) [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
- class domain(iterable: Iterable)[source]
Bases:
objectData structure for a domain of values that can be represented as a set of one-hot vectors.
>>> a = domain(['a', 'b', 'c']) >>> len(a) 3
- __mul__(other: domain) domain[source]
Combine two domains using the Cartesian product operation. This operation is associative.
>>> a = domain(['a', 'b']) >>> b = domain(range(2)) >>> c = a * b >>> list(c) [('a', 0), ('a', 1), ('b', 0), ('b', 1)]
- __call__(value: Any) onehot[source]
Retrieve the one-hot vector that represents the specified value in this domain.
>>> a = domain(['a', 'b', 'c']) >>> b = domain(range(4)) >>> c = a * b >>> list(c(('b', 2))) [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
- __getitem__(index: Union[int, onehot]) Any[source]
Retrieve a value in the domain using its index (i.e., the index of the sole 1 entry in the one-hot vector that represents the value).
>>> a = domain(['a', 'b', 'c']) >>> b = domain(range(4)) >>> c = a * b >>> c[6] ('b', 2)
- class matrix(function: Callable, domain: domain = None, codomain: domain = None)[source]
Bases:
objectData structure for representing a function as a matrix that can be applied to one-hot vectors.
>>> uint2 = domain(range(4)) >>> enum3 = domain(['less', 'same', 'more']) >>> def compare(x: uint2, y: uint2) -> enum3: ... if x < y: ... return 'less' ... elif x > y: ... return 'more' ... else: ... return 'same' >>> m = matrix(compare, uint2 * uint2, enum3) >>> v = (uint2 * uint2)((3, 2)) >>> tuple(m @ v) (0, 0, 1) >>> enum3[tuple(m @ v)] 'more'
If the domain and codomain are not explicitly provided to the constructor, the constructor attemps to find them in the context.
>>> def identity(x: 'domain(range(4))') -> 'domain(range(4))': ... return x >>> isinstance(matrix(identity), matrix) True
- __matmul__(other: onehot) onehot[source]
Apply the function represented by this instance to the supplied one-hot vector.
>>> uint2 = domain(range(4)) >>> def maximum(x: uint2, y: uint2) -> uint2: ... return max(x, y) >>> m = matrix(maximum, uint2 * uint2, uint2) >>> v = (uint2 * uint2)((3, 2)) >>> tuple(m @ v) (0, 0, 0, 1)
- __iter__() Iterable[source]
Yield the individual rows of the matrix represented by this instance.
>>> uint2 = domain(range(4)) >>> def maximum(x: uint2, y: uint2) -> uint2: ... return max(x, y) >>> m = matrix(maximum, uint2 * uint2, uint2) >>> for row in m: ... print(row) [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0] [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1]