piegy 1.1.6__py3-none-any.whl → 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- piegy/__version__.py +1 -0
- piegy/data_tools.py +16 -21
- piegy/simulation.py +109 -821
- piegy/simulation_py.py +808 -0
- piegy/test_var.py +2 -2
- {piegy-1.1.6.dist-info → piegy-2.0.0.dist-info}/METADATA +1 -1
- piegy-2.0.0.dist-info/RECORD +17 -0
- piegy-1.1.6.dist-info/RECORD +0 -16
- {piegy-1.1.6.dist-info → piegy-2.0.0.dist-info}/WHEEL +0 -0
- {piegy-1.1.6.dist-info → piegy-2.0.0.dist-info}/licenses/LICENSE.txt +0 -0
- {piegy-1.1.6.dist-info → piegy-2.0.0.dist-info}/top_level.txt +0 -0
piegy/simulation_py.py
ADDED
@@ -0,0 +1,808 @@
|
|
1
|
+
'''
|
2
|
+
Functions and class below are for Python-based simulations. Not maintained after v1.1.6 on Jun 26, 2025.
|
3
|
+
But you can still run them by calling:
|
4
|
+
|
5
|
+
>>> run_py(mod)
|
6
|
+
'''
|
7
|
+
|
8
|
+
from simulation import model
|
9
|
+
|
10
|
+
import math
|
11
|
+
import numpy as np
|
12
|
+
from timeit import default_timer as timer
|
13
|
+
|
14
|
+
|
15
|
+
class patch:
|
16
|
+
'''
|
17
|
+
A single patch in the N x M space.
|
18
|
+
Interacts with neighboring patches, assuming no spatial structure within a patch.
|
19
|
+
Initialized in single_init function.
|
20
|
+
|
21
|
+
Class Functions:
|
22
|
+
|
23
|
+
__init__:
|
24
|
+
Inputs:
|
25
|
+
U, V: initial value of U and V
|
26
|
+
matrix: payoff matrix for U and V. The canonical form is 2x2, here we ask for a flattened 1x4 form.
|
27
|
+
patch_var: np.array of [mu1, mu2, w1, w2, kappa1, kappa2]
|
28
|
+
|
29
|
+
__str__:
|
30
|
+
Print patch object in a nice way.
|
31
|
+
|
32
|
+
set_nb_pointers:
|
33
|
+
Set pointers to neighbors of this patch object.
|
34
|
+
|
35
|
+
update_pi:
|
36
|
+
Update Upi, Vpi and payoff rates (payoff rates are the first two numbers in self.pi_death_rates).
|
37
|
+
|
38
|
+
update_k:
|
39
|
+
Update natural death rates (the last two numbers in self.pi_death_rates).
|
40
|
+
|
41
|
+
update_mig:
|
42
|
+
Update migration rates.
|
43
|
+
|
44
|
+
get_pi_death_rates, get_mig_rates:
|
45
|
+
Return respective members.
|
46
|
+
|
47
|
+
change_popu:
|
48
|
+
Change U, V based on input signal.
|
49
|
+
'''
|
50
|
+
|
51
|
+
def __init__(self, U, V, matrix = [-0.1, 0.4, 0, 0.2], patch_var = [0.5, 0.5, 100, 100, 0.001, 0.001]):
|
52
|
+
|
53
|
+
self.U = U # int, U population. Initialized upon creating object.
|
54
|
+
self.V = V # int, V population
|
55
|
+
self.Upi = 0 # float, payoff
|
56
|
+
self.Vpi = 0
|
57
|
+
|
58
|
+
self.matrix = matrix # np.array or list, len = 4, payoff matrix
|
59
|
+
self.mu1 = patch_var[0] # float, how much proportion of the population migrates (U) each time
|
60
|
+
self.mu2 = patch_var[1]
|
61
|
+
self.w1 = patch_var[2] # float, strength of payoff-driven effect. Larger w <=> stronger payoff-driven motion
|
62
|
+
self.w2 = patch_var[3]
|
63
|
+
self.kappa1 = patch_var[4] # float, carrying capacity, determines death rates
|
64
|
+
self.kappa2 = patch_var[5]
|
65
|
+
|
66
|
+
self.nb = None # list of patch objects (pointers), point to neighbors, initialized seperatedly (after all patches are created)
|
67
|
+
self.pi_death_rates = [0 for _ in range(4)] # list, len = 4, rates of payoff & death
|
68
|
+
# first two are payoff rates, second two are death rates
|
69
|
+
self.mig_rates = [0 for _ in range(8)] # list, len = 8, migration rates, stored in an order: up, down, left, right,
|
70
|
+
# first 4 are U's mig_rate, the last 4 are V's
|
71
|
+
self.sum_pi_death_rates = 0 # float, sum of pi_death_rates
|
72
|
+
self.sum_mig_rates = 0 # float, sum of mig_rates
|
73
|
+
|
74
|
+
|
75
|
+
def __str__(self):
|
76
|
+
self_str = ''
|
77
|
+
self_str += 'U, V = ' + str(self.U) + ', ' + str(self.V) + '\n'
|
78
|
+
self_str += 'pi = ' + str(self.Upi) + ', ' + str(self.Vpi) + '\n'
|
79
|
+
self_str += 'matrix = ' + str(self.matrix) + '\n'
|
80
|
+
self_str += 'mu1, mu2 = ' + str(self.mu1) + ', ' + str(self.mu2) + '\n'
|
81
|
+
self_str += 'w1, w2 = ' + str(self.w1) + ', ' + str(self.w2) + '\n'
|
82
|
+
self_str += 'kappa1, kappa2 = ' + str(self.kappa1) + ', ' + str(self.kappa2) + '\n'
|
83
|
+
self_str += '\n'
|
84
|
+
self_str += 'nb = ' + str(self.nb)
|
85
|
+
self_str += 'pi_death_rates = ' + str(self.pi_death_rates) + '\n'
|
86
|
+
self_str += 'mig_rates = ' + str(self.mig_rates) + '\n'
|
87
|
+
self_str += 'sum_pi_death_rates = ' + str(self.sum_pi_death_rates) + '\n'
|
88
|
+
self_str += 'sum_mig_rates = ' + str(self.sum_mig_rates) + '\n'
|
89
|
+
|
90
|
+
return self_str
|
91
|
+
|
92
|
+
|
93
|
+
def set_nb_pointers(self, nb):
|
94
|
+
# nb is a list of pointers (point to patches)
|
95
|
+
# nb is passed from the model class
|
96
|
+
self.nb = nb
|
97
|
+
|
98
|
+
|
99
|
+
def update_pi_k(self):
|
100
|
+
# calculate payoff and natural death rates
|
101
|
+
|
102
|
+
U = self.U # bring the values to front
|
103
|
+
V = self.V
|
104
|
+
sum_minus_1 = U + V - 1 # this value is used several times
|
105
|
+
|
106
|
+
if sum_minus_1 > 0:
|
107
|
+
# interaction happens only if there is more than 1 individual
|
108
|
+
|
109
|
+
if U != 0:
|
110
|
+
# no payoff if U == 0
|
111
|
+
self.Upi = (U - 1) / sum_minus_1 * self.matrix[0] + V / sum_minus_1 * self.matrix[1]
|
112
|
+
else:
|
113
|
+
self.Upi = 0
|
114
|
+
|
115
|
+
if V != 0:
|
116
|
+
self.Vpi = U / sum_minus_1 * self.matrix[2] + (V - 1) / sum_minus_1 * self.matrix[3]
|
117
|
+
else:
|
118
|
+
self.Vpi = 0
|
119
|
+
|
120
|
+
else:
|
121
|
+
# no interaction, hence no payoff, if only 1 individual
|
122
|
+
self.Upi = 0
|
123
|
+
self.Vpi = 0
|
124
|
+
|
125
|
+
# update payoff rates
|
126
|
+
self.pi_death_rates[0] = abs(U * self.Upi)
|
127
|
+
self.pi_death_rates[1] = abs(V * self.Vpi)
|
128
|
+
|
129
|
+
# update natural death rates
|
130
|
+
self.pi_death_rates[2] = self.kappa1 * U * (sum_minus_1 + 1)
|
131
|
+
self.pi_death_rates[3] = self.kappa2 * V * (sum_minus_1 + 1)
|
132
|
+
|
133
|
+
# update sum of rates
|
134
|
+
self.sum_pi_death_rates = sum(self.pi_death_rates)
|
135
|
+
|
136
|
+
|
137
|
+
def update_mig(self):
|
138
|
+
# calculate migration rates
|
139
|
+
|
140
|
+
# store the 'weight' of migration, i.e. value of f/g functions for neighbors
|
141
|
+
U_weight = [0, 0, 0, 0]
|
142
|
+
V_weight = [0, 0, 0, 0]
|
143
|
+
|
144
|
+
for i in range(4):
|
145
|
+
if self.nb[i] != None:
|
146
|
+
U_weight[i] = 1 + pow(math.e, self.w1 * self.nb[i].Upi)
|
147
|
+
V_weight[i] = 1 + pow(math.e, self.w2 * self.nb[i].Vpi)
|
148
|
+
|
149
|
+
mu1_U = self.mu1 * self.U
|
150
|
+
mu2_V = self.mu2 * self.V
|
151
|
+
|
152
|
+
mu1_U_divide_sum = mu1_U / sum(U_weight)
|
153
|
+
mu2_V_divide_sum = mu2_V / sum(V_weight)
|
154
|
+
|
155
|
+
for i in range(4):
|
156
|
+
self.mig_rates[i] = mu1_U_divide_sum * U_weight[i]
|
157
|
+
self.mig_rates[i + 4] = mu2_V_divide_sum * V_weight[i]
|
158
|
+
|
159
|
+
# update sum of rates
|
160
|
+
self.sum_mig_rates = mu1_U + mu2_V
|
161
|
+
|
162
|
+
|
163
|
+
def get_sum_rates(self):
|
164
|
+
# return sum of all 12 rates
|
165
|
+
return self.sum_pi_death_rates + self.sum_mig_rates
|
166
|
+
|
167
|
+
|
168
|
+
def find_event(self, expected_sum):
|
169
|
+
# find the event within the 12 events based on expected sum-of-rates within this patch
|
170
|
+
|
171
|
+
if expected_sum < self.sum_pi_death_rates:
|
172
|
+
# in the first 4 events (payoff and death events)
|
173
|
+
event = 0
|
174
|
+
current_sum = 0
|
175
|
+
while current_sum < expected_sum:
|
176
|
+
current_sum += self.pi_death_rates[event]
|
177
|
+
event += 1
|
178
|
+
event -= 1
|
179
|
+
|
180
|
+
else:
|
181
|
+
# in the last 8 events (migration events):
|
182
|
+
event = 0
|
183
|
+
current_sum = self.sum_pi_death_rates
|
184
|
+
while current_sum < expected_sum:
|
185
|
+
current_sum += self.mig_rates[event]
|
186
|
+
event += 1
|
187
|
+
event += 3 # i.e., -= 1, then += 4 (to account for the first 4 payoff & death rates)
|
188
|
+
|
189
|
+
return event
|
190
|
+
|
191
|
+
|
192
|
+
def change_popu(self, s):
|
193
|
+
# convert s (a signal, passed from model class) to a change in population
|
194
|
+
|
195
|
+
# s = 0, 1, 2 are for U
|
196
|
+
# s = 0 for migration IN, receive an immigrant
|
197
|
+
if s == 0:
|
198
|
+
self.U += 1 # receive an immigrant
|
199
|
+
# s = 1 for migration OUT / death due to carrying capacity
|
200
|
+
elif s == 1:
|
201
|
+
if self.U > 0:
|
202
|
+
self.U -= 1
|
203
|
+
# s = 2 for natural birth / death, due to payoff
|
204
|
+
elif s == 2:
|
205
|
+
if self.Upi > 0:
|
206
|
+
self.U += 1 # natural growth due to payoff
|
207
|
+
elif self.U > 0:
|
208
|
+
self.U -= 1 # natural death due to payoff
|
209
|
+
|
210
|
+
# s = 3, 4, 5 are for V
|
211
|
+
elif s == 3:
|
212
|
+
self.V += 1
|
213
|
+
elif s == 4:
|
214
|
+
if self.V > 0:
|
215
|
+
self.V -= 1
|
216
|
+
else:
|
217
|
+
if self.Vpi > 0:
|
218
|
+
self.V += 1
|
219
|
+
elif self.V > 0:
|
220
|
+
self.V -= 1
|
221
|
+
|
222
|
+
|
223
|
+
|
224
|
+
def find_nb_zero_flux(N, M, i, j):
|
225
|
+
'''
|
226
|
+
Find neighbors of patch (i, j) in zero-flux boundary condition. i.e., the space is square with boundary.
|
227
|
+
Return neighbors' indices in an order: up, down, left, right.
|
228
|
+
Index will be None if no neighbor exists in that direction.
|
229
|
+
'''
|
230
|
+
nb_indices = []
|
231
|
+
|
232
|
+
if i != 0:
|
233
|
+
nb_indices.append([i - 1, j]) # up
|
234
|
+
else:
|
235
|
+
nb_indices.append(None) # neighbor doesn't exist
|
236
|
+
|
237
|
+
if i != N - 1:
|
238
|
+
nb_indices.append([i + 1, j]) # down
|
239
|
+
else:
|
240
|
+
nb_indices.append(None)
|
241
|
+
|
242
|
+
if j != 0:
|
243
|
+
nb_indices.append([i, j - 1]) # left
|
244
|
+
else:
|
245
|
+
nb_indices.append(None)
|
246
|
+
|
247
|
+
if j != M - 1:
|
248
|
+
nb_indices.append([i, j + 1]) # right
|
249
|
+
else:
|
250
|
+
nb_indices.append(None)
|
251
|
+
|
252
|
+
return nb_indices
|
253
|
+
|
254
|
+
|
255
|
+
|
256
|
+
|
257
|
+
def find_nb_periodical(N, M, i, j):
|
258
|
+
'''
|
259
|
+
Find neighbors of patch (i, j) in periodical boundary condition. i.e., the space is a sphere.
|
260
|
+
Return neighbors' indices in an order: up, down, left, right.
|
261
|
+
If space not 1D, a neighbor always exists.
|
262
|
+
If space is 1D, say N = 1, we don't allow (0, j) to migrate up & down (self-self migration is considered invalid)
|
263
|
+
'''
|
264
|
+
nb_indices = []
|
265
|
+
|
266
|
+
# up
|
267
|
+
if N != 1:
|
268
|
+
if i != 0:
|
269
|
+
nb_indices.append([i - 1, j])
|
270
|
+
else:
|
271
|
+
nb_indices.append([N - 1, j])
|
272
|
+
else:
|
273
|
+
nb_indices.append(None) # can't migrate to itself
|
274
|
+
|
275
|
+
# down
|
276
|
+
if N != 1:
|
277
|
+
if i != N - 1:
|
278
|
+
nb_indices.append([i + 1, j])
|
279
|
+
else:
|
280
|
+
nb_indices.append([0, j])
|
281
|
+
else:
|
282
|
+
nb_indices.append(None)
|
283
|
+
|
284
|
+
# left
|
285
|
+
# No need to check M == 1 because we explicitly asked for M > 1
|
286
|
+
if j != 0:
|
287
|
+
nb_indices.append([i, j - 1])
|
288
|
+
else:
|
289
|
+
nb_indices.append([i, M - 1])
|
290
|
+
|
291
|
+
# right
|
292
|
+
if j != M - 1:
|
293
|
+
nb_indices.append([i, j + 1])
|
294
|
+
else:
|
295
|
+
nb_indices.append([i, 0])
|
296
|
+
|
297
|
+
return nb_indices
|
298
|
+
|
299
|
+
|
300
|
+
|
301
|
+
|
302
|
+
def find_patch(expected_sum, patch_rates, sum_rates_by_row, sum_rates):
|
303
|
+
'''
|
304
|
+
Find which patch the event is in. Only patch index is found, patch.find_event find which event it is exactly.
|
305
|
+
|
306
|
+
Inputs:
|
307
|
+
expected_sum: a random number * sum of all rates. Essentially points to a random event.
|
308
|
+
We want to find the patch that contains this pointer.
|
309
|
+
patch_rates: a N x M np.array. Stores sum of the 12 rates in every patch.
|
310
|
+
sum_rates_by_row: a 1D np.array with len = N. Stores the sum of the M x 12 rates in every row.
|
311
|
+
sum_rates: sum of all N x M x 12 rates.
|
312
|
+
|
313
|
+
Returns:
|
314
|
+
row, col: row and column number of where the patch.
|
315
|
+
'''
|
316
|
+
|
317
|
+
# Find row first
|
318
|
+
if expected_sum < sum_rates / 2:
|
319
|
+
# search row forwards if in the first half of rows
|
320
|
+
current_sum = 0
|
321
|
+
row = 0
|
322
|
+
while current_sum < expected_sum:
|
323
|
+
current_sum += sum_rates_by_row[row]
|
324
|
+
row += 1
|
325
|
+
row -= 1
|
326
|
+
current_sum -= sum_rates_by_row[row] # need to subtract that row (which caused current sum to exceed expected_sum)
|
327
|
+
else:
|
328
|
+
# search row backwards if in the second half of rows
|
329
|
+
current_sum = sum_rates
|
330
|
+
row = len(patch_rates) - 1
|
331
|
+
while current_sum > expected_sum:
|
332
|
+
current_sum -= sum_rates_by_row[row]
|
333
|
+
row -= 1
|
334
|
+
row += 1
|
335
|
+
# don't need subtraction here, as current_sum is already < expected same
|
336
|
+
|
337
|
+
# Find col in that row
|
338
|
+
if (expected_sum - current_sum) < sum_rates_by_row[row] / 2:
|
339
|
+
# search col forwards if in the first half of that row
|
340
|
+
col = 0
|
341
|
+
while current_sum < expected_sum:
|
342
|
+
current_sum += patch_rates[row][col]
|
343
|
+
col += 1
|
344
|
+
col -= 1
|
345
|
+
current_sum -= patch_rates[row][col] # need a subtraction
|
346
|
+
else:
|
347
|
+
# search col backwards if in the second half of that row
|
348
|
+
current_sum += sum_rates_by_row[row]
|
349
|
+
col = len(patch_rates[0]) - 1
|
350
|
+
while current_sum > expected_sum:
|
351
|
+
current_sum -= patch_rates[row][col]
|
352
|
+
col -= 1
|
353
|
+
col += 1
|
354
|
+
# don't need subtraction
|
355
|
+
|
356
|
+
return row, col, current_sum
|
357
|
+
|
358
|
+
|
359
|
+
|
360
|
+
|
361
|
+
def make_signal_zero_flux(i, j, e):
|
362
|
+
'''
|
363
|
+
Find which patch to change what based on i, j, e (event number) value, for the zero-flux boundary condition
|
364
|
+
|
365
|
+
Inputs:
|
366
|
+
i, j is the position of the 'center' patch, e is which event to happen there.
|
367
|
+
Another patch might be influenced as well if a migration event was picked.
|
368
|
+
|
369
|
+
Possible values for e:
|
370
|
+
e = 0 or 1: natural change of U/V due to payoff.
|
371
|
+
Can be either brith or death (based on payoff is positive or negative).
|
372
|
+
Cooresponds to s = 2 or 5 in the patch class
|
373
|
+
e = 2 or 3: death of U/V due to carrying capacity.
|
374
|
+
Cooresponds to s = 1 or 4 in patch: make U/V -= 1
|
375
|
+
e = 4 ~ 7: migration events of U, patch (i, j) loses an individual, and another patch receives one.
|
376
|
+
we use the up-down-left-right rule for the direction. 4 means up, 5 means down, ...
|
377
|
+
Cooresponds to s = 0 for the mig-in patch (force U += 1), and s = 1 for the mig-out patch (force U -= 1)
|
378
|
+
e = 8 ~ 11: migration events of V.
|
379
|
+
Cooresponds to s = 3 for the mig-in patch (force V += 1), and s = 4 for the mig-out patch (force V -= 1)
|
380
|
+
'''
|
381
|
+
if e < 6:
|
382
|
+
if e == 0:
|
383
|
+
return [[i, j, 2]]
|
384
|
+
elif e == 1:
|
385
|
+
return [[i, j, 5]]
|
386
|
+
elif e == 2:
|
387
|
+
return [[i, j, 1]]
|
388
|
+
elif e == 3:
|
389
|
+
return [[i, j, 4]]
|
390
|
+
elif e == 4:
|
391
|
+
return [[i, j, 1], [i - 1, j, 0]]
|
392
|
+
else:
|
393
|
+
return [[i, j, 1], [i + 1, j, 0]]
|
394
|
+
else:
|
395
|
+
if e == 6:
|
396
|
+
return [[i, j, 1], [i, j - 1, 0]]
|
397
|
+
elif e == 7:
|
398
|
+
return [[i, j, 1], [i, j + 1, 0]]
|
399
|
+
elif e == 8:
|
400
|
+
return [[i, j, 4], [i - 1, j, 3]]
|
401
|
+
elif e == 9:
|
402
|
+
return [[i, j, 4], [i + 1, j, 3]]
|
403
|
+
elif e == 10:
|
404
|
+
return [[i, j, 4], [i, j - 1, 3]]
|
405
|
+
elif e == 11:
|
406
|
+
return [[i, j, 4], [i, j + 1, 3]]
|
407
|
+
else:
|
408
|
+
raise RuntimeError('A bug in code: invalid event number encountered:', e) # debug line
|
409
|
+
|
410
|
+
|
411
|
+
|
412
|
+
def make_signal_periodical(N, M, i, j, e):
|
413
|
+
'''
|
414
|
+
Find which patch to change what based on i, j, e value, for the periodical boundary condition
|
415
|
+
Similar to make_signal_zero_flux.
|
416
|
+
'''
|
417
|
+
|
418
|
+
if e < 6:
|
419
|
+
if e == 0:
|
420
|
+
return [[i, j, 2]]
|
421
|
+
elif e == 1:
|
422
|
+
return [[i, j, 5]]
|
423
|
+
elif e == 2:
|
424
|
+
return [[i, j, 1]]
|
425
|
+
elif e == 3:
|
426
|
+
return [[i, j, 4]]
|
427
|
+
elif e == 4:
|
428
|
+
if i != 0:
|
429
|
+
return [[i, j, 1], [i - 1, j, 0]]
|
430
|
+
else:
|
431
|
+
return [[i, j, 1], [N - 1, j, 0]]
|
432
|
+
else:
|
433
|
+
if i != N - 1:
|
434
|
+
return [[i, j, 1], [i + 1, j, 0]]
|
435
|
+
else:
|
436
|
+
return [[i, j, 1], [0, j, 0]]
|
437
|
+
else:
|
438
|
+
if e == 6:
|
439
|
+
if j != 0:
|
440
|
+
return [[i, j, 1], [i, j - 1, 0]]
|
441
|
+
else:
|
442
|
+
return [[i, j, 1], [i, M - 1, 0]]
|
443
|
+
elif e == 7:
|
444
|
+
if j != M - 1:
|
445
|
+
return [[i, j, 1], [i, j + 1, 0]]
|
446
|
+
else:
|
447
|
+
return [[i, j, 1], [i, 0, 0]]
|
448
|
+
elif e == 8:
|
449
|
+
if i != 0:
|
450
|
+
return [[i, j, 4], [i - 1, j, 3]]
|
451
|
+
else:
|
452
|
+
return [[i, j, 4], [N - 1, j, 3]]
|
453
|
+
elif e == 9:
|
454
|
+
if i != N - 1:
|
455
|
+
return [[i, j, 4], [i + 1, j, 3]]
|
456
|
+
else:
|
457
|
+
return [[i, j, 4], [0, j, 3]]
|
458
|
+
elif e == 10:
|
459
|
+
if j != 0:
|
460
|
+
return [[i, j, 4], [i, j - 1, 3]]
|
461
|
+
else:
|
462
|
+
return [[i, j, 4], [i, M - 1, 3]]
|
463
|
+
elif e == 11:
|
464
|
+
if j != M - 1:
|
465
|
+
return [[i, j, 4], [i, j + 1, 3]]
|
466
|
+
else:
|
467
|
+
return [[i, j, 4], [i, 0, 3]]
|
468
|
+
else:
|
469
|
+
raise RuntimeError('A bug in code: invalid event number encountered:', e) # debug line
|
470
|
+
|
471
|
+
|
472
|
+
|
473
|
+
|
474
|
+
def nb_need_change(ni, signal):
|
475
|
+
'''
|
476
|
+
Check whether a neighbor needs to change.
|
477
|
+
Two cases don't need change: either ni is None (doesn't exist) or in signal (is a last-change patch and already updated)
|
478
|
+
|
479
|
+
Inputs:
|
480
|
+
ni: index of a neighbor, might be None if patch doesn't exist.
|
481
|
+
signal: return value of make_signal_zero_flux or make_signal_periodical.
|
482
|
+
|
483
|
+
Returns:
|
484
|
+
True or False, whether the neighboring patch specified by ni needs change
|
485
|
+
'''
|
486
|
+
|
487
|
+
if ni == None:
|
488
|
+
return False
|
489
|
+
|
490
|
+
for si in signal:
|
491
|
+
if ni[0] == si[0] and ni[1] == si[1]:
|
492
|
+
return False
|
493
|
+
|
494
|
+
return True
|
495
|
+
|
496
|
+
|
497
|
+
|
498
|
+
|
499
|
+
def single_init(mod, rng):
|
500
|
+
'''
|
501
|
+
The first major function for the model.
|
502
|
+
Initialize all variables and run 1 round, then pass variables and results to single_test.
|
503
|
+
|
504
|
+
Input:
|
505
|
+
mod is a model object
|
506
|
+
rng is random number generator (np.random.default_rng), initialized by model.run
|
507
|
+
'''
|
508
|
+
|
509
|
+
#### Initialize Data Storage ####
|
510
|
+
|
511
|
+
world = [[patch(mod.I[i][j][0], mod.I[i][j][1], mod.X[i][j], mod.P[i][j]) for j in range(mod.M)] for i in range(mod.N)] # N x M patches
|
512
|
+
patch_rates = np.zeros((mod.N, mod.M), dtype = np.float64) # every patch's sum-of-12-srates
|
513
|
+
sum_rates_by_row = np.zeros((mod.N), dtype = np.float64) # every row's sum-of-patch, i.e., sum of 12 * M rates in every row.
|
514
|
+
sum_rates = 0 # sum of all N x M x 12 rates
|
515
|
+
|
516
|
+
signal = None
|
517
|
+
|
518
|
+
nb_indices = None
|
519
|
+
if mod.boundary:
|
520
|
+
nb_indices = [[find_nb_zero_flux(mod.N, mod.M, i, j) for j in range(mod.M)] for i in range(mod.N)]
|
521
|
+
else:
|
522
|
+
nb_indices = [[find_nb_periodical(mod.N, mod.M, i, j) for j in range(mod.M)] for i in range(mod.N)]
|
523
|
+
|
524
|
+
for i in range(mod.N):
|
525
|
+
for j in range(mod.M):
|
526
|
+
nb = []
|
527
|
+
for k in range(4):
|
528
|
+
if nb_indices[i][j][k] != None:
|
529
|
+
# append a pointer to the patch
|
530
|
+
nb.append(world[nb_indices[i][j][k][0]][nb_indices[i][j][k][1]])
|
531
|
+
else:
|
532
|
+
# nb doesn't exist
|
533
|
+
nb.append(None)
|
534
|
+
# pass it to patch class and store
|
535
|
+
world[i][j].set_nb_pointers(nb)
|
536
|
+
|
537
|
+
|
538
|
+
#### Begin Running ####
|
539
|
+
|
540
|
+
# initialize payoff & natural death rates
|
541
|
+
for i in range(mod.N):
|
542
|
+
for j in range(mod.M):
|
543
|
+
world[i][j].update_pi_k()
|
544
|
+
|
545
|
+
# initialize migration rates & the rates list
|
546
|
+
for i in range(mod.N):
|
547
|
+
for j in range(mod.M):
|
548
|
+
world[i][j].update_mig()
|
549
|
+
# store rates & sum of rates
|
550
|
+
patch_rates[i][j] = world[i][j].get_sum_rates()
|
551
|
+
sum_rates_by_row[i] = sum(patch_rates[i])
|
552
|
+
|
553
|
+
sum_rates = sum(sum_rates_by_row)
|
554
|
+
|
555
|
+
# pick the first random event
|
556
|
+
expected_sum = rng.random() * sum_rates
|
557
|
+
# find patch first
|
558
|
+
i0, j0, current_sum = find_patch(expected_sum, patch_rates, sum_rates_by_row, sum_rates)
|
559
|
+
# then find which event in that patch
|
560
|
+
e0 = world[i0][j0].find_event(expected_sum - current_sum)
|
561
|
+
|
562
|
+
# initialize signal
|
563
|
+
if mod.boundary:
|
564
|
+
signal = make_signal_zero_flux(i0, j0, e0) # walls around world
|
565
|
+
else:
|
566
|
+
signal = make_signal_periodical(mod.N, mod.M, i0, j0, e0) # no walls around world
|
567
|
+
|
568
|
+
# change U&V based on signal
|
569
|
+
for si in signal:
|
570
|
+
world[si[0]][si[1]].change_popu(si[2])
|
571
|
+
|
572
|
+
# time increment
|
573
|
+
time = (1 / sum_rates) * math.log(1 / rng.random())
|
574
|
+
|
575
|
+
# record
|
576
|
+
if time > mod.record_itv:
|
577
|
+
record_index = int(time / mod.record_itv)
|
578
|
+
for i in range(mod.N):
|
579
|
+
for j in range(mod.M):
|
580
|
+
for k in range(record_index):
|
581
|
+
mod.U[i][j][k] += world[i][j].U
|
582
|
+
mod.V[i][j][k] += world[i][j].V
|
583
|
+
mod.Upi[i][j][k] += world[i][j].Upi
|
584
|
+
mod.Vpi[i][j][k] += world[i][j].Vpi
|
585
|
+
# we simply add to that entry, and later divide by sim_time to get the average (division in run function)
|
586
|
+
|
587
|
+
return time, world, nb_indices, patch_rates, sum_rates_by_row, sum_rates, signal
|
588
|
+
|
589
|
+
|
590
|
+
|
591
|
+
|
592
|
+
def single_test(mod, front_info, end_info, update_sum_frequency, rng):
|
593
|
+
'''
|
594
|
+
Runs a single model, from time = 0 to mod.maxtime.
|
595
|
+
run recursively calls single_test to get the average data.
|
596
|
+
|
597
|
+
Inputs:
|
598
|
+
sim: a model object, created by user and carries all parameters & storage bins.
|
599
|
+
front_info, end_info: passed by run to show messages, like the current round number in run. Not intended for direct usages.
|
600
|
+
update_sum_frequency: re-calculate sums this many times in model.
|
601
|
+
Our sums are gradually updated over time. So might have precision errors for large maxtime.
|
602
|
+
rng: np.random.default_rng. Initialized by model.run
|
603
|
+
'''
|
604
|
+
|
605
|
+
# initialize helper variables
|
606
|
+
# used to print progress, i.e., how much percent is done
|
607
|
+
one_time = mod.maxtime / max(100, update_sum_frequency)
|
608
|
+
one_progress = 0
|
609
|
+
if mod.print_pct != None:
|
610
|
+
# print progress, x%
|
611
|
+
print(front_info + ' 0%' + end_info, end = '\r')
|
612
|
+
one_progress = mod.maxtime * mod.print_pct / 100
|
613
|
+
else:
|
614
|
+
one_progress = 2 * mod.maxtime # not printing
|
615
|
+
|
616
|
+
# our sums (sum_rates_by_row and sum_rates) are gradually updated over time. This may have precision errors for large maxtime.
|
617
|
+
# So re-sum everything every some percentage of maxtime.
|
618
|
+
one_update_sum = mod.maxtime / update_sum_frequency
|
619
|
+
|
620
|
+
current_time = one_time
|
621
|
+
current_progress = one_progress
|
622
|
+
current_update_sum = one_update_sum
|
623
|
+
|
624
|
+
max_record = int(mod.maxtime / mod.record_itv)
|
625
|
+
|
626
|
+
|
627
|
+
# initialize
|
628
|
+
time, world, nb_indices, patch_rates, sum_rates_by_row, sum_rates, signal = single_init(mod, rng)
|
629
|
+
record_index = int(time / mod.record_itv)
|
630
|
+
# record_time is how much time has passed since the last record
|
631
|
+
# if record_time > record_itv:
|
632
|
+
# we count how many record_itvs are there in record_time, denote the number by multi_records
|
633
|
+
# then store the current data in multi_records number of cells in the list
|
634
|
+
# and subtract record_time by the multiple of record_itv, so that record_time < record_itv
|
635
|
+
record_time = time - record_index * mod.record_itv
|
636
|
+
|
637
|
+
### Large while loop ###
|
638
|
+
|
639
|
+
while time < mod.maxtime:
|
640
|
+
|
641
|
+
# print progress & correct error of sum_rates
|
642
|
+
if time > current_time:
|
643
|
+
# a new 1% of time
|
644
|
+
current_time += one_time
|
645
|
+
if time > current_progress:
|
646
|
+
# print progress
|
647
|
+
print(front_info + ' ' + str(round(time / mod.maxtime * 100)) + '%' + end_info, end = '\r')
|
648
|
+
current_progress += one_progress
|
649
|
+
|
650
|
+
if time > current_update_sum:
|
651
|
+
current_update_sum += one_update_sum
|
652
|
+
for i in range(mod.N):
|
653
|
+
sum_rates_by_row[i] = sum(patch_rates[i])
|
654
|
+
sum_rates = sum(sum_rates_by_row)
|
655
|
+
|
656
|
+
|
657
|
+
# before updating last-changed patches, subtract old sum of rates (so as to update sum of rates by adding new rates later)
|
658
|
+
for si in signal:
|
659
|
+
# si[0] is row number, si[1] is col number
|
660
|
+
old_patch_rate = world[si[0]][si[1]].get_sum_rates()
|
661
|
+
sum_rates_by_row[si[0]] -= old_patch_rate
|
662
|
+
sum_rates -= old_patch_rate
|
663
|
+
|
664
|
+
# update last-changed patches
|
665
|
+
# update payoff and death rates first
|
666
|
+
for si in signal:
|
667
|
+
world[si[0]][si[1]].update_pi_k()
|
668
|
+
# then update migration rates, as mig_rates depend on neighbor's payoff
|
669
|
+
for si in signal:
|
670
|
+
world[si[0]][si[1]].update_mig()
|
671
|
+
|
672
|
+
# update rates stored
|
673
|
+
new_patch_rate = world[si[0]][si[1]].get_sum_rates()
|
674
|
+
# update patch_rates
|
675
|
+
patch_rates[si[0]][si[1]] = new_patch_rate
|
676
|
+
# update sum_rate_by_row and sum_rates_by_row by adding new rates
|
677
|
+
sum_rates_by_row[si[0]] += new_patch_rate
|
678
|
+
sum_rates += new_patch_rate
|
679
|
+
|
680
|
+
# update neighbors of last-changed patches
|
681
|
+
for si in signal:
|
682
|
+
for ni in nb_indices[si[0]][si[1]]:
|
683
|
+
# don't need to update if the patch is a last-change patch itself or None
|
684
|
+
# use helper function to check
|
685
|
+
if nb_need_change(ni, signal):
|
686
|
+
# update migratino rates
|
687
|
+
world[ni[0]][ni[1]].update_mig()
|
688
|
+
# Note: no need to update patch_rates and sum of rates, as update_mig doesn't change total rates in a patch.
|
689
|
+
# sum_mig_rate is decided by mu1 * U + mu2 * V, and pi_death_rate is not changed.
|
690
|
+
|
691
|
+
# pick the first random event
|
692
|
+
expected_sum = rng.random() * sum_rates
|
693
|
+
# find patch first
|
694
|
+
i0, j0, current_sum = find_patch(expected_sum, patch_rates, sum_rates_by_row, sum_rates)
|
695
|
+
# then find which event in that patch
|
696
|
+
e0 = world[i0][j0].find_event(expected_sum - current_sum)
|
697
|
+
|
698
|
+
# make signal
|
699
|
+
if mod.boundary:
|
700
|
+
signal = make_signal_zero_flux(i0, j0, e0)
|
701
|
+
else:
|
702
|
+
signal = make_signal_periodical(mod.N, mod.M, i0, j0, e0)
|
703
|
+
|
704
|
+
# let the event happen
|
705
|
+
for si in signal:
|
706
|
+
world[si[0]][si[1]].change_popu(si[2])
|
707
|
+
|
708
|
+
# increase time
|
709
|
+
r1 = rng.random()
|
710
|
+
dt = (1 / sum_rates) * math.log(1 / r1)
|
711
|
+
time += dt
|
712
|
+
record_time += dt
|
713
|
+
|
714
|
+
if time < mod.maxtime:
|
715
|
+
# if not exceeds maxtime
|
716
|
+
if record_time > mod.record_itv:
|
717
|
+
multi_records = int(record_time / mod.record_itv)
|
718
|
+
record_time -= multi_records * mod.record_itv
|
719
|
+
|
720
|
+
for i in range(mod.N):
|
721
|
+
for j in range(mod.M):
|
722
|
+
for k in range(record_index, record_index + multi_records):
|
723
|
+
mod.U[i][j][k] += world[i][j].U
|
724
|
+
mod.V[i][j][k] += world[i][j].V
|
725
|
+
mod.Upi[i][j][k] += world[i][j].Upi
|
726
|
+
mod.Vpi[i][j][k] += world[i][j].Vpi
|
727
|
+
record_index += multi_records
|
728
|
+
else:
|
729
|
+
# if already exceeds maxtime
|
730
|
+
for i in range(mod.N):
|
731
|
+
for j in range(mod.M):
|
732
|
+
for k in range(record_index, max_record):
|
733
|
+
mod.U[i][j][k] += world[i][j].U
|
734
|
+
mod.V[i][j][k] += world[i][j].V
|
735
|
+
mod.Upi[i][j][k] += world[i][j].Upi
|
736
|
+
mod.Vpi[i][j][k] += world[i][j].Vpi
|
737
|
+
|
738
|
+
### Large while loop ends ###
|
739
|
+
|
740
|
+
if mod.print_pct != None:
|
741
|
+
print(front_info + ' 100%' + ' ' * 20, end = '\r') # empty spaces to overwrite predicted runtime
|
742
|
+
|
743
|
+
|
744
|
+
|
745
|
+
|
746
|
+
def run_py(mod, predict_runtime = False, message = ''):
|
747
|
+
'''
|
748
|
+
Main function. Recursively calls single_test to run many models and then takes the average.
|
749
|
+
|
750
|
+
Inputs:
|
751
|
+
- mod is a model object.
|
752
|
+
- predict_runtime = False will not predict how much time still needed, set to True if you want to see.
|
753
|
+
- message is used by some functions in figures.py to print messages.
|
754
|
+
'''
|
755
|
+
|
756
|
+
if not mod.data_empty:
|
757
|
+
raise RuntimeError('mod has non-empty data')
|
758
|
+
|
759
|
+
start = timer() # runtime
|
760
|
+
|
761
|
+
mod.data_empty = False
|
762
|
+
rng = np.random.default_rng(mod.seed)
|
763
|
+
|
764
|
+
# passed to single_test to print progress
|
765
|
+
if mod.print_pct == 0:
|
766
|
+
mod.print_pct = 5 # default print_pct
|
767
|
+
|
768
|
+
update_sum_frequency = 4 # re-calculate sums this many times. See input desciption of single_test
|
769
|
+
|
770
|
+
### models ###
|
771
|
+
i = 0
|
772
|
+
|
773
|
+
while i < mod.sim_time:
|
774
|
+
# use while loop so that can go backwards if got numerical issues
|
775
|
+
|
776
|
+
end_info = ''
|
777
|
+
if predict_runtime:
|
778
|
+
if i > 0:
|
779
|
+
time_elapsed = timer() - start
|
780
|
+
pred_runtime = time_elapsed / i * (mod.sim_time - i)
|
781
|
+
end_info = ', ~' + str(round(pred_runtime, 2)) + 's left'
|
782
|
+
|
783
|
+
front_info = ''
|
784
|
+
if mod.print_pct != None:
|
785
|
+
front_info = message + 'round ' + str(i) + ':'
|
786
|
+
print(front_info + ' ' * 30, end = '\r') # the blank spaces are to overwrite percentages, e.g. 36 %
|
787
|
+
|
788
|
+
try:
|
789
|
+
single_test(mod, front_info, end_info, update_sum_frequency, rng)
|
790
|
+
i += 1
|
791
|
+
except IndexError:
|
792
|
+
update_sum_frequency *= 4
|
793
|
+
print('Numerical issue at round ' + str(i) + '. Trying higher precision now. See doc if err repeats')
|
794
|
+
# not increasing i: redo current round.
|
795
|
+
|
796
|
+
### models end ###
|
797
|
+
|
798
|
+
mod.calculate_ave()
|
799
|
+
|
800
|
+
stop = timer()
|
801
|
+
print(' ' * 30, end = '\r') # overwrite all previous prints
|
802
|
+
print(message + 'runtime: ' + str(round(stop - start, 2)) + ' s')
|
803
|
+
return
|
804
|
+
|
805
|
+
|
806
|
+
|
807
|
+
|
808
|
+
|