forked from jlemon/zlogger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mkresults.py
executable file
·1623 lines (1389 loc) · 49.6 KB
/
mkresults.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import sys, argparse
import json
import sqlite3
import os, time, stat
import re
import dateutil.parser
RICHMOND_LAP = 16 * 1000 # 1 lap of richmond = 16.09km
class rider():
def __init__(self, id):
self.id = id
self.pos = []
self.set_info(('Rider', str(id), None, 0, 0, 0, 0, 0))
self.has_info = False
self.finish = []
self.end_time = None
self.dq_time = None
self.dq_reason = None
self.distance = None
self.points = 0
self.end = None
self.strava_id = None
# allow accessing self via r[key]
def __getitem__(self, k):
return getattr(self, k)
def __str__(self):
return '%6d %-35.35s records: %d' % (
self.id, self.name, len(self.pos))
def set_info(self, v):
if not v:
return
self.fname = v[0]
self.lname = v[1]
self.cat = v[2] or 'X'
self.weight = int(v[3])
self.height = int(v[4])
self.age = int(v[5])
self.male = True if int(v[6]) else False
self._power = int(v[7]) or 0 # 0 .. 3
self.power = [ '?', '*', ' ', ' ' ][self._power]
self.name = (self.fname + ' ' + self.lname).encode('utf-8')
self.has_info = True
if len(v) > 8:
self.strava_id = v[8]
cat = None
#
# Try autodetecting cat from name.
# Could filter riders by race tag also.
#
# NAME (X)
# match category in parenthesis at end of name.
m = re.match('.*[(](.)[)]$', self.lname)
cat = m.group(1).upper() if m else None
# NAME X
# match single letter at end of name.
if cat is None:
m = re.match('.*\s(.)$', self.lname)
cat = m.group(1).upper() if m else None
# NAME RACE-X
# match single letter following dash at end of name.
if cat is None:
m = re.match('.*[-](.)$', self.lname)
cat = m.group(1).upper() if m else None
# NAME (RACE X)
# match single letter with trailing paren at end of name.
if cat is None:
m = re.match('.*\s(.)[)]$', self.lname)
cat = m.group(1).upper() if m else None
# NAME RACE-X INFO
# NAME RACE-X) INFO
# match single letter following dash in name.
if cat is None:
m = re.match('.*[-]\s?(.)[ )].*', self.lname)
cat = m.group(1).upper() if m else None
# NAME (X) INFO
# match category in parenthesis in name.
if cat is None:
m = re.match('.*[(](.)[)].*', self.lname)
cat = m.group(1).upper() if m else None
# NAME RACE X) INFO
# match single letter following space in name.
if cat is None:
m = re.match('.*\s(.)[)].*', self.lname)
cat = m.group(1).upper() if m else None
#
# Sanity check cat - force to known categories.
#
if cat is not None:
cat = cat if cat in 'ABCDW' else None
if ((self.cat is None) or (self.cat == 'X')) and \
((cat is not None) and (cat != 'X')):
self.cat = cat
#
# No Database or self-classification, report by start group.
#
if (args.no_cat):
self.cat = 'X'
#
# Rider is DQ'd at this time for the given reason.
# DQ is ignored if rider completes before the timepoint.
#
def set_dq(self, time_ms, reason):
if (self.dq_time is None) or (time_ms < self.dq_time):
self.dq_time = time_ms;
self.dq_reason = reason
def data(self):
return {
'id': self.id, 'fname': self.fname, 'lname': self.lname,
'cat': self.cat, 'height': self.height_cm,
'weight': self.weight_kg,
'power': self.power_type,
'male': True if self.male else False,
'strava_id': self.strava_id
}
#
# Ride properties for external data views.
#
@property
def height_cm(self):
return self.height / 10
#
# weight is kept in grams.
# truncate to kilograms.
@property
def weight_kg(self):
return int((self.weight / 100) + .5)/10.0
@property
def sex(self):
return 'M' if self.male else 'F'
@property
def power_type(self):
return [None, 'zpower', 'smart', 'meter'][self._power]
# distance ridden.
@property
def km(self):
return float(self.meters / 100) / 10
# returns pace in km/hr.
@property
def pace(self):
if self.msec:
v = (float(self.meters) / float(self.msec)) * 3600
return float(int(v * 100)) / 100
else:
return 0
@property
def date(self):
return conf.date
@property
def start_msec(self):
return stamp(self.pos[0].time_ms)
@property
def finish_msec(self):
return stamp(self.end.time_ms)
@property
def ride_msec(self):
return elapsed(self.msec)
@property
def start_hr(self):
return self.pos[0].hr
@property
def finish_hr(self):
return self.end.hr
@property
def ride_id(self):
return conf.id + '.' + conf.date
@property
def ride_uuid(self):
return self.ride_id + '.' + str(self.id)
def summarize_ride(r):
s = r.pos[0]
e = r.end
# for DNF, use last position seen.
if r.dnf:
e = r.pos[-1]
r.mwh = e.mwh - s.mwh
r.meters = e.meters - s.meters
r.msec = e.time_ms - s.time_ms
watts = 0
if r.msec:
watts = (float(r.mwh) * 3600) / r.msec
r.wkg = 0
if r.weight:
wkg = (watts * 1000) / r.weight
r.wkg = float(int(wkg * 100)) / 100
r.watts = int(watts)
if (r.wkg == 0): r.ecat = 'X'
elif (not r.male): r.ecat = 'W'
elif (r.wkg > 4): r.ecat = 'A'
elif (r.wkg > 3.2): r.ecat = 'B'
elif (r.wkg > 2.5): r.ecat = 'C'
else: r.ecat = 'D'
#
# Observed position record, keyed by observation time.
#
class pos():
def __init__(self, v):
self.time_ms = v[0]
self.line_id = int(v[1])
self.forward = int(v[2]) == 1
self.meters = float(v[3])
self.mwh = float(v[4])
self.duration = float(v[5])
self.elevation = float(v[6])
self.speed = float((float(v[7]) or 0) / 1000) # meters/hour
self.hr = float(v[8])
def __str__(self):
return ("time: %d %s line: %d %s metres: %d" %
(self.time_ms, time.ctime(self.time_ms / 1000), self.line_id,
'FWD' if self.forward else 'REV', self.meters))
def data(self):
return {
'time_ms': self.time_ms, 'mwh': self.mwh, 'line': self.line_id,
'duration': self.duration, 'meters': self.meters,
'hr': self.hr, 'speed': self.speed,
'forward': True if self.forward else False }
#
# Get all position events within the specified timeframe.
# Returns a list of riders, containing their position records.
#
def get_riders(begin_ms, end_ms):
R = {}
all_pos = []
c = dbh.cursor()
if hasattr(dbh, '__module__') and dbh.__module__.startswith('mysql'):
query = '''select riderid, msec, lineid, fwd,
meters, mwh, duration, elevation, speed, hr from live_results
where msec between %s and %s and backupwatcher is null order by msec asc'''
else:
query = '''select rider_id, time_ms, line_id, forward,
meters, mwh, duration, elevation, speed, hr from pos
where time_ms between ? and ? order by time_ms asc'''
ret = c.execute(query, (begin_ms, end_ms))
for data in c.fetchall():
id = data[0]
if not id in R:
R[id] = rider(id)
position = pos(data[1:])
R[id].pos.append(position)
if (args.debug):
print id, R[id].pos[-1]
all_pos.append((position, R[id]))
return R, all_pos
#
# Maps the chalkline name into a line_id.
#
def get_line(name):
c = dbh.cursor()
if hasattr(dbh, '__module__') and dbh.__module__.startswith('mysql'):
query = 'select line from chalkline where name = %s limit 1'
else:
query = 'select line_id from chalkline where name = ? limit 1'
c.execute(query, (name,))
data = c.fetchone()
if not data:
sys.exit('Could not find line { %s }' % name)
return int(data[0])
def rider_info(c, r):
if hasattr(dbh, '__module__') and dbh.__module__.startswith('mysql'):
query = 'select fname, lname, cat, weight, height, age, male, zpower from rider_names where rider_id = %s order by retrievaldate desc limit 1'
else:
query = 'select fname, lname, cat, weight, height, age, male, zpower from rider where rider_id = ? limit 1'
c.execute(query, (r.id,))
r.set_info(c.fetchone())
def bulk_rider_info(F, startTime, endTime):
if hasattr(dbh, '__module__') and dbh.__module__.startswith('mysql'):
query = '''
select rider_id, fname, lname, cat, weight, height, age, male, zpower, strava_id
from rider_names
left join athlete_names on rider_id = zwift_id
where rider_id in (%s)
and retrievaldate between from_unixtime(%%s) and from_unixtime(%%s)
order by retrievaldate desc
'''
else:
raise RuntimeError("Sqlite not implemented")
riders = {r.id: r for r in F}
c = dbh.cursor()
format_strings = ','.join(['%s'] * len(riders.keys()))
c.execute(query % format_strings, tuple(riders.keys()) + (startTime, endTime))
for row in c.fetchall():
if row[0] in riders:
riders[row[0]].set_info(row[1:])
del riders[row[0]]
#
# XXX - sample for organized team-only rides.
# XXX - deprecated
def get_odz(R):
ODZ = []
c = dbh.cursor()
for data in c.execute('select rider_id, team, cat from odz'):
id = data[0]
if not id in R:
R[id] = rider(id)
r.cat = r[2]
r.team = r[1]
ODZ.append(r)
return ODZ
MSEC_PER_HOUR = (60 * 60 * 1000)
MSEC_PER_MIN = (60 * 1000)
MSEC_PER_SEC = (1000)
class msec_time():
def __init__(self, msec):
msec = ((msec + 99) / 100) * 100 # roundup
self.hour = msec / MSEC_PER_HOUR
msec = msec - (self.hour * MSEC_PER_HOUR)
self.min = msec / MSEC_PER_MIN
msec = msec - (self.min * MSEC_PER_MIN)
self.sec = msec / MSEC_PER_SEC
msec = msec - (self.sec * MSEC_PER_SEC)
self.msec = msec / 100 # to 1/10th sec
#
# A generator which takes a list of finishers, sorts by finish time,
# saves the placement and time position, then yields the result.
#
def place(F):
place = 0
last_ms = 0
finish = sorted(F, key = lambda r: r.end_time)
for r in finish:
place = place + 1
r.place = place
r.timepos = make_timepos(last_ms, r.pos[0].time_ms, r.end.time_ms)
last_ms = r.end.time_ms
yield r
base_ms = 0
def make_timepos(prev_ms, start_ms, finish_ms):
global base_ms
mark = ' '
if (prev_ms == 0):
#
# save winner's finish timetime - all diffs are from this
#
base_ms = finish_ms
cur_ms = finish_ms - start_ms;
elif ((finish_ms - prev_ms) < 200):
return "--- ST ---"
else:
cur_ms = finish_ms - base_ms
mark = '+'
t = msec_time(cur_ms)
if (t.hour != 0):
timepos = "%2d:%02d:%02d.%d" % (t.hour, t.min, t.sec, t.msec)
elif (t.min != 0):
timepos = "%c %2d:%02d.%d" % (mark, t.min, t.sec, t.msec)
elif (t.sec != 0):
timepos = "%c :%02d.%d" % (mark, t.sec, t.msec)
elif (t.msec != 0):
timepos = "%c :00.%d" % (mark, t.msec)
else:
# s.t. is transitive, return first one
timepos = "--- ST ---";
return timepos
def show_nf(tag, finish):
h1 = '==== %s ' % (tag)
h1 += '=' * (54 - len(h1))
h1 += ' km'
print '\n' + h1
for r in finish:
line = ("%-15.15s %-35.35s %5.1f" %
(r.dq_reason or '',
r.name, r.km))
if (args.ident):
line += " ID %6d" % r.id
line += ' [ ' + r.start_msec + ' - '
if r.end:
line += r.finish_msec + ' ]'
if (args.debug):
line += ' start m=' + str(r.pos[0].meters)
print line
#
# Key is really just name. may have "team results".
# finish records, start_time, start_lead,
# start group AB, but finish results in A and B.
#
# Assume all riders have same start group.
# (otherwise the race doesn't make much sense...)
#
def show_results(F, tag):
N = 28
if not F:
return
grp = F[0].grp
h0 = ' ' * (N + 36);
h0 = '== START @ %s by %.22s' % (hms(grp.start_ms),
grp.starter.name if grp.starter else 'clock')
h0 += ' ' + '=' * (N + 18 - len(h0))
h0 += ' ' * 16
h0 += ' est ht hrtrate'
h1 = '== RESULTS for %s ' % (tag)
h1 += '=' * (N + 19 - len(h1))
h1 += ' km avgW W/kg cat cm beg end'
h1 += ' [ split times in km/hr ]' if args.split else ''
h1 += ' ID [ start time - finish time ]' if args.ident else ''
print '\n' + h0 + '\n' + h1
c = dbh.cursor()
for r in place(F):
s = r.pos[0]
e = r.end
line = ("%3d. %s%c %-*.*s %5.1f %3ld %4.2f %c %3d %3d %3d" % (
r.place,
r.timepos,
r.power,
N, N, r.name,
r.km,
r.watts, r.wkg, r.ecat, r.height_cm,
r.start_hr, r.finish_hr))
if (args.split):
l = s
split = []
end = r.pos.index(r.end)
for p in r.pos[1 : end + 1]:
# XXX - use same line x for split.
if p.line_id != s.line_id:
continue
dist = (p.meters - l.meters)
msec = (p.time_ms - l.time_ms)
pace = (float(dist) / float(msec)) * 3600
split.append("%4.1f" % (pace))
l = p
dist = (l.meters - s.meters)
msec = (l.time_ms - s.time_ms)
pace = (float(dist) / float(msec)) * 3600
split.append("= avg %4.1f" % (pace))
line += ' [ %s ]' % (' '.join(split))
if (args.ident):
line += ' %6d' % r.id
line += ' [ ' + r.start_msec + ' - '
line += r.finish_msec + ' ]'
print line
if (args.update_cat and (r.cat == 'X')):
c.execute('update rider set cat = ? where rider_id = ?',
(ecat, r.id))
dbh.commit();
def results(tag, F):
done = set()
t = msec_time(-time.timezone * 1000)
tzoff = 'UTC%+03d:%02d' % (t.hour, t.min)
print '=' * 80
print '=' * 10,
print '%s %s: %s' % (conf.date, conf.id, conf.name)
print '=' * 10,
print ' start: %s - %s grace: %s min' % (hms(conf.start_ms),
hms(conf.start_ms + conf.start_window_ms), min_sec(conf.grace_ms))
print '=' * 10,
print ' cutoff: %s %s' % (hms(conf.finish_ms), tzoff)
print '=' * 80
#
# create a sorted list of known rider categories
#
C = sorted(list(set([ r.cat for r in F ])))
for cat in C:
L = [ r for r in F if r.cat == cat ]
dnf = set([ r for r in L if filter_dnf(r) ])
dq = set([ r for r in L if filter_dq(r) ]).difference(dnf)
finish = set(L).difference(dq).difference(dnf)
show_results(list(finish), 'CAT ' + cat)
done = set(done).union(finish)
#
# Lump all DQ/dnf together...
#
dnf = set([ r for r in F if filter_dnf(r) ]).difference(done)
dq = set([ r for r in F if filter_dq(r) ]).difference(dnf)
if len(dq):
finish = sorted(dq, key = lambda r: r.distance, reverse = True)
finish = [ r for r in finish if r.distance > 0 ]
show_nf('DQ, all', finish)
if len(dnf):
finish = sorted(dnf, key = lambda r: r.distance, reverse = True)
finish = [ r for r in finish if r.distance > 0 ]
show_nf('DNF, all', finish)
if (True):
return
#
# repeat - show DQ and DNF at end.
#
for cat in C:
L = [ r for r in F if r.cat == cat ]
dnf = set([ r for r in L if filter_dnf(r) ])
dq = set([ r for r in L if filter_dq(r) ]).difference(dnf)
dq = dq - done
dnf = dnf - done
if len(dq):
finish = sorted(dq, key = lambda r: r.distance)
finish = [ r for r in finish if r.distance > 0 ]
show_nf('DQ, CAT ' + cat, finish)
if len(dnf):
finish = sorted(dnf, key = lambda r: r.distance)
finish = [ r for r in finish if r.distance > 0 ]
show_nf('DNF, CAT ' + cat, finish)
def json_cat(F, key, sprints=None):
cat_finish = []
for r in place(F):
s = r.pos[0]
e = r.end
finish = {
'timepos': r.timepos, 'meters': r.meters,
'mwh': r.mwh, 'duration': e.duration - s.duration,
'start_msec': s.time_ms, 'end_msec': e.time_ms,
'watts': r.watts, 'est_cat': r.ecat, 'pos': r.place,
'wkg': r.wkg,
'beg_hr': s.hr, 'end_hr': e.hr, 'points': r.points,
'dq_time': r.dq_time, 'dq_reason': r.dq_reason}
entry = {'rider': r.data(), 'finish': finish }
cat_finish.append(entry)
if not args.split:
continue
cross = []
end = r.pos.index(r.end)
for p in r.pos[0 : end + 1]:
cross.append(p.data())
entry['cross'] = cross
sprint_data = []
if sprints:
for i, s in enumerate(sprints):
sprint = {'name': 'sprint %s' % (i + 1),
'results': [ { 'points': e[0], 'rider_id': e[1].id,
'fname': e[1].fname, 'lname': e[1].lname }
for e in s ] }
sprint_data.append(sprint)
# distance, start_time
return { 'name': key, 'results': cat_finish, 'sprints': sprint_data }
def dump_json(race_name, start_ms, F, sprints):
result = []
C = sorted(list(set([ r.cat for r in F ])))
dq = set([ r for r in F if filter_dq(r) ])
for cat in C:
L = [ r for r in F if r.cat == cat ]
dq = set([ r for r in L if filter_dq(r) ])
dnf = set([ r for r in L if filter_dnf(r) ])
finish = set(L).difference(dq).difference(dnf)
finish = sorted(finish, key = lambda r: r.end_time)
result.append(json_cat(finish, cat))
if sprints:
cat_sprints = sprints.get(cat, None)
else:
cat_sprints = None
result.append(json_cat(finish, cat, cat_sprints))
if len(dq):
finish = sorted(dq, key = lambda r: r.distance)
finish = [ r for r in finish if r.distance > 0 ]
# take last record as finish pos... ugh.
for r in finish:
r.end = r.pos[-1]
r.end_time = r.end.time_ms
result.append(json_cat(finish, 'DQ-' + cat))
if len(dnf):
finish = sorted(dnf, key = lambda r: r.distance)
finish = [ r for r in finish if r.distance > 0 ]
# take last record as finish pos... ugh.
for r in finish:
r.end = r.pos[-1]
r.end_time = r.end.time_ms
result.append(json_cat(finish, 'DNF-' + cat))
race = { 'race': race_name, 'date': conf.date, 'group' : result }
print json.dumps(race)
def min2ms(x):
return int(x * 60 * 1000)
# timestamp msec -> H:M:S
def hms(msec):
t = time.localtime(msec / 1000)
return time.strftime('%H:%M:%S', t)
# timestamp msec -> M:S
def min_sec(msec):
t = time.localtime(msec / 1000)
return time.strftime('%M:%S', t)
# timestamp msec -> H:M:S.frac
def stamp(msec):
return hms(msec) + ('.%03d' % (msec % 1000))
# elapsed msec -> H:M:S.f
def elapsed(msec):
t = msec_time(msec)
return '%02d:%02d:%02d.%d' % (t.hour, t.min, t.sec, t.msec)
def avg_pace(start_pos, end_pos):
msec = float(end_pos.time_ms - start_pos.time_ms)
dist = float(end_pos.meters - start_pos.meters)
if msec:
return (dist / msec) * 3600
else:
return 0
def filter_tag(r, tag):
if not r.has_info:
return True
return re.search(tag, r.name, re.IGNORECASE) is not None
#
# Return only those riders which fall within the start window.
# Trim the position record to the correct start.
#
# rider may have crossed start line, then gone back and restarted.
# yes - happened in KISS race.
# find the _last_ correct line crossing in the start window.
# (may be larger for longer, delaeyed neutrals.
#
def filter_start(r):
start = None
for idx, p in enumerate(r.pos):
# Crossing is outside start window, stop searching.
if (p.time_ms > (conf.start_ms + conf.start_window_ms)):
break
# Skip if this isn't the correct line crossing.
if args.debug:
print "testing line %s forward %s against %s %s" % (p.line_id, p.forward, conf.start_line_id, conf.start_forward)
if (p.line_id != conf.start_line_id) or \
(p.forward != conf.start_forward):
continue
# First crossing seen, take it.
if start is None:
start = idx
continue
# Subsequent crossing.
# - before start window, take it.
if (p.time_ms < conf.start_ms):
start = idx
continue
# Subsequent crossing.
# - less than 3000 meters later, take it.
if ((p.meters - r.pos[start].meters) < 3000):
start = idx
continue
if start is None:
return False
s = r.pos[start]
# If there is a rider corral, and rider isn't a late starter,
# then perform further checks. (late starters can just fly through...)
if conf.corral_line and \
(s.time_ms < (conf.start_ms + (20 * MSEC_PER_SEC))):
# Find last crossing of corral line, from start.
for p in r.pos[start::-1]:
if (p.line_id != conf.corral_line_id):
continue
#
# make sure average pace through the corral is low.
#
pace = avg_pace(p, s)
if (pace > 18):
r.set_dq(p.time_ms, 'Corral: %2d km/h' % (pace))
break
del(r.pos[0:start])
if (args.debug):
print 'START', r.id, r.pos[0]
return True
#
# Starting with the second position (start has already been validated)
# check position records against course.
# (currently just checks alternate finish line crossings for w8topia)
#
# This should trim and flag any rides which do not match the course.
# distance and correct finish is validated later.
#
def trim_course(r):
forward = conf.start_forward
for idx, p in enumerate(r.pos[1:]):
if not (p.line_id == conf.finish_line_id):
continue
if conf.alternate is not None:
forward = not forward
if (p.forward != forward):
# crossed finish line in wrong direction
# trim the ride. idx starts at 0, so add one.
if (args.debug):
print 'WRONG', r.id, '%s' % ('fwd' if forward else 'rev'), p
r.set_dq(p.time_ms, "WRONG COURSE")
del (r.pos[idx + 1:])
break
return True
#
# Trims position records and sets maximum distance.
#
def trim_crash(r):
s = r.pos[0]
l = s
r.distance = 0
for idx, p in enumerate(r.pos[1:]):
d = p.meters - s.meters
if (p.meters < l.meters):
r.set_dq(p.time_ms, "----CRASHED---")
r.distance = max(r.distance, p.meters)
del(r.pos[idx + 1:])
break
r.distance = d # distance so far
if (p.mwh < l.mwh):
r.set_dq(p.time_ms, "----CRASHED---")
del(r.pos[idx + 1:])
break
if (p.duration < l.duration):
r.set_dq(p.time_ms, "----CRASHED---")
del(r.pos[idx + 1:])
break
return True
#
# Better off just to have a set of results for each class.
# then results just pick the "ASSIGNED" class, or the best weighted one.
#
class grp_finish():
def __init__(self, r, grp):
self.grp = grp
self.pos = None
self.dq_time = None
self.dq_reason = None
r.finish.append(self)
s = r.pos[0]
for idx, p in enumerate(r.pos[1:]):
if ((p.meters - s.meters) >= grp.distance) and \
(p.line_id == conf.finish_line_id) and \
(p.forward == conf.finish_forward):
self.pos = p
break
# if no end position, this is a DNF. (or crash)
if self.pos is None:
return
if (r.pos[0].time_ms > grp.start_ms):
return
#
# If jumped before grace period, set DQ (or apply penalty?)
#
if (r.pos[0].time_ms < (grp.start_ms - conf.grace_ms)):
t = msec_time(grp.start_ms - r.pos[0].time_ms)
self.dq_time = grp.start_ms
self.dq_reason = 'Early: -%2d:%02d' % (t.min, t.sec)
#
# Start with the time delta to this group start.
# Straight DNF == 0
# DQ without completing the required distance: -3
# DQ after completing ride: 2
# Successful ride: 10
#
def weight(self, r):
weight = -abs(self.grp.start_ms - r.pos[0].time_ms) / 1000
if self.dq_reason is not None:
weight = weight - 3
if self.pos is not None:
weight = weight + 10
return weight
#
# Select the appropriate finish group.
# Finish groups determine start time / dq / dnf.
#
def select_finish(r):
finish = max(r.finish, key = lambda f: f.weight(r))
if (r.cat == 'X') and args.no_cat:
r.cat = finish.grp.name # group all finishes together.
else:
#
# match any groups which have the cat letter in their name.
# if no match (group 'all', or cat 'W'), select the best one.
#
F = [ f for f in r.finish if r.cat in f.grp.name ]
finish = max(F, key = lambda f: f.weight(r)) if F else finish
if finish.dq_reason and (r.dq_reason is None):
r.set_dq(finish.dq_time, finish.dq_reason)
r.grp = finish.grp
r.end = finish.pos
if r.end is not None:
r.end_time = r.end.time_ms
#
# only one of dnf, dq should be true.
#
r.dnf = True if r.end is None else False
if ((r.dq_time is not None) and (not r.dnf) and \
(r.dq_time < r.end.time_ms)):
r.dq = True
else:
r.dq = False
# create the ride summary data for this finish.
summarize_ride(r)
#
# Calculate points for each rider by iterating through all the points
# definitions
# note: only call after select_finish has been called on all riders
#
def calculate_points(all_pos, points, points_final):
points_defs = {}
cur_defs = {}
next_defs = {}
sprints = {}
sprint_positions = {}
end_positions = {}
current_sprints = {}
end_sprints = {}
for cat in ('A', 'B', 'C', 'D', 'W'):
points_defs[cat] = iter(sorted(points, key=lambda p: p.distance))
cur_defs[cat] = next(points_defs[cat], None)
next_defs[cat] = next(points_defs[cat], None)
sprints[cat] = []
for p in all_pos:
(position, r) = p
if r.cat not in ('A', 'B', 'C', 'D', 'W'):
continue
if r.dq_time:
continue
distance = position.meters - r.pos[0].meters
if distance >= cur_defs[r.cat].distance:
while next_defs[r.cat] and distance >= next_defs[r.cat].distance:
cur_defs[r.cat] = next_defs[r.cat]
next_defs[r.cat] = next(points_defs[r.cat], None)
sprint_positions[r.cat] = 0
if current_sprints.get(r.cat, None):
sprints[r.cat].append(current_sprints[r.cat])
current_sprints[r.cat] = []
if r.end and (position.meters < r.end.meters) and \
(position.line_id == cur_defs[r.cat].line_id):
place = sprint_positions.get(r.cat, 0) + 1
sprint_positions[r.cat] = place
if place <= len(cur_defs[r.cat].points):
points = cur_defs[r.cat].points[place - 1]
r.points += points
if r.cat in current_sprints:
current_sprints[r.cat].append((points, r))
else:
current_sprints[r.cat] = [(points, r)]
if r.end and position.meters == r.end.meters:
place = end_positions.get(r.cat, 0) + 1
end_positions[r.cat] = place
if place <= len(points_final):
points = points_final[place - 1]
r.points += points
if r.cat in end_sprints:
end_sprints[r.cat].append((points, r))
else:
end_sprints[r.cat] = [(points, r)]
for cat in ('A', 'B', 'C', 'D', 'W'):
if current_sprints.get(cat, None):
sprints[cat].append(current_sprints[cat])
if end_sprints.get(cat, None):
sprints[cat].append(end_sprints[cat])
return sprints
#
# DNF = valid start, but distance < full distance.
# DQ = valid distance, but something went wrong.
#
def filter_dq(r):
return r.dq
def filter_dnf(r):
return r.dnf
def strT_to_sec(val):
m = re.match('(\d+):(\d+)', val)
if m:
return (int(m.group(1)) * 60) + int(m.group(2))
m = re.match('(\d+)', val)
if m:
return int(m.group(1))
sys.exit('Could not parse time %s' % val)
#
# XXX
# fix -- this is really a start group, not a single cat.
# cat (ABCDW) are determined by rider info.
#