-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatistics.py
84 lines (64 loc) · 2.66 KB
/
statistics.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
from abc import ABC, abstractmethod
import pandas as pd
from matplotlib import pyplot as plt
from logic.models import GenericModel
from logic.point import Point
import csv
import os
import re
PLOT_DIR = os.path.join('data', 'plot')
DATA_CSV_PATH = os.path.join('statistics', 'data.csv')
class Statistics(ABC):
"""Abstract class to handle simulation statistics"""
def __init__(self, model: GenericModel):
self.model = model
self.day = 0
self.fieldnames = ["Day"]
def update_day(self):
"""Method updating day counter"""
self.day += 1
def get_attributes_array(self):
return [self.day]
def save_field_names(self) -> None:
with open('statistics/data.csv', 'w') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=self.fieldnames)
csv_writer.writeheader()
if not os.path.exists(PLOT_DIR):
os.mkdir(PLOT_DIR)
else:
for filename in filter(lambda f: re.match(r'plot\d+\.png', f), os.listdir(PLOT_DIR)):
os.remove(os.path.join(PLOT_DIR, filename))
def generate_plot(self, idx: int, *args) -> None:
"""Method generating new statistics plot and removing old one"""
statistics_name = ['Exposed', 'Infected', 'Recovered', 'Quarantined', 'Deaths', 'Recovered 2', 'Vaccinated',
'Recovered V']
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
data = pd.read_csv('statistics/data.csv')
day = data['Day']
for arg in args:
if arg in statistics_name:
ax1.plot(day, data[arg], label=arg)
ax1.legend(loc='upper left')
ax2.plot(day, data['New cases'], label='New cases')
ax2.legend(loc='upper left')
if idx != 0:
os.remove(os.path.join(PLOT_DIR, f"plot{idx - 1}.png"))
plt.savefig(f"data/plot/plot{idx}.png")
plt.close('all')
@abstractmethod
def reset_statistics(self) -> None:
"""Method setting statistic to 0"""
@abstractmethod
def update_statistics(self, point: Point) -> None:
"""Method updating statistics by adding point's values"""
def update_data_file(self) -> None:
"""Method to add new stats to csv data file"""
info = dict(zip(self.fieldnames, self.get_attributes_array()))
with open(DATA_CSV_PATH, 'a') as csv_file:
csv_writer = csv.DictWriter(csv_file, fieldnames=self.fieldnames)
csv_writer.writerow(info)
@property
def current_stats_representations(self) -> dict[str, str]:
stats_representations = {
"day": f"Day: {self.day}"}
return stats_representations