-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsandpile.py
264 lines (208 loc) · 9.09 KB
/
sandpile.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import enum
import os
import time
import numpy
import pyopencl as cl
from pyopencl.tools import dtype_to_ctype
from PIL import Image
import pyopencl.array
class SymmetryMode(enum.Enum):
SYMMETRY_OFF = 0
SYMMETRY_ON = 1
SYMMETRY_ON_WITH_OVERLAP = 2
def isqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
def _gen_macros(ref_data, symmetry_modes):
yield 'ELEM_TYPE=%s' % dtype_to_ctype(ref_data.dtype)
yield 'GRID_WIDTH=%d' % ref_data.shape[0]
yield 'GRID_HEIGHT=%d' % ref_data.shape[1]
yield 'X_SYMMETRY_MODE=%s' % symmetry_modes[0].name
yield 'Y_SYMMETRY_MODE=%s' % symmetry_modes[1].name
class Sandpiles:
def __init__(self):
self._ctx = cl.create_some_context()
self._queue = cl.CommandQueue(self._ctx)
def create_sandpile(self, shape, symmetry_modes):
data = pyopencl.array.zeros(self._queue,
shape,
numpy.uint8)
return _Sandpile(self._ctx, self._queue, data, symmetry_modes)
def try_load_sandpile(self, filename):
if not filename.endswith('.npz'):
filename += '.npz'
if not os.path.exists(filename):
return None
n = numpy.load(filename)
data = pyopencl.array.to_device(self._queue,
n['array'])
symmetry_modes = (
SymmetryMode(n['symmetry_modes'][0]),
SymmetryMode(n['symmetry_modes'][1])
)
return _Sandpile(self._ctx,
self._queue,
data,
symmetry_modes)
def scale_sandpile(self, sandpile, factor_x, factor_y):
with open('resize_data.cl') as f:
program = cl.Program(self._ctx, f.read())
new_shape = (sandpile.data.shape[0]*factor_x,
sandpile.data.shape[1]*factor_y)
macros = list(_gen_macros(sandpile.data,
sandpile.symmetry_modes))
options = _macros_to_options(macros)
program.build(options=options)
dest = pyopencl.array.empty(self._queue,
new_shape,
numpy.uint8)
program.scale_grid(self._queue,
sandpile.data.shape,
None,
sandpile.data.base_data,
dest.base_data,
numpy.uint32(factor_x),
numpy.uint32(factor_y))
return _Sandpile(self._ctx, self._queue, dest, sandpile.symmetry_modes)
def reshape_sandpile(self, sandpile, new_shape, offsets):
assert(sandpile.data.shape[0]+offsets[0] <= new_shape[0])
assert(sandpile.data.shape[1]+offsets[1] <= new_shape[1])
with open('resize_data.cl') as f:
program = cl.Program(self._ctx, f.read())
macros = list(_gen_macros(sandpile.data,
sandpile.symmetry_modes))
options = _macros_to_options(macros)
program.build(options=options)
dest = pyopencl.array.zeros(self._queue,
new_shape,
numpy.uint8)
program.reshape_grid(self._queue,
sandpile.data.shape,
None,
sandpile.data.base_data,
dest.base_data,
numpy.uint32(new_shape[0]),
numpy.uint32(offsets[0]),
numpy.uint32(new_shape[1]),
numpy.uint32(offsets[1]))
return _Sandpile(self._ctx, self._queue, dest, sandpile.symmetry_modes)
def _macros_to_options(macros):
return ['-D' + m for m in macros]
class _Sandpile:
def __init__(self, ctx, queue, data, symmetry_modes):
self._ctx = ctx
self._queue = queue
self.symmetry_modes = symmetry_modes
self.data = data
ctype = dtype_to_ctype(data.dtype)
with open('sandpile.cl') as f:
program = cl.Program(self._ctx, f.read())
macros = _gen_macros(data, symmetry_modes)
options = _macros_to_options(macros)
self._program = program.build(options=options)
from pyopencl.reduction import ReductionKernel
self._diff_krnl = ReductionKernel(self._ctx,
numpy.uint32,
neutral='0',
reduce_expr='a+b',
map_expr='grid[i]!=new_grid[i]',
arguments='const __global %s *grid, const __global %s *new_grid' % (ctype,
ctype))
def solve(self):
start = time.perf_counter()
run_iter_krnl = self._program.run_iteration
iterations = 0
adaptive_iterations = 1
grid = self.data
new_grid = pyopencl.array.empty(self._queue,
grid.shape,
grid.dtype)
run_iter_krnl(self._queue,
grid.shape,
None,
grid.base_data,
new_grid.base_data)
grid, new_grid = new_grid, grid
iterations += 1
while True:
diff_evnt = self._diff_krnl(grid,
new_grid,
queue=self._queue)
for _ in range(adaptive_iterations):
iteration_event = run_iter_krnl(self._queue,
grid.shape,
None,
grid.base_data,
new_grid.base_data)
grid, new_grid = new_grid, grid
iterations += 1
diff_count = diff_evnt.get()
if 0 == diff_count:
self.data = new_grid
iteration_event.wait()
return iterations, time.perf_counter()-start
adaptive_iterations = isqrt(diff_count)
def to_image(self, colors):
return self._get_image_creator(colors).create_image(self.data)
def save(self, filename):
symmetry_modes = (
self.symmetry_modes[0].name,
self.symmetry_modes[1].name
)
numpy.savez_compressed(filename,
a=self.data.get(),
symmetry_modes=symmetry_modes)
def _get_image_creator(self, colors):
return _ImageCreator(self._ctx,
self._queue,
self.data,
self.symmetry_modes,
colors)
class _ImageCreator:
def __init__(self, ctx, queue, ref_data, symmetry_modes, colors):
self._ctx = ctx
self._queue = queue
self._shape = ref_data.shape
if symmetry_modes[0] == SymmetryMode.SYMMETRY_OFF:
image_width = ref_data.shape[0]
elif symmetry_modes[0] == SymmetryMode.SYMMETRY_ON:
image_width = 2*ref_data.shape[0]
elif symmetry_modes[0] == SymmetryMode.SYMMETRY_ON_WITH_OVERLAP:
image_width = 2*ref_data.shape[0]-1
if symmetry_modes[1] == SymmetryMode.SYMMETRY_OFF:
image_height = ref_data.shape[1]
elif symmetry_modes[1] == SymmetryMode.SYMMETRY_ON:
image_height = 2*ref_data.shape[1]
elif symmetry_modes[1] == SymmetryMode.SYMMETRY_ON_WITH_OVERLAP:
image_height = 2*ref_data.shape[1]-1
red = [str(c[0]) for c in colors]
green = [str(c[1]) for c in colors]
blue = [str(c[2]) for c in colors]
with open('to_image.cl') as f:
program = f.read()
macros = list(_gen_macros(ref_data, symmetry_modes))
macros.append('COLOR_COUNT=%d' % len(colors))
macros.append('RED_VALS=%s' % ', '.join(red))
macros.append('GREEN_VALS=%s' % ', '.join(green))
macros.append('BLUE_VALS=%s' % ', '.join(blue))
macros.append('IMAGE_WIDTH=%d' % image_width)
macros.append('IMAGE_HEIGHT=%s' % image_height)
options = _macros_to_options(macros)
self._program = cl.Program(self._ctx, program).build(options=options)
self._to_image_krnl = self._program.to_image
self._data = pyopencl.array.empty(self._queue,
(image_width, image_height, 3),
numpy.uint8)
def create_image(self, data):
shape = data.shape
assert(self._shape == shape)
self._to_image_krnl(self._queue,
shape,
None,
data.base_data,
self._data.base_data)
return Image.fromarray(self._data.get(), 'RGB')