taichi#

taichi.CRITICAL = critical#

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

taichi.DEBUG = debug#

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

taichi.ERROR = error#

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

class taichi.Field(_vars)#

Taichi field with SNode implementation.

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++ GlobalVariableExpression. A C++ GlobalVariableExpression wraps the corresponding SNode.

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.

property dtype(self)#

Gets data type of each individual value.

Returns

Data type of each individual value.

Return type

DataType

abstract fill(self, val)#

Fills self with a specific value.

Parameters

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

abstract from_numpy(self, arr)#

Loads all elements from a numpy array.

The shape of the numpy array needs to be the same as self.

Parameters

arr (numpy.ndarray) – The source numpy array.

from_torch(self, arr)#

Loads all elements from a torch tensor.

The shape of the torch tensor needs to be the same as self.

Parameters

arr (torch.tensor) – The source torch tensor.

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

property shape(self)#

Gets field shape.

Returns

Field shape.

Return type

Tuple[Int]

property snode(self)#

Gets representative SNode for info purposes.

Returns

Representative SNode (SNode of first field member).

Return type

SNode

abstract to_numpy(self, dtype=None)#

Converts self to a numpy array.

Parameters

dtype (DataType, optional) – The desired data type of returned numpy array.

Returns

The result numpy array.

Return type

numpy.ndarray

abstract to_torch(self, device=None)#

Converts self to a torch tensor.

Parameters

device (torch.device, optional) – The desired device of returned tensor.

Returns

The result torch tensor.

Return type

torch.tensor

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)

# Afer 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()
bit_array(self, indices: Union[Sequence[_Axis], _Axis], dimensions: Union[Sequence[int], int], num_bits: int)#

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

bit_struct(self, num_bits: int)#

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

bitmasked(self, indices: Union[Sequence[_Axis], _Axis], dimensions: Union[Sequence[int], int])#

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

deactivate_all(self)#

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

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

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

dynamic(self, index: Union[Sequence[_Axis], _Axis], dimension: Union[Sequence[int], int], chunk_size: Optional[int] = 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_grad(self)#

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

place(self, *args: Any, offset: Optional[Union[Sequence[int], int]] = None, shared_exponent: bool = False)#

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

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

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

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 EventFilter(*e_filter)#
match(self, e)#
class WidgetValue(gui, wid)#
property value(self)#
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)#

Draw 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)#

Draw a single 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)#

Draw a list of circles on canvas.

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

  • radius (Number, optional) – The radius of the circles in pixel. 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)#

Clear 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)#
cook_image(self, img)#
property fps_limit(self)#

Get the property of fps limit.

Returns

The property of fps limit of gui.

static get_bool_environ(key, default)#

Get an environment variable and cast to bool. :param key: The environment variable key. :type key: str :param default: The default value. :type default: bool

Returns

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

get_cursor_pos(self)#

Get the current position of mouse.

Returns

The current position of mouse.

get_event(self, *e_filter)#

Check if the specific event is triggered.

Parameters

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

Returns

Bool to indicate whether the specific event is triggered.

get_events(self, *e_filter)#

Get 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)#

Get the image data.

Returns

The image data in numpy contiguous array type.

Return type

numpy.array

get_key_event(self)#

Get keyboard triggered event.

Returns

The keyboard triggered event.

Return type

EVENT

has_key_event(self)#

Check if there are any key event registered.

Returns

Bool to indicate whether there is any key event registered.

is_pressed(self, *keys)#

Check if the specific key or keys are pressed.

Parameters

*keys (Union[str, List[str]]) – The string that stands for keys in keyboard.

Returns

Bool to indicate whether the key or keys are pressed.

label(self, text)#

Create 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)#

Draw 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)#

Draw 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)#

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

property running(self)#

Get the property of whether the gui is running.

Returns

The running property of gui(bool).

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[ti.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)#

Show the frame or save current frame as a picture.

Parameters

file (str, optional) – The path & name of the picture to be saved. Default is None.

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

Create a slider object on canvas to be manipulated with.

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

  • minimum (Number) – The minimum value of slider.

  • maximum (Number) – The maximum value of slider.

  • step (Number, optional) – The changing step of slider. Default is 1.

Returns

The created slider object.

Return type

WidgetValue

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

Draw 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)#

Draw 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)#

Draw 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 thrid 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.

class taichi.Layout#

Bases: enum.Enum

Layout of a Taichi field or ndarray.

Currently, AOS (array of structures) and SOA (structure of arrays) are supported.

AOS = 1#
SOA = 2#
name(self)#

The name of the Enum member.

value(self)#

The value of the Enum member.

class taichi.Matrix(arr, dt=None, suppress_warning=False)#

Bases: taichi.lang.common_ops.TaichiOperations

The matrix class.

A matrix is a 2-D rectangular array with scalar entries, it’s row-majored, and is aligned continously. We recommend only use matrix with no more than 32 elements for efficiency considerations.

Note: in taichi a matrix is strictly two-dimensional and only stores scalars.

Parameters
  • arr (Union[list, tuple, np.ndarray]) – the initial values of a matrix.

  • dt (primitive_types) – the element data type.

  • suppress_warning (bool) – whether raise warning or not when the matrix contains more than 32 elements.

Example:

use a 2d list to initialize a matrix

>>> @ti.kernel
>>> def test():
>>> n = 5
>>> M = ti.Matrix([[0] * n for _ in range(n)], ti.i32)
>>> print(M) # a 5x5 matrix with integer elements

get the number of rows and columns via the `n`, `m` property:

>>> M = ti.Matrix([[0, 1], [2, 3], [4, 5]], ti.i32)
>>> M.n # number of rows
3
>>> M.m # number of cols
>>> 2

you can even initialize a matrix with an empty list:

>>> M = ti.Matrix([[], []], ti.i32)
>>> M.n
2
>>> M.m
0
all(self)#

Test whether all element not equal zero.

Returns

True if all elements are not equal zero, False otherwise.

Return type

bool

any(self)#

Test whether any element not equal zero.

Returns

True if any element is not equal zero, False otherwise.

Return type

bool

cast(self, dtype)#

Cast the matrix element data type.

Parameters

dtype (DataType) – the data type of the casted matrix element.

Returns

A new matrix with each element’s type is dtype.

static cols(cols)#

Construct a Matrix instance by concatenating Vectors/lists column by column.

Parameters

cols (List) – A list of Vector (1-D Matrix) or a list of list.

Returns

A Matrix instance filled with the Vectors/lists column by column.

Return type

Matrix

cross(self, other)#

Perform the cross product with the input Vector (1-D Matrix).

Parameters

other (Matrix) – The input Vector (1-D Matrix) to perform the cross product.

Returns

The cross product result (1-D Matrix) of the two Vectors.

Return type

Matrix

determinant(a)#

Get the determinant of a matrix.

Note

The matrix dimension should be less than or equal to 4.

Returns

The determinant of a matrix.

Raises

Exception – Determinants of matrices with sizes >= 5 are not supported.

static diag(dim, val)#

Construct a diagonal square matrix.

Parameters
  • dim (int) – the dimension of a square matrix.

  • val (TypeVar) – the diagonal element value.

Returns

The constructed diagonal square matrix.

dot(self, other)#

Perform the dot product with the input Vector (1-D Matrix).

Parameters

other (Matrix) – The input Vector (1-D Matrix) to perform the dot product.

Returns

The dot product result (scalar) of the two Vectors.

Return type

DataType

classmethod field(cls, n, m, dtype, shape=None, name='', offset=None, needs_grad=False, layout=Layout.AOS)#

Construct a data container to hold all elements of the Matrix.

Parameters
  • n (int) – The desired number of rows of the Matrix.

  • m (int) – The desired number of columns of the Matrix.

  • dtype (DataType, optional) – The desired data type of the Matrix.

  • shape (Union[int, tuple of int], optional) – The desired shape of the Matrix.

  • name (string, optional) – The custom name of the field.

  • offset (Union[int, tuple of int], optional) – The coordinate offset of all elements in a field.

  • needs_grad (bool, optional) – Whether the Matrix need gradients.

  • layout (Layout, optional) – The field layout, i.e., Array Of Structure (AOS) or Structure Of Array (SOA).

Returns

A Matrix instance serves as the data container.

Return type

Matrix

fill(self, val)#

Fills the matrix with a specific value in Taichi scope.

Parameters

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

static identity(dt, n)#

Construct an identity Matrix with shape (n, n).

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

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

Returns

A n x n identity Matrix instance.

Return type

Matrix

inverse(self)#

The inverse of a matrix.

Note

The matrix dimension should be less than or equal to 4.

Returns

The inverse of a matrix.

Raises

Exception – Inversions of matrices with sizes >= 5 are not supported.

max(self)#

Return the maximum element value.

min(self)#

Return the minimum element value.

classmethod ndarray(cls, n, m, dtype, shape, layout=Layout.AOS)#

Defines a Taichi ndarray with matrix elements.

Parameters
  • n (int) – Number of rows of the matrix.

  • m (int) – Number of columns of the matrix.

  • dtype (DataType) – Data type of each value.

  • shape (Union[int, tuple[int]]) – Shape of the ndarray.

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

Example

The code below shows how a Taichi ndarray with matrix elements can be declared and defined:

>>> x = ti.Matrix.ndarray(4, 5, ti.f32, shape=(16, 8))
norm(self, eps=0)#

Return the square root of the sum of the absolute squares of its elements.

Parameters

eps (Number) – a safe-guard value for sqrt, usually 0.

Examples:

a = ti.Vector([3, 4])
a.norm() # sqrt(3*3 + 4*4 + 0) = 5
# `a.norm(eps)` is equivalent to `ti.sqrt(a.dot(a) + eps).`
Returns

The square root of the sum of the absolute squares of its elements.

norm_inv(self, eps=0)#

Return the inverse of the matrix/vector norm. For norm: please see norm().

Parameters

eps (Number) – a safe-guard value for sqrt, usually 0.

Returns

The inverse of the matrix/vector norm.

norm_sqr(self)#

Return the sum of the absolute squares of its elements.

normalized(self, eps=0)#

Normalize a vector.

Parameters

eps (Number) – a safe-guard value for sqrt, usually 0.

Examples:

a = ti.Vector([3, 4])
a.normalized() # [3 / 5, 4 / 5]
# `a.normalized()` is equivalent to `a / a.norm()`.

Note

Only vector normalization is supported.

static one(dt, n, m=None)#

Construct a Matrix filled with ones.

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

Perform the outer product with the input Vector (1-D Matrix).

Parameters

other (Matrix) – The input Vector (1-D Matrix) to perform the outer product.

Returns

The outer product result (Matrix) of the two Vectors.

Return type

Matrix

static rotation2d(alpha)#
static rows(rows)#

Construct a Matrix instance by concatenating Vectors/lists row by row.

Parameters

rows (List) – A list of Vector (1-D Matrix) or a list of list.

Returns

A Matrix instance filled with the Vectors/lists row by row.

Return type

Matrix

sum(self)#

Return the sum of all elements.

to_list(self)#
to_numpy(self, keep_dims=False)#

Converts the Matrix to a numpy array.

Parameters

keep_dims (bool, optional) – Whether to keep the dimension after conversion. When keep_dims=False, the resulting numpy array should skip the matrix dims with size 1.

Returns

The result numpy array.

Return type

numpy.ndarray

trace(self)#

The sum of a matrix diagonal elements.

Returns

The sum of a matrix diagonal elements.

transpose(self)#

Get the transpose of a matrix.

Returns

Get the transpose of a matrix.

static unit(n, i, dt=None)#

Construct an unit Vector (1-D matrix) i.e., a vector with only one entry filled with one and all other entries zeros.

Parameters
  • n (int) – The length of the vector.

  • i (int) – The index of the entry that will be filled with one.

  • dt (DataType, optional) – The desired data type.

Returns

An 1-D unit Matrix instance.

Return type

Matrix

property w(self)#

Get the fourth element of a matrix.

property x(self)#

Get the first element of a matrix.

property y(self)#

Get the second element of a matrix.

property z(self)#

Get the third element of a matrix.

static zero(dt, n, m=None)#

Construct 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)#

Bases: taichi.lang.field.Field

Taichi matrix field with SNode implementation.

Parameters
  • vars (List[Expr]) – Field members.

  • n (Int) – Number of rows.

  • m (Int) – Number of columns.

copy_from(self, other)#

Copies all elements from another field.

The shape of the other field needs to be the same as self.

Parameters

other (Field) – The source field.

property dtype(self)#

Gets data type of each individual value.

Returns

Data type of each individual value.

Return type

DataType

fill(self, val)#

Fills self with specific values.

Parameters

val (Union[Number, List, Tuple, Matrix]) – Values to fill, which should have dimension consistent with self.

from_numpy(self, arr)#

Loads all elements from a numpy array.

The shape of the numpy array needs to be the same as self.

Parameters

arr (numpy.ndarray) – The source numpy array.

from_torch(self, arr)#

Loads all elements from a torch tensor.

The shape of the torch tensor needs to be the same as self.

Parameters

arr (torch.tensor) – The source torch tensor.

get_scalar_field(self, *indices)#

Creates a ScalarField using a specific field member. Only used for quant.

Parameters

indices (Tuple[Int]) – Specified indices of the field member.

Returns

The result ScalarField.

Return type

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

property shape(self)#

Gets field shape.

Returns

Field shape.

Return type

Tuple[Int]

property snode(self)#

Gets representative SNode for info purposes.

Returns

Representative SNode (SNode of first field member).

Return type

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_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, layout)#

Bases: taichi.lang._ndarray.Ndarray

Taichi ndarray with matrix elements.

Parameters
  • n (int) – Number of rows of the matrix.

  • m (int) – Number of columns of the matrix.

  • dtype (DataType) – Data type of each value.

  • shape (Union[int, tuple[int]]) – Shape of the ndarray.

  • layout (Layout) – Memory layout.

copy_from(self, other)#

Copies all elements from another ndarray.

The shape of the other ndarray needs to be the same as self.

Parameters

other (Ndarray) – The source ndarray.

property element_shape(self)#

Gets ndarray element shape.

Returns

Ndarray element shape.

Return type

Tuple[Int]

fill(self, val)#

Fills ndarray with a specific scalar value.

Parameters

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

from_numpy(self, arr)#
to_numpy(self)#
class taichi.Mesh#
static Tet()#
static Tri()#
static generate_meta(data)#
static load_meta(filename)#
class taichi.Ndarray(dtype, arr_shape)#

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.

property element_shape(self)#

Gets ndarray element shape.

Returns

Ndarray element shape.

Return type

Tuple[Int]

fill(self, val)#

Fills ndarray with a specific scalar value.

Parameters

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

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.

bit_array(self, axes, dimensions, num_bits)#

Adds a bit_array SNode as a child component of self.

Parameters
  • axes (List[Axis]) – Axes to activate.

  • dimensions (Union[List[int], int]) – Shape of each axis.

  • num_bits (int) – Number of bits to use.

Returns

The added SNode instance.

bit_struct(self, num_bits: int)#

Adds a bit_struct SNode as a child component of self.

Parameters

num_bits – Number of bits to use.

Returns

The added SNode instance.

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

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.

  • shared_exponent (bool) – Only useful for quant types.

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.

property shape(self)#

Gets the number of elements from root in each axis of self.

Returns

The number of elements from root in each axis of self.

Return type

Tuple[int]

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.

property dtype(self)#

Gets data type of each individual value.

Returns

Data type of each individual value.

Return type

DataType

fill(self, val)#

Fills self with a specific value.

Parameters

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

from_numpy(self, arr)#

Loads all elements from a numpy array.

The shape of the numpy array needs to be the same as self.

Parameters

arr (numpy.ndarray) – The source numpy array.

from_torch(self, arr)#

Loads all elements from a torch tensor.

The shape of the torch tensor needs to be the same as self.

Parameters

arr (torch.tensor) – The source torch tensor.

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

property shape(self)#

Gets field shape.

Returns

Field shape.

Return type

Tuple[Int]

property snode(self)#

Gets representative SNode for info purposes.

Returns

Representative SNode (SNode of first field member).

Return type

SNode

to_numpy(self, dtype=None)#

Converts self to a numpy array.

Parameters

dtype (DataType, optional) – The desired data type of returned numpy array.

Returns

The result numpy array.

Return type

numpy.ndarray

to_torch(self, device=None)#

Converts self to a torch tensor.

Parameters

device (torch.device, optional) – The desired device of returned tensor.

Returns

The result torch tensor.

Return type

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.

property element_shape(self)#

Gets ndarray element shape.

Returns

Ndarray element shape.

Return type

Tuple[Int]

fill(self, val)#

Fills ndarray with a specific scalar value.

Parameters

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

from_numpy(self, arr)#
to_numpy(self)#
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 stuctures.

Parameters

entries (Dict[str, Union[Dict, Expr, Matrix, Struct]]) – keys and values for struct members.

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, shape=None, name='<Struct>', offset=None, needs_grad=False, layout=Layout.AOS)#
fill(self, val)#

Fills the Struct with a specific value in Taichi scope.

Parameters

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

property items(self)#
property keys(self)#
to_dict(self)#

Converts the Struct to a dictionary.

Args:

Returns

The result dictionary.

Return type

Dict

class taichi.StructField(field_dict, name=None)#

Bases: taichi.lang.field.Field

Taichi struct field with SNode implementation.

Instead of directly contraining Expr entries, the StructField object directly hosts members as Field instances to support nested structs.

Parameters
  • field_dict (Dict[str, Field]) – Struct field members.

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

property dtype(self)#

Gets data type of each individual value.

Returns

Data type of each individual value.

Return type

DataType

fill(self, val)#

Fills self with a specific value.

Parameters

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

from_numpy(self, array_dict)#

Loads all elements from a numpy array.

The shape of the numpy array needs to be the same as self.

Parameters

arr (numpy.ndarray) – The source numpy array.

from_torch(self, array_dict)#

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_member_field(self, key)#

Creates a ScalarField using a specific field member. Only used for quant.

Parameters

key (str) – Specified key of the field member.

Returns

The result ScalarField.

Return type

ScalarField

property keys(self)#
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

property shape(self)#

Gets field shape.

Returns

Field shape.

Return type

Tuple[Int]

property snode(self)#

Gets representative SNode for info purposes.

Returns

Representative SNode (SNode of first field member).

Return type

SNode

to_numpy(self)#
Converts the Struct field instance to a dictionary of NumPy arrays. The dictionary may be nested when converting

nested structs.

Args: :returns: The result NumPy array. :rtype: Dict[str, Union[numpy.ndarray, 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.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(pos, needed, provided)#

Bases: TaichiRuntimeError, TypeError

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

taichi.Tape(loss, clear_gradients=True)#

Return a context manager of TapeImpl. The context manager would catching all of the callings of functions that decorated by kernel() or grad_replaced() under with statement, and calculate all the partial gradients of a given loss variable by calling all of the gradient function of the callings caught in reverse order while with statement ended.

See also kernel() and grad_replaced() for gradient functions.

Parameters
  • loss (Expr) – The loss field, which shape should be ().

  • clear_gradients (Bool) – Before with body start, clear all gradients or not.

Returns

The context manager.

Return type

TapeImpl

Example:

>>> @ti.kernel
>>> def sum(a: ti.float32):
>>> for I in ti.grouped(x):
>>> y[None] += x[I] ** a
>>>
>>> with ti.Tape(loss = y):
>>> sum(2)
taichi.TetMesh()#
taichi.TriMesh()#
taichi.Vector(arr, dt=None, **kwargs)#

Construct a vector from given array.

A vector is an instance of a 2-D matrix with the second dimension being equal to 1.

Parameters
  • arr (Union[list, tuple, np.ndarray]) – The initial values of the Vector.

  • dt (primitive_types) – data type of the vector.

Returns

A vector instance.

Return type

Matrix

Example::
>>> u = ti.Vector([1, 2])
>>> print(u.m, u.n) # verify a vector is a matrix of shape (n, 1)
2 1
>>> v = ti.Vector([3, 4])
>>> u + v
[4 6]
class taichi.VectorNdarray(n, dtype, shape, layout)#

Bases: taichi.lang._ndarray.Ndarray

Taichi ndarray with vector elements.

Parameters
  • n (int) – Size of the vector.

  • dtype (DataType) – Data type of each value.

  • shape (Tuple[int]) – Shape of the ndarray.

  • layout (Layout) – Memory layout.

copy_from(self, other)#

Copies all elements from another ndarray.

The shape of the other ndarray needs to be the same as self.

Parameters

other (Ndarray) – The source ndarray.

property element_shape(self)#

Gets ndarray element shape.

Returns

Ndarray element shape.

Return type

Tuple[Int]

fill(self, val)#

Fills ndarray with a specific scalar value.

Parameters

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

from_numpy(self, arr)#
to_numpy(self)#
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.any_arr#

Alias for ArgAnyArray.

Example:

>>> @ti.kernel
>>> def to_numpy(x: ti.any_arr(), y: ti.any_arr()):
>>> for i in range(n):
>>> x[i] = y[i]
>>>
>>> y = ti.ndarray(ti.f64, shape=n)
>>> ... # calculate y
>>> x = numpy.zeros(n)
>>> to_numpy(x, y) # `x` will be filled with `y`'s data.
taichi.any_arr#

Alias for ArgAnyArray.

Example:

>>> @ti.kernel
>>> def to_numpy(x: ti.any_arr(), y: ti.any_arr()):
>>> for i in range(n):
>>> x[i] = y[i]
>>>
>>> y = ti.ndarray(ti.f64, shape=n)
>>> ... # calculate y
>>> x = numpy.zeros(n)
>>> to_numpy(x, y) # `x` will be filled with `y`'s data.
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 (types) – the data to be appended.

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)#
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.graphics/lang/articles/advanced/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)#

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.

Returns

The ceiling of each element in x, with float dtype.

Example:

>>> @ti.kernel
>>> def test():
>>> x = ti.Matrix([3.14, -1.5])
>>> y = ti.ceil(x)
>>> print(y) # [4.0, -1.0]
taichi.clear_all_gradients()#

Set the gradients of all fields to zero.

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.graphics/lang/articles/advanced/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.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.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. 2D implementation refers to taichi.eig2x2().

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.ext_arr()#

Type annotation for external arrays.

External arrays are formally defined as the data from other Python frameworks. For now, Taichi supports numpy and pytorch.

Example:

>>> @ti.kernel
>>> def to_numpy(arr: ti.ext_arr()):
>>> for i in x:
>>> arr[i] = x[i]
>>>
>>> arr = numpy.zeros(...)
>>> to_numpy(arr) # `arr` will be filled with `x`'s data.
taichi.ext_arr()#

Type annotation for external arrays.

External arrays are formally defined as the data from other Python frameworks. For now, Taichi supports numpy and pytorch.

Example:

>>> @ti.kernel
>>> def to_numpy(arr: ti.ext_arr()):
>>> for i in x:
>>> arr[i] = x[i]
>>>
>>> arr = numpy.zeros(...)
>>> to_numpy(arr) # `arr` will be filled with `x`'s data.
taichi.extension#

An instance of Taichi extension.

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

taichi.f16#

Alias for float16

taichi.f16#

Alias for float16

taichi.f32#

Alias for float32

taichi.f32#

Alias for float32

taichi.f64#

Alias for float64

taichi.f64#

Alias for float64

taichi.field(dtype, shape=None, name='', offset=None, needs_grad=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.graphics/lang/articles/basic/field

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

  • shape (Union[int, tuple[int]], optional) – shape of the field.

  • 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 and thus needs an adjoint 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)
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)#

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.

Returns

The floor of each element in x, with float type.

Example:

>>> @ti.kernel
>>> def test():
>>> x = ti.Matrix([3.14, -1.5])
>>> y = ti.floor(x)
>>> print(y) # [3.0, -2.0]
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.global_thread_idx()#
taichi.gpu#

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

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

Convert 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.i32#

Alias for int32

taichi.i64#

Alias for int64

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.

    • packed (bool): Enables the packed memory layout. See https://docs.taichi.graphics/lang/articles/advanced/layout.

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.graphics/lang/articles/contribution/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.graphics/lang/articles/basic/syntax#kernels.

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=None, parallelize=None)#
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)#
taichi.mesh_patch_idx()#
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 (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 scalar elements can be declared and defined:

>>> x = ti.ndarray(ti.f32, shape=(16, 8))
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 intepreted 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)#
taichi.one(x)#

Return 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. This is only a wrapper for taichi.polar_decompose().

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(x, a)#

First array elements raised to powers from second array \(x^a\), element-wise.

Negative values raised to a non-integral value will return nan. A zero value raised to a negative value will return inf.

Parameters
Returns

The bases in x1 raised to the exponents in x2. This is a scalar if both x1 and x2 are scalars.

Example:

>>> @ti.kernel
>>> def test():
>>> x = ti.Matrix([-2.0, 0.0, 2.0])
>>> y = -2.2
>>> z = ti.pow(x, y)
>>> print(z)
>>>
>>> test()
[-nan, inf, 0.217638]
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.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)#

Convert 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.graphics/lang/articles/advanced/layout

Example:

>>> x = ti.field(ti.f32)
>>> ti.root.pointer(ti.ij, 4).dense(ti.ij, 8).place(x)
taichi.round(x)#

Round to the nearest integer, element-wise.

Parameters

x (Union[primitive_types, Matrix]) – A scalar or a matrix.

Returns

The nearest integer of x.

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.graphics/lang/articles/contribution/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.]
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.graphics/lang/articles/advanced/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. 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)#
taichi.stop_grad(x)#
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. This is only a wrappers for taichi.svd().

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. 2D implementation refers to taichi.sym_eig2x2().

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()#
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.template#

Alias for Template.

taichi.u16#

Alias for uint16

taichi.u32#

Alias for uint32

taichi.u32#

Alias for uint32

taichi.u64#

Alias for uint64

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

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