piegy 2.1.8__cp37-cp37m-win32.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/simulation_py.py ADDED
@@ -0,0 +1,816 @@
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 + self.sum_mig_rates):
172
+ print("patch rate not large enough")
173
+
174
+ if expected_sum < self.sum_pi_death_rates:
175
+ # in the first 4 events (payoff and death events)
176
+ event = 0
177
+ current_sum = 0
178
+ while current_sum < expected_sum:
179
+ current_sum += self.pi_death_rates[event]
180
+ event += 1
181
+ event -= 1
182
+
183
+ else:
184
+ # in the last 8 events (migration events):
185
+ event = 0
186
+ current_sum = self.sum_pi_death_rates
187
+ while current_sum < expected_sum:
188
+ current_sum += self.mig_rates[event]
189
+ event += 1
190
+ event += 3 # i.e., -= 1, then += 4 (to account for the first 4 payoff & death rates)
191
+
192
+ return event
193
+
194
+
195
+ def change_popu(self, s):
196
+ # convert s (a signal, passed from model class) to a change in population
197
+
198
+ # s = 0, 1, 2 are for U
199
+ # s = 0 for migration IN, receive an immigrant
200
+ if s == 0:
201
+ self.U += 1 # receive an immigrant
202
+ # s = 1 for migration OUT / death due to carrying capacity
203
+ elif s == 1:
204
+ if self.U > 0:
205
+ self.U -= 1
206
+ # s = 2 for natural birth / death, due to payoff
207
+ elif s == 2:
208
+ if self.Upi > 0:
209
+ self.U += 1 # natural growth due to payoff
210
+ elif self.U > 0:
211
+ self.U -= 1 # natural death due to payoff
212
+
213
+ # s = 3, 4, 5 are for V
214
+ elif s == 3:
215
+ self.V += 1
216
+ elif s == 4:
217
+ if self.V > 0:
218
+ self.V -= 1
219
+ else:
220
+ if self.Vpi > 0:
221
+ self.V += 1
222
+ elif self.V > 0:
223
+ self.V -= 1
224
+
225
+
226
+
227
+ def find_nb_zero_flux(N, M, i, j):
228
+ '''
229
+ Find neighbors of patch (i, j) in zero-flux boundary condition. i.e., the space is square with boundary.
230
+ Return neighbors' indices in an order: up, down, left, right.
231
+ Index will be None if no neighbor exists in that direction.
232
+ '''
233
+ nb_indices = []
234
+
235
+ if i != 0:
236
+ nb_indices.append([i - 1, j]) # up
237
+ else:
238
+ nb_indices.append(None) # neighbor doesn't exist
239
+
240
+ if i != N - 1:
241
+ nb_indices.append([i + 1, j]) # down
242
+ else:
243
+ nb_indices.append(None)
244
+
245
+ if j != 0:
246
+ nb_indices.append([i, j - 1]) # left
247
+ else:
248
+ nb_indices.append(None)
249
+
250
+ if j != M - 1:
251
+ nb_indices.append([i, j + 1]) # right
252
+ else:
253
+ nb_indices.append(None)
254
+
255
+ return nb_indices
256
+
257
+
258
+
259
+
260
+ def find_nb_periodical(N, M, i, j):
261
+ '''
262
+ Find neighbors of patch (i, j) in periodical boundary condition. i.e., the space is a sphere.
263
+ Return neighbors' indices in an order: up, down, left, right.
264
+ If space not 1D, a neighbor always exists.
265
+ If space is 1D, say N = 1, we don't allow (0, j) to migrate up & down (self-self migration is considered invalid)
266
+ '''
267
+ nb_indices = []
268
+
269
+ # up
270
+ if N != 1:
271
+ if i != 0:
272
+ nb_indices.append([i - 1, j])
273
+ else:
274
+ nb_indices.append([N - 1, j])
275
+ else:
276
+ nb_indices.append(None) # can't migrate to itself
277
+
278
+ # down
279
+ if N != 1:
280
+ if i != N - 1:
281
+ nb_indices.append([i + 1, j])
282
+ else:
283
+ nb_indices.append([0, j])
284
+ else:
285
+ nb_indices.append(None)
286
+
287
+ # left
288
+ # No need to check M == 1 because we explicitly asked for M > 1
289
+ if j != 0:
290
+ nb_indices.append([i, j - 1])
291
+ else:
292
+ nb_indices.append([i, M - 1])
293
+
294
+ # right
295
+ if j != M - 1:
296
+ nb_indices.append([i, j + 1])
297
+ else:
298
+ nb_indices.append([i, 0])
299
+
300
+ return nb_indices
301
+
302
+
303
+
304
+
305
+ def find_patch(expected_sum, patch_rates, sum_rates_by_row, sum_rates):
306
+ '''
307
+ Find which patch the event is in. Only patch index is found, patch.find_event find which event it is exactly.
308
+
309
+ Inputs:
310
+ expected_sum: a random number * sum of all rates. Essentially points to a random event.
311
+ We want to find the patch that contains this pointer.
312
+ patch_rates: a N x M np.array. Stores sum of the 12 rates in every patch.
313
+ sum_rates_by_row: a 1D np.array with len = N. Stores the sum of the M x 12 rates in every row.
314
+ sum_rates: sum of all N x M x 12 rates.
315
+
316
+ Returns:
317
+ row, col: row and column number of where the patch.
318
+ '''
319
+
320
+ # Find row first
321
+ if expected_sum < sum_rates / 2:
322
+ # search row forwards if in the first half of rows
323
+ current_sum = 0
324
+ row = 0
325
+ while current_sum < expected_sum:
326
+ current_sum += sum_rates_by_row[row]
327
+ row += 1
328
+ row -= 1
329
+ current_sum -= sum_rates_by_row[row] # need to subtract that row (which caused current sum to exceed expected_sum)
330
+ else:
331
+ # search row backwards if in the second half of rows
332
+ current_sum = sum_rates
333
+ row = len(patch_rates) - 1
334
+ while current_sum > expected_sum:
335
+ current_sum -= sum_rates_by_row[row]
336
+ row -= 1
337
+ row += 1
338
+ # don't need subtraction here, as current_sum is already < expected same
339
+
340
+ # Find col in that row
341
+ if (expected_sum - current_sum) < sum_rates_by_row[row] / 2:
342
+ # search col forwards if in the first half of that row
343
+ col = 0
344
+ while current_sum < expected_sum:
345
+ current_sum += patch_rates[row][col]
346
+ col += 1
347
+ col -= 1
348
+ current_sum -= patch_rates[row][col] # need a subtraction
349
+ else:
350
+ # search col backwards if in the second half of that row
351
+ current_sum += sum_rates_by_row[row]
352
+ col = len(patch_rates[0]) - 1
353
+ while current_sum > expected_sum:
354
+ current_sum -= patch_rates[row][col]
355
+ col -= 1
356
+ col += 1
357
+ # don't need subtraction
358
+
359
+ return row, col, current_sum
360
+
361
+
362
+
363
+
364
+ def make_signal_zero_flux(i, j, e):
365
+ '''
366
+ Find which patch to change what based on i, j, e (event number) value, for the zero-flux boundary condition
367
+
368
+ Inputs:
369
+ i, j is the position of the 'center' patch, e is which event to happen there.
370
+ Another patch might be influenced as well if a migration event was picked.
371
+
372
+ Possible values for e:
373
+ e = 0 or 1: natural change of U/V due to payoff.
374
+ Can be either brith or death (based on payoff is positive or negative).
375
+ Cooresponds to s = 2 or 5 in the patch class
376
+ e = 2 or 3: death of U/V due to carrying capacity.
377
+ Cooresponds to s = 1 or 4 in patch: make U/V -= 1
378
+ e = 4 ~ 7: migration events of U, patch (i, j) loses an individual, and another patch receives one.
379
+ we use the up-down-left-right rule for the direction. 4 means up, 5 means down, ...
380
+ Cooresponds to s = 0 for the mig-in patch (force U += 1), and s = 1 for the mig-out patch (force U -= 1)
381
+ e = 8 ~ 11: migration events of V.
382
+ Cooresponds to s = 3 for the mig-in patch (force V += 1), and s = 4 for the mig-out patch (force V -= 1)
383
+ '''
384
+ if e < 6:
385
+ if e == 0:
386
+ return [[i, j, 2]]
387
+ elif e == 1:
388
+ return [[i, j, 5]]
389
+ elif e == 2:
390
+ return [[i, j, 1]]
391
+ elif e == 3:
392
+ return [[i, j, 4]]
393
+ elif e == 4:
394
+ return [[i, j, 1], [i - 1, j, 0]]
395
+ else:
396
+ return [[i, j, 1], [i + 1, j, 0]]
397
+ else:
398
+ if e == 6:
399
+ return [[i, j, 1], [i, j - 1, 0]]
400
+ elif e == 7:
401
+ return [[i, j, 1], [i, j + 1, 0]]
402
+ elif e == 8:
403
+ return [[i, j, 4], [i - 1, j, 3]]
404
+ elif e == 9:
405
+ return [[i, j, 4], [i + 1, j, 3]]
406
+ elif e == 10:
407
+ return [[i, j, 4], [i, j - 1, 3]]
408
+ elif e == 11:
409
+ return [[i, j, 4], [i, j + 1, 3]]
410
+ else:
411
+ raise RuntimeError('A bug in code: invalid event number encountered:', e) # debug line
412
+
413
+
414
+
415
+ def make_signal_periodical(N, M, i, j, e):
416
+ '''
417
+ Find which patch to change what based on i, j, e value, for the periodical boundary condition
418
+ Similar to make_signal_zero_flux.
419
+ '''
420
+
421
+ if e < 6:
422
+ if e == 0:
423
+ return [[i, j, 2]]
424
+ elif e == 1:
425
+ return [[i, j, 5]]
426
+ elif e == 2:
427
+ return [[i, j, 1]]
428
+ elif e == 3:
429
+ return [[i, j, 4]]
430
+ elif e == 4:
431
+ if i != 0:
432
+ return [[i, j, 1], [i - 1, j, 0]]
433
+ else:
434
+ return [[i, j, 1], [N - 1, j, 0]]
435
+ else:
436
+ if i != N - 1:
437
+ return [[i, j, 1], [i + 1, j, 0]]
438
+ else:
439
+ return [[i, j, 1], [0, j, 0]]
440
+ else:
441
+ if e == 6:
442
+ if j != 0:
443
+ return [[i, j, 1], [i, j - 1, 0]]
444
+ else:
445
+ return [[i, j, 1], [i, M - 1, 0]]
446
+ elif e == 7:
447
+ if j != M - 1:
448
+ return [[i, j, 1], [i, j + 1, 0]]
449
+ else:
450
+ return [[i, j, 1], [i, 0, 0]]
451
+ elif e == 8:
452
+ if i != 0:
453
+ return [[i, j, 4], [i - 1, j, 3]]
454
+ else:
455
+ return [[i, j, 4], [N - 1, j, 3]]
456
+ elif e == 9:
457
+ if i != N - 1:
458
+ return [[i, j, 4], [i + 1, j, 3]]
459
+ else:
460
+ return [[i, j, 4], [0, j, 3]]
461
+ elif e == 10:
462
+ if j != 0:
463
+ return [[i, j, 4], [i, j - 1, 3]]
464
+ else:
465
+ return [[i, j, 4], [i, M - 1, 3]]
466
+ elif e == 11:
467
+ if j != M - 1:
468
+ return [[i, j, 4], [i, j + 1, 3]]
469
+ else:
470
+ return [[i, j, 4], [i, 0, 3]]
471
+ else:
472
+ raise RuntimeError('A bug in code: invalid event number encountered:', e) # debug line
473
+
474
+
475
+
476
+
477
+ def nb_need_change(ni, signal):
478
+ '''
479
+ Check whether a neighbor needs to change.
480
+ Two cases don't need change: either ni is None (doesn't exist) or in signal (is a last-change patch and already updated)
481
+
482
+ Inputs:
483
+ ni: index of a neighbor, might be None if patch doesn't exist.
484
+ signal: return value of make_signal_zero_flux or make_signal_periodical.
485
+
486
+ Returns:
487
+ True or False, whether the neighboring patch specified by ni needs change
488
+ '''
489
+
490
+ if ni == None:
491
+ return False
492
+
493
+ for si in signal:
494
+ if ni[0] == si[0] and ni[1] == si[1]:
495
+ return False
496
+
497
+ return True
498
+
499
+
500
+
501
+
502
+ def single_init(mod, rng):
503
+ '''
504
+ The first major function for the model.
505
+ Initialize all variables and run 1 round, then pass variables and results to single_test.
506
+
507
+ Input:
508
+ mod is a model object
509
+ rng is random number generator (np.random.default_rng), initialized by model.run
510
+ '''
511
+
512
+ #### Initialize Data Storage ####
513
+
514
+ 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
515
+ patch_rates = np.zeros((mod.N, mod.M), dtype = np.float64) # every patch's sum-of-12-srates
516
+ 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.
517
+ sum_rates = 0 # sum of all N x M x 12 rates
518
+
519
+ signal = None
520
+
521
+ nb_indices = None
522
+ if mod.boundary:
523
+ nb_indices = [[find_nb_zero_flux(mod.N, mod.M, i, j) for j in range(mod.M)] for i in range(mod.N)]
524
+ else:
525
+ nb_indices = [[find_nb_periodical(mod.N, mod.M, i, j) for j in range(mod.M)] for i in range(mod.N)]
526
+
527
+ for i in range(mod.N):
528
+ for j in range(mod.M):
529
+ nb = []
530
+ for k in range(4):
531
+ if nb_indices[i][j][k] != None:
532
+ # append a pointer to the patch
533
+ nb.append(world[nb_indices[i][j][k][0]][nb_indices[i][j][k][1]])
534
+ else:
535
+ # nb doesn't exist
536
+ nb.append(None)
537
+ # pass it to patch class and store
538
+ world[i][j].set_nb_pointers(nb)
539
+
540
+
541
+ #### Begin Running ####
542
+
543
+ # initialize payoff & natural death rates
544
+ for i in range(mod.N):
545
+ for j in range(mod.M):
546
+ world[i][j].update_pi_k()
547
+
548
+ # initialize migration rates & the rates list
549
+ for i in range(mod.N):
550
+ for j in range(mod.M):
551
+ world[i][j].update_mig()
552
+ # store rates & sum of rates
553
+ patch_rates[i][j] = world[i][j].get_sum_rates()
554
+ sum_rates_by_row[i] = sum(patch_rates[i])
555
+
556
+ sum_rates = sum(sum_rates_by_row)
557
+
558
+ # pick the first random event
559
+ expected_sum = rng.random() * sum_rates
560
+ # find patch first
561
+ i0, j0, current_sum = find_patch(expected_sum, patch_rates, sum_rates_by_row, sum_rates)
562
+ # then find which event in that patch
563
+ e0 = world[i0][j0].find_event(expected_sum - current_sum)
564
+
565
+ # initialize signal
566
+ if mod.boundary:
567
+ signal = make_signal_zero_flux(i0, j0, e0) # walls around world
568
+ else:
569
+ signal = make_signal_periodical(mod.N, mod.M, i0, j0, e0) # no walls around world
570
+
571
+ # change U&V based on signal
572
+ for si in signal:
573
+ world[si[0]][si[1]].change_popu(si[2])
574
+
575
+ # time increment
576
+ time = (1 / sum_rates) * math.log(1 / rng.random())
577
+
578
+ # record
579
+ if time > mod.record_itv:
580
+ record_index = int(time / mod.record_itv)
581
+ for i in range(mod.N):
582
+ for j in range(mod.M):
583
+ for k in range(record_index):
584
+ mod.U[i][j][k] += world[i][j].U
585
+ mod.V[i][j][k] += world[i][j].V
586
+ mod.Upi[i][j][k] += world[i][j].Upi
587
+ mod.Vpi[i][j][k] += world[i][j].Vpi
588
+ # we simply add to that entry, and later divide by sim_time to get the average (division in run function)
589
+
590
+ return time, world, nb_indices, patch_rates, sum_rates_by_row, sum_rates, signal
591
+
592
+
593
+
594
+
595
+ def single_test(mod, front_info, end_info, update_sum_frequency, rng):
596
+ '''
597
+ Runs a single model, from time = 0 to mod.maxtime.
598
+ run recursively calls single_test to get the average data.
599
+
600
+ Inputs:
601
+ sim: a model object, created by user and carries all parameters & storage bins.
602
+ front_info, end_info: passed by run to show messages, like the current round number in run. Not intended for direct usages.
603
+ update_sum_frequency: re-calculate sums this many times in model.
604
+ Our sums are gradually updated over time. So might have precision errors for large maxtime.
605
+ rng: np.random.default_rng. Initialized by model.run
606
+ '''
607
+
608
+ # initialize helper variables
609
+ # used to print progress, i.e., how much percent is done
610
+ one_time = mod.maxtime / max(100, update_sum_frequency)
611
+ one_progress = 0
612
+ if mod.print_pct != None:
613
+ # print progress, x%
614
+ print(front_info + ' 0%' + end_info, end = '\r')
615
+ one_progress = mod.maxtime * mod.print_pct / 100
616
+ else:
617
+ one_progress = 2 * mod.maxtime # not printing
618
+
619
+ # our sums (sum_rates_by_row and sum_rates) are gradually updated over time. This may have precision errors for large maxtime.
620
+ # So re-sum everything every some percentage of maxtime.
621
+ one_update_sum = mod.maxtime / update_sum_frequency
622
+
623
+ current_time = one_time
624
+ current_progress = one_progress
625
+ current_update_sum = one_update_sum
626
+
627
+ max_record = int(mod.maxtime / mod.record_itv)
628
+
629
+
630
+ # initialize
631
+ time, world, nb_indices, patch_rates, sum_rates_by_row, sum_rates, signal = single_init(mod, rng)
632
+ record_index = int(time / mod.record_itv)
633
+ # record_time is how much time has passed since the last record
634
+ # if record_time > record_itv:
635
+ # we count how many record_itvs are there in record_time, denote the number by multi_records
636
+ # then store the current data in multi_records number of cells in the list
637
+ # and subtract record_time by the multiple of record_itv, so that record_time < record_itv
638
+ record_time = time - record_index * mod.record_itv
639
+
640
+ ### Large while loop ###
641
+
642
+ while time < mod.maxtime:
643
+
644
+ # print progress & correct error of sum_rates
645
+ if time > current_time:
646
+ # a new 1% of time
647
+ current_time += one_time
648
+ if time > current_progress:
649
+ # print progress
650
+ print(front_info + ' ' + str(round(time / mod.maxtime * 100)) + '%' + end_info, end = '\r')
651
+ current_progress += one_progress
652
+
653
+ if time > current_update_sum:
654
+ current_update_sum += one_update_sum
655
+ for i in range(mod.N):
656
+ sum_rates_by_row[i] = sum(patch_rates[i])
657
+ sum_rates = sum(sum_rates_by_row)
658
+
659
+
660
+ # before updating last-changed patches, subtract old sum of rates (so as to update sum of rates by adding new rates later)
661
+ for si in signal:
662
+ # si[0] is row number, si[1] is col number
663
+ old_patch_rate = world[si[0]][si[1]].get_sum_rates()
664
+ sum_rates_by_row[si[0]] -= old_patch_rate
665
+ sum_rates -= old_patch_rate
666
+
667
+ # update last-changed patches
668
+ # update payoff and death rates first
669
+ for si in signal:
670
+ world[si[0]][si[1]].update_pi_k()
671
+ # then update migration rates, as mig_rates depend on neighbor's payoff
672
+ for si in signal:
673
+ world[si[0]][si[1]].update_mig()
674
+
675
+ # update rates stored
676
+ new_patch_rate = world[si[0]][si[1]].get_sum_rates()
677
+ # update patch_rates
678
+ patch_rates[si[0]][si[1]] = new_patch_rate
679
+ # update sum_rate_by_row and sum_rates_by_row by adding new rates
680
+ sum_rates_by_row[si[0]] += new_patch_rate
681
+ sum_rates += new_patch_rate
682
+
683
+ # update neighbors of last-changed patches
684
+ for si in signal:
685
+ for ni in nb_indices[si[0]][si[1]]:
686
+ # don't need to update if the patch is a last-change patch itself or None
687
+ # use helper function to check
688
+ if nb_need_change(ni, signal):
689
+ # update migratino rates
690
+ world[ni[0]][ni[1]].update_mig()
691
+ # Note: no need to update patch_rates and sum of rates, as update_mig doesn't change total rates in a patch.
692
+ # sum_mig_rate is decided by mu1 * U + mu2 * V, and pi_death_rate is not changed.
693
+
694
+ # pick the first random event
695
+ expected_sum = rng.random() * sum_rates
696
+ # find patch first
697
+ i0, j0, current_sum = find_patch(expected_sum, patch_rates, sum_rates_by_row, sum_rates)
698
+ # then find which event in that patch
699
+ e0 = world[i0][j0].find_event(expected_sum - current_sum)
700
+
701
+ # make signal
702
+ if mod.boundary:
703
+ signal = make_signal_zero_flux(i0, j0, e0)
704
+ else:
705
+ signal = make_signal_periodical(mod.N, mod.M, i0, j0, e0)
706
+
707
+ # let the event happen
708
+ for si in signal:
709
+ world[si[0]][si[1]].change_popu(si[2])
710
+
711
+ # increase time
712
+ r1 = rng.random()
713
+ dt = (1 / sum_rates) * math.log(1 / r1)
714
+ time += dt
715
+ record_time += dt
716
+
717
+ if time < mod.maxtime:
718
+ # if not exceeds maxtime
719
+ if record_time > mod.record_itv:
720
+ multi_records = int(record_time / mod.record_itv)
721
+ record_time -= multi_records * mod.record_itv
722
+
723
+ for i in range(mod.N):
724
+ for j in range(mod.M):
725
+ for k in range(record_index, record_index + multi_records):
726
+ mod.U[i][j][k] += world[i][j].U
727
+ mod.V[i][j][k] += world[i][j].V
728
+ mod.Upi[i][j][k] += world[i][j].Upi
729
+ mod.Vpi[i][j][k] += world[i][j].Vpi
730
+ record_index += multi_records
731
+ else:
732
+ # if already exceeds maxtime
733
+ for i in range(mod.N):
734
+ for j in range(mod.M):
735
+ for k in range(record_index, max_record):
736
+ mod.U[i][j][k] += world[i][j].U
737
+ mod.V[i][j][k] += world[i][j].V
738
+ mod.Upi[i][j][k] += world[i][j].Upi
739
+ mod.Vpi[i][j][k] += world[i][j].Vpi
740
+
741
+ ### Large while loop ends ###
742
+
743
+ if mod.print_pct != None:
744
+ print(front_info + ' 100%' + ' ' * 20, end = '\r') # empty spaces to overwrite predicted runtime
745
+
746
+
747
+
748
+
749
+ def run_py(mod, predict_runtime = False, message = ''):
750
+ '''
751
+ Main function. Recursively calls single_test to run many models and then takes the average.
752
+
753
+ Inputs:
754
+ - mod is a model object.
755
+ - predict_runtime = False will not predict how much time still needed, set to True if you want to see.
756
+ - message is used by some functions in figures.py to print messages.
757
+ '''
758
+
759
+ if not mod.data_empty:
760
+ raise RuntimeError('mod has non-empty data')
761
+
762
+ mod.U = np.zeros((mod.N, mod.M, mod.max_record))
763
+ mod.V = np.zeros((mod.N, mod.M, mod.max_record))
764
+ mod.Vpi = np.zeros((mod.N, mod.M, mod.max_record))
765
+ mod.Upi = np.zeros((mod.N, mod.M, mod.max_record))
766
+
767
+ start = timer() # runtime
768
+
769
+ mod.data_empty = False
770
+ rng = np.random.default_rng(mod.seed)
771
+
772
+ # passed to single_test to print progress
773
+ if mod.print_pct == 0:
774
+ mod.print_pct = 5 # default print_pct
775
+
776
+ update_sum_frequency = 4 # re-calculate sums this many times. See input desciption of single_test
777
+
778
+ ### models ###
779
+ i = 0
780
+
781
+ while i < mod.sim_time:
782
+ # use while loop so that can go backwards if got numerical issues
783
+
784
+ end_info = ''
785
+ if predict_runtime:
786
+ if i > 0:
787
+ time_elapsed = timer() - start
788
+ pred_runtime = time_elapsed / i * (mod.sim_time - i)
789
+ end_info = ', ~' + str(round(pred_runtime, 2)) + 's left'
790
+
791
+ front_info = ''
792
+ if mod.print_pct != None:
793
+ front_info = message + 'round ' + str(i) + ':'
794
+ print(front_info + ' ' * 30, end = '\r') # the blank spaces are to overwrite percentages, e.g. 36 %
795
+
796
+ try:
797
+ single_test(mod, front_info, end_info, update_sum_frequency, rng)
798
+ i += 1
799
+ except IndexError:
800
+ update_sum_frequency *= 4
801
+ print('Numerical issue at round ' + str(i) + '. Trying higher precision now. See doc if err repeats')
802
+ # not increasing i: redo current round.
803
+
804
+ ### models end ###
805
+
806
+ mod.calculate_ave()
807
+
808
+ stop = timer()
809
+ print(' ' * 30, end = '\r') # overwrite all previous prints
810
+ print(message + 'runtime: ' + str(round(stop - start, 2)) + ' s')
811
+ return
812
+
813
+
814
+
815
+
816
+