-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathplay_bmsb.py
330 lines (262 loc) · 16 KB
/
play_bmsb.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
"""
Copyright (c) 2019 Eric Shook. All rights reserved.
Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
@author: eshook (Eric Shook, [email protected])
@contributors: <Contribute and add your name here!>
"""
# Load forest
from forest import *
# PyCUDA imports
import pycuda.autoinit
import pycuda.driver as drv
import pycuda.gpuarray as gpuarray
import pycuda.curandom as curandom
from pycuda.compiler import SourceModule
from pycuda.characterize import sizeof
# Other imports
import matplotlib.pyplot as plt
from os import path
import sys
# Switch Engine to GPU
Config.engine = cuda_engine
print("Running Engine",Config.engine)
# .tif files to use as initial population and survival layer probabilities
initial_population_file = '/home/iaa/bures024/Forest/2000_init_pop.tif'
survival_probabilities_file = '/home/iaa/bures024/Forest/2000_surv_probs.tif'
# Make sure both files exist
if (path.isfile(initial_population_file) == False) or (path.isfile(survival_probabilities_file) == False):
print('Error. File not found. Exiting program...')
sys.exit()
# Load initial population and survival layer probabilities as numpy arrays
initial_population = plt.imread(initial_population_file).astype(np.float32)
survival_probabilities = plt.imread(survival_probabilities_file).astype(np.float32)
survival_probabilities = np.divide(survival_probabilities,255)
# Make sure initial population and survival layer probabilities grids are square (n x n)
if (initial_population.shape[0] != initial_population.shape[1]) or (survival_probabilities.shape[0] != survival_probabilities.shape[1]):
print('Invalid dimensions. Grid must be square (n x n dimensions). Exiting program...')
sys.exit()
# Make sure initial population and survival layer probabilities grids are the same dimensions
if (initial_population.shape[0] != survival_probabilities.shape[0]) or (initial_population.shape[1] != survival_probabilities.shape[1]):
print('Invalid entry. Initial population grid and survival probabilities grid must be same shape. Exiting program...')
sys,exit()
# Constants
matrix_size = initial_population.shape[0] # Size of square grid
block_dims = 32 # CUDA block dimensions - maximum dimensions = 32 x 32
grid_dims = (matrix_size + block_dims - 1) // block_dims # CUDA grid dimensions
p_local = 0.50 # probability an agent spreads during local diffusion
p_non_local = 0.33 # probability an agent spreads during non-local diffusion
growth_rate = 0.25 # expnential growth rate of population layer
mu = 0.0 # location parameter of cauchy distribution
gamma = 1.0 # scale parameter of cauchy distribution
n_iters = 1 # number of iterations
kernel_code = """
#include <curand_kernel.h>
#include <math.h>
extern "C" {
__device__ float get_random_number(curandState* global_state, int thread_id) {
curandState local_state = global_state[thread_id];
float num = curand_uniform(&local_state);
global_state[thread_id] = local_state;
return num;
}
__device__ float get_random_angle_in_radians(curandState* global_state, int thread_id) {
float radians = get_random_number(global_state, thread_id) * 2 * M_PI;
return radians;
}
__device__ float get_random_cauchy_distance(curandState* global_state, int thread_id, float mu, float gamma) {
float distance = fabsf(mu + gamma * tan(M_PI * (get_random_number(global_state,thread_id) - 0.5)));
return distance;
}
__device__ int get_x_coord(int x, float radians, float distance) {
int x_coord = (int) roundf(x + distance * sin(radians));
return x_coord;
}
__device__ int get_y_coord(int y, float radians, float distance) {
int y_coord = (int) roundf(y + distance * cos(radians));
return y_coord;
}
__global__ void init_generators(curandState* global_state, int seed, int grid_size) {
int x = threadIdx.x + blockIdx.x * blockDim.x; // column index of cell
int y = threadIdx.y + blockIdx.y * blockDim.y; // row index of cell
// make sure this cell is within bounds of grid
if (x < grid_size && y < grid_size) {
int thread_id = y * grid_size + x; // thread index
curandState local_state;
curand_init(seed, thread_id, 0, &local_state);
global_state[thread_id] = local_state;
}
}
__global__ void local_diffuse(float* grid_a, float* grid_b, curandState* global_state, int grid_size, float prob, int time) {
int x = threadIdx.x + blockIdx.x * blockDim.x; // column index of cell
int y = threadIdx.y + blockIdx.y * blockDim.y; // row index of cell
// make sure this cell is within bounds of grid
if (x < grid_size && y < grid_size) {
int thread_id = y * grid_size + x; // thread index
grid_b[thread_id] = grid_a[thread_id]; // copy current cell
int edge = (x == 0) || (x == grid_size - 1) || (y == 0) || (y == grid_size - 1);
// ignore cell if its an edge cell
if (!edge) {
// ignore cell if it is not already populated
if (grid_a[thread_id] > 0.0) {
int count = 0; // number of agents looked at so far
int n_iters = grid_a[thread_id]; // number of agents in this cell
float num; // random number between (0,1]
int neighbor;
// each agent has a chance to spread
while (count < n_iters) {
num = get_random_number(global_state, thread_id);
// this agent spreads to a neighbor
if (num < prob) {
// randomly select a neighbor
neighbor = (int) ceilf(get_random_number(global_state, thread_id) * 8.0);
atomicAdd(&grid_b[thread_id], (float)(-1.0));
switch(neighbor) {
case 1: // above
atomicAdd(&grid_b[thread_id - grid_size], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x, y - 1, time);
break;
case 2: // above and left
atomicAdd(&grid_b[thread_id - grid_size - 1], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x - 1, y - 1, time);
break;
case 3: // above and right
atomicAdd(&grid_b[thread_id - grid_size + 1], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x + 1, y - 1, time);
break;
case 4: // below
atomicAdd(&grid_b[thread_id + grid_size], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x, y + 1, time);
break;
case 5: // below and left
atomicAdd(&grid_b[thread_id + grid_size - 1], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x - 1, y + 1, time);
break;
case 6: // below and right
atomicAdd(&grid_b[thread_id + grid_size + 1], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x + 1, y + 1, time);
break;
case 7: // left
atomicAdd(&grid_b[thread_id - 1], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x - 1, y, time);
break;
case 8: // right
atomicAdd(&grid_b[thread_id + 1], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x + 1, y, time);
break;
default: // should never reach here
printf("Invalid number encountered\\n");
break;
}
}
count += 1;
}
}
}
}
}
__global__ void non_local_diffuse(float* grid_a, float* grid_b, curandState* global_state, int grid_size, float prob, float mu, float gamma, int time) {
int x = threadIdx.x + blockIdx.x * blockDim.x; // column index of cell
int y = threadIdx.y + blockIdx.y * blockDim.y; // row index of cell
// make sure this cell is within bounds of grid
if (x < grid_size && y < grid_size) {
int thread_id = y * grid_size + x; // thread index
grid_b[thread_id] = grid_a[thread_id]; // copy current cell
// ignore cell if it is not already populated
if (grid_a[thread_id] > 0.0) {
int count = 0; // number of agents looked at so far
int n_iters = grid_a[thread_id]; // number of agents in this cell
float num; // random number between (0,1]
float radians; // random angle between (0,2*PI)
float distance; // distance drawn from cauchy distribution
int x_coord; // row index of cell to spread to
int y_coord; // column index of cell to spread to
int spread_index; // thread index of cell to spread to
// each agent has a chance to spread
while (count < n_iters) {
num = get_random_number(global_state, thread_id);
// this agent spreads to a neighbor
if (num < prob) {
// randomly select a cell
radians = get_random_angle_in_radians(global_state, thread_id);
distance = get_random_cauchy_distance(global_state, thread_id, mu, gamma);
x_coord = get_x_coord(x, radians, distance);
y_coord = get_y_coord(y, radians, distance);
//printf("Radians = %f\\tDistance = %f\\tX = %d\\tY = %d\\tX_coord = %d\\tY_coord = %d\\n", radians, distance, x, y, x_coord, y_coord);
// make sure chosen cell is in the grid dimensions and is not the current cell
if (x_coord < grid_size && x_coord >= 0 && y_coord < grid_size && y_coord >= 0 && (x_coord != x || y_coord != y)) {
spread_index = y_coord * grid_size + x_coord;
atomicAdd(&grid_b[thread_id], (float)(-1.0));
atomicAdd(&grid_b[spread_index], (float)1.0);
//printf("Cell (%d,%d) spread to cell (%d,%d) at time %d\\n", x, y, x_coord, y_coord, time);
}
}
count += 1;
}
}
}
}
__global__ void survival_of_the_fittest(float* grid_a, float* grid_b, curandState* global_state, int grid_size, float* survival_probabilities, int time) {
int x = threadIdx.x + blockIdx.x * blockDim.x; // column index of cell
int y = threadIdx.y + blockIdx.y * blockDim.y; // row index of cell
// make sure this cell is within bounds of grid
if (x < grid_size && y < grid_size) {
int thread_id = y * grid_size + x; // thread index
grid_b[thread_id] = grid_a[thread_id]; // copy current cell
float num; // random number between (0,1]
// ignore cell if it is not already populated
if (grid_a[thread_id] > 0.0) {
num = get_random_number(global_state, thread_id);
// agents in this cell die
if (num < survival_probabilities[thread_id]) {
grid_b[thread_id] = 0.0;
//printf("Cell (%d,%d) died at time %d (probability of death was %f)\\n", x, y, time, survival_probabilities[thread_id]);
}
}
}
}
__global__ void population_growth(float* grid_a, float* grid_b, int grid_size, float growth_rate, int time) {
int x = threadIdx.x + blockIdx.x * blockDim.x; // column index of cell
int y = threadIdx.y + blockIdx.y * blockDim.y; // row index of cell
// make sure this cell is within bounds of grid
if (x < grid_size && y < grid_size) {
int thread_id = y * grid_size + x; // thread index
grid_b[thread_id] = grid_a[thread_id]; // copy current cell
//printf("Value at (%d,%d) is %f\\n", x, y, grid_b[thread_id]);
// ignore cell if population is 0
if (grid_a[thread_id] > 0.0) {
// growth formula: x(t) = x(t-1) * (1 + growth_rate)^time
int pop = grid_a[thread_id];
int add_pop = (int) truncf(pop * pow((1 + growth_rate), time));
grid_b[thread_id] += add_pop;
//printf("Cell (%d,%d)'s population grew by %d at time %d\\n", x, y, add_pop, time);
}
}
}
} // end extern "C"
"""
mod = SourceModule(kernel_code, no_extern_c = True)
# Get kernel functions
local = mod.get_function('local_diffuse')
non_local = mod.get_function('non_local_diffuse')
survival_layer = mod.get_function('survival_of_the_fittest')
population_layer = mod.get_function('population_growth')
init_generators = mod.get_function('init_generators')
# Initialize random number generator
generator = curandom.XORWOWRandomNumberGenerator()
data_type_size = sizeof(generator.state_type, "#include <curand_kernel.h>")
generator._state = drv.mem_alloc((matrix_size * matrix_size) * data_type_size)
seed = 123456789
init_generators(generator.state, np.int32(seed), np.int32(matrix_size),
grid = (grid_dims, grid_dims), block = (block_dims, block_dims, 1))
# Run n_iters of the Brown Marmorated Stink Bug (BMSB) Diffusion Simulation
run_primitive(
empty_grid.vars(matrix_size) ==
initialize_grid.vars(matrix_size, initial_population, survival_probabilities, generator) ==
bmsb_stop_condition.vars(n_iters) <=
local_diffusion.vars(local, matrix_size, p_local, grid_dims, block_dims) ==
non_local_diffusion.vars(non_local, matrix_size, p_non_local, mu, gamma, grid_dims, block_dims) ==
survival_function.vars(survival_layer, matrix_size, grid_dims, block_dims) ==
population_growth.vars(population_layer, matrix_size, growth_rate, grid_dims, block_dims) ==
bmsb_stop >=
AGStore.file("output.tif")
)