From 4d228b97361bedd5c7d88b0695a168d3ebe76d44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E4=BA=8E=E6=96=8C?= <1931127624@qq.com> Date: Sun, 3 May 2020 19:18:42 +0800 Subject: [PATCH] [Example] Add example/bitmasked.py (#905) * [skip ci] [Example] Add example/bitmasked.py * [skip ci] fix indent * [skip ci] fix * [skip ci] enforce code format * [skip ci] apply review * [skip ci] apply reviews * [skip ci] fix random alias * [skip ci] use np.zeros to fix Co-authored-by: Taichi Gardener --- examples/bitmasked.py | 46 ++++++++++++++++++++++++++++++++++++++ python/taichi/lang/expr.py | 4 ++-- 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100755 examples/bitmasked.py diff --git a/examples/bitmasked.py b/examples/bitmasked.py new file mode 100755 index 0000000000000..7c6197a6f995c --- /dev/null +++ b/examples/bitmasked.py @@ -0,0 +1,46 @@ +import taichi as ti +import math + +ti.init(arch=ti.gpu) + +n = 256 +x = ti.var(ti.f32) +# `bitmasked` is a tensor that supports sparsity, in that each element can be +# activated individually. (It can be viewed as `dense`, with an extra bit for each +# element to mark its activation). Assigning to an element will activate it +# automatically. Use struct-for syntax to loop over the active elements only. +ti.root.bitmasked(ti.ij, (n, n)).place(x) + + +@ti.kernel +def activate(): + # All elements in bitmasked is initially deactivated + # Let's activate elements in the rectangle now! + for i, j in ti.ndrange((100, 125), (100, 125)): + x[i, j] = 233 # assign any value to activate the element at (i, j) + + +@ti.kernel +def paint_active_pixels(color: ti.f32): + # struct-for syntax: loop over active pixels, inactive pixels are skipped + for i, j in x: + x[i, j] = color + + +@ti.kernel +def paint_all_pixels(color: ti.f32): + # range-for syntax: loop over all pixels, no matter active or not + for i, j in ti.ndrange(n, n): + x[i, j] = color + + +ti.root.deactivate_all() +activate() + +gui = ti.GUI('bitmasked', (n, n)) +for frame in range(10000): + color = math.sin(frame * 0.05) * 0.5 + 0.5 + paint_active_pixels(color) + #paint_all_pixels(color) # try this and compare the difference! + gui.set_image(x) + gui.show() diff --git a/python/taichi/lang/expr.py b/python/taichi/lang/expr.py index 9e4c6eb86ec72..ee9129d16a40c 100644 --- a/python/taichi/lang/expr.py +++ b/python/taichi/lang/expr.py @@ -384,7 +384,7 @@ def shape(self): def to_numpy(self): from .meta import tensor_to_ext_arr import numpy as np - arr = np.empty(shape=self.shape(), + arr = np.zeros(shape=self.shape(), dtype=to_numpy_type(self.snode().data_type())) tensor_to_ext_arr(self, arr) import taichi as ti @@ -394,7 +394,7 @@ def to_numpy(self): def to_torch(self, device=None): from .meta import tensor_to_ext_arr import torch - arr = torch.empty(size=self.shape(), + arr = torch.zeros(size=self.shape(), dtype=to_pytorch_type(self.snode().data_type()), device=device) tensor_to_ext_arr(self, arr)