piegy 1.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/__init__.py ADDED
@@ -0,0 +1,96 @@
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 .model import simulation, run, demo_model
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_val, 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
+ model_members = ['simulation', 'run', 'get_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_sim']
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__ = model_members + videos_members + data_members + figures_members + analysis_members + test_var_members
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+ # Below might be better suited for documents
60
+ '''
61
+ To run a simulation, start by defining some parameter. Here is a complete set of params::
62
+
63
+ >>> N = 5
64
+ >>> M = 5
65
+ >>> maxtime = 300
66
+ >>> sim_time = 3
67
+ >>> I = [[[22, 44] for i in range(N)] for j in range(M)]
68
+ >>> X = [[[-0.1, 0.4, 0, 0.2] for i in range(N)] for j in range(M)]
69
+ >>> X[1][1] = [0.1, 0.6, 0.2, 0.4]
70
+ >>> P = [[[0.5, 0.5, 100, 100, 0.001, 0.001] for i in range(N)] for j in range(M)]
71
+ >>> boundary = True
72
+ >>> print_pct = 5
73
+ >>> seed = None
74
+
75
+ These parameters essentially define the spatial size, initial population, payoff matrices...
76
+ For a detailed explanation, see simulation object.
77
+
78
+ Then create a 'simulation' object with those parameters::
79
+
80
+ >>> sim = simulation(N, M, maxtime, sim_time, I, X, P, boundary, print_pct, seed)
81
+
82
+ This 'sim' object will be the basis of our simulation. It carries all the necessary parameters
83
+ and storage bin for the results.
84
+
85
+ Now let's run the simulation (assuming you imported)::
86
+
87
+ >>> multi_test(sim)
88
+
89
+ And that's the simulation! It takes 30s ~ 1min. You can see the progress.
90
+
91
+ Now, to see the results, let's use figures::
92
+
93
+ >>> fig = UV_heatmap(sim)
94
+
95
+
96
+ '''
piegy/__version__.py ADDED
@@ -0,0 +1,17 @@
1
+ __version__ = '1.0.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
+
17
+ '''
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 simulation objects and return a new one (the first two unchanged).
7
+ Intended usage: say you have sim1, sim2 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 model as model
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(sim):
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 sim.maxtime.
35
+ Calculated based on expected_UV.
36
+ '''
37
+
38
+ N = sim.N
39
+ M = sim.M
40
+ U_expected, V_expected = figures.UV_expected_val(sim)
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 = model.patch(U_expected[i][j], V_expected[i][j], sim.X[i][j], sim.P[i][j])
50
+
51
+ nb_indices = None
52
+ if sim.boundary:
53
+ nb_indices = model.find_nb_zero_flux(N, M, i, j)
54
+ else:
55
+ nb_indices = model.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 = model.patch(U_expected[i_nb][j_nb], V_expected[i_nb][j_nb], sim.X[i_nb][j_nb], sim.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(sim.maxtime / delta_t_expected)
77
+
78
+ return r_expected
79
+
80
+
81
+
82
+
83
+ def scale_maxtime(sim1, sim2, scale_interval = True):
84
+ '''
85
+ NOTE: Not well-developed. Not recommending to use.
86
+
87
+ Scale sim1's maxtime towards sim2'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 sim1's interval as well, so that the same number of data will be stored.
92
+ '''
93
+
94
+ r_expected1 = rounds_expected(sim1)
95
+ r_expected2 = rounds_expected(sim2)
96
+ ratio = r_expected2 / r_expected1
97
+
98
+ new_maxtime = sim1.maxtime * ratio
99
+ old_max_record = sim1.maxtime / sim1.interval
100
+
101
+ if scale_interval:
102
+ sim1.interval = new_maxtime / old_max_record
103
+
104
+ sim1.change_maxtime(new_maxtime)
105
+
106
+
107
+
108
+
109
+ def check_convergence(sim, 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 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, sim.compress_itv)
132
+
133
+ start_index = int(sim.max_record * start) # where the tail starts
134
+ num_interval = int((sim.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(sim.U[:, :, start_index : start_index + interval])
139
+ max_U = np.mean(sim.U[:, :, start_index : start_index + interval])
140
+ min_V = np.mean(sim.V[:, :, start_index : start_index + interval])
141
+ max_V = np.mean(sim.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(sim.U[:, :, lower : upper])
149
+ ave_V = np.mean(sim.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(sim1, sim2):
174
+ '''
175
+ Combine data of sim1 and sim2.
176
+ Intended usage: assume sim1 and sim2 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
+ - sim1, sim2: both stochastic_model.simulation object. 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 simulation object whose U, V, U_pi, V_pi are weighted averages of sim1 and sim2
187
+ (weighted by sim_time).
188
+ sim3.print_pct is set to sim1's, seed set to None, sim_time set to sum of sim1's and sim2's. All other params same as sim1
189
+ '''
190
+ if not (sim1.N == sim2.N and
191
+ sim1.M == sim2.M and
192
+ sim1.maxtime == sim2.maxtime and
193
+ sim1.record_itv == sim2.record_itv and
194
+ sim1.boundary == sim2.boundary and
195
+ sim1.max_record == sim2.max_record and
196
+ np.array_equal(sim1.I, sim2.I) and
197
+ np.array_equal(sim1.X, sim2.X) and
198
+ np.array_equal(sim1.P, sim2.P)):
199
+
200
+ raise ValueError('sim1 and sim2 have different input parameters (N, M, maxtime, interval, boundary, max_record, or I, X, P).')
201
+
202
+ if sim1.seed == sim2.seed:
203
+ raise ValueError('Cannot combine two simulations with the same seed.')
204
+
205
+ # copy sim1, except for no data and a different sim_time
206
+ combined_sim_time = sim1.sim_time + sim2.sim_time
207
+ sim3 = sim1.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] = (sim1.U[i][j][k] * sim1.sim_time + sim2.U[i][j][k] * sim2.sim_time) / combined_sim_time
215
+ sim3.V[i][j][k] = (sim1.V[i][j][k] * sim1.sim_time + sim2.V[i][j][k] * sim2.sim_time) / combined_sim_time
216
+ sim3.U_pi[i][j][k] = (sim1.U_pi[i][j][k] * sim1.sim_time + sim2.U_pi[i][j][k] * sim2.sim_time) / combined_sim_time
217
+ sim3.V_pi[i][j][k] = (sim1.V_pi[i][j][k] * sim1.sim_time + sim2.V_pi[i][j][k] * sim2.sim_time) / combined_sim_time
218
+
219
+ return sim3
220
+
221
+
222
+
piegy/data_tools.py ADDED
@@ -0,0 +1,129 @@
1
+ '''
2
+ Stores and reads a simulation object.
3
+
4
+ Functions:
5
+ - save_data: save a simulation object.
6
+ - read_data: read a simulation object.
7
+ '''
8
+
9
+
10
+ from . import model as model
11
+
12
+ import json
13
+ import gzip
14
+ import os
15
+
16
+
17
+ def save_data(sim, dirs = '', print_msg = True):
18
+ '''
19
+ Saves a simulation object. Data will be stored at dirs/data.json.gz
20
+
21
+ Inputs:
22
+ - sim: Your simulation object.
23
+ - dirs: Where to save it.
24
+ - print_msg: Whether to print message after saving.
25
+ '''
26
+
27
+ try:
28
+ _ = sim.N
29
+ except AttributeError:
30
+ raise ValueError('sim is not a simulation 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
+ inputs1 = []
42
+ inputs1.append(sim.N)
43
+ inputs1.append(sim.M)
44
+ inputs1.append(sim.maxtime)
45
+ inputs1.append(sim.record_itv)
46
+ inputs1.append(sim.sim_time)
47
+ inputs1.append(sim.boundary)
48
+ inputs1.append(sim.I.tolist())
49
+ inputs1.append(sim.X.tolist())
50
+ inputs1.append(sim.P.tolist())
51
+ data.append(inputs1)
52
+
53
+ inputs2 = []
54
+ inputs2.append(sim.print_pct)
55
+ inputs2.append(sim.seed)
56
+ inputs2.append(sim.UV_dtype)
57
+ inputs2.append(sim.pi_dtype)
58
+ data.append(inputs2)
59
+
60
+ # skipped rng
61
+
62
+ outputs = []
63
+ outputs.append(sim.max_record)
64
+ outputs.append(sim.compress_itv)
65
+ outputs.append(sim.U.tolist())
66
+ outputs.append(sim.V.tolist())
67
+ outputs.append(sim.U_pi.tolist())
68
+ outputs.append(sim.V_pi.tolist())
69
+ # H&V_pi_total are not saved, will be calculated when reading the data
70
+ data.append(outputs)
71
+
72
+ data_json = json.dumps(data)
73
+ data_bytes = data_json.encode('utf-8')
74
+ data_dirs = dirs + 'data.json.gz'
75
+
76
+ with gzip.open(data_dirs, 'w') as f:
77
+ f.write(data_bytes)
78
+
79
+ if print_msg:
80
+ print('data saved: ' + data_dirs)
81
+
82
+
83
+
84
+ def read_data(dirs):
85
+ '''
86
+ Reads and returns a simulation object.
87
+
88
+ Inputs:
89
+ - dirs: where to read from, just provide the folder-subfolder names. Don't include 'data.json.gz'
90
+ - print_msg: this function prints a message when the sim.compress_itv != None. Setting print_msg = False will skip ignore this message.
91
+
92
+ Returns:
93
+ - sim: a piegy.model.simulation object read from the data.
94
+ '''
95
+
96
+ if dirs != '':
97
+ # add slash '/'
98
+ if dirs[:-1] != '/':
99
+ dirs += '/'
100
+ if not os.path.exists(dirs):
101
+ raise FileNotFoundError('dirs not found: ' + dirs)
102
+
103
+ if not os.path.isfile(dirs + 'data.json.gz'):
104
+ raise FileNotFoundError('data not found in ' + dirs)
105
+
106
+ with gzip.open(dirs + 'data.json.gz', 'r') as f:
107
+ data_bytes = f.read()
108
+ data_json = data_bytes.decode('utf-8')
109
+ data = json.loads(data_json)
110
+
111
+ # inputs
112
+ try:
113
+ sim = model.simulation(N = data[0][0], M = data[0][1], maxtime = data[0][2], record_itv = data[0][3],
114
+ sim_time = data[0][4], boundary = data[0][5], I = data[0][6], X = data[0][7], P = data[0][8],
115
+ print_pct = data[1][0], seed = data[1][1], UV_dtype = data[1][2], pi_dtype = data[1][3])
116
+ except:
117
+ raise ValueError('Invalid input parameters saved in data')
118
+
119
+ # outputs
120
+ try:
121
+ sim.set_data(False, data[2][0], data[2][1], data[2][2], data[2][3], data[2][4], data[2][5])
122
+ except:
123
+ raise ValueError('Invalid simulation results saved in data')
124
+
125
+ return sim
126
+
127
+
128
+
129
+