Skip to content

Commit

Permalink
[Example] Add example/bitmasked.py (#905)
Browse files Browse the repository at this point in the history
* [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 <taichigardener@gmail.com>
  • Loading branch information
archibate and taichi-gardener authored May 3, 2020
1 parent e8dd87a commit 4d228b9
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
46 changes: 46 additions & 0 deletions examples/bitmasked.py
Original file line number Diff line number Diff line change
@@ -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()
4 changes: 2 additions & 2 deletions python/taichi/lang/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down

0 comments on commit 4d228b9

Please sign in to comment.