The term field is borrowed from mathematics and physics. If you already know scalar field (for exampl……
The term field is borrowed from mathematics and physics. If you already know scalar field (for example heat field), or vector field (for example gravitational field), then it is easy for you to understand fields in Taichi.
Fields in Taichi are the global data containers, which can be accessed from both the Python scope and the Taichi scope. Just like an ndarray in NumPy or a tensor in PyTorch, a field in Taichi is defined as a multi-dimensional array of elements, and elements in a field can be a Scalar, a Vector, a Matrix, or a Struct.
Scalar fields refer to the fields that store scalars and are the most basic fields.
The simplest way to declare a scalar field is to call ti.field(dtype, shape)
, where dtype
is a primitive data type as explained in the Type System and shape
is a tuple of integers.
When declaring a 0D scalar field, you need to set its shape to the empty tuple ()
:
f_0d = ti.field(ti.f32, shape=())
An illustration of f_0d
:
┌─────┐
│ │
└─────┘
└─────┘
f_0d.shape=()
When declaring a 1D scalar field of length n
, set its shape to n
or (n,)
:
f_1d = ti.field(ti.i32, shape=9)
An illustration of f_1d
:
┌───┬───┬───┬───┬───┬───┬───┬───┬───┐
│ │ │ │ │ │ │ │ │ │
└───┴───┴───┴───┴───┴───┴───┴───┴───┘
└───────────────────────────────────┘
f_1d.shape = (9,)
There is little difference between a 0D field and a 1D field of length 1 except for their indexing rules. You must use None
as the index to access a 0D field and 0
as the index to access a 1D field of length 1:
f1 = ti.field(int, shape=())
f2 = ti.field(int, shape=1)
f1[None] = 1
f2[0] = 1
When declaring a 2D scalar field, you need to set its two dimensions (numbers of rows and columns) respectively. For example, the following code snippet defines a 2D scalar field with the shape (3, 6) (three rows and six columns):
f_2d = ti.field(int, shape=(3, 6))
Here is an illustration of f_2d
:
f_2d.shape[1]
(=6)
┌───────────────────────┐
┌ ┌───┬───┬───┬───┬───┬───┐ ┐
│ │ │ │ │ │ │ │ │
│ ├───┼───┼───┼───┼───┼───┤ │
f_2d.shape[0] │ │ │ │ │ │ │ │ │
(=3) │ ├───┼───┼───┼───┼───┼───┤ │
│ │ │ │ │ │ │ │ │
└ └───┴───┴───┴───┴───┴───┘ ┘
Scalar fields of higher dimensions can be similarly defined.
Taichi only supports fields of dimensions ≤ 8.
Once a field is declared, Taichi automatically initializes its elements to zero.
To access an element in a scalar field, you need to explicitly specify the element’s index.