Skip to content

Instantly share code, notes, and snippets.

@villares
Created August 3, 2024 15:27
Show Gist options
  • Save villares/6517551ede1c5cf49cbbf55cacbc39e1 to your computer and use it in GitHub Desktop.
Save villares/6517551ede1c5cf49cbbf55cacbc39e1 to your computer and use it in GitHub Desktop.
taichi + py5 failure (taichi needs the main thread)
import taichi as ti
import taichi.math as tm
import py5
#ti.init(arch=ti.gpu)
ti.init()
@ti.func
def complex_sqr(z): # complex square of a 2D vector
return tm.vec2(z[0] * z[0] - z[1] * z[1], 2 * z[0] * z[1])
@ti.kernel
def paint(t: float):
for i, j in pixels: # Parallelized over all pixels
c = tm.vec2(-0.8, tm.cos(t) * 0.2)
z = tm.vec2(i / n - 1, j / n - 0.5) * 2
iterations = 0
while z.norm() < 20 and iterations < 50:
z = complex_sqr(z) + c
iterations += 1
pixels[i, j] = 1 - iterations * 0.02
#gui = ti.GUI("Julia Set", res=(n * 2, n))
# i = 0
# while gui.running:
# paint(i * 0.03)
# gui.set_image(pixels)
# gui.show()
# i += 1
def setup():
global pixels, n
py5.size(640, 320)
n = 320
pixels = ti.field(dtype=float, shape=(n * 2, n))
def draw():
#paint(py5.frame_count * 0.03)
py5.set_np_pixels(pixels.to_numpy())
py5.run_sketch(block=False)
@villares
Copy link
Author

villares commented Aug 3, 2024

>>> %Run hello_fractal_py5.py n
[Taichi] version 1.7.1, llvm 15.0.4, commit 0f143b2f, linux, python 3.9.19
[Taichi] Starting on arch=x64
>>> [E 08/03/24 12:24:40.242 73612] [llvm_context.cpp:add_struct_module@674] Assertion failure: std::this_thread::get_id() == main_thread_id_

Update: In further attempts to use py5.set_numpy_pixels with the taichi field, the array dimensions where "wrong", I managed to swap width and height and use bands "L" just to see where it went (but then it went nowhere).

@hx2A
Copy link

hx2A commented Aug 4, 2024

You are running this on linux?

I have heard of taichi but have not used it. It it incompatible with py5?

@villares
Copy link
Author

villares commented Aug 4, 2024

Hi! Yes, I'm on Linux... I'm not sure it is incompatible, my mental model of the whole thing is sketchy... my first intuitions (and attempts) are that it might require the main thread in a way incompatible to py5? but again, you are the expert :D

@hx2A
Copy link

hx2A commented Aug 4, 2024

I tried using taichi a few times in the past and didn't get very far.

Usually the "main thread issue" is for MacOS. It could be taichi uses the GPU in a special way that requires it to be the context thread, much like how OpenGL works. You aren't using P2D or P3D here though. It could be confused though because calling taichi method sfrom inside draw like that means the executing thread originates with Java, not Python. If taichi is finicky about what threads it will run in, it might not be happy about that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment