Tensor#
- class discopy.tensor.Tensor(dom, cod, array)[source]#
Bases:
Box
Implements a tensor with dom, cod and numpy array.
Examples
>>> m = Tensor(Dim(2), Dim(2), [0, 1, 1, 0]) >>> v = Tensor(Dim(1), Dim(2), [0, 1]) >>> v >> m >> v.dagger() Tensor(dom=Dim(1), cod=Dim(1), array=[0])
Notes
Tensors can have sympy symbols as free variables.
>>> from sympy.abc import phi, psi >>> v = Tensor(Dim(1), Dim(2), [phi, psi]) >>> d = v >> v.dagger() >>> assert v >> v.dagger() == Tensor( ... Dim(1), Dim(1), [phi * phi.conjugate() + psi * psi.conjugate()])
These can be substituted and lambdifed.
>>> v.subs(phi, 0).lambdify(psi)(1) Tensor(dom=Dim(1), cod=Dim(2), array=[0, 1])
We can also use jax.numpy using Tensor.backend.
>>> with Tensor.backend('jax'): ... f = lambda *xs: d.lambdify(phi, psi)(*xs).array ... import jax ... assert jax.grad(f)(1., 2.) == 2.
- property array#
Numpy array.
- transpose(left=False)[source]#
Returns the diagrammatic transpose.
Note
This is not the same as the algebraic transpose for complex dims.
- conjugate(diagrammatic=True)[source]#
Returns the conjugate of a tensor.
- Parameters:
diagrammatic (bool, default: True) – Whether to use the diagrammatic or algebraic conjugate.
- property l#
Returns the conjugate of a tensor.
- Parameters:
diagrammatic (bool, default: True) – Whether to use the diagrammatic or algebraic conjugate.
- property r#
Returns the conjugate of a tensor.
- Parameters:
diagrammatic (bool, default: True) – Whether to use the diagrammatic or algebraic conjugate.
- static zeros(dom, cod)[source]#
Returns the zero tensor of a given shape.
Examples
>>> assert Tensor.zeros(Dim(2), Dim(2))\ ... == Tensor(Dim(2), Dim(2), [0, 0, 0, 0])
- jacobian(variables, **params)[source]#
Jacobian with respect to
variables
.- Parameters:
variables (List[sympy.Symbol]) – Differentiated variables.
- Returns:
tensor – with
tensor.dom == self.dom
andtensor.cod == Dim(len(variables)) @ self.cod
.- Return type:
Examples
>>> from sympy.abc import x, y, z >>> vector = Tensor(Dim(1), Dim(2), [x ** 2, y * z]) >>> vector.jacobian([x, y, z]) Tensor(dom=Dim(1), cod=Dim(3, 2), array=[2.0*x, 0, 0, 1.0*z, 0, 1.0*y])