与外部数组进行交互

External arrays refer to numpy.ndarray or torch.Tensor.

Taichi张量与外部数组之间的转换

使用 to_numpy/from_numpy/to_torch/from_torch

  1. import taichi as ti
  2. import numpy as np
  3. ti.init()
  4. n = 4
  5. m = 7
  6. # Taichi tensors
  7. val = ti.var(ti.i32, shape=(n, m))
  8. vec = ti.Vector(3, dt=ti.i32, shape=(n, m))
  9. mat = ti.Matrix(3, 4, dt=ti.i32, shape=(n, m))
  10. # Scalar
  11. arr = np.ones(shape=(n, m), dtype=np.int32)
  12. val.from_numpy(arr)
  13. arr = val.to_numpy()
  14. # Vector
  15. arr = np.ones(shape=(n, m, 3), dtype=np.int32)
  16. vec.from_numpy(arr)
  17. arr = np.ones(shape=(n, m, 3, 1), dtype=np.int32)
  18. vec.from_numpy(arr)
  19. arr = vec.to_numpy()
  20. assert arr.shape == (n, m, 3)
  21. arr = vec.to_numpy(keep_dims=True)
  22. assert arr.shape == (n, m, 3, 1)
  23. # Matrix
  24. arr = np.ones(shape=(n, m, 3, 4), dtype=np.int32)
  25. mat.from_numpy(arr)
  26. arr = mat.to_numpy()
  27. assert arr.shape == (n, m, 3, 4)

TODO: add API reference

Using external arrays as Taichi kernel parameters

外部数组参数的类型提示是 ti.ext_arr()。请参阅下面的示例。请注意,结构for循环不支持外部数组。

  1. import taichi as ti
  2. import numpy as np
  3. ti.init()
  4. n = 4
  5. m = 7
  6. val = ti.var(ti.i32, shape=(n, m))
  7. @ti.kernel
  8. def test_numpy(arr: ti.ext_arr()):
  9. for i in range(n):
  10. for j in range(m):
  11. arr[i, j] += i + j
  12. a = np.empty(shape=(n, m), dtype=np.int32)
  13. for i in range(n):
  14. for j in range(m):
  15. a[i, j] = i * j
  16. test_numpy(a)
  17. for i in range(n):
  18. for j in range(m):
  19. assert a[i, j] == i * j + i + j