-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataHandler.py
241 lines (198 loc) · 9.69 KB
/
DataHandler.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import csv
import math
import os
import sqlite3
from datetime import datetime, timedelta
from os import path
from CalendarHandler import CalendarHandler
class DataHandler():
def __init__(self):
self.calHandler = CalendarHandler()
self.csv_format = {
'teamA': 0,
'teamB': 1,
'field': 2,
'time': 3
}
self.team_names_to_row = {
'ER-Force': 0,
'RoboCIn': 1,
'RoboTeam Twente': 2,
'KIKS': 3,
'TIGERs Mannheim': 4,
'KgpKubs': 5,
'RoboIME': 6,
'RoboFEI': 7,
'UBC Thunderbots': 8,
'RoboDragons': 9,
'MRL': 10,
'RoboJackets': 11,
'Tritons RCSC': 12,
'Omid': 13,
'URoboRus': 14,
'SRC': 15
}
self.init_referee_counter(self.team_names_to_row)
return
def date_to_hour(self, date):
# Assumes that we start on Monday!
timestamp = datetime.strptime(date, '%Y-%m-%d %H:%M')
hour = (timestamp.timetuple().tm_wday * 24 + 24) - (24 - timestamp.timetuple().tm_hour)
return math.floor(int(hour) / 24), hour
def hour_to_date(self, hour):
# Assumes that we start on Monday!
starttime = datetime.strptime('2021-06-21 00:00', '%Y-%m-%d %H:%M')
date = starttime + timedelta(hours=hour)
return str(date)[0:10], str(date)[11:-3] # date, time
def field_number_to_letter(self, number):
if (number == 0): return 'A'
if (number == 1): return 'B'
if (number == 2): return 'C'
if (number == 3): return 'D'
def field_letter_to_number(self, letter):
if (letter == 'A'): return 0
if (letter == 'B'): return 1
if (letter == 'C'): return 2
if (letter == 'D'): return 3
def get_db_connection(self, name):
database = name + ".db"
conn_schedule = sqlite3.connect('data/' + database)
conn_schedule.row_factory = sqlite3.Row
return conn_schedule
def clear_friendly_requests(self):
conn = self.get_db_connection('friendlies')
cursor = conn.cursor()
cursor.execute('DELETE FROM friendlies')
conn.commit()
conn.close()
def schedule_csv_to_db(self, name, init=False): # use this only once for the initial database
filename = name + '.csv'
conn = self.get_db_connection('schedule')
cursor = conn.cursor()
# write csv to database, update calendar
if (init):
cursor.execute('DELETE FROM schedule') # delete contents to avoid doubles
schedule_updated = open('data/schedule_updated.csv', 'w+')
schedule_updated.close()
reader = csv.reader(open('data/' + filename, 'r'), delimiter=',')
# sortedreader = sorted(reader, key=lambda row: int(row[self.csv_format['time']]), reverse=False)
for data in reader:
# get referees
referee = self.get_referee(data[self.csv_format['time']]) # get referee for the match
day, data[self.csv_format['time']] = self.hour_to_date(int(data[self.csv_format['time']]))
data[self.csv_format['field']] = self.field_number_to_letter(int(data[self.csv_format['field']]))
cursor.execute(
'INSERT INTO schedule(day, teamA, teamB, starttime, field, referee) VALUES (?,?,?,?,?,?)',
(day, data[self.csv_format['teamA']], data[self.csv_format['teamB']], data[self.csv_format['time']],
data[self.csv_format['field']], referee))
self.calHandler.write_event_to_calendar(teamA=data[self.csv_format['teamA']], teamB=data[self.csv_format['teamB']], field=data[self.csv_format['field']],
date=day, time=data[self.csv_format['time']], referee=referee, type='match')
conn.commit()
conn.close()
self.export_schedule_to_csv()
def update_tournament_db(self):
if path.exists('data/new_match.csv'):
print('[DataHandler][update_tournament_db] Entering new matches')
self.update_team_availability(name='new_match', type='csv') # update team availability
self.schedule_csv_to_db('new_match') # add data to database
# remove new_match
os.remove('data/new_match.csv')
else:
return
def export_schedule_to_csv(self):
filename = 'schedule_updated.csv'
writer = csv.writer(open('data/' + filename, 'w', newline=''))
conn = self.get_db_connection('schedule')
cursor = conn.cursor()
data = cursor.execute('SELECT * FROM schedule').fetchall()
for row in data:
date = row['day']
time = row['starttime']
field = self.field_letter_to_number(row['field'])
day, hour = self.date_to_hour(date + ' ' + time)
writer.writerow([row['teamA'], row['teamB'], field, day, hour, row['scoreTeamA'], row['scoreTeamB']])
def update_team_availability(self, type, init=False, name='None', data=None):
if data is None:
data = []
if (init == True):
# set base availability for all teams
base = list(csv.reader(open('data/team_availability_base.csv', 'r'), delimiter=','))
csv.writer(open('data/team_availability.csv', 'w', newline='')).writerows(base)
csv.writer(open('data/team_availability_copy.csv', 'w', newline='')).writerows(base)
# write matches from file to team_availability
reader_availability = csv.reader(open('data/team_availability_copy.csv', 'r'), delimiter=',')
writer = csv.writer(open('data/team_availability.csv', 'w', newline=''))
availability = list(reader_availability)
if (type == 'csv'):
reader_file = csv.reader(open('data/' + name + '.csv', 'r'), delimiter=',')
for row in reader_file:
# set team availability to zero because they have to play a match
availability[self.team_names_to_row[row[self.csv_format['teamA']]]][
int(row[self.csv_format['time']]) + 1] = 0
availability[self.team_names_to_row[row[self.csv_format['teamB']]]][
int(row[self.csv_format['time']]) + 1] = 0
elif (type == 'list'):
availability[self.team_names_to_row[data[0]]][int(data[2]) + 1] = 0
availability[self.team_names_to_row[data[1]]][int(data[2]) + 1] = 0
elif (type == 'ref'):
availability[self.team_names_to_row[data[0]]][int(data[1]) + 1] = 0
elif (type == 'oldref'):
availability[self.team_names_to_row[data[0]]][int(data[1]) + 1] = 1
writer.writerows(availability)
# copy new availability to the copied file
csv.writer(open('data/team_availability_copy.csv', 'w', newline='')).writerows(availability)
# REFEREE STUFF
def init_referee_counter(self, teams):
self.referee_counter = []
self.second_referee_counter = []
for team in teams:
self.referee_counter.append([team, 0])
self.second_referee_counter.append([team, 0])
def find_available_teams(self, hour):
reader = csv.reader(open('data/team_availability.csv', 'r'), delimiter=',')
availability = list(reader)
available_teams = []
for row in availability:
if (int(row[int(hour) + 1]) == 1) and (row[0] != 'MRL'):
available_teams.append(row[0])
return available_teams
def get_referee(self, hour):
teams = self.find_available_teams(hour=hour)
if len(teams) == 0:
return 'OC, TC'
lowest_count = 900 # arbitrary high number
first_referee = ''
for team in teams:
count = self.referee_counter[list(list(zip(*self.referee_counter))[0]).index(team)][1]
if count < lowest_count:
lowest_count = count
first_referee = team
self.update_team_availability(type='ref', data=[first_referee, hour])
self.update_referee_counter(team=first_referee, type='first')
if len(teams) == 1:
return first_referee + ', OC'
# remove first referee from options and determine second
teams.remove(first_referee)
lowest_count = 900
second_referee = ''
for team in teams:
count = self.second_referee_counter[list(list(zip(*self.second_referee_counter))[0]).index(team)][1]
if count < lowest_count:
lowest_count = count
second_referee = team
self.update_team_availability(type='ref', data=[second_referee, hour])
self.update_referee_counter(team=second_referee, type='second')
return first_referee + ', ' + second_referee
def update_referee_counter(self, team, type):
if type == 'first':
self.referee_counter[list(list(zip(*self.referee_counter))[0]).index(team)][1] = \
self.referee_counter[list(list(zip(*self.referee_counter))[0]).index(team)][1] + 1
elif type == 'second':
self.second_referee_counter[list(list(zip(*self.second_referee_counter))[0]).index(team)][1] = \
self.second_referee_counter[list(list(zip(*self.second_referee_counter))[0]).index(team)][1] + 1
elif type == 'old_first':
self.referee_counter[list(list(zip(*self.referee_counter))[0]).index(team)][1] = \
self.referee_counter[list(list(zip(*self.referee_counter))[0]).index(team)][1] - 1
elif type == 'old_second':
self.second_referee_counter[list(list(zip(*self.second_referee_counter))[0]).index(team)][1] = \
self.second_referee_counter[list(list(zip(*self.second_referee_counter))[0]).index(team)][1] - 1