taichi.lang
#
- class taichi.lang.BitpackedFields(max_num_bits)#
Taichi bitpacked fields, where fields with quantized types are packed together.
- Parameters:
max_num_bits (int) – Maximum number of bits all fields inside can occupy in total. Only 32 or 64 is allowed.
- class taichi.lang.DeviceCapability#
- spirv_has_atomic_float = spirv_has_atomic_float#
- spirv_has_atomic_float16 = spirv_has_atomic_float16#
- spirv_has_atomic_float16_add = spirv_has_atomic_float16_add#
- spirv_has_atomic_float16_minmax = spirv_has_atomic_float16_minmax#
- spirv_has_atomic_float64 = spirv_has_atomic_float64#
- spirv_has_atomic_float64_add = spirv_has_atomic_float64_add#
- spirv_has_atomic_float64_minmax = spirv_has_atomic_float64_minmax#
- spirv_has_atomic_float_add = spirv_has_atomic_float_add#
- spirv_has_atomic_float_minmax = spirv_has_atomic_float_minmax#
- spirv_has_atomic_int64 = spirv_has_atomic_int64#
- spirv_has_float16 = spirv_has_float16#
- spirv_has_float64 = spirv_has_float64#
- spirv_has_int16 = spirv_has_int16#
- spirv_has_int64 = spirv_has_int64#
- spirv_has_int8 = spirv_has_int8#
- spirv_has_no_integer_wrap_decoration = spirv_has_no_integer_wrap_decoration#
- spirv_has_non_semantic_info = spirv_has_non_semantic_info#
- spirv_has_physical_storage_buffer = spirv_has_physical_storage_buffer#
- spirv_has_subgroup_arithmetic = spirv_has_subgroup_arithmetic#
- spirv_has_subgroup_ballot = spirv_has_subgroup_ballot#
- spirv_has_subgroup_basic = spirv_has_subgroup_basic#
- spirv_has_subgroup_vote = spirv_has_subgroup_vote#
- spirv_has_variable_ptr = spirv_has_variable_ptr#
- spirv_version_1_3 = spirv_version=66304#
- spirv_version_1_4 = spirv_version=66560#
- spirv_version_1_5 = spirv_version=66816#
- class taichi.lang.Field(_vars)#
Taichi field class.
A field is constructed by a list of field members. For example, a scalar field has 1 field member, while a 3x3 matrix field has 9 field members. A field member is a Python Expr wrapping a C++ FieldExpression.
- Parameters:
vars (List[Expr]) – Field members.
- 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.
- from_paddle(self, arr)#
Loads all elements from a paddle tensor.
The shape of the paddle tensor needs to be the same as self.
- Parameters:
arr (paddle.Tensor) – The source paddle tensor.
- 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.
- taichi.lang.Format#
- taichi.lang.Layout#
- class taichi.lang.Matrix(arr, dt=None)#
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 continuously. 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.ndim (int optional) – the number of dimensions of the matrix; forced reshape if given.
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
Example:
>>> v = ti.Vector([0, 0, 1]) >>> v.all() False
- any(self)#
Test whether any element not equal zero.
- Returns:
True if any element is not equal zero, False otherwise.
- Return type:
bool
Example:
>>> v = ti.Vector([0, 0, 1]) >>> v.any() True
- cast(self, dtype)#
Cast the matrix elements to a specified data type.
- Parameters:
dtype (
primitive_types
) – data type of the returned matrix.- Returns:
A new matrix with the specified data dtype.
- Return type:
Example:
>>> A = ti.Matrix([0, 1, 2], ti.i32) >>> B = A.cast(ti.f32) >>> B [0.0, 1.0, 2.0]
- static cols(cols)#
Constructs a Matrix instance by concatenating Vectors/lists column by column.
- Parameters:
cols (List) – A list of Vector (1-D Matrix) or a list of list.
- Returns:
A matrix.
- Return type:
Example:
>>> @ti.kernel >>> def test(): >>> v1 = ti.Vector([1, 2, 3]) >>> v2 = ti.Vector([4, 5, 6]) >>> m = ti.Matrix.cols([v1, v2]) >>> print(m) >>> >>> test() [[1, 4], [2, 5], [3, 6]]
- cross(self, other)#
Performs the cross product with the input vector (1-D Matrix).
Both two vectors must have the same dimension <= 3.
For two 2d vectors (x1, y1) and (x2, y2), the return value is the scalar x1*y2 - x2*y1.
For two 3d vectors v and w, the return value is the 3d vector v x w.
- determinant(a)#
Returns the determinant of this matrix.
Note
The matrix dimension should be less than or equal to 4.
- Returns:
The determinant of this matrix.
- Return type:
dtype
- Raises:
Exception – Determinants of matrices with sizes >= 5 are not supported.
- static diag(dim, val)#
Returns a diagonal square matrix with the diagonals filled with val.
- Parameters:
dim (int) – the dimension of the wanted square matrix.
val (TypeVar) – value for the diagonal elements.
- Returns:
The wanted diagonal matrix.
- Return type:
Example:
>>> m = ti.Matrix.diag(3, 1) [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
- dot(self, other)#
Performs the dot product of two vectors.
To call this method, both multiplicatives must be vectors.
- Parameters:
other (
Matrix
) – The input Vector.- Returns:
The dot product result (scalar) of the two Vectors.
- Return type:
Example:
>>> v1 = ti.Vector([1, 2, 3]) >>> v2 = ti.Vector([3, 4, 5]) >>> v1.dot(v2) 26
- classmethod field(cls, n, m, dtype, shape=None, order=None, name='', offset=None, needs_grad=False, needs_dual=False, layout=Layout.AOS, ndim=None)#
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.
order (str, optional) – order of the shape laid out in memory.
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 grad field (reverse mode autodiff).
needs_dual (bool, optional) – Whether the Matrix need dual field (forward mode autodiff).
layout (Layout, optional) – The field layout, either Array Of Structure (AOS) or Structure Of Array (SOA).
- Returns:
A matrix.
- Return type:
- fill(self, val)#
Fills the matrix with a specified value.
- Parameters:
val (Union[int, float]) – Value to fill.
Example:
>>> A = ti.Matrix([0, 1, 2, 3]) >>> A.fill(-1) >>> A [-1, -1, -1, -1]
- get_shape(self)#
- static identity(dt, n)#
Constructs an identity Matrix with shape (n, n).
- inverse(self)#
Returns the inverse of this matrix.
Note
The matrix dimension should be less than or equal to 4.
- Returns:
The inverse of a matrix.
- Return type:
- Raises:
Exception – Inversions of matrices with sizes >= 5 are not supported.
- max(self)#
Returns the maximum element value.
- min(self)#
Returns the minimum element value.
- classmethod ndarray(cls, n, m, dtype, shape)#
Defines a Taichi ndarray with matrix elements. This function must be called in Python scope, and after ti.init is called.
- 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.
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)#
Returns the square root of the sum of the absolute squares of its elements.
- Parameters:
eps (Number) – a safe-guard value for sqrt, usually 0.
Example:
>>> a = ti.Vector([3, 4]) >>> a.norm() 5
- Returns:
The square root of the sum of the absolute squares of its elements.
- norm_inv(self, eps=0)#
The inverse of the matrix
norm()
.- Parameters:
eps (float) – a safe-guard value for sqrt, usually 0.
- Returns:
The inverse of the matrix/vector norm.
- norm_sqr(self)#
Returns the sum of the absolute squares of its elements.
- normalized(self, eps=0)#
Normalize a vector, i.e. matrices with the second dimension being equal to one.
The normalization of a vector v is a vector of length 1 and has the same direction with v. It’s equal to v/|v|.
- Parameters:
eps (float) – a safe-guard value for sqrt, usually 0.
Example:
>>> a = ti.Vector([3, 4], ti.f32) >>> a.normalized() [0.6, 0.8]
- static one(dt, n, m=None)#
Constructs a Matrix filled with ones.
- outer_product(self, other)#
Performs the outer product with the input Vector (1-D Matrix).
The outer_product of two vectors v = (x1, x2, …, xn), w = (y1, y2, …, yn) is a n times n square matrix, and its (i, j) entry is equal to xi*yj.
- static rows(rows)#
Constructs a matrix by concatenating a list of vectors/lists row by row. Must be called in Taichi scope.
- Parameters:
rows (List) – A list of Vector (1-D Matrix) or a list of list.
- Returns:
A matrix.
- Return type:
Example:
>>> @ti.kernel >>> def test(): >>> v1 = ti.Vector([1, 2, 3]) >>> v2 = ti.Vector([4, 5, 6]) >>> m = ti.Matrix.rows([v1, v2]) >>> print(m) >>> >>> test() [[1, 2, 3], [4, 5, 6]]
- sum(self)#
Return the sum of all elements.
Example:
>>> m = ti.Matrix([[1, 2], [3, 4]]) >>> m.sum() 10
- to_list(self)#
Return this matrix as a 1D list.
This is similar to numpy.ndarray’s flatten and ravel methods, the difference is that this function always returns a new list.
- to_numpy(self)#
Converts this matrix to a numpy array.
- Returns:
The result numpy array.
- Return type:
numpy.ndarray
Example:
>>> A = ti.Matrix([[0], [1], [2], [3]]) >>> A.to_numpy() >>> A array([[0], [1], [2], [3]])
- trace(self)#
The sum of a matrix diagonal elements.
To call this method the matrix must be square-like.
- Returns:
The sum of a matrix diagonal elements.
Example:
>>> m = ti.Matrix([[1, 2], [3, 4]]) >>> m.trace() 5
- transpose(self)#
Returns the transpose of a matrix.
- Returns:
The transpose of this matrix.
- Return type:
Example:
>>> A = ti.Matrix([[0, 1], [2, 3]]) >>> A.transpose() [[0, 2], [1, 3]]
- static unit(n, i, dt=None)#
Constructs a n-D vector with the i-th entry being equal to one and the remaining entries are all zeros.
- Parameters:
n (int) – The length of the vector.
i (int) – The index of the entry that will be filled with one.
dt (
primitive_types
, optional) – The desired data type.
- Returns:
The returned vector.
- Return type:
Example:
>>> A = ti.Matrix.unit(3, 1) >>> A [0, 1, 0]
- class taichi.lang.MatrixField(_vars, n, m, ndim=2)#
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.
ndim (Int) – Number of dimensions; forced reshape if given.
- 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.
- fill(self, val)#
Fills this matrix field with specified values.
- Parameters:
val (Union[Number, Expr, List, Tuple, Matrix]) – Values to fill, should have consistent dimension consistent with self.
- from_numpy(self, arr)#
Copies an numpy.ndarray into this field.
Example:
>>> m = ti.Matrix.field(2, 2, ti.f32, shape=(3, 3)) >>> arr = numpy.ones((3, 3, 2, 2)) >>> m.from_numpy(arr)
- from_paddle(self, arr)#
Loads all elements from a paddle tensor.
The shape of the paddle tensor needs to be the same as self.
- Parameters:
arr (paddle.Tensor) – The source paddle tensor.
- 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.
- 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:
- 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_paddle(self, place=None, keep_dims=False)#
Converts the field instance to a Paddle tensor.
- Parameters:
place (paddle.CPUPlace()/CUDAPlace(n), optional) – The desired place of returned tensor.
keep_dims (bool, optional) – Whether to keep the dimension after conversion. See
to_numpy()
for more detailed explanation.
- Returns:
The result paddle tensor.
- Return type:
paddle.Tensor
- 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.MatrixNdarray(n, m, dtype, shape)#
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.
Example:
>>> arr = ti.MatrixNdarray(2, 2, ti.f32, shape=(3, 3))
- 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.
- fill(self, val)#
Fills ndarray with a specific scalar value.
- Parameters:
val (Union[int, float]) – Value to fill.
- from_numpy(self, arr)#
Copies the data of a numpy.ndarray into this array.
Example:
>>> m = ti.MatrixNdarray(2, 2, ti.f32, shape=(2, 1), layout=0) >>> arr = np.ones((2, 1, 2, 2)) >>> m.from_numpy(arr)
- get_type(self)#
- to_numpy(self)#
Converts this ndarray to a numpy.ndarray.
Example:
>>> arr = ti.MatrixNdarray(2, 2, ti.f32, shape=(2, 1)) >>> arr.to_numpy() [[[[0. 0.] [0. 0.]]] [[[0. 0.] [0. 0.]]]]
- class taichi.lang.Mesh#
The Mesh type class.
MeshTaichi offers first-class support for triangular/tetrahedral meshes and allows efficient computation on these irregular data structures, only available for backends supporting ti.extension.mesh.
See more details in https://github.com/taichi-dev/meshtaichi
- static generate_meta(data)#
- static load_meta(filename)#
- class taichi.lang.MeshInstance#
- add_mesh_attribute(self, element_type, snode, reorder_type)#
- get_position_as_numpy(self)#
Get the vertex position of current mesh to numpy array.
- Returns:
[x, y, z] with float-format.
- Return type:
3d numpy array
- get_relation_access(self, from_index, to_element_type, neighbor_idx_ptr)#
- get_relation_size(self, from_index, to_element_type)#
- set_index_mapping(self, element_type: MeshElementType, conv_type: ConvType, mapping: taichi.lang.field.ScalarField)#
- set_num_patches(self, num_patches: int)#
- set_owned_offset(self, element_type: MeshElementType, owned_offset: taichi.lang.field.ScalarField)#
- set_patch_max_element_num(self, element_type: MeshElementType, max_element_num: int)#
- set_relation_dynamic(self, rel_type: MeshRelationType, value: taichi.lang.field.ScalarField, patch_offset: taichi.lang.field.ScalarField, offset: taichi.lang.field.ScalarField)#
- set_relation_fixed(self, rel_type: MeshRelationType, value: taichi.lang.field.ScalarField)#
- set_total_offset(self, element_type: MeshElementType, total_offset: taichi.lang.field.ScalarField)#
- class taichi.lang.Ndarray#
Taichi ndarray class.
- Parameters:
dtype (DataType) – Data type of each value.
shape (Tuple[int]) – Shape of the Ndarray.
- 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.
- fill(self, val)#
Fills ndarray with a specific scalar value.
- Parameters:
val (Union[int, float]) – Value to fill.
- get_type(self)#
- class taichi.lang.SNode(ptr)#
A Python-side SNode wrapper.
For more information on Taichi’s SNode system, please check out these references:
- Arg:
ptr (pointer): The C++ side SNode pointer.
- bitmasked(self, axes, dimensions)#
Adds a bitmasked SNode as a child component of self.
- Parameters:
axes (List[Axis]) – Axes to activate.
dimensions (Union[List[int], int]) – Shape of each axis.
- Returns:
The added
SNode
instance.
- deactivate_all(self)#
Recursively deactivate all children components of self.
- dense(self, axes, dimensions)#
Adds a dense SNode as a child component of self.
- Parameters:
axes (List[Axis]) – Axes to activate.
dimensions (Union[List[int], int]) – Shape of each axis.
- Returns:
The added
SNode
instance.
- dynamic(self, axis, dimension, chunk_size=None)#
Adds a dynamic SNode as a child component of self.
- Parameters:
axis (List[Axis]) – Axis to activate, must be 1.
dimension (int) – Shape of the axis.
chunk_size (int) – Chunk size.
- Returns:
The added
SNode
instance.
- lazy_dual(self)#
Automatically place the dual fields following the layout of their primal fields.
- lazy_grad(self)#
Automatically place the adjoint fields following the layout of their primal fields.
Users don’t need to specify
needs_grad
when they define scalar/vector/matrix fields (primal fields) using autodiff. When all the primal fields are defined, usingtaichi.root.lazy_grad()
could automatically generate their corresponding adjoint fields (gradient field).To know more details about primal, adjoint fields and
lazy_grad()
, please see Page 4 and Page 13-14 of DiffTaichi Paper: https://arxiv.org/pdf/1910.00935.pdf
- parent(self, n=1)#
Gets an ancestor of self in the SNode tree.
- Parameters:
n (int) – the number of levels going up from self.
- Returns:
The n-th parent of self.
- Return type:
Union[None, _Root, SNode]
- place(self, *args, offset=None)#
Places a list of Taichi fields under the self container.
- Parameters:
*args (List[ti.field]) – A list of Taichi fields to place.
offset (Union[Number, tuple[Number]]) – Offset of the field domain.
- Returns:
The self container.
- pointer(self, axes, dimensions)#
Adds a pointer SNode as a child component of self.
- Parameters:
axes (List[Axis]) – Axes to activate.
dimensions (Union[List[int], int]) – Shape of each axis.
- Returns:
The added
SNode
instance.
- quant_array(self, axes, dimensions, max_num_bits)#
Adds a quant_array SNode as a child component of self.
- Parameters:
axes (List[Axis]) – Axes to activate.
dimensions (Union[List[int], int]) – Shape of each axis.
max_num_bits (int) – Maximum number of bits it can hold.
- Returns:
The added
SNode
instance.
- class taichi.lang.ScalarField(var)#
Bases:
Field
Taichi scalar field with SNode implementation.
- Parameters:
var (Expr) – Field member.
- 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.
- fill(self, val)#
Fills this scalar field with a specified value.
- from_numpy(self, arr)#
Copies the data from a numpy.ndarray into this field.
- from_paddle(self, arr)#
Loads all elements from a paddle tensor.
The shape of the paddle tensor needs to be the same as self.
- Parameters:
arr (paddle.Tensor) – The source paddle tensor.
- 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.
- 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:
- to_numpy(self, dtype=None)#
Converts this field to a numpy.ndarray.
- to_paddle(self, place=None)#
Converts this field to a paddle.Tensor.
- to_torch(self, device=None)#
Converts this field to a torch.tensor.
- class taichi.lang.ScalarNdarray(dtype, arr_shape)#
Bases:
Ndarray
Taichi ndarray with scalar elements.
- Parameters:
dtype (DataType) – Data type of each value.
shape (Tuple[int]) – Shape of the ndarray.
- 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.
- fill(self, val)#
Fills ndarray with a specific scalar value.
- Parameters:
val (Union[int, float]) – Value to fill.
- from_numpy(self, arr)#
- get_type(self)#
- to_numpy(self)#
- class taichi.lang.Struct(*args, **kwargs)#
The Struct type class.
A struct is a dictionary-like data structure that stores members as (key, value) pairs. Valid data members of a struct can be scalars, matrices or other dictionary-like structures.
- Parameters:
entries (Dict[str, Union[Dict, Expr, Matrix, Struct]]) – keys and values for struct members. Entries can optionally include a dictionary of functions with the key ‘__struct_methods’ which will be attached to the struct for executing on the struct data.
- Returns:
An instance of this struct.
Example:
>>> vec3 = ti.types.vector(3, ti.f32) >>> a = ti.Struct(v=vec3([0, 0, 0]), t=1.0) >>> print(a.items) dict_items([('v', [0. 0. 0.]), ('t', 1.0)]) >>> >>> B = ti.Struct(v=vec3([0., 0., 0.]), t=1.0, A=a) >>> print(B.items) dict_items([('v', [0. 0. 0.]), ('t', 1.0), ('A', {'v': [[0.], [0.], [0.]], 't': 1.0})])
- classmethod field(cls, members, methods={}, shape=None, name='<Struct>', offset=None, needs_grad=False, needs_dual=False, layout=Layout.AOS)#
Creates a
StructField
with each element has this struct as its type.- Parameters:
members (dict) – a dict, each item is like name: type.
methods (dict) – a dict of methods that should be included with the field. Each struct item of the field will have the methods as instance functions.
shape (Tuple[int]) – width and height of the field.
offset (Tuple[int]) – offset of the indices of the created field. For example if offset=(-10, -10) the indices of the field will start at (-10, -10), not (0, 0).
needs_grad (bool) – enabling grad field (reverse mode autodiff) or not.
needs_dual (bool) – enabling dual field (forward mode autodiff) or not.
layout – AOS or SOA.
Example
>>> vec3 = ti.types.vector(3, ti.f32) >>> sphere = {"center": vec3, "radius": float} >>> F = ti.Struct.field(sphere, shape=(3, 3)) >>> F {'center': array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
- [[0., 0., 0.],
[0., 0., 0.], [0., 0., 0.]],
- [[0., 0., 0.],
[0., 0., 0.], [0., 0., 0.]]], dtype=float32), ‘radius’: array([[0., 0., 0.],
[0., 0., 0.], [0., 0., 0.]], dtype=float32)}
- to_dict(self, include_methods=False, include_ndim=False)#
Converts the Struct to a dictionary.
- Parameters:
include_methods (bool) – Whether any struct methods should be included in the result dictionary under the key ‘__struct_methods’.
- Returns:
The result dictionary.
- Return type:
Dict
- class taichi.lang.StructField(field_dict, struct_methods, name=None, is_primal=True)#
Bases:
taichi.lang.field.Field
Taichi struct field with SNode implementation.
Instead of directly constraining Expr entries, the StructField object directly hosts members as Field instances to support nested structs.
- Parameters:
field_dict (Dict[str, Field]) – Struct field members.
struct_methods (Dict[str, callable]) – Dictionary of functions to apply to each struct instance in the field.
name (string, optional) – The custom name of the field.
- 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.
- fill(self, val)#
Fills this struct field with a specified value.
- Parameters:
val (Union[int, float]) – Value to fill.
- from_numpy(self, array_dict)#
Copies the data from a set of numpy.array into this field.
The argument array_dict must be a dictionay-like object, it contains all the keys in this field and the copying process between corresponding items can be performed.
- from_paddle(self, array_dict)#
Copies the data from a set of paddle.Tensor into this field.
The argument array_dict must be a dictionay-like object, it contains all the keys in this field and the copying process between corresponding items can be performed.
- from_torch(self, array_dict)#
Copies the data from a set of torch.tensor into this field.
The argument array_dict must be a dictionay-like object, it contains all the keys in this field and the copying process between corresponding items can be performed.
- get_member_field(self, key)#
Creates a ScalarField using a specific field member.
- Parameters:
key (str) – Specified key of the field member.
- Returns:
The result ScalarField.
- Return type:
- to_numpy(self)#
Converts the Struct field instance to a dictionary of NumPy arrays.
The dictionary may be nested when converting nested structs.
- Returns:
The result NumPy array.
- Return type:
Dict[str, Union[numpy.ndarray, Dict]]
- to_paddle(self, place=None)#
Converts the Struct field instance to a dictionary of Paddle tensors.
The dictionary may be nested when converting nested structs.
- Parameters:
place (paddle.CPUPlace()/CUDAPlace(n), optional) – The desired place of returned tensor.
- Returns:
- The result
Paddle tensor.
- Return type:
Dict[str, Union[paddle.Tensor, Dict]]
- to_torch(self, device=None)#
Converts the Struct field instance to a dictionary of PyTorch tensors.
The dictionary may be nested when converting nested structs.
- Parameters:
device (torch.device, optional) – The desired device of returned tensor.
- Returns:
- The result
PyTorch tensor.
- Return type:
Dict[str, Union[torch.Tensor, Dict]]
- exception taichi.lang.TaichiAssertionError#
Bases:
TaichiRuntimeError
,AssertionError
Thrown when assertion fails at runtime.
- class args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception taichi.lang.TaichiCompilationError#
Bases:
Exception
Base class for all compilation exceptions.
- class args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception taichi.lang.TaichiNameError#
Bases:
TaichiCompilationError
,NameError
Thrown when an undefine name is found during compilation.
- class args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception taichi.lang.TaichiRuntimeError#
Bases:
RuntimeError
Thrown when the compiled program cannot be executed due to unspecified reasons.
- class args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception taichi.lang.TaichiRuntimeTypeError#
Bases:
TaichiRuntimeError
,TypeError
Thrown when the compiled program cannot be executed due to unspecified reasons.
- class args#
- static get(pos, needed, provided)#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception taichi.lang.TaichiSyntaxError#
Bases:
TaichiCompilationError
,SyntaxError
Thrown when a syntax error is found during compilation.
- class args#
- class filename#
exception filename
- class lineno#
exception lineno
- class msg#
exception msg
- class offset#
exception offset
- class print_file_and_line#
exception print_file_and_line
- class text#
exception text
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception taichi.lang.TaichiTypeError#
Bases:
TaichiCompilationError
,TypeError
Thrown when a type mismatch is found during compilation.
- class args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class taichi.lang.Texture(fmt, arr_shape)#
Taichi Texture class.
- Parameters:
fmt (ti.Format) – Color format of the texture.
shape (Tuple[int]) – Shape of the Texture.
- from_field(self, field)#
Loads a field to texture.
- Parameters:
field (ti.Field) – Source field to load from.
- from_image(self, image)#
Loads a PIL image to texture. This method is only allowed a 2D texture with ti.Format.rgba8.
- Parameters:
image (PIL.Image.Image) – Source PIL image to load from.
- from_ndarray(self, ndarray)#
Loads an ndarray to texture.
- Parameters:
ndarray (ti.Ndarray) – Source ndarray to load from.
- to_image(self)#
Saves a texture to a PIL image in RGB mode. This method is only allowed a 2D texture with ti.Format.rgba8.
- Returns:
a PIL image in RGB mode, with the same size as source texture.
- Return type:
img (PIL.Image.Image)
- class taichi.lang.Vector(arr, dt=None, **kwargs)#
Bases:
Matrix
The matrix class.
A matrix is a 2-D rectangular array with scalar entries, it’s row-majored, and is aligned continuously. 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.ndim (int optional) – the number of dimensions of the matrix; forced reshape if given.
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
Example:
>>> v = ti.Vector([0, 0, 1]) >>> v.all() False
- any(self)#
Test whether any element not equal zero.
- Returns:
True if any element is not equal zero, False otherwise.
- Return type:
bool
Example:
>>> v = ti.Vector([0, 0, 1]) >>> v.any() True
- cast(self, dtype)#
Cast the matrix elements to a specified data type.
- Parameters:
dtype (
primitive_types
) – data type of the returned matrix.- Returns:
A new matrix with the specified data dtype.
- Return type:
Example:
>>> A = ti.Matrix([0, 1, 2], ti.i32) >>> B = A.cast(ti.f32) >>> B [0.0, 1.0, 2.0]
- static cols(cols)#
Constructs a Matrix instance by concatenating Vectors/lists column by column.
- Parameters:
cols (List) – A list of Vector (1-D Matrix) or a list of list.
- Returns:
A matrix.
- Return type:
Example:
>>> @ti.kernel >>> def test(): >>> v1 = ti.Vector([1, 2, 3]) >>> v2 = ti.Vector([4, 5, 6]) >>> m = ti.Matrix.cols([v1, v2]) >>> print(m) >>> >>> test() [[1, 4], [2, 5], [3, 6]]
- cross(self, other)#
Performs the cross product with the input vector (1-D Matrix).
Both two vectors must have the same dimension <= 3.
For two 2d vectors (x1, y1) and (x2, y2), the return value is the scalar x1*y2 - x2*y1.
For two 3d vectors v and w, the return value is the 3d vector v x w.
- determinant(a)#
Returns the determinant of this matrix.
Note
The matrix dimension should be less than or equal to 4.
- Returns:
The determinant of this matrix.
- Return type:
dtype
- Raises:
Exception – Determinants of matrices with sizes >= 5 are not supported.
- static diag(dim, val)#
Returns a diagonal square matrix with the diagonals filled with val.
- Parameters:
dim (int) – the dimension of the wanted square matrix.
val (TypeVar) – value for the diagonal elements.
- Returns:
The wanted diagonal matrix.
- Return type:
Example:
>>> m = ti.Matrix.diag(3, 1) [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
- dot(self, other)#
Performs the dot product of two vectors.
To call this method, both multiplicatives must be vectors.
- Parameters:
other (
Matrix
) – The input Vector.- Returns:
The dot product result (scalar) of the two Vectors.
- Return type:
Example:
>>> v1 = ti.Vector([1, 2, 3]) >>> v2 = ti.Vector([3, 4, 5]) >>> v1.dot(v2) 26
- classmethod field(cls, n, dtype, *args, **kwargs)#
ti.Vector.field
- fill(self, val)#
Fills the matrix with a specified value.
- Parameters:
val (Union[int, float]) – Value to fill.
Example:
>>> A = ti.Matrix([0, 1, 2, 3]) >>> A.fill(-1) >>> A [-1, -1, -1, -1]
- get_shape(self)#
- static identity(dt, n)#
Constructs an identity Matrix with shape (n, n).
- inverse(self)#
Returns the inverse of this matrix.
Note
The matrix dimension should be less than or equal to 4.
- Returns:
The inverse of a matrix.
- Return type:
- Raises:
Exception – Inversions of matrices with sizes >= 5 are not supported.
- max(self)#
Returns the maximum element value.
- min(self)#
Returns the minimum element value.
- classmethod ndarray(cls, n, dtype, shape)#
Defines a Taichi ndarray with vector elements.
- Parameters:
n (int) – Size of the vector.
dtype (DataType) – Data type of each value.
shape (Union[int, tuple[int]]) – Shape of the ndarray.
Example
The code below shows how a Taichi ndarray with vector elements can be declared and defined:
>>> x = ti.Vector.ndarray(3, ti.f32, shape=(16, 8))
- norm(self, eps=0)#
Returns the square root of the sum of the absolute squares of its elements.
- Parameters:
eps (Number) – a safe-guard value for sqrt, usually 0.
Example:
>>> a = ti.Vector([3, 4]) >>> a.norm() 5
- Returns:
The square root of the sum of the absolute squares of its elements.
- norm_inv(self, eps=0)#
The inverse of the matrix
norm()
.- Parameters:
eps (float) – a safe-guard value for sqrt, usually 0.
- Returns:
The inverse of the matrix/vector norm.
- norm_sqr(self)#
Returns the sum of the absolute squares of its elements.
- normalized(self, eps=0)#
Normalize a vector, i.e. matrices with the second dimension being equal to one.
The normalization of a vector v is a vector of length 1 and has the same direction with v. It’s equal to v/|v|.
- Parameters:
eps (float) – a safe-guard value for sqrt, usually 0.
Example:
>>> a = ti.Vector([3, 4], ti.f32) >>> a.normalized() [0.6, 0.8]
- static one(dt, n, m=None)#
Constructs a Matrix filled with ones.
- outer_product(self, other)#
Performs the outer product with the input Vector (1-D Matrix).
The outer_product of two vectors v = (x1, x2, …, xn), w = (y1, y2, …, yn) is a n times n square matrix, and its (i, j) entry is equal to xi*yj.
- static rows(rows)#
Constructs a matrix by concatenating a list of vectors/lists row by row. Must be called in Taichi scope.
- Parameters:
rows (List) – A list of Vector (1-D Matrix) or a list of list.
- Returns:
A matrix.
- Return type:
Example:
>>> @ti.kernel >>> def test(): >>> v1 = ti.Vector([1, 2, 3]) >>> v2 = ti.Vector([4, 5, 6]) >>> m = ti.Matrix.rows([v1, v2]) >>> print(m) >>> >>> test() [[1, 2, 3], [4, 5, 6]]
- sum(self)#
Return the sum of all elements.
Example:
>>> m = ti.Matrix([[1, 2], [3, 4]]) >>> m.sum() 10
- to_list(self)#
Return this matrix as a 1D list.
This is similar to numpy.ndarray’s flatten and ravel methods, the difference is that this function always returns a new list.
- to_numpy(self)#
Converts this matrix to a numpy array.
- Returns:
The result numpy array.
- Return type:
numpy.ndarray
Example:
>>> A = ti.Matrix([[0], [1], [2], [3]]) >>> A.to_numpy() >>> A array([[0], [1], [2], [3]])
- trace(self)#
The sum of a matrix diagonal elements.
To call this method the matrix must be square-like.
- Returns:
The sum of a matrix diagonal elements.
Example:
>>> m = ti.Matrix([[1, 2], [3, 4]]) >>> m.trace() 5
- transpose(self)#
Returns the transpose of a matrix.
- Returns:
The transpose of this matrix.
- Return type:
Example:
>>> A = ti.Matrix([[0, 1], [2, 3]]) >>> A.transpose() [[0, 2], [1, 3]]
- static unit(n, i, dt=None)#
Constructs a n-D vector with the i-th entry being equal to one and the remaining entries are all zeros.
- Parameters:
n (int) – The length of the vector.
i (int) – The index of the entry that will be filled with one.
dt (
primitive_types
, optional) – The desired data type.
- Returns:
The returned vector.
- Return type:
Example:
>>> A = ti.Matrix.unit(3, 1) >>> A [0, 1, 0]
- class taichi.lang.VectorNdarray(n, dtype, shape)#
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.
Example:
>>> a = ti.VectorNdarray(3, ti.f32, (3, 3))
- 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.
- fill(self, val)#
Fills ndarray with a specific scalar value.
- Parameters:
val (Union[int, float]) – Value to fill.
- from_numpy(self, arr)#
Copies the data from a numpy.ndarray into this ndarray.
The shape and data type of arr must match this ndarray.
Example:
>>> import numpy as np >>> a = ti.VectorNdarray(3, ti.f32, (2, 2), 0) >>> b = np.ones((2, 2, 3), dtype=np.float32) >>> a.from_numpy(b)
- get_type(self)#
- to_numpy(self)#
Converts this vector ndarray to a numpy.ndarray.
Example:
>>> a = ti.VectorNdarray(3, ti.f32, (2, 2)) >>> a.to_numpy() array([[[0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.]]], dtype=float32)
- taichi.lang.abs(x)#
Compute the absolute value \(|x|\) of x, element-wise.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.- Returns:
The absolute value of each element in x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([-1.0, 0.0, 1.0]) >>> y = ti.abs(x) >>> print(y) >>> >>> test() [1.0, 0.0, 1.0]
- taichi.lang.acos(x)#
Trigonometric inverse cosine, element-wise.
The inverse of cos so that, if y = cos(x), then x = acos(y).
For input x not in the domain [-1, 1], this function returns nan if it’s called in taichi scope, or raises exception if it’s called in python scope.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – A scalar or a matrix with elements in [-1, 1].- Returns:
The inverse cosine of each element in x, in radians and in the closed interval [0, pi]. This is a scalar if x is a scalar.
Example:
>>> from math import pi >>> ti.acos(ti.Matrix([-1.0, 0.0, 1.0])) * 180 / pi [180., 90., 0.]
- taichi.lang.activate(node, indices)#
Explicitly activate a cell of node at location indices.
- taichi.lang.amdgpu#
The AMDGPU backend.
- taichi.lang.append(node, indices, val)#
Append a value val to a SNode node at index indices.
- Parameters:
node (
SNode
) – Input SNode.indices (Union[int,
Vector
]) – the indices to visit.val (Union[
primitive_types
,compound_types
]) – the data to be appended.
- taichi.lang.arm64#
The ARM CPU backend.
- taichi.lang.asin(x)#
Trigonometric inverse sine, element-wise.
The inverse of sin so that, if y = sin(x), then x = asin(y).
For input x not in the domain [-1, 1], this function returns nan if it’s called in taichi scope, or raises exception if it’s called in python scope.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – A scalar or a matrix with elements in [-1, 1].- Returns:
The inverse sine of each element in x, in radians and in the closed interval [-pi/2, pi/2].
Example:
>>> from math import pi >>> ti.asin(ti.Matrix([-1.0, 0.0, 1.0])) * 180 / pi [-90., 0., 90.]
- taichi.lang.assume_in_range(val, base, low, high)#
Hints the compiler that a value is between a specified range, for the compiler to perform scatchpad optimization, and return the value untouched.
The assumed range is [base + low, base + high).
- Parameters:
val (Number) – The input value.
base (Number) – The base point for the range interval.
low (Number) – The lower offset relative to base (included).
high (Number) – The higher offset relative to base (excluded).
- Returns:
Return the input value untouched.
Example:
>>> # hint the compiler that x is in range [8, 12). >>> x = ti.assume_in_range(x, 10, -2, 2) >>> x 10
- taichi.lang.atan2(x1, x2)#
Element-wise arc tangent of x1/x2.
- Parameters:
x1 (Union[
primitive_types
,Matrix
]) – y-coordinates.x2 (Union[
primitive_types
,Matrix
]) – x-coordinates.
- Returns:
Angles in radians, in the range [-pi, pi]. This is a scalar if both x1 and x2 are scalars.
Example:
>>> from math import pi >>> @ti.kernel >>> def test(): >>> x = ti.Matrix([-1.0, 1.0, -1.0, 1.0]) >>> y = ti.Matrix([-1.0, -1.0, 1.0, 1.0]) >>> z = ti.atan2(y, x) * 180 / pi >>> print(z) >>> >>> test() [-135.0, -45.0, 135.0, 45.0]
- taichi.lang.atomic_add(x, y)#
Atomically compute x + y, store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input.y (Union[
primitive_types
,Matrix
]) – The input.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([0, 0, 0]) >>> y = ti.Vector([1, 2, 3]) >>> z = ti.atomic_add(x, y) >>> print(x) # [1, 2, 3] the new value of x >>> print(z) # [0, 0, 0], the old value of x >>> >>> ti.atomic_add(1, x) # will raise TaichiSyntaxError
- taichi.lang.atomic_and(x, y)#
Atomically compute the bit-wise AND of x and y, element-wise. Store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input. When both are matrices they must have the same shape.y (Union[
primitive_types
,Matrix
]) – The input. When both are matrices they must have the same shape.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([-1, 0, 1]) >>> y = ti.Vector([1, 2, 3]) >>> z = ti.atomic_and(x, y) >>> print(x) # [1, 0, 1] the new value of x >>> print(z) # [-1, 0, 1], the old value of x >>> >>> ti.atomic_and(1, x) # will raise TaichiSyntaxError
- taichi.lang.atomic_max(x, y)#
Atomically compute the maximum of x and y, element-wise. Store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input.y (Union[
primitive_types
,Matrix
]) – The input.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = 1 >>> y = 2 >>> z = ti.atomic_max(x, y) >>> print(x) # 2 the new value of x >>> print(z) # 1, the old value of x >>> >>> ti.atomic_max(1, x) # will raise TaichiSyntaxError
- taichi.lang.atomic_min(x, y)#
Atomically compute the minimum of x and y, element-wise. Store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input.y (Union[
primitive_types
,Matrix
]) – The input.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = 2 >>> y = 1 >>> z = ti.atomic_min(x, y) >>> print(x) # 1 the new value of x >>> print(z) # 2, the old value of x >>> >>> ti.atomic_min(1, x) # will raise TaichiSyntaxError
- taichi.lang.atomic_mul(x, y)#
Atomically compute x * y, store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input.y (Union[
primitive_types
,Matrix
]) – The input.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([1, 2, 3]) >>> y = ti.Vector([4, 5, 6]) >>> z = ti.atomic_mul(x, y) >>> print(x) # [1, 2, 3] the new value of x >>> print(z) # [4, 10, 18], the old value of x >>> >>> ti.atomic_mul(1, x) # will raise TaichiSyntaxError
- taichi.lang.atomic_or(x, y)#
Atomically compute the bit-wise OR of x and y, element-wise. Store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input. When both are matrices they must have the same shape.y (Union[
primitive_types
,Matrix
]) – The input. When both are matrices they must have the same shape.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([-1, 0, 1]) >>> y = ti.Vector([1, 2, 3]) >>> z = ti.atomic_or(x, y) >>> print(x) # [-1, 2, 3] the new value of x >>> print(z) # [-1, 0, 1], the old value of x >>> >>> ti.atomic_or(1, x) # will raise TaichiSyntaxError
- taichi.lang.atomic_sub(x, y)#
Atomically subtract x by y, store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input.y (Union[
primitive_types
,Matrix
]) – The input.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([0, 0, 0]) >>> y = ti.Vector([1, 2, 3]) >>> z = ti.atomic_sub(x, y) >>> print(x) # [-1, -2, -3] the new value of x >>> print(z) # [0, 0, 0], the old value of x >>> >>> ti.atomic_sub(1, x) # will raise TaichiSyntaxError
- taichi.lang.atomic_xor(x, y)#
Atomically compute the bit-wise XOR of x and y, element-wise. Store the result in x, and return the old value of x.
x must be a writable target, constant expressions or scalars are not allowed.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input. When both are matrices they must have the same shape.y (Union[
primitive_types
,Matrix
]) – The input. When both are matrices they must have the same shape.
- Returns:
The old value of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([-1, 0, 1]) >>> y = ti.Vector([1, 2, 3]) >>> z = ti.atomic_xor(x, y) >>> print(x) # [-2, 2, 2] the new value of x >>> print(z) # [-1, 0, 1], the old value of x >>> >>> ti.atomic_xor(1, x) # will raise TaichiSyntaxError
- taichi.lang.axes(*x: Iterable[int])#
Defines a list of axes to be used by a field.
- Parameters:
*x – A list of axes to be activated
Note that Taichi has already provided a set of commonly used axes. For example, ti.ij is just axes(0, 1) under the hood.
- taichi.lang.bit_cast(obj, dtype)#
Copy and cast a scalar to a specified data type with its underlying bits preserved. Must be called in taichi scope.
This function is equivalent to reinterpret_cast in C++.
- Parameters:
obj (
primitive_types
) – Input scalar.dtype (
primitive_types
) – Target data type, must have the same precision bits as the input (hence f32 -> f64 is not allowed).
- Returns:
A copy of obj, casted to the specified data type dtype.
Example:
>>> @ti.kernel >>> def test(): >>> x = 3.14 >>> y = ti.bit_cast(x, ti.i32) >>> print(y) # 1078523331 >>> >>> z = ti.bit_cast(y, ti.f32) >>> print(z) # 3.14
- taichi.lang.bit_shr(x1, x2)#
Elements in x1 shifted to the right by number of bits in x2. Both x1, x2 must have integer type.
- Parameters:
x1 (Union[
primitive_types
,Matrix
]) – Input data.x2 (Union[
primitive_types
,Matrix
]) – Number of bits to remove at the right of x1.
- Returns:
Return x1 with bits shifted x2 times to the right. This is a scalar if both x1 and x2 are scalars.
- Example::
>>> @ti.kernel >>> def main(): >>> x = ti.Matrix([7, 8]) >>> y = ti.Matrix([1, 2]) >>> print(ti.bit_shr(x, y)) >>> >>> main() [3, 2]
- taichi.lang.block_local(*args)#
Hints Taichi to cache the fields and to enable the BLS optimization.
Please visit https://docs.taichi-lang.org/docs/performance for how BLS is used.
- Parameters:
*args (List[Field]) – A list of sparse Taichi fields.
- taichi.lang.cache_read_only(*args)#
- taichi.lang.cast(obj, dtype)#
Copy and cast a scalar or a matrix to a specified data type. Must be called in Taichi scope.
- Parameters:
obj (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.dtype (
primitive_types
) – A primitive type defined inprimitive_types
.
- Returns:
A copy of obj, casted to the specified data type dtype.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Matrix([0, 1, 2], ti.i32) >>> y = ti.cast(x, ti.f32) >>> print(y) >>> >>> test() [0.0, 1.0, 2.0]
- taichi.lang.ceil(x, dtype=None)#
Return the ceiling of the input, element-wise.
The ceil of the scalar x is the smallest integer k, such that k >= x.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.dtype – (
primitive_types
): the returned type, default to None. If set to None the retuned value will have the same type with x.
- Returns:
The ceiling of each element in x, with return value type dtype.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Matrix([3.14, -1.5]) >>> y = ti.ceil(x) >>> print(y) # [4.0, -1.0]
- taichi.lang.cos(x)#
Trigonometric cosine, element-wise.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Angle, in radians.- Returns:
The cosine of each element of x.
Example:
>>> from math import pi >>> x = ti.Matrix([-pi, 0, pi/2.]) >>> ti.cos(x) [-1., 1., 0.]
- taichi.lang.cpu#
A list of CPU backends supported on the current system. Currently contains ‘x64’, ‘x86_64’, ‘arm64’.
When this is used, Taichi automatically picks the matching CPU backend.
- taichi.lang.cuda#
The CUDA backend.
- taichi.lang.data_oriented(cls)#
Marks a class as Taichi compatible.
To allow for modularized code, Taichi provides this decorator so that Taichi kernels can be defined inside a class.
See also https://docs.taichi-lang.org/docs/odop
Example:
>>> @ti.data_oriented >>> class TiArray: >>> def __init__(self, n): >>> self.x = ti.field(ti.f32, shape=n) >>> >>> @ti.kernel >>> def inc(self): >>> for i in self.x: >>> self.x[i] += 1.0 >>> >>> a = TiArray(32) >>> a.inc()
- Parameters:
cls (Class) – the class to be decorated
- Returns:
The decorated class.
- taichi.lang.dataclass(cls)#
Converts a class with field annotations and methods into a taichi struct type.
This will return a normal custom struct type, with the functions added to it. Struct fields can be generated in the normal way from the struct type. Functions in the class can be run on the struct instance.
- This class decorator inspects the class for annotations and methods and
Sets the annotations as fields for the struct
Attaches the methods to the struct type
Example:
>>> @ti.dataclass >>> class Sphere: >>> center: vec3 >>> radius: ti.f32 >>> >>> @ti.func >>> def area(self): >>> return 4 * 3.14 * self.radius * self.radius >>> >>> my_spheres = Sphere.field(shape=(n, )) >>> my_sphere[2].area()
- Parameters:
cls (Class) – the class with annotations and methods to convert to a struct
- Returns:
- A taichi struct with the annotations as fields
and methods from the class attached.
- taichi.lang.deactivate(node, indices)#
Explicitly deactivate a cell of node at location indices.
After deactivation, the Taichi runtime automatically recycles and zero-fills the memory of the deactivated cell.
- taichi.lang.deactivate_all_snodes()#
Recursively deactivate all SNodes.
- taichi.lang.dx11#
The DX11 backend.
- taichi.lang.dx12#
The DX11 backend.
- taichi.lang.exp(x)#
Compute the exponential of all elements in x, element-wise.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.- Returns:
Element-wise exponential of x.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Matrix([-1.0, 0.0, 1.0]) >>> y = ti.exp(x) >>> print(y) >>> >>> test() [0.367879, 1.000000, 2.718282]
- taichi.lang.extension#
An instance of Taichi extension.
The list of currently available extensions is [‘sparse’, ‘quant’, ‘mesh’, ‘quant_basic’, ‘data64’, ‘adstack’, ‘bls’, ‘assertion’, ‘extfunc’].
- taichi.lang.field(dtype, *args, **kwargs)#
Defines a Taichi field.
A Taichi field can be viewed as an abstract N-dimensional array, hiding away the complexity of how its underlying
SNode
are actually defined. The data in a Taichi field can be directly accessed by a Taichikernel()
.See also https://docs.taichi-lang.org/docs/field
- Parameters:
dtype (DataType) – data type of the field. Note it can be vector or matrix types as well.
shape (Union[int, tuple[int]], optional) – shape of the field.
order (str, optional) – order of the shape laid out in memory.
name (str, optional) – name of the field.
offset (Union[int, tuple[int]], optional) – offset of the field domain.
needs_grad (bool, optional) – whether this field participates in autodiff (reverse mode) and thus needs an adjoint field to store the gradients.
needs_dual (bool, optional) – whether this field participates in autodiff (forward mode) and thus needs an dual field to store the gradients.
Example:
The code below shows how a Taichi field can be declared and defined:: >>> x1 = ti.field(ti.f32, shape=(16, 8)) >>> # Equivalently >>> x2 = ti.field(ti.f32) >>> ti.root.dense(ti.ij, shape=(16, 8)).place(x2) >>> >>> x3 = ti.field(ti.f32, shape=(16, 8), order='ji') >>> # Equivalently >>> x4 = ti.field(ti.f32) >>> ti.root.dense(ti.j, shape=8).dense(ti.i, shape=16).place(x4) >>> >>> x5 = ti.field(ti.math.vec3, shape=(16, 8))
- taichi.lang.floor(x, dtype=None)#
Return the floor of the input, element-wise. The floor of the scalar x is the largest integer k, such that k <= x.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.dtype – (
primitive_types
): the returned type, default to None. If set to None the retuned value will have the same type with x.
- Returns:
The floor of each element in x, with return value type dtype.
- Example::
>>> @ti.kernel >>> def test(): >>> x = ti.Matrix([-1.1, 2.2, 3.]) >>> y = ti.floor(x, ti.f64) >>> print(y) # [-2.000000000000, 2.000000000000, 3.000000000000]
- taichi.lang.frexp(x)#
- taichi.lang.func(fn, is_real_function=False)#
Marks a function as callable in Taichi-scope.
This decorator transforms a Python function into a Taichi one. Taichi will JIT compile it into native instructions.
- Parameters:
fn (Callable) – The Python function to be decorated
is_real_function (bool) – Whether the function is a real function
- Returns:
The decorated function
- Return type:
Callable
Example:
>>> @ti.func >>> def foo(x): >>> return x + 2 >>> >>> @ti.kernel >>> def run(): >>> print(foo(40)) # 42
- taichi.lang.get_addr(f, indices)#
Query the memory address (on CUDA/x64) of field f at index indices.
Currently, this function can only be called inside a taichi kernel.
- Parameters:
f (Union[
Field
,MatrixField
]) – Input taichi field for memory address query.indices (Union[int,
Vector
]) – The specified field indices of the query.
- Returns:
The memory address of f[indices].
- Return type:
ti.u64
- taichi.lang.gles#
The OpenGL ES backend. OpenGL ES 3.1 required.
- taichi.lang.global_thread_idx()#
Returns the global thread id of this running thread, only available for cpu and cuda backends.
For cpu backends this is equal to the cpu thread id, For cuda backends this is equal to block_id * block_dim + thread_id.
Example:
>>> f = ti.field(ti.f32, shape=(16, 16)) >>> @ti.kernel >>> def test(): >>> for i in ti.grouped(f): >>> print(ti.global_thread_idx()) >>> test()
- taichi.lang.gpu#
A list of GPU backends supported on the current system. Currently contains ‘cuda’, ‘metal’, ‘opengl’, ‘vulkan’, ‘dx11’, ‘dx12’, ‘gles’, ‘amdgpu’.
When this is used, Taichi automatically picks the matching GPU backend. If no GPU is detected, Taichi falls back to the CPU backend.
- taichi.lang.grouped(x)#
Groups the indices in the iterator returned by ndrange() into a 1-D vector.
This is often used when you want to iterate over all indices returned by ndrange() in one for loop and a single index.
- Parameters:
x (
ndrange()
) – an iterator object returned by ti.ndrange.
- Example::
>>> # without ti.grouped >>> for I in ti.ndrange(2, 3): >>> print(I) prints 0, 1, 2, 3, 4, 5
>>> # with ti.grouped >>> for I in ti.grouped(ndrange(2, 3)): >>> print(I) prints [0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]
- taichi.lang.i#
Axis 0. For multi-dimensional arrays it’s the direction downward the rows. For a 1d array it’s the direction along this array.
- taichi.lang.ij#
Axes (0, 1).
- taichi.lang.ijk#
Axes (0, 1, 2).
- taichi.lang.ijkl#
Axes (0, 1, 2, 3).
- taichi.lang.ijl#
Axes (0, 1, 3).
- taichi.lang.ik#
Axes (0, 2).
- taichi.lang.ikl#
Axes (0, 2, 3).
- taichi.lang.il#
Axes (0, 3).
- taichi.lang.init(arch=None, default_fp=None, default_ip=None, _test_mode=False, enable_fallback=True, require_version=None, **kwargs)#
Initializes the Taichi runtime.
This should always be the entry point of your Taichi program. Most importantly, it sets the backend used throughout the program.
- Parameters:
default_fp (Optional[type]) – Default floating-point type.
default_ip (Optional[type]) – Default integral type.
require_version (Optional[string]) – A version string.
**kwargs –
Taichi provides highly customizable compilation through
kwargs
, which allows for fine grained control of Taichi compiler behavior. Below we list some of the most frequently used ones. For a complete list, please check out https://github.com/taichi-dev/taichi/blob/master/taichi/program/compile_config.h.cpu_max_num_threads
(int): Sets the number of threads used by the CPU thread pool.debug
(bool): Enables the debug mode, under which Taichi does a few more things like boundary checks.print_ir
(bool): Prints the CHI IR of the Taichi kernels.
*
offline_cache
(bool): Enables offline cache of the compiled kernels. Default to True. When this is enabled Taichi will cache compiled kernel on your local disk to accelerate future calls. *random_seed
(int): Sets the seed of the random generator. The default is 0.
- taichi.lang.is_active(node, indices)#
Explicitly query whether a cell in a SNode node at location indices is active or not.
- taichi.lang.j#
Axis 1. For multi-dimensional arrays it’s the direction across the columns.
- taichi.lang.jk#
Axes (1, 2).
- taichi.lang.jkl#
Axes (1, 2, 3).
- taichi.lang.jl#
Axes (1, 3).
- taichi.lang.k#
Axis 2. For arrays of dimension d >= 3, view each cell as an array of lower dimension d-2, it’s the first axis of this cell.
- taichi.lang.kernel(fn)#
Marks a function as a Taichi kernel.
A Taichi kernel is a function written in Python, and gets JIT compiled by Taichi into native CPU/GPU instructions (e.g. a series of CUDA kernels). The top-level
for
loops are automatically parallelized, and distributed to either a CPU thread pool or massively parallel GPUs.Kernel’s gradient kernel would be generated automatically by the AutoDiff system.
See also https://docs.taichi-lang.org/docs/syntax#kernel.
- Parameters:
fn (Callable) – the Python function to be decorated
- Returns:
The decorated function
- Return type:
Callable
Example:
>>> x = ti.field(ti.i32, shape=(4, 8)) >>> >>> @ti.kernel >>> def run(): >>> # Assigns all the elements of `x` in parallel. >>> for i in x: >>> x[i] = i
- taichi.lang.kl#
Axes (2, 3).
- taichi.lang.l#
Axis 3. For arrays of dimension d >= 4, view each cell as an array of lower dimension d-2, it’s the second axis of this cell.
- taichi.lang.length(node, indices)#
Return the length of the dynamic SNode node at index indices.
- taichi.lang.log(x)#
Compute the natural logarithm, element-wise.
The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.- Returns:
The natural logarithm of x, element-wise.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([-1.0, 0.0, 1.0]) >>> y = ti.log(x) >>> print(y) >>> >>> test() [-nan, -inf, 0.000000]
- taichi.lang.loop_config(block_dim=None, serialize=False, parallelize=None, block_dim_adaptive=True, bit_vectorize=False)#
Sets directives for the next loop
- Parameters:
block_dim (int) – The number of threads in a block on GPU
serialize (bool) – Whether to let the for loop execute serially, serialize=True equals to parallelize=1
parallelize (int) – The number of threads to use on CPU
block_dim_adaptive (bool) – Whether to allow backends set block_dim adaptively, enabled by default
bit_vectorize (bool) – Whether to enable bit vectorization of struct fors on quant_arrays.
Examples:
@ti.kernel def break_in_serial_for() -> ti.i32: a = 0 ti.loop_config(serialize=True) for i in range(100): # This loop runs serially a += i if i == 10: break return a break_in_serial_for() # returns 55 n = 128 val = ti.field(ti.i32, shape=n) @ti.kernel def fill(): ti.loop_config(parallelize=8, block_dim=16) # If the kernel is run on the CPU backend, 8 threads will be used to run it # If the kernel is run on the CUDA backend, each block will have 16 threads. for i in range(n): val[i] = i u1 = ti.types.quant.int(bits=1, signed=False) x = ti.field(dtype=u1) y = ti.field(dtype=u1) cell = ti.root.dense(ti.ij, (128, 4)) cell.quant_array(ti.j, 32).place(x) cell.quant_array(ti.j, 32).place(y) @ti.kernel def copy(): ti.loop_config(bit_vectorize=True) # 32 bits, instead of 1 bit, will be copied at a time for i, j in x: y[i, j] = x[i, j]
- taichi.lang.max(*args)#
Compute the maximum of the arguments, element-wise.
This function takes no effect on a single argument, even it’s array-like. When there are both scalar and matrix arguments in args, the matrices must have the same shape, and scalars will be broadcasted to the same shape as the matrix.
- Parameters:
args – (List[
primitive_types
,Matrix
]): The input.- Returns:
Maximum of the inputs.
Example:
>>> @ti.kernel >>> def foo(): >>> x = ti.Vector([0, 1, 2]) >>> y = ti.Vector([3, 4, 5]) >>> z = ti.max(x, y, 4) >>> print(z) # [4, 4, 5]
- taichi.lang.mesh_local(*args)#
Hints the compiler to cache the mesh attributes and to enable the mesh BLS optimization, only available for backends supporting ti.extension.mesh and to use with mesh-for loop.
Related to https://github.com/taichi-dev/taichi/issues/3608
- Parameters:
*args (List[Attribute]) – A list of mesh attributes or fields accessed as attributes.
Examples:
# instantiate model mesh_builder = ti.Mesh.tri() mesh_builder.verts.place({ 'x' : ti.f32, 'y' : ti.f32 }) model = mesh_builder.build(meta) @ti.kernel def foo(): # hint the compiler to cache mesh vertex attribute `x` and `y`. ti.mesh_local(model.verts.x, model.verts.y) for v0 in model.verts: # mesh-for loop for v1 in v0.verts: v0.x += v1.y
- taichi.lang.mesh_patch_idx()#
Returns the internal mesh patch id of this running thread, only available for backends supporting ti.extension.mesh and to use within mesh-for loop.
- taichi.lang.metal#
The Apple Metal backend.
- taichi.lang.min(*args)#
Compute the minimum of the arguments, element-wise.
This function takes no effect on a single argument, even it’s array-like. When there are both scalar and matrix arguments in args, the matrices must have the same shape, and scalars will be broadcasted to the same shape as the matrix.
- Parameters:
args – (List[
primitive_types
,Matrix
]): The input.- Returns:
Minimum of the inputs.
Example:
>>> @ti.kernel >>> def foo(): >>> x = ti.Vector([0, 1, 2]) >>> y = ti.Vector([3, 4, 5]) >>> z = ti.min(x, y, 1) >>> print(z) # [0, 1, 1]
- taichi.lang.ndarray(dtype, shape, needs_grad=False)#
Defines a Taichi ndarray with scalar elements.
- Parameters:
dtype (Union[DataType, MatrixType]) – Data type of each element. This can be either a scalar type like ti.f32 or a compound type like ti.types.vector(3, ti.i32).
shape (Union[int, tuple[int]]) – Shape of the ndarray.
Example
The code below shows how a Taichi ndarray with scalar elements can be declared and defined:
>>> x = ti.ndarray(ti.f32, shape=(16, 8)) # ndarray of shape (16, 8), each element is ti.f32 scalar. >>> vec3 = ti.types.vector(3, ti.i32) >>> y = ti.ndarray(vec3, shape=(10, 2)) # ndarray of shape (10, 2), each element is a vector of 3 ti.i32 scalars. >>> matrix_ty = ti.types.matrix(3, 4, float) >>> z = ti.ndarray(matrix_ty, shape=(4, 5)) # ndarray of shape (4, 5), each element is a matrix of (3, 4) ti.float scalars.
- taichi.lang.ndrange(*args) Iterable #
Return an immutable iterator object for looping over multi-dimensional indices.
This returned set of multi-dimensional indices is the direct product (in the set-theory sense) of n groups of integers, where n equals the number of arguments in the input list, and looks like
range(x1, y1) x range(x2, y2) x … x range(xn, yn)
The k-th argument corresponds to the k-th range() factor in the above product, and each argument must be an integer or a pair of two integers. An integer argument n will be interpreted as range(0, n), and a pair of two integers (start, end) will be interpreted as range(start, end).
You can loop over these multi-dimensonal indices in different ways, see the examples below.
- Parameters:
entries – (int, tuple): Must be either an integer, or a tuple/list of two integers.
- Returns:
An immutable iterator object.
Example:
You can loop over 1-D integers in range [start, end), as in native Python >>> @ti.kernel >>> def loop_1d(): >>> start = 2 >>> end = 5 >>> for i in ti.ndrange((start, end)): >>> print(i) # will print 2 3 4 Note the braces around `(start, end)` in the above code. If without them, the parameter `2` will be interpreted as `range(0, 2)`, `5` will be interpreted as `range(0, 5)`, and you will get a set of 2-D indices which contains 2x5=10 elements, and need two indices i, j to loop over them: >>> @ti.kernel >>> def loop_2d(): >>> for i, j in ti.ndrange(2, 5): >>> print(i, j) 0 0 ... 0 4 ... 1 4 But you do can use a single index i to loop over these 2-D indices, in this case the indices are returned as a 1-D array `(0, 1, ..., 9)`: >>> @ti.kernel >>> def loop_2d_as_1d(): >>> for i in ti.ndrange(2, 5): >>> print(i) will print 0 1 2 3 4 5 6 7 8 9 In general, you can use any `1 <= k <= n` iterators to loop over a set of n-D indices. For `k=n` all the indices are n-dimensional, and they are returned in lexical order, but for `k<n` iterators the last n-k+1 dimensions will be collapsed into a 1-D array of consecutive integers `(0, 1, 2, ...)` whose length equals the total number of indices in the last n-k+1 dimensions: >>> @ti.kernel >>> def loop_3d_as_2d(): >>> # use two iterators to loop over a set of 3-D indices >>> # the last two dimensions for 4, 5 will collapse into >>> # the array [0, 1, 2, ..., 19] >>> for i, j in ti.ndrange(3, 4, 5): >>> print(i, j) will print 0 0, 0 1, ..., 0 19, ..., 2 19. A typical usage of `ndrange` is when you want to loop over a tensor and process its entries in parallel. You should avoid writing nested `for` loops here since only top level `for` loops are paralleled in taichi, instead you can use `ndrange` to hold all entries in one top level loop: >>> @ti.kernel >>> def loop_tensor(): >>> for row, col, channel in ti.ndrange(image_height, image_width, channels): >>> image[row, col, channel] = ...
- taichi.lang.no_activate(*args)#
Deactivates a SNode pointer.
- taichi.lang.one(x)#
Returns an array of ones with the same shape and type as the input. It’s also a scalar if the input is a scalar.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input.- Returns:
A new copy of the input but filled with ones.
Example:
>>> x = ti.Vector([0, 0]) >>> @ti.kernel >>> def test(): >>> y = ti.one(x) >>> print(y) [1, 1]
- taichi.lang.opengl#
The OpenGL backend. OpenGL 4.3 required.
- taichi.lang.pow(base, exponent)#
First array elements raised to second array elements \({base}^{exponent}\), element-wise.
The result type of two scalar operands is determined as follows: - If the exponent is an integral value, then the result type takes the type of the base. - Otherwise, the result type follows
[Implicit type casting in binary operations](https://docs.taichi-lang.org/docs/type#implicit-type-casting-in-binary-operations).
With the above rules, an integral value raised to a negative integral value cannot have a feasible type. Therefore, an exception will be raised if debug mode or optimization passes are on; otherwise 1 will be returned.
In the following situations, the result is undefined: - A negative value raised to a non-integral value. - A zero value raised to a non-positive value.
- Parameters:
base (Union[
primitive_types
,Matrix
]) – The bases.exponent (Union[
primitive_types
,Matrix
]) – The exponents.
- Returns:
base raised to exponent. This is a scalar if both base and exponent are scalars.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Matrix([-2.0, 2.0]) >>> y = -3 >>> z = ti.pow(x, y) >>> print(z) >>> >>> test() [-0.125000, 0.125000]
- taichi.lang.pyfunc(fn)#
Marks a function as callable in both Taichi and Python scopes.
When called inside the Taichi scope, Taichi will JIT compile it into native instructions. Otherwise it will be invoked directly as a Python function.
See also
func()
.- Parameters:
fn (Callable) – The Python function to be decorated
- Returns:
The decorated function
- Return type:
Callable
- taichi.lang.random(dtype=float) float | int #
Return a single random float/integer according to the specified data type. Must be called in taichi scope.
If the required dtype is float type, this function returns a random number sampled from the uniform distribution in the half-open interval [0, 1).
For integer types this function returns a random integer in the half-open interval [0, 2^32) if a 32-bit integer is required, or a random integer in the half-open interval [0, 2^64) if a 64-bit integer is required.
- Parameters:
dtype (
primitive_types
) – Type of the required random value.- Returns:
A random value with type dtype.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.random(float) >>> print(x) # 0.090257 >>> >>> y = ti.random(ti.f64) >>> print(y) # 0.716101627301 >>> >>> i = ti.random(ti.i32) >>> print(i) # -963722261 >>> >>> j = ti.random(ti.i64) >>> print(j) # 73412986184350777
- taichi.lang.raw_div(x1, x2)#
Return x1 // x2 if both x1, x2 are integers, otherwise return x1/x2.
- Parameters:
x1 (Union[
primitive_types
,Matrix
]) – Dividend.x2 (Union[
primitive_types
,Matrix
]) – Divisor.
- Returns:
Return x1 // x2 if both x1, x2 are integers, otherwise return x1/x2.
Example:
>>> @ti.kernel >>> def main(): >>> x = 5 >>> y = 3 >>> print(raw_div(x, y)) # 1 >>> z = 4.0 >>> print(raw_div(x, z)) # 1.25
- taichi.lang.raw_mod(x1, x2)#
Return the remainder of x1/x2, element-wise. This is the C-style mod function.
- Parameters:
x1 (Union[
primitive_types
,Matrix
]) – The dividend.x2 (Union[
primitive_types
,Matrix
]) – The divisor.
- Returns:
The remainder of x1 divided by x2.
Example:
>>> @ti.kernel >>> def main(): >>> print(ti.mod(-4, 3)) # 2 >>> print(ti.raw_mod(-4, 3)) # -1
- taichi.lang.rescale_index(a, b, I)#
Rescales the index ‘I’ of field (or SNode) ‘a’ to match the shape of SNode ‘b’.
- Parameters:
a (Union[
Field
,MatrixField
) – Input taichi fields or snodes.b (Union[
Field
,MatrixField
) – Input taichi fields or snodes.I (Union[list,
Vector
]) – grouped loop index.
- Returns:
rescaled grouped loop index
- Return type:
Ib (
Vector
)
- taichi.lang.reset()#
Resets Taichi to its initial state. This will destroy all the allocated fields and kernels, and restore the runtime to its default configuration.
Example:
>>> a = ti.field(ti.i32, shape=()) >>> a[None] = 1 >>> print("before reset: ", a) before rest: 1 >>> >>> ti.reset() >>> print("after reset: ", a) # will raise error because a is unavailable after reset.
- taichi.lang.root#
Root of the declared Taichi :func:`~taichi.lang.impl.field`s.
See also https://docs.taichi-lang.org/docs/layout
Example:
>>> x = ti.field(ti.f32) >>> ti.root.pointer(ti.ij, 4).dense(ti.ij, 8).place(x)
- taichi.lang.round(x, dtype=None)#
Round to the nearest integer, element-wise.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – A scalar or a matrix.dtype – (
primitive_types
): the returned type, default to None. If set to None the retuned value will have the same type with x.
- Returns:
The nearest integer of x, with return value type dtype.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Vector([-1.5, 1.2, 2.7]) >>> print(ti.round(x)) [-2., 1., 3.]
- taichi.lang.rsqrt(x)#
The reciprocal of the square root function.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – A scalar or a matrix.- Returns:
The reciprocal of sqrt(x).
- taichi.lang.select(cond, x1, x2)#
Return an array drawn from elements in x1 or x2, depending on the conditions in cond.
- Parameters:
cond (Union[
primitive_types
,Matrix
]) – The array of conditions.x1 (Union[
primitive_types
,Matrix
]) – The arrays where the output elements are taken from.x2 (Union[
primitive_types
,Matrix
]) – The arrays where the output elements are taken from.
- Returns:
The output at position k is the k-th element of x1 if the k-th element in cond is True, otherwise it’s the k-th element of x2.
Example:
>>> @ti.kernel >>> def main(): >>> cond = ti.Matrix([0, 1, 0, 1]) >>> x = ti.Matrix([1, 2, 3, 4]) >>> y = ti.Matrix([-1, -2, -3, -4]) >>> print(ti.select(cond, x, y)) >>> >>> main() [-1, 2, -3, 4]
- taichi.lang.sin(x)#
Trigonometric sine, element-wise.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Angle, in radians.- Returns:
The sine of each element of x.
Example:
>>> from math import pi >>> x = ti.Matrix([-pi/2., 0, pi/2.]) >>> ti.sin(x) [-1., 0., 1.]
- taichi.lang.sqrt(x)#
Return the non-negative square-root of a scalar or a matrix, element wise. If x < 0 an exception is raised.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The scalar or matrix whose square-roots are required.- Returns:
The square-root y so that y >= 0 and y^2 = x. y has the same type as x.
Example:
>>> x = ti.Matrix([1., 4., 9.]) >>> y = ti.sqrt(x) >>> y [1.0, 2.0, 3.0]
- taichi.lang.static(x, *xs) Any #
Evaluates a Taichi-scope expression at compile time.
static() is what enables the so-called metaprogramming in Taichi. It is in many ways similar to
constexpr
in C++.See also https://docs.taichi-lang.org/docs/meta.
- Parameters:
x (Any) – an expression to be evaluated
*xs (Any) – for Python-ish swapping assignment
Example
The most common usage of static() is for compile-time evaluation:
>>> cond = False >>> >>> @ti.kernel >>> def run(): >>> if ti.static(cond): >>> do_a() >>> else: >>> do_b()
Depending on the value of
cond
,run()
will be directly compiled into eitherdo_a()
ordo_b()
. Thus there won’t be a runtime condition check.Another common usage is for compile-time loop unrolling:
>>> @ti.kernel >>> def run(): >>> for i in ti.static(range(3)): >>> print(i) >>> >>> # The above will be unrolled to: >>> @ti.kernel >>> def run(): >>> print(0) >>> print(1) >>> print(2)
- taichi.lang.static_assert(cond, msg=None)#
Throw AssertionError when cond is False.
This function is called at compile time and has no runtime overhead. The bool value in cond must can be determined at compile time.
- Parameters:
cond (bool) – an expression with a bool value.
msg (str) – assertion message.
Example:
>>> year = 2001 >>> @ti.kernel >>> def test(): >>> ti.static_assert(year % 4 == 0, "the year must be a lunar year") AssertionError: the year must be a lunar year
- taichi.lang.static_print(*args, __p=print, **kwargs)#
The print function in Taichi scope.
This function is called at compile time and has no runtime overhead.
- taichi.lang.stop_grad(x)#
Stops computing gradients during back propagation.
- Parameters:
x (
Field
) – A field.
- taichi.lang.sync()#
Blocks the calling thread until all the previously launched Taichi kernels have completed.
- taichi.lang.tan(x)#
Trigonometric tangent function, element-wise.
Equivalent to ti.sin(x)/ti.cos(x) element-wise.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.- Returns:
The tangent values of x.
Example:
>>> from math import pi >>> @ti.kernel >>> def test(): >>> x = ti.Matrix([-pi, pi/2, pi]) >>> y = ti.tan(x) >>> print(y) >>> >>> test() [-0.0, -22877334.0, 0.0]
- taichi.lang.tanh(x)#
Compute the hyperbolic tangent of x, element-wise.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – Input scalar or matrix.- Returns:
The corresponding hyperbolic tangent values.
Example:
>>> @ti.kernel >>> def test(): >>> x = ti.Matrix([-1.0, 0.0, 1.0]) >>> y = ti.tanh(x) >>> print(y) >>> >>> test() [-0.761594, 0.000000, 0.761594]
- taichi.lang.vulkan#
The Vulkan backend.
- taichi.lang.x64#
The X64 CPU backend.
- taichi.lang.x86_64#
The x64 CPU backend.
- taichi.lang.zero(x)#
Returns an array of zeros with the same shape and type as the input. It’s also a scalar if the input is a scalar.
- Parameters:
x (Union[
primitive_types
,Matrix
]) – The input.- Returns:
A new copy of the input but filled with zeros.
Example:
>>> x = ti.Vector([1, 1]) >>> @ti.kernel >>> def test(): >>> y = ti.zero(x) >>> print(y) [0, 0]