taichi.lang.matrix
#
- class taichi.lang.matrix.Matrix(arr, dt=None, suppress_warning=False)#
Bases:
taichi.lang.common_ops.TaichiOperations
The matrix class.
A matrix is a 2-D rectangular array with scalar entries, it’s row-majored, and is aligned continously. We recommend only use matrix with no more than 32 elements for efficiency considerations.
Note: in taichi a matrix is strictly two-dimensional and only stores scalars.
- Parameters
arr (Union[list, tuple, np.ndarray]) – the initial values of a matrix.
dt (
primitive_types
) – the element data type.suppress_warning (bool) – whether raise warning or not when the matrix contains more than 32 elements.
Example:
use a 2d list to initialize a matrix
>>> @ti.kernel
>>> def test():
>>> n = 5
>>> M = ti.Matrix([[0] * n for _ in range(n)], ti.i32)
>>> print(M) # a 5x5 matrix with integer elements
get the number of rows and columns via the `n`, `m` property:
>>> M = ti.Matrix([[0, 1], [2, 3], [4, 5]], ti.i32)
>>> M.n # number of rows
3
>>> M.m # number of cols
>>> 2
you can even initialize a matrix with an empty list:
>>> M = ti.Matrix([[], []], ti.i32)
>>> M.n
2
>>> M.m
0- all(self)#
Test whether all element not equal zero.
- Returns
True if all elements are not equal zero, False otherwise.
- Return type
bool
- any(self)#
Test whether any element not equal zero.
- Returns
True if any element is not equal zero, False otherwise.
- Return type
bool
- cast(self, dtype)#
Cast the matrix element data type.
- Parameters
dtype (DataType) – the data type of the casted matrix element.
- Returns
A new matrix with each element’s type is dtype.
- static cols(cols)#
Construct a Matrix instance by concatenating Vectors/lists column by column.
- cross(self, other)#
Perform the cross product with the input Vector (1-D Matrix).
- determinant(a)#
Get the determinant of a matrix.
Note
The matrix dimension should be less than or equal to 4.
- Returns
The determinant of a matrix.
- Raises
Exception – Determinants of matrices with sizes >= 5 are not supported.
- static diag(dim, val)#
Construct a diagonal square matrix.
- Parameters
dim (int) – the dimension of a square matrix.
val (TypeVar) – the diagonal element value.
- Returns
The constructed diagonal square matrix.
- dot(self, other)#
Perform the dot product with the input Vector (1-D Matrix).
- Parameters
other (
Matrix
) – The input Vector (1-D Matrix) to perform the dot product.- Returns
The dot product result (scalar) of the two Vectors.
- Return type
DataType
- classmethod field(cls, n, m, dtype, shape=None, name='', offset=None, needs_grad=False, layout=Layout.AOS)#
Construct a data container to hold all elements of the Matrix.
- Parameters
n (int) – The desired number of rows of the Matrix.
m (int) – The desired number of columns of the Matrix.
dtype (DataType, optional) – The desired data type of the Matrix.
shape (Union[int, tuple of int], optional) – The desired shape of the Matrix.
name (string, optional) – The custom name of the field.
offset (Union[int, tuple of int], optional) – The coordinate offset of all elements in a field.
needs_grad (bool, optional) – Whether the Matrix need gradients.
layout (Layout, optional) – The field layout, i.e., Array Of Structure (AOS) or Structure Of Array (SOA).
- Returns
A
Matrix
instance serves as the data container.- Return type
- fill(self, val)#
Fills the matrix with a specific value in Taichi scope.
- Parameters
val (Union[int, float]) – Value to fill.
- static identity(dt, n)#
Construct an identity Matrix with shape (n, n).
- inverse(self)#
The inverse of a matrix.
Note
The matrix dimension should be less than or equal to 4.
- Returns
The inverse of a matrix.
- Raises
Exception – Inversions of matrices with sizes >= 5 are not supported.
- max(self)#
Return the maximum element value.
- min(self)#
Return the minimum element value.
- classmethod ndarray(cls, n, m, dtype, shape, layout=Layout.AOS)#
Defines a Taichi ndarray with matrix elements.
- Parameters
n (int) – Number of rows of the matrix.
m (int) – Number of columns of the matrix.
dtype (DataType) – Data type of each value.
shape (Union[int, tuple[int]]) – Shape of the ndarray.
layout (Layout, optional) – Memory layout, AOS by default.
Example
The code below shows how a Taichi ndarray with matrix elements can be declared and defined:
>>> x = ti.Matrix.ndarray(4, 5, ti.f32, shape=(16, 8))
- norm(self, eps=0)#
Return the square root of the sum of the absolute squares of its elements.
- Parameters
eps (Number) – a safe-guard value for sqrt, usually 0.
Examples:
a = ti.Vector([3, 4])
a.norm() # sqrt(3*3 + 4*4 + 0) = 5
# `a.norm(eps)` is equivalent to `ti.sqrt(a.dot(a) + eps).`- Returns
The square root of the sum of the absolute squares of its elements.
- norm_inv(self, eps=0)#
Return the inverse of the matrix/vector norm. For norm: please see
norm()
.- Parameters
eps (Number) – a safe-guard value for sqrt, usually 0.
- Returns
The inverse of the matrix/vector norm.
- norm_sqr(self)#
Return the sum of the absolute squares of its elements.
- normalized(self, eps=0)#
Normalize a vector.
- Parameters
eps (Number) – a safe-guard value for sqrt, usually 0.
Examples:
a = ti.Vector([3, 4])
a.normalized() # [3 / 5, 4 / 5]
# `a.normalized()` is equivalent to `a / a.norm()`.Note
Only vector normalization is supported.
- static one(dt, n, m=None)#
Construct a Matrix filled with ones.
- outer_product(self, other)#
Perform the outer product with the input Vector (1-D Matrix).
- static rotation2d(alpha)#
- static rows(rows)#
Construct a Matrix instance by concatenating Vectors/lists row by row.
- sum(self)#
Return the sum of all elements.
- to_list(self)#
- to_numpy(self, keep_dims=False)#
Converts the Matrix to a numpy array.
- Parameters
keep_dims (bool, optional) – Whether to keep the dimension after conversion. When keep_dims=False, the resulting numpy array should skip the matrix dims with size 1.
- Returns
The result numpy array.
- Return type
numpy.ndarray
- trace(self)#
The sum of a matrix diagonal elements.
- Returns
The sum of a matrix diagonal elements.
- transpose(self)#
Get the transpose of a matrix.
- Returns
Get the transpose of a matrix.
- static unit(n, i, dt=None)#
Construct an unit Vector (1-D matrix) i.e., a vector with only one entry filled with one and all other entries zeros.
- property w(self)#
Get the fourth element of a matrix.
- property x(self)#
Get the first element of a matrix.
- property y(self)#
Get the second element of a matrix.
- property z(self)#
Get the third element of a matrix.
- class taichi.lang.matrix.MatrixField(_vars, n, m)#
Bases:
taichi.lang.field.Field
Taichi matrix field with SNode implementation.
- Parameters
vars (List[Expr]) – Field members.
n (Int) – Number of rows.
m (Int) – Number of columns.
- copy_from(self, other)#
Copies all elements from another field.
The shape of the other field needs to be the same as self.
- Parameters
other (Field) – The source field.
- property dtype(self)#
Gets data type of each individual value.
- Returns
Data type of each individual value.
- Return type
DataType
- fill(self, val)#
Fills self with specific values.
- Parameters
val (Union[Number, List, Tuple, Matrix]) – Values to fill, which should have dimension consistent with self.
- from_numpy(self, arr)#
Loads all elements from a numpy array.
The shape of the numpy array needs to be the same as self.
- Parameters
arr (numpy.ndarray) – The source numpy array.
- from_torch(self, arr)#
Loads all elements from a torch tensor.
The shape of the torch tensor needs to be the same as self.
- Parameters
arr (torch.tensor) – The source torch tensor.
- get_scalar_field(self, *indices)#
Creates a ScalarField using a specific field member. Only used for quant.
- Parameters
indices (Tuple[Int]) – Specified indices of the field member.
- Returns
The result ScalarField.
- Return type
- parent(self, n=1)#
Gets an ancestor of the representative SNode in the SNode tree.
- Parameters
n (int) – the number of levels going up from the representative SNode.
- Returns
The n-th parent of the representative SNode.
- Return type
- property shape(self)#
Gets field shape.
- Returns
Field shape.
- Return type
Tuple[Int]
- property snode(self)#
Gets representative SNode for info purposes.
- Returns
Representative SNode (SNode of first field member).
- Return type
- to_numpy(self, keep_dims=False, dtype=None)#
Converts the field instance to a NumPy array.
- Parameters
keep_dims (bool, optional) – Whether to keep the dimension after conversion. When keep_dims=True, on an n-D matrix field, the numpy array always has n+2 dims, even for 1x1, 1xn, nx1 matrix fields. When keep_dims=False, the resulting numpy array should skip the matrix dims with size 1. For example, a 4x1 or 1x4 matrix field with 5x6x7 elements results in an array of shape 5x6x7x4.
dtype (DataType, optional) – The desired data type of returned numpy array.
- Returns
The result NumPy array.
- Return type
numpy.ndarray
- to_torch(self, device=None, keep_dims=False)#
Converts the field instance to a PyTorch tensor.
- Parameters
device (torch.device, optional) – The desired device of returned tensor.
keep_dims (bool, optional) – Whether to keep the dimension after conversion. See
to_numpy()
for more detailed explanation.
- Returns
The result torch tensor.
- Return type
torch.tensor
- class taichi.lang.matrix.MatrixNdarray(n, m, dtype, shape, layout)#
Bases:
taichi.lang._ndarray.Ndarray
Taichi ndarray with matrix elements.
- Parameters
n (int) – Number of rows of the matrix.
m (int) – Number of columns of the matrix.
dtype (DataType) – Data type of each value.
shape (Union[int, tuple[int]]) – Shape of the ndarray.
layout (Layout) – Memory layout.
- copy_from(self, other)#
Copies all elements from another ndarray.
The shape of the other ndarray needs to be the same as self.
- Parameters
other (Ndarray) – The source ndarray.
- property element_shape(self)#
Gets ndarray element shape.
- Returns
Ndarray element shape.
- Return type
Tuple[Int]
- fill(self, val)#
Fills ndarray with a specific scalar value.
- Parameters
val (Union[int, float]) – Value to fill.
- from_numpy(self, arr)#
- to_numpy(self)#
- taichi.lang.matrix.Vector(arr, dt=None, **kwargs)#
Construct a vector from given array.
A vector is an instance of a 2-D matrix with the second dimension being equal to 1.
- Parameters
arr (Union[list, tuple, np.ndarray]) – The initial values of the Vector.
dt (
primitive_types
) – data type of the vector.
- Returns
A vector instance.
- Return type
- Example::
>>> u = ti.Vector([1, 2])
>>> print(u.m, u.n) # verify a vector is a matrix of shape (n, 1)
2 1
>>> v = ti.Vector([3, 4])
>>> u + v
[4 6]
- class taichi.lang.matrix.VectorNdarray(n, dtype, shape, layout)#
Bases:
taichi.lang._ndarray.Ndarray
Taichi ndarray with vector elements.
- Parameters
n (int) – Size of the vector.
dtype (DataType) – Data type of each value.
shape (Tuple[int]) – Shape of the ndarray.
layout (Layout) – Memory layout.
- copy_from(self, other)#
Copies all elements from another ndarray.
The shape of the other ndarray needs to be the same as self.
- Parameters
other (Ndarray) – The source ndarray.
- property element_shape(self)#
Gets ndarray element shape.
- Returns
Ndarray element shape.
- Return type
Tuple[Int]
- fill(self, val)#
Fills ndarray with a specific scalar value.
- Parameters
val (Union[int, float]) – Value to fill.
- from_numpy(self, arr)#
- to_numpy(self)#