aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--fieldicle.py222
-rw-r--r--implosion.py228
2 files changed, 228 insertions, 222 deletions
diff --git a/fieldicle.py b/fieldicle.py
deleted file mode 100644
index 42af810..0000000
--- a/fieldicle.py
+++ /dev/null
@@ -1,222 +0,0 @@
-import pyopencl as cl
-mf = cl.mem_flags
-from pyopencl.tools import get_gl_sharing_context_properties
-
-from string import Template
-
-from OpenGL.GL import * # OpenGL - GPU rendering interface
-from OpenGL.GLU import * # OpenGL tools (mipmaps, NURBS, perspective projection, shapes)
-from OpenGL.GLUT import * # OpenGL tool to make a visualization window
-from OpenGL.arrays import vbo
-
-import numpy
-import threading
-
-import gi
-gi.require_version('Gtk', '3.0')
-from gi.repository import Gtk
-
-class ParticleWindow:
- window_width = 500
- window_height = 500
-
- world_width = 20.
- world_height = 20.
-
- num_particles = 100000
- time_step = .005
-
- gtk_active = False
-
- def glut_window(self):
- glutInit(sys.argv)
- glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
- glutInitWindowSize(self.window_width, self.window_height)
- glutInitWindowPosition(0, 0)
- window = glutCreateWindow("fieldicle")
-
- glutDisplayFunc(self.on_display)
- glutSpecialFunc(self.on_keyboard)
- glutTimerFunc(5, self.on_timer, 5)
- glutReshapeFunc(self.on_window_resize)
-
- glViewport(0, 0, self.window_width, self.window_height)
- glMatrixMode(GL_PROJECTION)
- glLoadIdentity()
-
- glOrtho(
- -(self.world_width/2), self.world_width/2,
- -(self.world_height/2), self.world_height/2,
- 0.1, 100.0
- )
-
- return(window)
-
- def on_keyboard(self, key, x, y):
- if key == GLUT_KEY_F1:
- self.gtk_active = True
- ParamWindow(self).show_all()
-
- def initial_buffers(self, num_particles):
- self.np_position = numpy.ndarray((self.num_particles, 4), dtype=numpy.float32)
- self.np_color = numpy.ndarray((num_particles, 4), dtype=numpy.float32)
-
- self.set_particle_start_positions()
-
- self.np_color[:,:] = [1.,1.,1.,1.]
- self.np_color[:,3] = numpy.random.random_sample((self.num_particles,))
-
- self.gl_position = vbo.VBO(data=self.np_position, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER)
- self.gl_position.bind()
- self.gl_color = vbo.VBO(data=self.np_color, usage=GL_DYNAMIC_DRAW, target=GL_ARRAY_BUFFER)
- self.gl_color.bind()
-
- return (self.np_position, self.gl_position, self.gl_color)
-
- def on_timer(self, t):
- glutTimerFunc(t, self.on_timer, t)
- glutPostRedisplay()
- if self.gtk_active:
- Gtk.main_iteration_do(False)
-
- def set_particle_start_positions(self):
- self.np_position[:,0] = self.world_width * numpy.random.random_sample((self.num_particles,)) - (self.world_width/2)
- self.np_position[:,1] = self.world_height * numpy.random.random_sample((self.num_particles,)) - (self.world_height/2)
- self.np_position[:,2] = 0.
- self.np_position[:,3] = 1.
- self.cl_start_position = cl.Buffer(self.context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=self.np_position)
-
- def on_window_resize(self, width, height):
- self.window_width = width
- self.window_height = height
- self.world_height = self.world_width / self.window_width * self.window_height;
-
- glViewport(0, 0, self.window_width, self.window_height)
- glLoadIdentity()
- glOrtho(
- -(self.world_width/2), self.world_width/2,
- -(self.world_height/2), self.world_height/2,
- 0.1, 100.0
- )
-
- self.set_particle_start_positions()
-
- def update_field(self, fx, fy):
- self.program = cl.Program(self.context, Template(self.kernel).substitute({
- 'fx': fx,
- 'fy': fy,
- 'time_step': self.time_step
- })).build()
-
- def on_display(self):
- # Update or particle positions by calling the OpenCL kernel
- cl.enqueue_acquire_gl_objects(self.queue, [self.cl_gl_position, self.cl_gl_color])
- kernelargs = (self.cl_gl_position, self.cl_gl_color, self.cl_start_position)
- self.program.update_particles(self.queue, (self.num_particles,), None, *(kernelargs))
- cl.enqueue_release_gl_objects(self.queue, [self.cl_gl_position, self.cl_gl_color])
- self.queue.finish()
- glFlush()
-
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
- glMatrixMode(GL_MODELVIEW)
- glLoadIdentity()
-
- glTranslatef(0., 0., -1.)
-
- # Render the particles
- glEnable(GL_POINT_SMOOTH)
- glPointSize(1)
- glEnable(GL_BLEND)
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
-
- # Set up the VBOs
- self.gl_color.bind()
- glColorPointer(4, GL_FLOAT, 0, self.gl_color)
- self.gl_position.bind()
- glVertexPointer(4, GL_FLOAT, 0, self.gl_position)
- glEnableClientState(GL_VERTEX_ARRAY)
- glEnableClientState(GL_COLOR_ARRAY)
-
- # Draw the VBOs
- glDrawArrays(GL_POINTS, 0, self.num_particles)
-
- glDisableClientState(GL_COLOR_ARRAY)
- glDisableClientState(GL_VERTEX_ARRAY)
-
- glDisable(GL_BLEND)
-
- glutSwapBuffers()
-
- def run(self):
- self.window = self.glut_window()
-
- self.platform = cl.get_platforms()[0]
- self.context = cl.Context(properties=[(cl.context_properties.PLATFORM, self.platform)] + get_gl_sharing_context_properties())
- self.queue = cl.CommandQueue(self.context)
-
- (self.np_position, self.gl_position, self.gl_color) = self.initial_buffers(self.num_particles)
-
- self.cl_start_position = cl.Buffer(self.context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=self.np_position)
-
- self.cl_gl_position = cl.GLBuffer(self.context, mf.READ_WRITE, int(self.gl_position))
- self.cl_gl_color = cl.GLBuffer(self.context, mf.READ_WRITE, int(self.gl_color))
-
- self.kernel = """__kernel void update_particles(__global float4* position,
- __global float4* color,
- __global float4* start_position)
- {
- unsigned int i = get_global_id(0);
- float4 p = position[i];
-
- float life = color[i].w;
- life -= $time_step;
-
- if (life <= 0.f) {
- p = start_position[i];
- life = 1.0f;
- }
-
- p.x += ($fx) * $time_step;
- p.y += ($fy) * $time_step;
-
- position[i] = p;
- color[i].w = life;
- }"""
- self.program = cl.Program(self.context, Template(self.kernel).substitute({
- 'fx': 'cos(p.x)',
- 'fy': 'sin(p.y*p.x)',
- 'time_step': self.time_step
- })).build()
-
- glutMainLoop()
-
-
-particleWindow = ParticleWindow()
-
-glfwThread = threading.Thread(target=particleWindow.run)
-glfwThread.start()
-
-class ParamWindow(Gtk.Dialog):
- def __init__(self, particleWin):
- Gtk.Dialog.__init__(self, title="Field Parameters")
- self.particleWin = particleWin
-
- self.updateBtn = Gtk.Button(label="Update field")
- self.updateBtn.connect("clicked", self.on_update_clicked)
-
- self.entryFx = Gtk.Entry()
- self.entryFx.set_text("cos(p.x)")
- self.entryFy = Gtk.Entry()
- self.entryFy.set_text("sin(p.y*p.x)")
-
- layout = self.get_content_area()
-
- layout.add(self.entryFx)
- layout.add(self.entryFy)
- layout.add(self.updateBtn)
-
- def on_update_clicked(self, widget):
- self.particleWin.update_field(
- self.entryFx.get_text(),
- self.entryFy.get_text()
- )
diff --git a/implosion.py b/implosion.py
new file mode 100644
index 0000000..c70f21a
--- /dev/null
+++ b/implosion.py
@@ -0,0 +1,228 @@
+import pyopencl as cl
+mf = cl.mem_flags
+
+from string import Template
+
+import numpy
+import matplotlib.pyplot as plt
+
+import time
+
+kernel = """
+float constant w[9] = {
+ 1./36., 1./9., 1./36.,
+ 1./9. , 4./9., 1./9. ,
+ 1./36 , 1./9., 1./36.
+};
+
+unsigned int indexOfDirection(int i, int j) {
+ return (i+1) + 3*(1-j);
+}
+
+unsigned int indexOfCell(int x, int y)
+{
+ return y * $nX + x;
+}
+
+unsigned int idx(int x, int y, int i, int j) {
+ return indexOfDirection(i,j)*$nCells + indexOfCell(x,y);
+}
+
+__global float f_i(__global __read_only float* f, int x, int y, int i, int j) {
+ return f[idx(x,y,i,j)];
+}
+
+float comp(int i, int j, float2 v) {
+ return i*v.x + j*v.y;
+}
+
+float sq(float x) {
+ return x*x;
+}
+
+float f_eq(float w, float d, float2 v, int i, int j, float dotv) {
+ return w * d * (1.f + 3.f*comp(i,j,v) + 4.5f*sq(comp(i,j,v)) - 1.5f*dotv);
+}
+
+__kernel void collide_and_stream(__global __write_only float* f_a,
+ __global __read_only float* f_b,
+ __global __write_only float* moments,
+ __global __read_only int* material)
+{
+ const unsigned int gid = indexOfCell(get_global_id(0), get_global_id(1));
+
+ const uint2 cell = (uint2)(get_global_id(0), get_global_id(1));
+
+ const int m = material[gid];
+
+ if ( m == 0 ) {
+ return;
+ }
+
+ float f0 = f_i(f_b, cell.x+1, cell.y-1, -1, 1);
+ float f1 = f_i(f_b, cell.x , cell.y-1, 0, 1);
+ float f2 = f_i(f_b, cell.x-1, cell.y-1, 1, 1);
+ float f3 = f_i(f_b, cell.x+1, cell.y , -1, 0);
+ float f4 = f_i(f_b, cell.x , cell.y , 0, 0);
+ float f5 = f_i(f_b, cell.x-1, cell.y , 1, 0);
+ float f6 = f_i(f_b, cell.x+1, cell.y+1, -1,-1);
+ float f7 = f_i(f_b, cell.x , cell.y+1, 0,-1);
+ float f8 = f_i(f_b, cell.x-1, cell.y+1, 1,-1);
+
+ const float d = f0 + f1 + f2 + f3 + f4 + f5 + f6 + f7 + f8;
+
+ float2 v = (float2)(
+ (f5 - f3 + f2 - f6 + f8 - f0) / d,
+ (f1 - f7 + f2 - f6 - f8 + f0) / d
+ );
+
+ if ( m == 2 ) {
+ v = (float2)(0.0f, 0.0f);
+ }
+
+ const float dotv = dot(v,v);
+
+ f0 += $omega * (f_eq(w[0], d,v,-1, 1, dotv) - f0);
+ f1 += $omega * (f_eq(w[1], d,v, 0, 1, dotv) - f1);
+ f2 += $omega * (f_eq(w[2], d,v, 1, 1, dotv) - f2);
+ f3 += $omega * (f_eq(w[3], d,v,-1, 0, dotv) - f3);
+ f4 += $omega * (f_eq(w[4], d,v, 0, 0, dotv) - f4);
+ f5 += $omega * (f_eq(w[5], d,v, 1, 0, dotv) - f5);
+ f6 += $omega * (f_eq(w[6], d,v,-1,-1, dotv) - f6);
+ f7 += $omega * (f_eq(w[7], d,v, 0,-1, dotv) - f7);
+ f8 += $omega * (f_eq(w[8], d,v, 1,-1, dotv) - f8);
+
+ f_a[0*$nCells + gid] = f0;
+ f_a[1*$nCells + gid] = f1;
+ f_a[2*$nCells + gid] = f2;
+ f_a[3*$nCells + gid] = f3;
+ f_a[4*$nCells + gid] = f4;
+ f_a[5*$nCells + gid] = f5;
+ f_a[6*$nCells + gid] = f6;
+ f_a[7*$nCells + gid] = f7;
+ f_a[8*$nCells + gid] = f8;
+
+ moments[1*gid] = d;
+ moments[2*gid] = v.x;
+ moments[3*gid] = v.y;
+}"""
+
+class D2Q9_BGK_Lattice:
+ def idx(self, x, y):
+ return y * self.nX + x;
+
+ def __init__(self, nX, nY):
+ self.nX = nX
+ self.nY = nY
+ self.nCells = nX * nY
+ self.tick = True
+
+ self.platform = cl.get_platforms()[0]
+ self.context = cl.Context(properties=[(cl.context_properties.PLATFORM, self.platform)])
+ self.queue = cl.CommandQueue(self.context)
+
+ self.np_pop_a = numpy.ndarray(shape=(9, self.nCells), dtype=numpy.float32)
+ self.np_pop_b = numpy.ndarray(shape=(9, self.nCells), dtype=numpy.float32)
+
+ self.np_moments = numpy.ndarray(shape=(3, self.nCells), dtype=numpy.float32)
+ self.np_material = numpy.ndarray(shape=(self.nCells, 1), dtype=numpy.int32)
+
+ self.setup_geometry()
+
+ self.equilibrilize()
+ self.setup_anomaly()
+
+ self.cl_pop_a = cl.Buffer(self.context, mf.READ_WRITE | mf.USE_HOST_PTR, hostbuf=self.np_pop_a)
+ self.cl_pop_b = cl.Buffer(self.context, mf.READ_WRITE | mf.USE_HOST_PTR, hostbuf=self.np_pop_b)
+
+ self.cl_material = cl.Buffer(self.context, mf.READ_ONLY | mf.USE_HOST_PTR, hostbuf=self.np_material)
+ self.cl_moments = cl.Buffer(self.context, mf.READ_WRITE | mf.USE_HOST_PTR, hostbuf=self.np_moments)
+
+ self.build_kernel()
+
+ def setup_geometry(self):
+ self.np_material[:] = 0
+ for x in range(1,self.nX-1):
+ for y in range(1,self.nY-1):
+ if x == 1 or y == 1 or x == self.nX-2 or y == self.nY-2:
+ self.np_material[self.idx(x,y)] = 2
+ else:
+ self.np_material[self.idx(x,y)] = 1
+
+ def equilibrilize(self):
+ self.np_pop_a[(0,2,6,8),:] = 1./36.
+ self.np_pop_a[(1,3,5,7),:] = 1./9.
+ self.np_pop_a[4,:] = 4./9.
+
+ self.np_pop_b[(0,2,6,8),:] = 1./36.
+ self.np_pop_b[(1,3,5,7),:] = 1./9.
+ self.np_pop_b[4,:] = 4./9.
+
+ def setup_anomaly(self):
+ bubbles = [ [ self.nX//4, self.nY//4],
+ [ self.nX//4,self.nY-self.nY//4],
+ [self.nX-self.nX//4, self.nY//4],
+ [self.nX-self.nX//4,self.nY-self.nY//4] ]
+
+ for x in range(0,self.nX-1):
+ for y in range(0,self.nY-1):
+ for [a,b] in bubbles:
+ if numpy.sqrt((x-a)*(x-a)+(y-b)*(y-b)) < self.nX//10:
+ self.np_pop_a[:,self.idx(x,y)] = 1./24.
+ self.np_pop_b[:,self.idx(x,y)] = 1./24.
+
+ def build_kernel(self):
+ self.program = cl.Program(self.context, Template(kernel).substitute({
+ 'nX' : self.nX,
+ 'nY' : self.nY,
+ 'nCells': self.nCells,
+ 'omega': 1.0/0.8
+ })).build() #'-cl-single-precision-constant -cl-fast-relaxed-math')
+
+ def evolve(self):
+ if self.tick:
+ self.tick = False
+ self.program.collide_and_stream(self.queue, (self.nX,self.nY), (64,1), self.cl_pop_a, self.cl_pop_b, self.cl_moments, self.cl_material)
+ else:
+ self.tick = True
+ self.program.collide_and_stream(self.queue, (self.nX,self.nY), (64,1), self.cl_pop_b, self.cl_pop_a, self.cl_moments, self.cl_material)
+
+ def sync(self):
+ self.queue.finish()
+
+ def show(self, i):
+ cl.enqueue_copy(LBM.queue, LBM.np_moments, LBM.cl_moments).wait();
+
+ density = numpy.ndarray(shape=(self.nX-2, self.nY-2))
+ for y in range(1,self.nY-1):
+ for x in range(1,self.nX-1):
+ density[x-1,y-1] = self.np_moments[0,self.idx(x,y)]
+
+ plt.imshow(density, vmin=0.2, vmax=2.0, cmap=plt.get_cmap("seismic"))
+ plt.savefig("result/density_" + str(i) + ".png")
+
+
+def MLUPS(cells, steps, time):
+ return cells * steps / time * 1e-6
+
+nUpdates = 1000
+nStat = 100
+
+print("Initializing simulation...\n")
+
+LBM = D2Q9_BGK_Lattice(1024, 1024)
+
+print("Starting simulation using %d cells...\n" % LBM.nCells)
+
+lastStat = time.time()
+
+for i in range(1,nUpdates+1):
+ if i % nStat == 0:
+ LBM.sync()
+ #LBM.show(i)
+ print("i = %4d; %3.0f MLUPS" % (i, MLUPS(LBM.nCells, nStat, time.time() - lastStat)))
+ lastStat = time.time()
+
+ LBM.evolve()
+
+LBM.show(nUpdates)