Skip to main content

taichi#

class taichi.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.

place(self, *args, shared_exponent=False)#

Places a list of fields with quantized types inside.

Parameters:
  • *args (List[Field]) – A list of fields with quantized types to place.

  • shared_exponent (bool) – Whether the fields have a shared exponent.

taichi.CRITICAL = critical#

The str ‘critical’, used for the critical logging level.

taichi.DEBUG = debug#

The str ‘debug’, used for the debug logging level.

class taichi.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=1.3#
spirv_version_1_4 = spirv_version=1.4#
spirv_version_1_5 = spirv_version=1.5#
taichi.ERROR = error#

The str ‘error’, used for the error logging level.

class taichi.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.

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:

SNode

class taichi.FieldsBuilder#

A builder that constructs a SNodeTree instance.

Example:

x = ti.field(ti.i32)
y = ti.field(ti.f32)
fb = ti.FieldsBuilder()
fb.dense(ti.ij, 8).place(x)
fb.pointer(ti.ij, 8).dense(ti.ij, 4).place(y)

# After this line, `x` and `y` are placed. No more fields can be placed
# into `fb`.
#
# The tree looks like the following:
# (implicit root)
#  |
#  +-- dense +-- place(x)
#  |
#  +-- pointer +-- dense +-- place(y)
fb.finalize()
bitmasked(self, indices: Sequence[_Axis] | _Axis, dimensions: Sequence[int] | int)#

Same as taichi.lang.snode.SNode.bitmasked()

deactivate_all(self)#

Same as taichi.lang.snode.SNode.deactivate_all()

dense(self, indices: Sequence[_Axis] | _Axis, dimensions: Sequence[int] | int)#

Same as taichi.lang.snode.SNode.dense()

dynamic(self, index: Sequence[_Axis] | _Axis, dimension: Sequence[int] | int, chunk_size: int | None = None)#

Same as taichi.lang.snode.SNode.dynamic()

finalize(self, raise_warning=True)#

Constructs the SNodeTree and finalizes this builder.

Parameters:

raise_warning (bool) – Raise warning or not.

lazy_dual(self)#

Same as taichi.lang.snode.SNode.lazy_dual()

lazy_grad(self)#

Same as taichi.lang.snode.SNode.lazy_grad()

place(self, *args: Any, offset: Sequence[int] | int | None = None)#

Same as taichi.lang.snode.SNode.place()

pointer(self, indices: Sequence[_Axis] | _Axis, dimensions: Sequence[int] | int)#

Same as taichi.lang.snode.SNode.pointer()

quant_array(self, indices: Sequence[_Axis] | _Axis, dimensions: Sequence[int] | int, max_num_bits: int)#

Same as taichi.lang.snode.SNode.quant_array()

taichi.Format#
class taichi.GUI(name='Taichi', res=512, background_color=0, show_gui=True, fullscreen=False, fast_gui=False)#

Taichi Graphical User Interface class.

Parameters:
  • name (str, optional) – The name of the GUI to be constructed. Default is ‘Taichi’.

  • res (Union[int, List[int]], optional) – The resolution of created GUI. Default is 512*512. If res is scalar, then width will be equal to height.

  • background_color (int, optional) – The background color of created GUI. Default is 0x000000.

  • show_gui (bool, optional) – Specify whether to render the GUI. Default is True.

  • fullscreen (bool, optional) – Specify whether to render the GUI in fullscreen mode. Default is False.

  • fast_gui (bool, optional) – Specify whether to use fast gui mode of Taichi. Default is False.

Returns:

The created taichi GUI object.

Return type:

GUI

class Event#

Class for holding a gui event.

An event is represented by:

  • type (PRESS, MOTION, RELEASE)

  • modifier (modifier keys like ctrl, shift, etc)

  • pos (mouse position)

  • key (event key)

  • delta (for holding mouse wheel)

class EventFilter(*e_filter)#

A set to store detected user events.

match(self, e)#

Check if a specified event e is among the detected events.

class WidgetValue(gui, wid)#

Class for maintaining id of gui widgets.

ALT = Alt#
BACKSPACE = BackSpace#
CAPSLOCK = Caps_Lock#
CTRL = Control#
DOWN = Down#
ESCAPE = Escape#
EXIT = WMClose#
LEFT = Left#
LMB = LMB#
MMB = MMB#
MOTION#
MOVE = Motion#
PRESS#
RELEASE#
RETURN = Return#
RIGHT = Right#
RMB = RMB#
SHIFT = Shift#
SPACE =#
TAB = Tab#
UP = Up#
WHEEL = Wheel#
arrow(self, orig, direction, radius=1, color=16777215, **kwargs)#

Draws a single arrow on canvas.

Parameters:
  • orig (List[Number]) – The position where arrow starts. Shape must be 2.

  • direction (List[Number]) – The direction where arrow points to. Shape must be 2.

  • radius (Number, optional) – The width of arrow. Default is 1.

  • color (int, optional) – The color of arrow. Default is 0xFFFFFF.

arrow_field(self, direction, radius=1, color=16777215, bound=0.5, **kwargs)#

Draw a field of arrows on canvas.

Parameters:
  • direction (np.array) – The pattern and direction of the field of arrows.

  • color (Union[int, np.array], optional) – The color or colors of arrows. Default is 0xFFFFFF.

  • bound (Number, optional) – The boundary of the field. Default is 0.5.

arrows(self, orig, direction, radius=1, color=16777215, **kwargs)#

Draw a list arrows on canvas.

Parameters:
  • orig (numpy.array) – The positions where arrows start.

  • direction (numpy.array) – The directions where arrows point to.

  • radius (Union[Number, np.array], optional) – The width of arrows. Default is 1.

  • color (Union[int, np.array], optional) – The color or colors of arrows. Default is 0xffffff.

button(self, text, event_name=None)#

Create a button object on canvas to be manipulated with.

Parameters:
  • text (str) – The title of button.

  • event_name (str, optional) – The event name associated with button. Default is WidgetButton_{text}

Returns:

The event name associated with created button.

circle(self, pos, color=16777215, radius=1)#

Draws a circle on canvas.

Parameters:
  • pos (Union[List[int], numpy.array]) – The position of the circle.

  • color (int, Optional) – The color of the circle. Default is 0xFFFFFF.

  • radius (Number, Optional) – The radius of the circle in pixel. Default is 1.

circles(self, pos, radius=1, color=16777215, palette=None, palette_indices=None)#

Draws a list of circles on canvas.

Parameters:
  • pos (numpy.array) – The positions of the circles.

  • radius (Union[Number, numpy.array], optional) – The radius of the circles in pixel. Can be either a number, which will be applied to all circles, or a 1D NumPy array of the same length as pos. The default is 1.

  • color (int, optional) – The color of the circles. Default is 0xFFFFFF.

  • palette (list[int], optional) – The List of colors from which to choose to draw. Default is None.

  • palette_indices (Union[list[int], ti.field, numpy.array], optional) – The List of indices that choose color from palette for each circle. Shape must match pos. Default is None.

clear(self, color=None)#

Clears the canvas with the color provided.

Parameters:

color (int, optional) – Specify the color to clear the canvas. Default is the background color of GUI.

close(self)#

Close this GUI.

Example:

>>> while gui.running:
>>>     if gui.get_event(gui.PRESS, ti.GUI.ESCAPE):
>>>         gui.close()
>>>     gui.show()
cook_image(self, img)#

Converts an img to range [0, 1] for display.

The input image is stored in a numpy.ndarray, if it’s dtype is int it will be rescaled and mapped into range [0, 1]. If the dtype is float it will be directly casted to 32-bit float type.

static get_bool_environ(key, default)#

Get an environment variable and cast it to bool.

Parameters:
  • key (str) – The environment variable key.

  • default (bool) – The default value.

Returns:

The environment variable value cast to bool. If the value is not found, directly return argument ‘default’.

get_cursor_pos(self)#

Returns the current position of mouse as a pair of floats in the range [0, 1] x [0, 1].

The origin of the coordinates system is located at the lower left corner, with +x direction points to the right, and +y direcntion points upward.

Returns:

The current position of mouse.

get_event(self, *e_filter)#

Checks if the specified event is triggered.

Parameters:

*e_filter (ti.GUI.EVENT) – The specific event to be checked.

Returns:

whether or not the specified event is triggered.

Return type:

bool

get_events(self, *e_filter)#

Gets a list of events that are triggered.

Parameters:

*e_filter (List[ti.GUI.EVENT]) – The type of events to be filtered.

Returns:

A list of events that are triggered.

Return type:

EVENT

get_image(self)#

Return the window content as an numpy.ndarray.

Returns:

The image data in numpy contiguous array type.

Return type:

numpy.array

get_key_event(self)#

Gets keyboard triggered event.

Returns:

The keyboard triggered event.

Return type:

EVENT

has_key_event(self)#

Check if there is any key event registered.

Returns:

whether or not there is any key event registered.

Return type:

bool

is_pressed(self, *keys)#

Checks if any key among a set of specified keys is pressed.

Parameters:

*keys (Union[str, List[str]]) – The keys to be listened to.

Returns:

whether or not any key among the specified keys is pressed.

Return type:

bool

label(self, text)#

Creates a label object on canvas.

Parameters:

text (str) – The title of label.

Returns:

The created label object.

Return type:

WidgetValue

line(self, begin, end, radius=1, color=16777215)#

Draws a single line on canvas.

Parameters:
  • begin (List[Number]) – The position of one end of line. Shape must be 2.

  • end (List[Number]) – The position of the other end of line. Shape must be 2.

  • radius (Number, optional) – The width of line. Default is 1.

  • color (int, optional) – The color of line. Default is 0xFFFFFF.

lines(self, begin, end, radius=1, color=16777215)#

Draw a list of lines on canvas.

Parameters:
  • begin (numpy.array) – The positions of one end of lines.

  • end (numpy.array) – The positions of the other end of lines.

  • radius (Union[Number, numpy.array], optional) – The width of lines. Can be either a single width or a list of width whose shape matches the shape of begin & end. Default is 1.

  • color (Union[int, numpy.array], optional) – The color or colors of lines. Can be either a single color or a list of colors whose shape matches the shape of begin & end. Default is 0xFFFFFF.

point_field(self, radius, color=16777215, bound=0.5)#

Draws a field of points on canvas.

Parameters:
  • radius (np.array) – The pattern and radius of the field of points.

  • color (Union[int, np.array], optional) – The color or colors of points. Default is 0xFFFFFF.

  • bound (Number, optional) – The boundary of the field. Default is 0.5.

rect(self, topleft, bottomright, radius=1, color=16777215)#

Draws a single rectangle on canvas.

Parameters:
  • topleft (List[Number]) – The position of the topleft corner of rectangle. Shape must be 2.

  • bottomright (List[Number]) – The position of the bottomright corner of rectangle. Shape must be 2.

  • radius (Number, optional) – The width of rectangle’s sides. Default is 1.

  • color (int, optional) – The color of rectangle. Default is 0xFFFFFF.

set_image(self, img)#

Sets an image to display on the window.

The image pixels are set from the values of img[i, j], where i indicates the horizontal coordinates (from left to right) and j the vertical coordinates (from bottom to top).

If the window size is (x, y), then img must be one of:
  • ti.field(shape=(x, y)), a gray-scale image

  • ti.field(shape=(x, y, 3)), where 3 is for (r, g, b) channels

  • ti.field(shape=(x, y, 2)), where 2 is for (r, g) channels

  • ti.Vector.field(3, shape=(x, y)) (r, g, b) channels on each component

  • ti.Vector.field(2, shape=(x, y)) (r, g) channels on each component

  • np.ndarray(shape=(x, y))

  • np.ndarray(shape=(x, y, 3))

  • np.ndarray(shape=(x, y, 2))

The data type of img must be one of:
  • uint8, range [0, 255]

  • uint16, range [0, 65535]

  • uint32, range [0, 4294967295]

  • float32, range [0, 1]

  • float64, range [0, 1]

Parameters:

img (Union[taichi.field, numpy.array]) – The color array representing the image to be drawn. Support greyscale, RG, RGB, and RGBA color representations. Its shape must match GUI resolution.

show(self, file=None)#

Shows the frame content in the gui window, or save the content to an image file.

Parameters:

file (str, optional) – output filename. The default is None, and the frame content is displayed in the gui window. If it’s a valid image filename the frame will be saved as the specified image.

slider(self, text, minimum, maximum, step=1)#

Creates a slider object on canvas to be manipulated with.

Parameters:
  • text (str) – The title of slider.

  • minimum (int, float) – The minimum value of slider.

  • maximum (int, float) – The maximum value of slider.

  • step (int, float) – The changing step of slider. Optional and default to 1.

Returns:

The created slider object.

Return type:

WidgetValue

text(self, content, pos, font_size=15, color=16777215)#

Draws texts on canvas.

Parameters:
  • content (str) – The text to be drawn on canvas.

  • pos (List[Number]) – The position where the text is to be put.

  • font_size (Number, optional) – The font size of the text.

  • color (int, optional) – The color of the text. Default is 0xFFFFFF.

triangle(self, a, b, c, color=16777215)#

Draws a single triangle on canvas.

Parameters:
  • a (List[Number]) – The position of the first point of triangle. Shape must be 2.

  • b (List[Number]) – The position of the second point of triangle. Shape must be 2.

  • c (List[Number]) – The position of the third point of triangle. Shape must be 2.

  • color (int, optional) – The color of the triangle. Default is 0xFFFFFF.

triangles(self, a, b, c, color=16777215)#

Draws a list of triangles on canvas.

Parameters:
  • a (numpy.array) – The positions of the first points of triangles.

  • b (numpy.array) – The positions of the second points of triangles.

  • c (numpy.array) – The positions of the third points of triangles.

  • color (Union[int, numpy.array], optional) – The color or colors of triangles. Can be either a single color or a list of colors whose shape matches the shape of a & b & c. Default is 0xFFFFFF.

taichi.INFO = info#

The str ‘info’, used for the info logging level.

taichi.Layout#
class taichi.Matrix(arr, dt=None, ndim=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:

taichi.Matrix

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:

Matrix

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.

Parameters:

other (Matrix) – The input Vector.

Returns:

The cross product of the two Vectors.

Return type:

Matrix

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:

Matrix

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:

DataType

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:

Matrix

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).

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The number of rows/columns.

Returns:

An n x n identity matrix.

Return type:

Matrix

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:

Matrix

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.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with ones.

Return type:

Matrix

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.

Parameters:

other (Matrix) – The input Vector.

Returns:

The outer product of the two Vectors.

Return type:

Matrix

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:

Matrix

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, keep_dims=False)#

Converts this matrix to a numpy array.

Parameters:

keep_dims (bool, optional) – Whether to keep the dimension after conversion. If set to False, the resulting numpy array will discard the axis of length one.

Returns:

The result numpy array.

Return type:

numpy.ndarray

Example:

>>> A = ti.Matrix([[0], [1], [2], [3]])
>>> A.to_numpy(keep_dims=False)
>>> 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:

Matrix

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:

Matrix

Example:

>>> A = ti.Matrix.unit(3, 1)
>>> A
[0, 1, 0]
static zero(dt, n, m=None)#

Constructs a Matrix filled with zeros.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with zeros.

Return type:

Matrix

class taichi.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:

ScalarField

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:

SNode

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.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.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.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.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.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, using taichi.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.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:

SNode

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.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.Struct(*args, **kwargs)#

Bases: taichi.lang.common_ops.TaichiOperations

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)}

fill(self, val)#

Fills the Struct with a specific value in Taichi scope.

Parameters:

val (Union[int, float]) – Value to fill.

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.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:

ScalarField

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]]

taichi.TRACE = trace#

The str ‘trace’, used for the debug logging level.

exception taichi.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.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.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.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.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.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.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.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.u8 dtype and num_channels=4.

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.u8 dtype and num_channels=4.

Returns:

a PIL image in RGB mode, with the same size as source texture.

Return type:

img (PIL.Image.Image)

class taichi.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:

taichi.Matrix

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:

Matrix

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.

Parameters:

other (Matrix) – The input Vector.

Returns:

The cross product of the two Vectors.

Return type:

Matrix

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:

Matrix

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:

DataType

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).

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The number of rows/columns.

Returns:

An n x n identity matrix.

Return type:

Matrix

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:

Matrix

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.

  • layout (Layout, optional) – Memory layout, AOS by default.

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.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with ones.

Return type:

Matrix

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.

Parameters:

other (Matrix) – The input Vector.

Returns:

The outer product of the two Vectors.

Return type:

Matrix

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:

Matrix

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, keep_dims=False)#

Converts this matrix to a numpy array.

Parameters:

keep_dims (bool, optional) – Whether to keep the dimension after conversion. If set to False, the resulting numpy array will discard the axis of length one.

Returns:

The result numpy array.

Return type:

numpy.ndarray

Example:

>>> A = ti.Matrix([[0], [1], [2], [3]])
>>> A.to_numpy(keep_dims=False)
>>> 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:

Matrix

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:

Matrix

Example:

>>> A = ti.Matrix.unit(3, 1)
>>> A
[0, 1, 0]
static zero(dt, n, m=None)#

Constructs a Matrix filled with zeros.

Parameters:
  • dt (DataType) – The desired data type.

  • n (int) – The first dimension (row) of the matrix.

  • m (int, optional) – The second dimension (column) of the matrix.

Returns:

A Matrix instance filled with zeros.

Return type:

Matrix

class taichi.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.

  • layout (Layout) – Memory layout.

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.WARN = warn#

The str ‘warn’, used for the warn logging level.

taichi.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.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.activate(node, indices)#

Explicitly activate a cell of node at location indices.

Parameters:
  • node (SNode) – Must be a pointer, hash or bitmasked node.

  • indices (Union[int, Vector]) – the indices to activate.

taichi.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 (primitive_types) – the scalar data to be appended, only i32 value is support for now.

taichi.arm64#

The ARM CPU backend.

taichi.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.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.atan2(x1, x2)#

Element-wise arc tangent of x1/x2.

Parameters:
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.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:
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.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:
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.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:
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.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:
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.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:
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.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:
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.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:
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.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.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.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:
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.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.cache_read_only(*args)#
taichi.cast(obj, dtype)#

Copy and cast a scalar or a matrix to a specified data type. Must be called in Taichi scope.

Parameters:
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.cc#
taichi.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.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.cpu#

A list of CPU backends supported on the current system. Currently contains ‘x64’, ‘x86_64’, ‘arm64’, ‘cc’, ‘wasm’.

When this is used, Taichi automatically picks the matching CPU backend.

taichi.cuda#

The CUDA backend.

taichi.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.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
  1. Sets the annotations as fields for the struct

  2. 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.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.

Parameters:
  • node (SNode) – Must be a pointer, hash or bitmasked node.

  • indices (Union[int, Vector]) – the indices to deactivate.

taichi.deactivate_all_snodes()#

Recursively deactivate all SNodes.

taichi.dx11#

The DX11 backend.

taichi.dx12#

The DX11 backend.

taichi.eig(A, dt=None)#

Compute the eigenvalues and right eigenvectors of a real matrix.

Mathematical concept refers to https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix.

Parameters:
  • A (ti.Matrix(n, n)) – 2D Matrix for which the eigenvalues and right eigenvectors will be computed.

  • dt (DataType) – The datatype for the eigenvalues and right eigenvectors.

Returns:

The eigenvalues in complex form. Each row stores one eigenvalue. The first number of the eigenvalue represents the real part and the second number represents the imaginary part. eigenvectors (ti.Matrix(n*2, n)): The eigenvectors in complex form. Each column stores one eigenvector. Each eigenvector consists of n entries, each of which is represented by two numbers for its real part and imaginary part.

Return type:

eigenvalues (ti.Matrix(n, 2))

taichi.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.extension#

An instance of Taichi extension.

The list of currently available extensions is [‘sparse’, ‘quant’, ‘mesh’, ‘quant_basic’, ‘data64’, ‘adstack’, ‘bls’, ‘assertion’, ‘extfunc’, ‘dynamic_index’].

taichi.f16#

Alias for float16

taichi.f32#

Alias for float32

taichi.f64#

Alias for float64

taichi.field(dtype, shape=None, order=None, name='', offset=None, needs_grad=False, needs_dual=False)#

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 Taichi kernel().

See also https://docs.taichi-lang.org/docs/field

Parameters:
  • dtype (DataType) – data type of the field.

  • 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)
taichi.float16#

16-bit precision floating point data type.

taichi.float32#

32-bit single precision floating point data type.

taichi.float64#

64-bit double precision floating point data type.

taichi.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.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.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.get_compute_stream_device_time_elapsed_us() float#
taichi.gles#

The OpenGL ES backend. OpenGL ES 3.1 required.

taichi.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.gpu#

A list of GPU backends supported on the current system. Currently contains ‘cuda’, ‘metal’, ‘opengl’, ‘vulkan’, ‘dx11’, ‘dx12’, ‘gles’.

When this is used, Taichi automatically picks the matching GPU backend. If no GPU is detected, Taichi falls back to the CPU backend.

taichi.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.hex_to_rgb(color)#

Converts hex color format to rgb color format.

Parameters:

color (int) – The hex representation of color.

Returns:

The rgb representation of color.

taichi.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.i16#

Alias for int16

taichi.i32#

Alias for int32

taichi.i64#

Alias for int64

taichi.i8#

Alias for int8

taichi.ij#

Axes (0, 1).

taichi.ijk#

Axes (0, 1, 2).

taichi.ijkl#

Axes (0, 1, 2, 3).

taichi.ijl#

Axes (0, 1, 3).

taichi.ik#

Axes (0, 2).

taichi.ikl#

Axes (0, 2, 3).

taichi.il#

Axes (0, 3).

taichi.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:
  • arch – Backend to use. This is usually cpu or gpu.

  • 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.int16#

16-bit signed integer data type.

taichi.int32#

32-bit signed integer data type.

taichi.int64#

64-bit signed integer data type.

taichi.int8#

8-bit signed integer data type.

taichi.is_active(node, indices)#

Explicitly query whether a cell in a SNode node at location indices is active or not.

Parameters:
  • node (SNode) – Must be a pointer, hash or bitmasked node.

  • indices (Union[int, list, Vector]) – the indices to visit.

Returns:

the cell node[indices] is active or not.

Return type:

bool

taichi.is_logging_effective(level)#

Check if the specified logging level is effective. All levels below current level will be effective. The default level is ‘info’.

See also https://docs.taichi-lang.org/docs/developer_utilities#logging.

Parameters:

level (str) – The string represents logging level. Effective levels include: ‘trace’, ‘debug’, ‘info’, ‘warn’, ‘error’, ‘critical’.

Returns:

Indicate whether the logging level is effective.

Return type:

Bool

Example:

>>> # assume current level is 'info'
>>> print(ti.is_logging_effective("trace"))     # False
>>> print(ti.is_logging_effective("debug"))     # False
>>> print(ti.is_logging_effective("info"))      # True
>>> print(ti.is_logging_effective("warn"))      # True
>>> print(ti.is_logging_effective("error"))     # True
>>> print(ti.is_logging_effective("critical"))  # True
taichi.j#

Axis 1. For multi-dimensional arrays it’s the direction across the columns.

taichi.jk#

Axes (1, 2).

taichi.jkl#

Axes (1, 2, 3).

taichi.jl#

Axes (1, 3).

taichi.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.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.kl#

Axes (2, 3).

taichi.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.length(node, indices)#

Return the length of the dynamic SNode node at index indices.

Parameters:
  • node (SNode) – a dynamic SNode.

  • indices (Union[int, Vector]) – the indices to query.

Returns:

the length of cell node[indices].

Return type:

int

taichi.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.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.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.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.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.

Related to https://github.com/taichi-dev/taichi/issues/3608

taichi.metal#

The Apple Metal backend.

taichi.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.ndarray(dtype, shape)#

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.ndrange(*args)#

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.no_activate(*args)#

Deactivates a SNode pointer.

taichi.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.opengl#

The OpenGL backend. OpenGL 4.3 required.

taichi.polar_decompose(A, dt=None)#

Perform polar decomposition (A=UP) for arbitrary size matrix.

Mathematical concept refers to https://en.wikipedia.org/wiki/Polar_decomposition.

Parameters:
  • A (ti.Matrix(n, n)) – input nxn matrix A.

  • dt (DataType) – date type of elements in matrix A, typically accepts ti.f32 or ti.f64.

Returns:

Decomposed nxn matrices U and P.

taichi.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

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:
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.randn(dt=None)#

Generate a random float sampled from univariate standard normal (Gaussian) distribution of mean 0 and variance 1, using the Box-Muller transformation. Must be called in Taichi scope.

Parameters:

dt (DataType) – Data type of the required random number. Default to None. If set to None dt will be determined dynamically in runtime.

Returns:

The generated random float.

Example:

>>> @ti.kernel
>>> def main():
>>>     print(ti.randn())
>>>
>>> main()
-0.463608
taichi.random(dtype=float)#

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.raw_div(x1, x2)#

Return x1 // x2 if both x1, x2 are integers, otherwise return x1/x2.

Parameters:
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.raw_mod(x1, x2)#

Return the remainder of x1/x2, element-wise. This is the C-style mod function.

Parameters:
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.ref(tp)#
taichi.rescale_index(a, b, I)#

Rescales the index ‘I’ of field (or SNode) ‘a’ to match the shape of SNode ‘b’.

Parameters:
Returns:

rescaled grouped loop index

Return type:

Ib (Vector)

taichi.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.rgb_to_hex(c)#

Converts rgb color format to hex color format.

Parameters:

c (List[int]) – The rgb representation of color.

Returns:

The hex representation of color.

taichi.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.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.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.select(cond, x1, x2)#

Return an array drawn from elements in x1 or x2, depending on the conditions in cond.

Parameters:
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.set_logging_level(level)#

Setting the logging level to a specified value. Available levels are: ‘trace’, ‘debug’, ‘info’, ‘warn’, ‘error’, ‘critical’.

Note that after calling this function, logging levels below the specified one will also be effective. For example if level is set to ‘warn’, then the levels below it, which are ‘error’ and ‘critical’ in this case, will also be effective.

See also https://docs.taichi-lang.org/docs/developer_utilities#logging.

Parameters:

level (str) – Logging level.

Example:

>>> set_logging_level('debug')
taichi.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.solve(A, b, dt=None)#

Solve a matrix using Gauss elimination method.

Parameters:
  • A (ti.Matrix(n, n)) – input nxn matrix A.

  • b (ti.Vector(n, 1)) – input nx1 vector b.

  • dt (DataType) – The datatype for the A and b.

Returns:

the solution of Ax=b.

Return type:

x (ti.Vector(n, 1))

class taichi.sparse_matrix_builder#
taichi.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.static(x, *xs)#

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 either do_a() or do_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.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.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.stop_grad(x)#

Stops computing gradients during back propagation.

Parameters:

x (Field) – A field.

taichi.svd(A, dt=None)#

Perform singular value decomposition (A=USV^T) for arbitrary size matrix.

Mathematical concept refers to https://en.wikipedia.org/wiki/Singular_value_decomposition.

Parameters:
  • A (ti.Matrix(n, n)) – input nxn matrix A.

  • dt (DataType) – date type of elements in matrix A, typically accepts ti.f32 or ti.f64.

Returns:

Decomposed nxn matrices U, ‘S’ and V.

taichi.sym_eig(A, dt=None)#

Compute the eigenvalues and right eigenvectors of a real symmetric matrix.

Mathematical concept refers to https://en.wikipedia.org/wiki/Eigendecomposition_of_a_matrix.

Parameters:
  • A (ti.Matrix(n, n)) – Symmetric Matrix for which the eigenvalues and right eigenvectors will be computed.

  • dt (DataType) – The datatype for the eigenvalues and right eigenvectors.

Returns:

The eigenvalues. Each entry store one eigen value. eigenvectors (ti.Matrix(n, n)): The eigenvectors. Each column stores one eigenvector.

Return type:

eigenvalues (ti.Vector(n))

taichi.sync()#

Blocks the calling thread until all the previously launched Taichi kernels have completed.

taichi.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.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.template#

Alias for Template.

taichi.u16#

Alias for uint16

taichi.u32#

Alias for uint32

taichi.u64#

Alias for uint64

taichi.u8#

Alias for uint8

taichi.uint16#

16-bit unsigned integer data type.

taichi.uint32#

32-bit unsigned integer data type.

taichi.uint64#

64-bit unsigned integer data type.

taichi.uint8#

8-bit unsigned integer data type.

taichi.vulkan#

The Vulkan backend.

taichi.wasm#

The WebAssembly backend.

taichi.x64#

The X64 CPU backend.

taichi.x86_64#

The x64 CPU backend.

taichi.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]
Was this helpful?