-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulation.py
191 lines (151 loc) · 6.14 KB
/
Simulation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main graphics simulation class
"""
import pickle
import matplotlib.pyplot as plt
from matplotlib import patches
from numpy import arange
from typing import Tuple, Iterable, List, Optional, IO, Union
from models.Board import BoardConfig, Board, SimulationStepData
from models.Country import Country
from models.Disease import Disease
from models.Person import InfectionStatus
__author__ = "Filip Koprivec"
__email__ = "[email protected]"
class Simulation:
"""
Krovni objekt simulacije
"""
def __init__(self, country: Country, disease: Disease, board_config: BoardConfig,
initial_infections: Optional[Iterable[Tuple[int, int]]] = None, seed: Optional[int] = None) -> None:
if seed is None:
import time
seed = int(time.time())
import random
random.seed(seed)
self.seed = seed
self.board = Board.create_board(country, disease, board_config)
self.board.init_board()
self.board.manually_infect(initial_infections or [(self.board.height // 2, self.board.width // 2)])
def simulate_steps(self, steps: int = 10, verbose=True,
save_file: Optional[IO[bytes]] = None) -> List[SimulationStepData]:
"""
Simulira več korakov simulacije (ali do konca), po želji te korake izpisuje in shranjuje v datoteko
:param steps: število korakov
:param verbose: natančnost izpisovanja
:param save_file: datoteka za shranjevanje
:return: Rezultati korakov simulacije
"""
results = [] # type: List[SimulationStepData]
while not self.board.stopped and steps > 0:
steps -= 1
results.append(self.board.next_step())
if verbose:
print(results[-1].pp())
if save_file is not None:
pickle.dump(results, save_file)
return results
def simulate(self, verbose: bool = True, save_file: Optional[IO[bytes]] = None) -> List[SimulationStepData]:
"""
Odsimulira celotno simulacijo in jo po potrebi shrani
:param verbose: Pogostost izpisa
:param save_file: datoteka za sranjevanje
:return: REzultati korakov simulacije
"""
results = [] # type: List[SimulationStepData]
while not self.board.stopped:
results.append(self.board.next_step())
if verbose:
print(results[-1].pp())
else:
if self.board.step_num % 20 == 0:
print(results[-1].pp())
if save_file is not None:
pickle.dump((results, self), save_file)
return results
# Analysis part
def draw_analysis(sim_steps: List[SimulationStepData], simulation: Simulation, show: bool = True) -> List[
Tuple[str, Union[int, str]]]:
"""
Iziriše grafe za analizo
:param sim_steps: koraki simulacije
:param simulation: objekt simulacije
:param show: Ali pokaže graf
:return: None
"""
def attribute_getter(attr_name: str) -> List[int]:
"""Pridobi posamezne atribute iz podatkov simulacije"""
return list(map(lambda x: getattr(x, attr_name), sim_steps))
t = arange(sim_steps[-1].step_num)
infected = attribute_getter("infected")
infected_col = "r"
inf_patch = patches.Patch(color=infected_col, label="Okuženi")
infectious = attribute_getter("infectious")
infectious_col = "m"
infcs_patch = patches.Patch(color=infectious_col, label="Kužni")
symptomatic = attribute_getter("symptomatic")
symptomatic_col = "c"
sym_patch = patches.Patch(color=symptomatic_col, label="Simptomatski")
dead = attribute_getter("dead")
dead_col = "k"
dead_patch = patches.Patch(color=dead_col, label="Mrtvi")
touched = attribute_getter("touched")
touched_col = "b"
touched_patch = patches.Patch(color=touched_col, label="Možnost okužbe")
untouched_col = "g"
untouched_patch = patches.Patch(color=untouched_col, label="Brez možnosti okužbe")
f, (graph, img, report) = plt.subplots(1, 3)
graph.set_title("Število posameznikov glede na stanje bolezni")
graph.legend(handles=[inf_patch, infcs_patch, sym_patch, dead_patch])
graph.plot(t, infected, infected_col, t, infectious, infectious_col, t, symptomatic, symptomatic_col, t, dead,
dead_col)
img.set_title("Zemljevid stanja okužbe ob koncu")
img.legend(handles=[untouched_patch, touched_patch, inf_patch, dead_patch])
img.imshow(simulation.board.to_final_np_image_array(), interpolation="nearest")
report.set_title("Poročilo")
report.axis("tight")
report.axis("off")
columns = ("Atribut", "Vrednost")
inf_all = 0
for j in simulation.board.board:
for person in j:
if person.infection_status != InfectionStatus.NOT_INFECTED:
inf_all += 1
# inf_all = sum(attribute_getter("newly_infected"))
data = [
("Random seed", simulation.seed),
("Število celic", simulation.board.height * simulation.board.width),
("Ljudi v celici", simulation.board.board_config.cell_ratio),
("Skupaj okuženih", inf_all),
("Število mrtvih", simulation.board.dead_num),
("Število prebolelih", inf_all - simulation.board.dead_num),
("Število prizadetih", simulation.board.touched_num),
("Delež prizadete \n populacije",
"{0:.3f}%".format(float(simulation.board.touched_num) / (simulation.board.height * simulation.board.width)))
]
table = report.table(cellText=data, colLabels=columns, loc='center')
table.auto_set_font_size(False)
table.set_fontsize(14)
table.scale(1, 2)
try:
mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)
except:
try:
mng = plt.get_current_fig_manager()
mng.window.showMaximized()
except:
try:
mng = plt.get_current_fig_manager()
mng.resize(*mng.window.maxsize())
except:
pass
if show:
plt.show()
return data
def main() -> bool:
return True
if __name__ == "__main__":
main()