piegy 2.1.0__cp38-cp38-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/C_core/piegyc.cp38-win32.pyd +0 -0
- piegy/__init__.py +56 -0
- piegy/__version__.py +31 -0
- piegy/analysis.py +222 -0
- piegy/data_tools.py +127 -0
- piegy/figures.py +491 -0
- piegy/simulation.py +500 -0
- piegy/simulation_py.py +817 -0
- piegy/test_var.py +583 -0
- piegy/tools/__init__.py +15 -0
- piegy/tools/figure_tools.py +238 -0
- piegy/tools/file_tools.py +29 -0
- piegy/videos.py +303 -0
- piegy-2.1.0.dist-info/LICENSE.txt +28 -0
- piegy-2.1.0.dist-info/METADATA +112 -0
- piegy-2.1.0.dist-info/RECORD +18 -0
- piegy-2.1.0.dist-info/WHEEL +5 -0
- piegy-2.1.0.dist-info/top_level.txt +1 -0
Binary file
|
piegy/__init__.py
ADDED
@@ -0,0 +1,56 @@
|
|
1
|
+
'''
|
2
|
+
Payoff-Driven Stochastic Spatial Model for Evolutionary Game Theory
|
3
|
+
-----------------------------------------------------------------------------
|
4
|
+
|
5
|
+
Provides:
|
6
|
+
1. A stochastic spatial model for simulating the interaction and evolution of two species in either 1D or 2D space
|
7
|
+
2. Plot & video functions to visualize simulation results.
|
8
|
+
3. Module to test influence of certain variables on results.
|
9
|
+
4. Data saving & reading module.
|
10
|
+
4. Additional analytical tools.
|
11
|
+
|
12
|
+
Websites:
|
13
|
+
- The *piegy* documentation: https://piegy.readthedocs.io/en/
|
14
|
+
- GitHub repository at: https://github.com/Chenning04/piegy.git
|
15
|
+
- PyPI page: https://pypi.org/project/piegy/
|
16
|
+
|
17
|
+
|
18
|
+
Last update: May 12, 2025
|
19
|
+
'''
|
20
|
+
|
21
|
+
from .__version__ import __version__
|
22
|
+
|
23
|
+
from .simulation import model, run, demo_model, UV_expected_val, check_overflow_func
|
24
|
+
from .videos import make_video, SUPPORTED_FIGURES
|
25
|
+
from .data_tools import save_data, read_data
|
26
|
+
|
27
|
+
from .analysis import rounds_expected, scale_maxtime, check_convergence, combine_sim
|
28
|
+
|
29
|
+
from .figures import (UV_heatmap, UV_bar, UV_dyna, UV_hist, UV_std, UV_expected,
|
30
|
+
pi_heatmap, pi_bar, pi_dyna, pi_hist, pi_std, UV_pi)
|
31
|
+
|
32
|
+
from .test_var import (test_var1, var_UV1, var_pi1, var_convergence1, get_dirs1,
|
33
|
+
test_var2, var_UV2, var_pi2, var_convergence2, get_dirs2)
|
34
|
+
|
35
|
+
|
36
|
+
simulation_memebers = ['model', 'run', 'demo_model']
|
37
|
+
|
38
|
+
videos_members = ['make_video', 'SUPPORTED_FIGURES']
|
39
|
+
|
40
|
+
data_members = ['save_data', 'read_data']
|
41
|
+
|
42
|
+
analysis_members = ['expected_rounds', 'scale_maxtime', 'check_convergence', 'combine_mod']
|
43
|
+
|
44
|
+
figures_members = ['UV_heatmap', 'UV_bar', 'UV_dyna', 'UV_hist', 'UV_std', 'UV_expected_val', 'UV_expected',
|
45
|
+
'pi_heatmap', 'pi_bar', 'pi_dyna', 'pi_hist', 'pi_std', 'UV_pi']
|
46
|
+
|
47
|
+
test_var_members = ['test_var1', 'var_UV1', 'var_pi1', 'var_convergence1', 'get_dirs1',
|
48
|
+
'test_var2', 'var_UV2', 'var_pi2', 'var_convergence2', 'get_dirs2']
|
49
|
+
|
50
|
+
|
51
|
+
__all__ = simulation_memebers + videos_members + data_members + figures_members + analysis_members + test_var_members
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
|
56
|
+
|
piegy/__version__.py
ADDED
@@ -0,0 +1,31 @@
|
|
1
|
+
__version__ = '2.1.0'
|
2
|
+
|
3
|
+
'''
|
4
|
+
version history:
|
5
|
+
|
6
|
+
0.1.0: first publishing, May 11, 2025
|
7
|
+
0.1.1: fix dependency errors
|
8
|
+
0.1.2: fixing module not find error
|
9
|
+
0.1.3: restructuring package
|
10
|
+
0.1.4 ~ 0.1.6: fixing moviepy import issue
|
11
|
+
0.1.7: changed name back to 'piegy'
|
12
|
+
0.1.8: updated installation in README
|
13
|
+
0.1.9: first round of full debugging
|
14
|
+
|
15
|
+
1.0.0: first version in PyPI.
|
16
|
+
1.1.0: debugging. Updated a range of functions, in the following modules: figures, videos, test_var, model, figure_tools
|
17
|
+
1.1.1: minor debugging in model module.
|
18
|
+
1.1.2: fix text bad location in figure_tools, update labeling and titling in figures and test_var. Add dpi param to make_video in videos. Remove reset_data function in model.
|
19
|
+
1.1.3: update README.
|
20
|
+
1.1.4: changed name: ``model`` module to ``simulation``, and ``model.simulation`` class to ``simulation.model``. Bug fix in videos.
|
21
|
+
1.1.5: update README.
|
22
|
+
1.1.6: change name of variables in model class -- for compatability with the new C core. 1.1.6 is the last verion of v1. From v2 on, the piegy package has C core.
|
23
|
+
|
24
|
+
2.0.0: update simulation core to C-based.
|
25
|
+
2.0.1: re-upload, the C core is not included in package.
|
26
|
+
2.0.2: update version number in __version__.py and update README.
|
27
|
+
2.0.3: speed boost & debugging in C core. Add check_overflow feature in simulation module, checks whether overflow/too large numbers might be encountered in simulation.
|
28
|
+
2.0.4: minor debuggings.
|
29
|
+
2.0.5: fix error in random number generator.
|
30
|
+
2.1.0: redo random number generator. Update package upload so that more compatible across platforms.
|
31
|
+
'''
|
piegy/analysis.py
ADDED
@@ -0,0 +1,222 @@
|
|
1
|
+
'''
|
2
|
+
This file contains pre-processing, post-processing, and analytical tools for simulations.
|
3
|
+
|
4
|
+
Public Funcions:
|
5
|
+
- check_convergence: Check whether a simulation result converges. i.e. whether U, V's fluctuation are very small.
|
6
|
+
- combine_sim: Combine two model objects and return a new one (the first two unchanged).
|
7
|
+
Intended usage: say you have mod1, mod2 with same parameters except for sim_time, say 10 and 20.
|
8
|
+
Then combine_sim takes a weighted average (with ratio 1:2) of results and return a new sim3.
|
9
|
+
So that you now have sim3 with 30 sim_time.
|
10
|
+
|
11
|
+
Private Functions:
|
12
|
+
- rounds_expected: Roughly calculates how many rounds are expected in a single simulation (which reflects runtime).
|
13
|
+
NOTE: Not well-developed. Not recommending to use.
|
14
|
+
- scale_maxtime: Given two simulation objects, scale first one's maxtime towards the second, so that the two have the same expected rounds.
|
15
|
+
Intended to possibly decrease maxtime and save runtime.
|
16
|
+
NOTE: Not well-developed. Not recommending to use.
|
17
|
+
|
18
|
+
'''
|
19
|
+
|
20
|
+
from . import simulation as simulation
|
21
|
+
from . import figures as figures
|
22
|
+
from .tools import figure_tools as figure_t
|
23
|
+
|
24
|
+
import numpy as np
|
25
|
+
import math
|
26
|
+
|
27
|
+
|
28
|
+
|
29
|
+
|
30
|
+
def rounds_expected(mod):
|
31
|
+
'''
|
32
|
+
NOTE: Not well-developed. Not recommending to use.
|
33
|
+
|
34
|
+
Predict how many rounds will run in single_test. i.e., how many for loops from time = 0 to mod.maxtime.
|
35
|
+
Calculated based on expected_UV.
|
36
|
+
'''
|
37
|
+
|
38
|
+
N = mod.N
|
39
|
+
M = mod.M
|
40
|
+
U_expected, V_expected = figures.UV_expected_val(mod)
|
41
|
+
|
42
|
+
rates = []
|
43
|
+
patch0 = None # simulate patch i, j
|
44
|
+
patch0_nb = [] # simulate neighbors of patch i, j
|
45
|
+
|
46
|
+
# loop through N, M, create a sample patch to calculate rates, store them
|
47
|
+
for i in range(N):
|
48
|
+
for j in range(M):
|
49
|
+
patch0 = simulation.patch(U_expected[i][j], V_expected[i][j], mod.X[i][j], mod.P[i][j])
|
50
|
+
|
51
|
+
nb_indices = None
|
52
|
+
if mod.boundary:
|
53
|
+
nb_indices = simulation.find_nb_zero_flux(N, M, i, j)
|
54
|
+
else:
|
55
|
+
nb_indices = simulation.find_nb_periodical(N, M, i, j)
|
56
|
+
|
57
|
+
for k in range(4):
|
58
|
+
if nb_indices[k] != None:
|
59
|
+
i_nb = nb_indices[k][0]
|
60
|
+
j_nb = nb_indices[k][1]
|
61
|
+
patch0_nb_k = simulation.patch(U_expected[i_nb][j_nb], V_expected[i_nb][j_nb], mod.X[i_nb][j_nb], mod.P[i_nb][j_nb])
|
62
|
+
patch0_nb_k.update_pi_k()
|
63
|
+
patch0_nb.append(patch0_nb_k)
|
64
|
+
|
65
|
+
else:
|
66
|
+
patch0_nb.append(None)
|
67
|
+
|
68
|
+
patch0.nb = patch0_nb
|
69
|
+
patch0.update_pi_k()
|
70
|
+
patch0.update_mig()
|
71
|
+
|
72
|
+
rates += patch0.pi_death_rates
|
73
|
+
rates += patch0.mig_rates
|
74
|
+
|
75
|
+
delta_t_expected = (1 / sum(rates)) * math.log(1 / 0.5)
|
76
|
+
r_expected = round(mod.maxtime / delta_t_expected)
|
77
|
+
|
78
|
+
return r_expected
|
79
|
+
|
80
|
+
|
81
|
+
|
82
|
+
|
83
|
+
def scale_maxtime(mod1, mod2, scale_interval = True):
|
84
|
+
'''
|
85
|
+
NOTE: Not well-developed. Not recommending to use.
|
86
|
+
|
87
|
+
Scale mod1's maxtime towards mod2's, so they will run similar number of rounds in single_test, and hence similar runtime.
|
88
|
+
Intended to reduce the effect of changing params on runtime.
|
89
|
+
|
90
|
+
Input:
|
91
|
+
- scale_interval decides whether to scale mod1's interval as well, so that the same number of data will be stored.
|
92
|
+
'''
|
93
|
+
|
94
|
+
r_expected1 = rounds_expected(mod1)
|
95
|
+
r_expected2 = rounds_expected(mod2)
|
96
|
+
ratio = r_expected2 / r_expected1
|
97
|
+
|
98
|
+
new_maxtime = mod1.maxtime * ratio
|
99
|
+
old_max_record = mod1.maxtime / mod1.interval
|
100
|
+
|
101
|
+
if scale_interval:
|
102
|
+
mod1.interval = new_maxtime / old_max_record
|
103
|
+
|
104
|
+
mod1.change_maxtime(new_maxtime)
|
105
|
+
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
def check_convergence(mod, interval = 20, start = 0.8, fluc = 0.07):
|
110
|
+
'''
|
111
|
+
Check whether a simulation converges or not.
|
112
|
+
Based on whether the fluctuation of U, V, pi all < 'fluc' in the later 'tail' portion of time.
|
113
|
+
|
114
|
+
Essentially find the max and min values (of population) in every small interval, and then check whether their difference > min * fluc.
|
115
|
+
|
116
|
+
Inputs:
|
117
|
+
- sim: a simulation.model object
|
118
|
+
- interval: int, how many records to take average over,
|
119
|
+
and then compare this "local mean" with "whole-tail mean" and expect the difference to be less than fluc.
|
120
|
+
- start: (0, 1) float, decides where you expect to check convergence from. Smaller start needs earlier convergence.
|
121
|
+
- fluc: (0, 1) float. How much fluctuation is allowed between the average value of a small interval and the mean.
|
122
|
+
'''
|
123
|
+
|
124
|
+
if (start < 0) or (start > 1):
|
125
|
+
raise ValueError("start should be a float in (0, 1)")
|
126
|
+
if (fluc < 0) or (fluc > 1):
|
127
|
+
raise ValueError("fluc should be a float in (0, 1)")
|
128
|
+
if (type(interval) != int) or (interval < 1):
|
129
|
+
raise ValueError("interval should be an int >= 1")
|
130
|
+
|
131
|
+
interval = figure_t.scale_interval(interval, mod.compress_itv)
|
132
|
+
|
133
|
+
start_index = int(mod.max_record * start) # where the tail starts
|
134
|
+
num_interval = int((mod.max_record - start_index) / interval) # how many intervals in total
|
135
|
+
|
136
|
+
# find the max and min value of the small intervals
|
137
|
+
# initiate as average of the first interval
|
138
|
+
min_U = np.mean(mod.U[:, :, start_index : start_index + interval])
|
139
|
+
max_U = np.mean(mod.U[:, :, start_index : start_index + interval])
|
140
|
+
min_V = np.mean(mod.V[:, :, start_index : start_index + interval])
|
141
|
+
max_V = np.mean(mod.V[:, :, start_index : start_index + interval])
|
142
|
+
|
143
|
+
for i in range(1, num_interval):
|
144
|
+
# lower and upper bound of current interval
|
145
|
+
lower = start_index + i * interval
|
146
|
+
upper = lower + interval
|
147
|
+
|
148
|
+
ave_U = np.mean(mod.U[:, :, lower : upper])
|
149
|
+
ave_V = np.mean(mod.V[:, :, lower : upper])
|
150
|
+
|
151
|
+
# Compare with min, max
|
152
|
+
if ave_U > max_U:
|
153
|
+
max_U = ave_U
|
154
|
+
if ave_U < min_U:
|
155
|
+
min_U = ave_U
|
156
|
+
|
157
|
+
if ave_V > max_V:
|
158
|
+
max_V = ave_V
|
159
|
+
if ave_V < min_V:
|
160
|
+
min_V = ave_V
|
161
|
+
|
162
|
+
# check whether (max - min) > min * fluc
|
163
|
+
if (max_U - min_U) > min_U * fluc:
|
164
|
+
return False
|
165
|
+
if (max_V - min_V) > min_V * fluc:
|
166
|
+
return False
|
167
|
+
|
168
|
+
return True
|
169
|
+
|
170
|
+
|
171
|
+
|
172
|
+
|
173
|
+
def combine_sim(mod1, mod2):
|
174
|
+
'''
|
175
|
+
Combine data of mod1 and mod2.
|
176
|
+
Intended usage: assume mod1 and mod2 has the same N, M, maxtime, interval, boundary, max_record, and I, X, P
|
177
|
+
combine_sim then combines the two results and calculate a new weighted average of the two data, return a new sim object.
|
178
|
+
Essentially allows breaking up many rounds of simulations into several smaller pieces, and then put together.
|
179
|
+
|
180
|
+
Inputs:
|
181
|
+
- mod1, mod2: both simulation.model objects. All input parameters the same except for sim_time, print_pct and seed.
|
182
|
+
Raises error if not.
|
183
|
+
|
184
|
+
Returns:
|
185
|
+
|
186
|
+
- sim3: a new model object whose U, V, Upi, Vpi are weighted averages of mod1 and mod2
|
187
|
+
(weighted by sim_time).
|
188
|
+
sim3.print_pct is set to mod1's, seed set to None, sim_time set to sum of mod1's and mod2's. All other params same as mod1
|
189
|
+
'''
|
190
|
+
if not (mod1.N == mod2.N and
|
191
|
+
mod1.M == mod2.M and
|
192
|
+
mod1.maxtime == mod2.maxtime and
|
193
|
+
mod1.record_itv == mod2.record_itv and
|
194
|
+
mod1.boundary == mod2.boundary and
|
195
|
+
mod1.max_record == mod2.max_record and
|
196
|
+
np.array_equal(mod1.I, mod2.I) and
|
197
|
+
np.array_equal(mod1.X, mod2.X) and
|
198
|
+
np.array_equal(mod1.P, mod2.P)):
|
199
|
+
|
200
|
+
raise ValueError('mod1 and mod2 have different input parameters (N, M, maxtime, interval, boundary, max_record, or I, X, P).')
|
201
|
+
|
202
|
+
if mod1.seed == mod2.seed:
|
203
|
+
raise ValueError('Cannot combine two simulations with the same seed.')
|
204
|
+
|
205
|
+
# copy mod1, except for no data and a different sim_time
|
206
|
+
combined_sim_time = mod1.sim_time + mod2.sim_time
|
207
|
+
sim3 = mod1.copy(copy_data = False)
|
208
|
+
sim3.sim_time = combined_sim_time
|
209
|
+
sim3.seed = None
|
210
|
+
|
211
|
+
for i in range(sim3.N):
|
212
|
+
for j in range(sim3.M):
|
213
|
+
for k in range(sim3.max_record):
|
214
|
+
sim3.U[i][j][k] = (mod1.U[i][j][k] * mod1.sim_time + mod2.U[i][j][k] * mod2.sim_time) / combined_sim_time
|
215
|
+
sim3.V[i][j][k] = (mod1.V[i][j][k] * mod1.sim_time + mod2.V[i][j][k] * mod2.sim_time) / combined_sim_time
|
216
|
+
sim3.Upi[i][j][k] = (mod1.Upi[i][j][k] * mod1.sim_time + mod2.Upi[i][j][k] * mod2.sim_time) / combined_sim_time
|
217
|
+
sim3.Vpi[i][j][k] = (mod1.Vpi[i][j][k] * mod1.sim_time + mod2.Vpi[i][j][k] * mod2.sim_time) / combined_sim_time
|
218
|
+
|
219
|
+
return sim3
|
220
|
+
|
221
|
+
|
222
|
+
|
piegy/data_tools.py
ADDED
@@ -0,0 +1,127 @@
|
|
1
|
+
'''
|
2
|
+
Stores and reads a model object.
|
3
|
+
|
4
|
+
Functions:
|
5
|
+
- save_data: save a model object.
|
6
|
+
- read_data: read a model object.
|
7
|
+
'''
|
8
|
+
|
9
|
+
|
10
|
+
from . import simulation
|
11
|
+
|
12
|
+
import json
|
13
|
+
import gzip
|
14
|
+
import os
|
15
|
+
|
16
|
+
|
17
|
+
def save_data(mod, dirs = '', print_msg = True):
|
18
|
+
'''
|
19
|
+
Saves a model object. Data will be stored at dirs/data.json.gz
|
20
|
+
|
21
|
+
Inputs:
|
22
|
+
- mod: Your model object.
|
23
|
+
- dirs: Where to save it.
|
24
|
+
- print_msg: Whether to print message after saving.
|
25
|
+
'''
|
26
|
+
|
27
|
+
try:
|
28
|
+
_ = mod.N
|
29
|
+
except AttributeError:
|
30
|
+
raise ValueError('mod is not a model object')
|
31
|
+
|
32
|
+
if dirs != '':
|
33
|
+
# add slash '/'
|
34
|
+
if dirs[:-1] != '/':
|
35
|
+
dirs += '/'
|
36
|
+
if not os.path.exists(dirs):
|
37
|
+
os.makedirs(dirs)
|
38
|
+
|
39
|
+
data = []
|
40
|
+
|
41
|
+
inputs = []
|
42
|
+
inputs.append(mod.N)
|
43
|
+
inputs.append(mod.M)
|
44
|
+
inputs.append(mod.maxtime)
|
45
|
+
inputs.append(mod.record_itv)
|
46
|
+
inputs.append(mod.sim_time)
|
47
|
+
inputs.append(mod.boundary)
|
48
|
+
inputs.append(mod.I.tolist())
|
49
|
+
inputs.append(mod.X.tolist())
|
50
|
+
inputs.append(mod.P.tolist())
|
51
|
+
inputs.append(mod.print_pct)
|
52
|
+
inputs.append(mod.seed)
|
53
|
+
inputs.append(mod.check_overflow)
|
54
|
+
data.append(inputs)
|
55
|
+
|
56
|
+
# skipped rng
|
57
|
+
|
58
|
+
outputs = []
|
59
|
+
outputs.append(mod.max_record)
|
60
|
+
outputs.append(mod.compress_itv)
|
61
|
+
outputs.append(mod.U.tolist())
|
62
|
+
outputs.append(mod.V.tolist())
|
63
|
+
outputs.append(mod.Upi.tolist())
|
64
|
+
outputs.append(mod.Vpi.tolist())
|
65
|
+
# H&Vpi_total are not saved, will be calculated when reading the data
|
66
|
+
data.append(outputs)
|
67
|
+
|
68
|
+
data_json = json.dumps(data)
|
69
|
+
data_bytes = data_json.encode('utf-8')
|
70
|
+
data_dirs = dirs + 'data.json.gz'
|
71
|
+
|
72
|
+
with gzip.open(data_dirs, 'w') as f:
|
73
|
+
f.write(data_bytes)
|
74
|
+
|
75
|
+
if print_msg:
|
76
|
+
print('data saved: ' + data_dirs)
|
77
|
+
|
78
|
+
|
79
|
+
|
80
|
+
def read_data(dirs):
|
81
|
+
'''
|
82
|
+
Reads and returns a model object.
|
83
|
+
|
84
|
+
Inputs:
|
85
|
+
- dirs: where to read from, just provide the folder-subfolder names. Don't include 'data.json.gz'
|
86
|
+
- print_msg: this function prints a message when the mod.compress_itv != None. Setting print_msg = False will skip ignore this message.
|
87
|
+
|
88
|
+
Returns:
|
89
|
+
- mod: a piegy.model.model object read from the data.
|
90
|
+
'''
|
91
|
+
|
92
|
+
if dirs != '':
|
93
|
+
# add slash '/'
|
94
|
+
if dirs[:-1] != '/':
|
95
|
+
dirs += '/'
|
96
|
+
if not os.path.exists(dirs):
|
97
|
+
raise FileNotFoundError('dirs not found: ' + dirs)
|
98
|
+
|
99
|
+
if not os.path.isfile(dirs + 'data.json.gz'):
|
100
|
+
raise FileNotFoundError('data not found in ' + dirs)
|
101
|
+
|
102
|
+
with gzip.open(dirs + 'data.json.gz', 'r') as f:
|
103
|
+
data_bytes = f.read()
|
104
|
+
data_json = data_bytes.decode('utf-8')
|
105
|
+
data = json.loads(data_json)
|
106
|
+
|
107
|
+
# inputs
|
108
|
+
try:
|
109
|
+
mod = simulation.model(N = data[0][0], M = data[0][1], maxtime = data[0][2], record_itv = data[0][3],
|
110
|
+
sim_time = data[0][4], boundary = data[0][5], I = data[0][6], X = data[0][7], P = data[0][8],
|
111
|
+
print_pct = data[0][9], seed = data[0][10], check_overflow = data[0][11])
|
112
|
+
except:
|
113
|
+
raise ValueError('Invalid input parameters saved in data')
|
114
|
+
|
115
|
+
# outputs
|
116
|
+
try:
|
117
|
+
mod.set_data(data_empty = False, max_record = data[1][0], compress_itv = data[1][1],
|
118
|
+
U = data[1][2], V = data[1][3], Upi = data[1][4], Vpi = data[1][5])
|
119
|
+
except:
|
120
|
+
raise ValueError('Invalid model results saved in data')
|
121
|
+
|
122
|
+
return mod
|
123
|
+
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
|