forked from Trygve/otime
738 lines
27 KiB
Python
738 lines
27 KiB
Python
import copy
|
|
import datetime
|
|
import re
|
|
import xml.etree.ElementTree as etree
|
|
import pdf
|
|
|
|
class Runner:
|
|
def __init__(self, id: int, first: str, last: str, club=None, club_id=None,
|
|
country=None, card_id=None, o_class_str=None, o_class=None,
|
|
fork=0, start_time=None, fee_id=None, fee=None):
|
|
self.id = id
|
|
self.first = first
|
|
self.last = last
|
|
self.club = club
|
|
self.club_id = club_id
|
|
self.country = country
|
|
self.card_id = card_id
|
|
self.o_class = o_class
|
|
self.fork = fork
|
|
self.start_time = start_time
|
|
self.fee_id = fee_id
|
|
self.status_override = ''
|
|
def __repr__(self):
|
|
return(f'name({self.fullname()})')
|
|
|
|
def from_ttime_string(ttime_db_line):
|
|
# Reads 1 line of a ttime db
|
|
#https://web.archive.org/web/20191229124046/http://wiki.ttime.no/index.php/Developer
|
|
runner_data = ttime_db_line.split(';')
|
|
eventorid = runner_data[0]
|
|
country = ''
|
|
name = runner_data[2].split(',')
|
|
try:
|
|
first = name[1].strip()
|
|
except:
|
|
first = ''
|
|
last = name[0]
|
|
try:
|
|
club = runner_data[4]
|
|
except:
|
|
club = ''
|
|
try:
|
|
card = int(runner_data[6])
|
|
except:
|
|
card = 0
|
|
try:
|
|
o_class = runner_data[3]
|
|
except:
|
|
o_class = ''
|
|
options = runner_data[5].split(',')
|
|
try:
|
|
club_id = options[options.index('A')+3]
|
|
except:
|
|
club_id = 0
|
|
try:
|
|
start_time = options[options.index('U')+1]
|
|
except:
|
|
start_time = None
|
|
return Runner(eventorid, first, last, club=club, club_id=club_id,
|
|
country=country, card_id=card, o_class=o_class, start_time=start_time)
|
|
|
|
def fullname(self):
|
|
return '{} {}'.format(self.first, self.last)
|
|
|
|
# TODO: må forbedres
|
|
def rank(self, allrunners):
|
|
c_ranked = rank_runners(allrunners, self.o_class)
|
|
try:
|
|
return c_ranked.index(self) + 1
|
|
except ValueError:
|
|
return None
|
|
|
|
def get_codes(self):
|
|
if self.o_class.course.forked is False:
|
|
return self.o_class.course.codes
|
|
else:
|
|
return self.o_class.course.variations[self.fork]
|
|
|
|
# TODO: Mange bugs med løyper som har samme post flere ganger
|
|
# Used for making result files and tables
|
|
def get_splits(self):
|
|
if self.status() == 'OK':
|
|
splits_cpy = self.card_r.splits.copy()
|
|
for control in self.card_r.controls:
|
|
if control not in self.res_codes():
|
|
index = self.card_r.controls.index(control)
|
|
split = self.card_r.splits[index]
|
|
splits_cpy.remove(split)
|
|
return splits_cpy
|
|
|
|
else:
|
|
splits_cpy = self.card_r.splits.copy()
|
|
for control in self.card_r.controls:
|
|
if control not in self.res_codes():
|
|
index = self.card_r.controls.index(control)
|
|
split = self.card_r.splits[index]
|
|
try:
|
|
splits_cpy.remove(split)
|
|
except Exception:
|
|
print('aaaaaa')
|
|
|
|
|
|
punches = self.card_r.controls.copy()
|
|
splits = []
|
|
for code in self.res_codes():
|
|
if punches[0] == code:
|
|
splits.append(splits_cpy[0])
|
|
splits_cpy.pop(0)
|
|
punches.pop(0)
|
|
continue
|
|
else:
|
|
splits.append(None)
|
|
return splits
|
|
|
|
def asdict(self):
|
|
return {
|
|
'id': self.id,
|
|
'first': self.first,
|
|
'last': self.last,
|
|
'club_id': self.club_id,
|
|
'club': self.club,
|
|
'country': self.country,
|
|
'card': self.card,
|
|
'o_class_str': self.o_class_str,
|
|
'fork' : self.fork,
|
|
'start_time': self.start_time,
|
|
'fee_id': self.fee_id
|
|
}
|
|
|
|
class CardDump:
|
|
def __init__(self, card, controls, splits, read_time, s_time, f_time):
|
|
self.card = card
|
|
self.controls = controls
|
|
self.splits = splits
|
|
self.read_time = read_time
|
|
self.s_time = s_time
|
|
self.f_time = f_time
|
|
|
|
def __repr__(self):
|
|
return f'card({self.card}) controls({self.controls}) splits({self.splits})'
|
|
|
|
def from_mtr_bytes(datamsg):
|
|
card = int.from_bytes(datamsg[20:23], 'little')
|
|
|
|
#Extract codes and splits:
|
|
controls = []
|
|
splits = []
|
|
splits_offset = 26
|
|
code_numbytes = 1
|
|
time_numbytes = 2
|
|
split_numbytes = code_numbytes + time_numbytes
|
|
for split_index in range(50):
|
|
code_offset = splits_offset + split_index * split_numbytes
|
|
time_offset = code_offset + code_numbytes
|
|
code = int.from_bytes(datamsg[code_offset:code_offset+code_numbytes], 'little')
|
|
time = int.from_bytes(datamsg[time_offset:time_offset+time_numbytes], 'little')
|
|
if code != 0:
|
|
controls.append(code)
|
|
splits.append(time)
|
|
|
|
# Extract start time:
|
|
year = int.from_bytes(datamsg[8:9], 'little')
|
|
month = int.from_bytes(datamsg[9:10], 'little')
|
|
day = int.from_bytes(datamsg[10:11], 'little')
|
|
hours = int.from_bytes(datamsg[11:12], 'little')
|
|
minutes = int.from_bytes(datamsg[12:13], 'little')
|
|
seconds = int.from_bytes(datamsg[13:14], 'little')
|
|
milliseconds = int.from_bytes(datamsg[14:16], 'little')
|
|
|
|
read_time = datetime.datetime(year, month, day, hours, minutes, seconds, milliseconds)
|
|
if len(controls) > 2:
|
|
s_time = read_time - datetime.timedelta(seconds=splits[-1])
|
|
f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2]))
|
|
else:
|
|
s_time = read_time
|
|
f_time = read_time
|
|
|
|
return(CardDump(card, controls, splits, read_time, s_time, f_time))
|
|
|
|
def list_from_mtr_f(mtr_file):
|
|
with open(mtr_file) as f:
|
|
data = [i.replace('"','').split(',') for i in f.readlines()]
|
|
cards = []
|
|
# hver rad er brikkenummer med tilhørende info
|
|
for row in data:
|
|
controls = []
|
|
splits = []
|
|
# postkodene kommer på oddetall fra og med den 11. De blir hevet inn i controls
|
|
for item in row[11::2]:
|
|
if item == '250':
|
|
controls.append(int(item))
|
|
break
|
|
elif item == '000':
|
|
break
|
|
else:
|
|
controls.append(int(item))
|
|
# strekktidene kommer på partall fra og med den 12. De blir hevet i splits.
|
|
for item in row[12::2]:
|
|
if item == '00000':
|
|
break
|
|
else:
|
|
splits.append(int(item))
|
|
# looper gjonnom løperobjektene og legger til poster og strekktider + start og sluttid
|
|
# usikker på om dette er riktig klokeslett
|
|
tl = row[5].split(' ')
|
|
tl[0] = tl[0].split('.')
|
|
tl[0][2] = '20' + tl[0][2]
|
|
tl[0] = list(map(int, tl[0]))
|
|
tl[1] = tl[1].split(':')
|
|
tl[1][2] = float(tl[1][2])
|
|
tl[1] = list(map(int, tl[1]))
|
|
read_time = datetime.datetime(tl[0][2], tl[0][1], tl[0][0], tl[1][0], tl[1][1], tl[1][2])
|
|
if len(controls) > 2 and len(splits) > 2:
|
|
s_time = read_time - datetime.timedelta(seconds=splits[-1])
|
|
f_time = read_time - (datetime.timedelta(seconds=splits[-1]) + datetime.timedelta(seconds=splits[-2]))
|
|
else:
|
|
s_time = read_time
|
|
f_time = read_time
|
|
cards.append(CardDump(int(row[6]), controls, splits, read_time, s_time, f_time))
|
|
return cards
|
|
|
|
def asdict(self):
|
|
return {
|
|
'card': self.card,
|
|
'controls': self.controls,
|
|
'splits': self.splits,
|
|
'read_time': self.read_time.isoformat(),
|
|
's_time': self.s_time.isoformat(),
|
|
'f_time': self.f_time.isoformat()
|
|
}
|
|
|
|
# Stored in Event.courses
|
|
class Course:
|
|
def __init__(self, name, codes, forked=False, variations=None):
|
|
self.name = name
|
|
self.codes = codes
|
|
self.forked = forked
|
|
# Variations is a list
|
|
self.variations = variations
|
|
|
|
def __repr__(self):
|
|
return f'name({self.name})'
|
|
|
|
def asdict(self):
|
|
return {
|
|
'name': self.name,
|
|
'codes': self.codes,
|
|
'forked': self.forked,
|
|
'variations': self.variations
|
|
}
|
|
|
|
# Stored in Event.o_classes
|
|
class OClass:
|
|
def __init__(self, name, course):
|
|
self.name = name
|
|
self.course = course
|
|
|
|
def __repr__(self):
|
|
return f'name({self.name})'
|
|
|
|
class RunnerResult:
|
|
def __init__(self, runner_id: int, first: str, last: str, status: str, place: int, total_time: int, splits: list[int], end_time,
|
|
club=None, club_id=None, country=None, card_id=None, o_class=None, controls=None, fork=0, start_time=None, fee_id=None):
|
|
self.id = runner_id
|
|
self.first = first
|
|
self.last = last
|
|
self.club = club
|
|
self.country = country
|
|
self.card_id = card_id
|
|
self.o_class = o_class
|
|
self.controls = controls
|
|
self.fork = fork
|
|
self.start_time = start_time
|
|
self.fee_id = fee_id
|
|
|
|
self.status = status
|
|
self.place = place
|
|
self.total_time = total_time
|
|
self.splits = splits
|
|
self.end_time = end_time
|
|
|
|
def fullname(self):
|
|
return f'{self.first} {self.last}'
|
|
|
|
class ClassResult:
|
|
def __init__(self, name: str, course: Course, runner_results: list[RunnerResult]):
|
|
self.name = name
|
|
self.course = course
|
|
self.runner_results = runner_results
|
|
|
|
class Event:
|
|
def __init__(self, eventid, name, start_time=None, end_time=None,
|
|
organiser=None, courses=[], o_classes=[], runners=[],
|
|
card_dumps=[], fees=[]):
|
|
self.id = eventid
|
|
self.name = name
|
|
self.start_time = start_time
|
|
self.end_time = end_time
|
|
self.organiser = organiser
|
|
self.courses = courses
|
|
self.o_classes = o_classes
|
|
self.runners = runners
|
|
self.card_dumps = card_dumps
|
|
self.fees = fees
|
|
|
|
def __repr__(self):
|
|
return(f'id({self.id}), name({self.name}), organiser({self.organiser}), courses({self.courses}), o_classes({self.o_classes}), runners({self.runners})')
|
|
|
|
def add_course(self, *args):
|
|
for n in args:
|
|
self.courses.append(n)
|
|
|
|
def add_o_class(self, *args):
|
|
for n in args:
|
|
self.o_classes.append(n)
|
|
|
|
def add_runners(self, *args):
|
|
for n in args:
|
|
self.runners.append(n)
|
|
|
|
def get_runners_in_o_class(self, o_class: str) -> list[Runner]:
|
|
return [i for i in self.runners if i.o_class == o_class]
|
|
|
|
def add_fees(self, *args):
|
|
for n in args:
|
|
self.fees.append(n)
|
|
|
|
def get_course(self, name):
|
|
return next((copy.copy(i) for i in self.courses if i.name == name), None)
|
|
|
|
def get_o_class(self, name):
|
|
return next((copy.copy(i) for i in self.o_classes if i.name == name), None)
|
|
|
|
def get_card_dump(self, id):
|
|
return next((copy.copy(i) for i in self.card_dumps if i.card == id), None)
|
|
|
|
def get_runner(self, id):
|
|
return next((copy.copy(i) for i in self.runners if i.id == id), None)
|
|
|
|
def get_runner_status(self, id):
|
|
# https://github.com/international-orienteering-federation/datastandard-v3/blob/24eb108e4c6b5e2904e5f8f0e49142e45e2c5230/IOF.xsd#L2903C3-L2903C3
|
|
runner = self.get_runner(id)
|
|
if runner.status_override: return runner.status_override
|
|
o_class = self.get_o_class(runner.o_class)
|
|
course = self.get_course(o_class.course)
|
|
if self.get_card_dump(runner.card_id) == None:
|
|
return 'Active'
|
|
if contains(course.codes, self.get_card_dump(runner.card_id).controls):
|
|
return 'OK'
|
|
else:
|
|
return 'MissingPunch'
|
|
|
|
def get_runner_time(self, id):
|
|
runner = self.get_runner(id)
|
|
card_dump = self.get_card_dump(runner.card_id)
|
|
if card_dump == None:
|
|
return False
|
|
|
|
f_control = card_dump.controls[-1]
|
|
# TODO: Må gjøres mer robust
|
|
try:
|
|
index = card_dump.controls.index(f_control)
|
|
return card_dump.splits[index]
|
|
except:
|
|
return False
|
|
|
|
def get_runner_splits(self, id):
|
|
try:
|
|
runner = self.get_runner(id)
|
|
card_dump = self.get_card_dump(runner.card_id)
|
|
course = self.get_course(self.get_o_class(runner.o_class).course)
|
|
except AttributeError:
|
|
return None
|
|
|
|
if card_dump == None:
|
|
return None
|
|
|
|
split_iter = zip(card_dump.controls, card_dump.splits).__iter__()
|
|
splits = [0] * len(course.codes)
|
|
for n, control in enumerate(course.codes):
|
|
if control not in card_dump.controls:
|
|
continue
|
|
split_debt = 0
|
|
while True:
|
|
try:
|
|
punched_control, split = next(split_iter)
|
|
except StopIteration:
|
|
break
|
|
if punched_control == control:
|
|
splits[n] = split + split_debt
|
|
break
|
|
else:
|
|
split_debt += split
|
|
return splits
|
|
|
|
def get_runner_controls(self, id):
|
|
try:
|
|
return self.get_card_dump(self.get_runner(id).card_id).controls
|
|
except AttributeError:
|
|
return None
|
|
|
|
def get_runner_end_clock(self, id):
|
|
try:
|
|
return self.get_card_dump(self.get_runner(id).card_id).f_time
|
|
except AttributeError:
|
|
return None
|
|
|
|
def get_result(self, o_classes: list[str] = []) -> list[ClassResult]:
|
|
if not o_classes:
|
|
o_classes = [i.name for i in self.o_classes]
|
|
return [produce_class_result(copy.deepcopy(self), i) for i in o_classes]
|
|
|
|
def read_xml_entries(self, xml_file):
|
|
self.add_runners(*runners_from_xml_entries(xml_file))
|
|
self.add_fees(*fees_from_xml_entries(xml_file))
|
|
|
|
# Må endres
|
|
def from_xml_entries(xml_file):
|
|
tree = ET.parse(xml_file)
|
|
root = tree.getroot()
|
|
|
|
url = '{http://www.orienteering.org/datastandard/3.0}'
|
|
event_el = root.find(f'./{url}Event')
|
|
event_id = int(event_el.find(f'./{url}Id').text)
|
|
name = event_el.find(f'./{url}Name').text
|
|
organiser = event_el.find(f'./{url}Organiser/{url}Name').text
|
|
|
|
start_ds = event_el.find(f'./{url}StartTime/{url}Date').text
|
|
start_ts = event_el.find(f'./{url}StartTime/{url}Time').text[:-1]
|
|
start_time = datetime.datetime.fromisoformat(f'{start_ds}T{start_ts}')
|
|
|
|
end_ds = event_el.find(f'./{url}EndTime/{url}Date').text
|
|
end_ts = event_el.find(f'./{url}EndTime/{url}Time').text[:-1]
|
|
end_time = datetime.datetime.fromisoformat(f'{end_ds}T{end_ts}')
|
|
|
|
runners = runners_from_xml_entries(xml_file)
|
|
fees = fees_from_xml_entries(xml_file)
|
|
|
|
return Event(event_id, name, organiser=organiser, runners=runners,
|
|
fees=fees, start_time=start_time, end_time=end_time)
|
|
|
|
def read_xml_courses(self, xml_file):
|
|
self.courses = courses_from_xml(xml_file)
|
|
|
|
def read_ttime_cnf(self, ttime_file):
|
|
self.add_course(*courses_from_ttime_conf(ttime_file))
|
|
self.add_o_class(*classes_from_ttime_conf(ttime_file, self.courses))
|
|
|
|
def read_ttime_db(self, ttime_file):
|
|
with open(ttime_file) as f:
|
|
data = f.readlines()
|
|
self.runners = [Runner.from_ttime_string(i) for i in data if i]
|
|
|
|
def read_mtr_file(self, mtr_file):
|
|
self.card_dumps = CardDump.list_from_mtr_f(mtr_file)
|
|
|
|
def create_start_list_pdf(self, file_path):
|
|
pdf.create_start_list(copy.deepcopy(self), file_path)
|
|
|
|
def create_result_pdf(self, file_path):
|
|
pdf.create_result_list(copy.deepcopy(self), file_path)
|
|
|
|
def create_result_xml(self):
|
|
root = ET.Element('ResultList')
|
|
root.set('xmlns', 'http://www.orienteering.org/datastandard/3.0')
|
|
root.set('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance')
|
|
root.set('iofVersion', '3.0')
|
|
root.set('createTime', datetime.datetime.now().isoformat(timespec='seconds'))
|
|
root.set('creator', 'oTime')
|
|
root.set('status', 'Complete')
|
|
tree = ET.ElementTree(root)
|
|
event = ET.SubElement(root, 'Event')
|
|
xml_child(event, 'Id', self.id)
|
|
xml_child(event, 'Name', self.name)
|
|
for i in self.o_classes:
|
|
print('Hmmmmmm')
|
|
# <ClassResult>
|
|
class_result = ET.SubElement(root, 'ClassResult')
|
|
# <Class>
|
|
t = ET.SubElement(class_result, 'Class')
|
|
xml_child(t, 'Name', i.name)
|
|
# <PersonResult>
|
|
runners_same_c = get_runners_in_class(self.runners, i)
|
|
runners_ranked = rank_runners(runners_same_c, i)
|
|
# Put the OK runners first and Active last
|
|
runners_sorted = [i for i in runners_same_c if i not in runners_ranked]
|
|
runners_ranked.extend(runners_sorted)
|
|
|
|
for n in runners_ranked:
|
|
person_result = ET.SubElement(class_result, 'PersonResult')
|
|
# <Person>
|
|
person = ET.SubElement(person_result, 'Person')
|
|
xml_child(person, 'Id', n.id)
|
|
# <Name>
|
|
name = ET.SubElement(person, 'Name')
|
|
xml_child(name, 'Family', n.last)
|
|
xml_child(name, 'Given', n.first)
|
|
# </Name>
|
|
# </Person>
|
|
# <Organisation>
|
|
org = ET.SubElement(person_result, 'Organisation')
|
|
xml_child(org, 'Id', n.club_id)
|
|
xml_child(org, 'Name', n.club)
|
|
country = ET.SubElement(org, 'Country')
|
|
# TODO: hent land fra løperobjektet
|
|
country.text = 'Norway'
|
|
country.set('code', 'NOR')
|
|
# </Organisation>
|
|
# <Result>
|
|
result = ET.SubElement(person_result, 'Result')
|
|
|
|
# TODO: Dette bør skrives om til å bruke Runner metoder så mye som mulig.
|
|
if hasattr(n, 'card_r') and len(n.card_r.splits) > 2:
|
|
xml_child(result, 'StartTime', n.card_r.s_time.isoformat())
|
|
xml_child(result, 'FinishTime', n.card_r.f_time.isoformat())
|
|
xml_child(result, 'Time', n.totaltime())
|
|
if n.status() == 'OK':
|
|
# <TimeBehind>
|
|
xml_child(result, 'TimeBehind', n.totaltime() - runners_ranked[0].totaltime())
|
|
# </TimeBehind>
|
|
xml_child(result, 'Position', n.rank(self.runners))
|
|
xml_child(result, 'Status', n.status())
|
|
# <SplitTime>
|
|
# TODO: ta utgangspunkt i løypa, ikke det brikka har stempla
|
|
for code, split in zip(n.card_r.controls, n.card_r.splits):
|
|
st = ET.SubElement(result, 'SplitTime')
|
|
xml_child(st, 'ControlCode', code)
|
|
xml_child(st, 'Time', split)
|
|
if code == n.res_codes()[-1]:
|
|
break
|
|
# </SplitTime>
|
|
elif n.status() == 'Disqualified':
|
|
xml_child(result, 'Status', n.status())
|
|
for code, split in zip(n.res_codes(), n.res_splits()):
|
|
st = ET.SubElement(result, 'SplitTime')
|
|
xml_child(st, 'ControlCode', code)
|
|
if split is not None:
|
|
xml_child(st, 'Time', split)
|
|
else:
|
|
xml_child(result, 'Status', n.status())
|
|
else:
|
|
xml_child(result, 'Status', n.status())
|
|
# </Result>
|
|
# </PersonResult>
|
|
# </Class>
|
|
ET.indent(root, space=' ', level=0)
|
|
return tree
|
|
|
|
class Fee:
|
|
def __init__(self, fee_id, name, currency, amount, from_birth_date=None,
|
|
to_birth_date=None):
|
|
self.id = fee_id
|
|
self.name = name
|
|
self.currency = currency
|
|
self.amount = amount
|
|
self.from_birth_date = from_birth_date
|
|
self.to_birth_date = to_birth_date
|
|
|
|
def asdict(self):
|
|
return {
|
|
'id': self.id,
|
|
'name': self.name,
|
|
'currency': self.currency,
|
|
'amount': self.amount,
|
|
'from_birth_date': self.from_birth_date,
|
|
'to_birth_date': self.to_birth_date
|
|
}
|
|
|
|
def produce_class_result(event, o_class_name) -> ClassResult:
|
|
o_class = event.get_o_class(o_class_name)
|
|
runners = event.get_runners_in_o_class(o_class_name)
|
|
ok_runners = [i for i in runners if event.get_runner_status(i.id) == 'OK']
|
|
ok_runners.sort(key=lambda i: event.get_runner_time(i.id))
|
|
dsq_runners = [i for i in runners if event.get_runner_status(i.id) == 'MissingPunch' or event.get_runner_status(i.id) == 'Disqualified']
|
|
other_runners = [i for i in runners if i not in ok_runners and i not in dsq_runners]
|
|
|
|
results = [RunnerResult(i.id, i.first, i.last, event.get_runner_status(i.id), ok_runners.index(i)+1, event.get_runner_time(i.id), event.get_runner_splits(i.id),
|
|
event.get_runner_end_clock(i.id), i.club, i.country, i.card_id, i.o_class, event.get_runner_controls(i.id)) for i in ok_runners]
|
|
results += [RunnerResult(i.id, i.first, i.last, event.get_runner_status(i.id), 0, event.get_runner_time(i.id), event.get_runner_splits(i.id),
|
|
event.get_runner_end_clock(i.id), i.club, i.country, i.card_id, i.o_class, event.get_runner_controls(i.id)) for i in dsq_runners]
|
|
results += [RunnerResult(i.id, i.first, i.last, event.get_runner_status(i.id), 0, event.get_runner_time(i.id), event.get_runner_splits(i.id),
|
|
event.get_runner_end_clock(i.id), i.club, i.country, i.card_id, i.o_class, event.get_runner_controls(i.id)) for i in other_runners]
|
|
|
|
return ClassResult(o_class.name, o_class.course, results)
|
|
|
|
# TODO: Take string instead of file.
|
|
def courses_from_ttime_conf(ttime_file):
|
|
with open(ttime_file, 'r') as f:
|
|
data = f.readlines()
|
|
courses = []
|
|
for line in data:
|
|
if '-codes' in line:
|
|
code_list = re.search(r'(?<=\")(.*?)(?=\")', line).group().split(';')
|
|
loops = 0
|
|
for n in code_list:
|
|
n = n.split(',')
|
|
loops += 1
|
|
n = list(map(int, n))
|
|
courses.append(Course('course_'+str(loops), n))
|
|
return courses
|
|
|
|
def classes_from_ttime_conf(ttime_file, courses):
|
|
with open(ttime_file, 'r') as f:
|
|
data = f.readlines()
|
|
o_classes = []
|
|
for line in data:
|
|
if '-courses' in line:
|
|
raw_courselist = re.search(r'(?<=\")(.*?)(?=\")', line).group().split(';')
|
|
loops = 0
|
|
for n in raw_courselist:
|
|
split = n.split(',')
|
|
for i in split:
|
|
o_classes.append(OClass(i, courses[loops].name))
|
|
loops += 1
|
|
return o_classes
|
|
|
|
def runners_from_xml_entries(xml_file):
|
|
tree = ET.parse(xml_file)
|
|
root = tree.getroot()
|
|
|
|
url = '{http://www.orienteering.org/datastandard/3.0}'
|
|
runners = []
|
|
person_entries = root.findall(f'./{url}PersonEntry')
|
|
for p_entry in person_entries:
|
|
|
|
rid = p_entry[1][0].text
|
|
|
|
person = p_entry.find(f'./{url}Person')
|
|
name = person.find(f'./{url}Name')
|
|
first = name.find(f'./{url}Given').text
|
|
last = name.find(f'./{url}Family').text
|
|
|
|
organisation = p_entry.find(f'./{url}Organisation')
|
|
if organisation is not None:
|
|
club_id = organisation.find(f'./{url}Id').text
|
|
club_name = organisation.find(f'./{url}Name').text
|
|
club_name_short = organisation.find(f'./{url}ShortName').text
|
|
country = organisation.find(f'./{url}Country').attrib['code']
|
|
else:
|
|
club_id = club_name = club_name_short = country = None
|
|
|
|
class_el = p_entry.find(f'./{url}Class')
|
|
class_str = class_el.find(f'./{url}Name').text
|
|
|
|
fee_id = int(p_entry.find(f'./{url}AssignedFee/{url}Fee/{url}Id').text)
|
|
|
|
try:
|
|
card = int(p_entry.find(f'./{url}ControlCard').text)
|
|
except AttributeError:
|
|
card = None
|
|
|
|
start_time = None
|
|
runners.append(Runner(rid, first, last, club=club_name, club_id=club_id,
|
|
country=country,card=card, o_class_str=class_str,
|
|
start_time=start_time, fee_id=fee_id))
|
|
return runners
|
|
|
|
def fees_from_xml_entries(xml_file):
|
|
tree = ET.parse(xml_file)
|
|
root = tree.getroot()
|
|
|
|
url = '{http://www.orienteering.org/datastandard/3.0}'
|
|
allfees = root.findall(f'.//{url}Fee')
|
|
added_ids = []
|
|
fee_objs = []
|
|
for fee in allfees:
|
|
f_id = int(fee.find(f'./{url}Id').text)
|
|
if f_id not in added_ids:
|
|
added_ids.append(f_id)
|
|
|
|
fee_id = f_id
|
|
name = fee.find(f'./{url}Name').text
|
|
currency = fee.find(f'./{url}Amount').attrib['currency']
|
|
amount = int(fee.find(f'./{url}Amount').text)
|
|
try:
|
|
from_birth_date = fee.find(f'./{url}FromDateOfBirth').text
|
|
except AttributeError:
|
|
from_birth_date = None
|
|
try:
|
|
to_birth_date = fee.find(f'./{url}ToDateOfBirth').text
|
|
except AttributeError:
|
|
to_birth_date = None
|
|
|
|
fee_objs.append(Fee(fee_id, name, currency, amount,
|
|
from_birth_date=from_birth_date, to_birth_date=to_birth_date))
|
|
return fee_objs
|
|
|
|
def courses_from_xml(xml_file):
|
|
tree = ET.parse(xml_file)
|
|
root = tree.getroot()
|
|
|
|
url = '{http://www.orienteering.org/datastandard/3.0}'
|
|
allcourses = root.findall(f'.//{url}Course')
|
|
courseobjs = []
|
|
for c in allcourses:
|
|
name = c.find(f'./{url}Name').text
|
|
controls = []
|
|
allcontrols = c.findall(f'./{url}CourseControl')
|
|
for n in allcontrols:
|
|
controls.append(n.find(f'./{url}Control').text)
|
|
controls.remove('STA1')
|
|
controls.remove('FIN1')
|
|
controls = [int(l) for l in controls]
|
|
courseobjs.append(Course(name, controls))
|
|
return courseobjs
|
|
|
|
# Checks if small list is in big list
|
|
def contains(small, big):
|
|
valid = True
|
|
mark = 0
|
|
map_bl = []
|
|
for i in small:
|
|
for n, control in enumerate(big[mark:]):
|
|
if i == control:
|
|
mark += n
|
|
map_bl.append(mark)
|
|
break
|
|
else:
|
|
valid = False
|
|
if valid:
|
|
return map_bl
|
|
else:
|
|
return False
|
|
|
|
def rank_runners(allrunners, o_class):
|
|
runners = get_runners_in_class(allrunners, o_class)
|
|
runners_ranked = []
|
|
for i in runners:
|
|
if i.status() == 'OK':
|
|
runners_ranked.append(i)
|
|
runners_ranked.sort(key=lambda x: x.totaltime())
|
|
return runners_ranked
|
|
|
|
|
|
# Used to make creating xml files easier
|
|
def xml_child(parent, tag, content):
|
|
e = ET.SubElement(parent, tag)
|
|
e.text = str(content) |