forked from esitarski/CrossMgr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.py
More file actions
2828 lines (2344 loc) · 80.5 KB
/
Copy pathModel.py
File metadata and controls
2828 lines (2344 loc) · 80.5 KB
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
import os
import io
import re
import six
import sys
import math
import time
import copy
import bisect
import socket
import random
import getpass
import datetime
import itertools
import functools
import operator
import traceback
import threading
from os.path import commonprefix
from collections import defaultdict
import Utils
import LapStats
import Version
from BatchPublishAttrs import setDefaultRaceAttr
import minimal_intervals
from InSortedIntervalList import InSortedIntervalList
CurrentUser = getpass.getuser()
CurrentComputer = socket.gethostname()
maxInterpolateTime = 7.0*60.0*60.0 # 7 hours.
lock = threading.RLock()
#----------------------------------------------------------------------
class memoize(object):
"""
Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
Does NOT work with kwargs.
"""
cache = {}
rlock = threading.RLock()
@classmethod
def clear( cls ):
cls.cache = {}
def __init__(self, func):
# print( 'memoize:', func.__name__ )
self.func = func
def __call__(self, *args):
# print( self.func.__name__, args )
try:
return memoize.cache[self.func.__name__][args]
except KeyError:
with self.rlock:
value = self.func(*args)
memoize.cache.setdefault(self.func.__name__, {})[args] = value
return value
except TypeError:
with self.rlock:
# uncachable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
with self.rlock:
return self.func(*args)
def __repr__(self):
"""Return the function's docstring."""
return self.func.__doc__
def __get__(self, obj, objtype):
"""Support instance methods."""
return functools.partial(self.__call__, obj)
#------------------------------------------------------------------------------
# Define a global current race.
race = None
def getRace():
global race
return race
def newRace():
global race
memoize.clear()
race = Race()
return race
def setRace( r ):
global race
memoize.clear()
race = r
if race:
race.setChanged()
def resetCache():
memoize.clear()
class LockRace:
def __enter__(self):
lock.acquire()
return race
def __exit__( self, type, value, traceback ):
lock.release()
return False
#----------------------------------------------------------------------
def SetToIntervals( s ):
if not s:
return []
all_nums = sorted( s )
nBegin = nLast = all_nums.pop( 0 )
intervals = []
for n in all_nums:
if n != nLast + 1:
intervals.append( (nBegin, nLast) )
nBegin = n
nLast = n
intervals.append( (nBegin, nLast) )
return intervals
def IntervalsToSet( intervals ):
return set.union( *[set(range(i[0], i[1]+1)) for i in intervals] ) if intervals else set()
#----------------------------------------------------------------------
class Category(object):
DistanceByLap = 0
DistanceByRace = 1
badRangeCharsRE = re.compile( u'[^0-9,\-]' )
active = True
CatWave = 0
CatComponent = 1
CatCustom = 2
catType = 0
publishFlag = True
uploadFlag = True
seriesFlag = True
distance = None
firstLapDistance = None
distanceType = DistanceByLap
raceMinutes = None
lappedRidersMustContinue = False
prizes = []
MaxBib = 999999
# Attributes to be merged from existing catgories in category import or when reading categories from the Excel sheet.
MergeAttributes = (
'active',
'numLaps',
'raceMinutes',
'startOffset',
'distance',
'distanceType',
'firstLapDistance',
'publishFlag',
'uploadFlag',
'seriesFlag',
'catType',
)
PublishFlags = tuple( a for a in MergeAttributes if a.endswith('Flag') )
def _getStr( self ):
s = ['{}'.format(i[0]) if i[0] == i[1] else '{}-{}'.format(*i) for i in self.intervals]
s.extend( ['-{}'.format(i[0]) if i[0] == i[1] else '-{}-{}'.format(*i) for i in SetToIntervals(self.exclude)] )
return ','.join( s )
def _setStr( self, s ):
s = self.badRangeCharsRE.sub( u'', u'{}'.format(s) )
if not s:
s = u'{}-{}'.format(self.MaxBib, self.MaxBib)
self.intervals = []
self.exclude = set()
for f in s.split(','):
if not f:
continue
try:
if f.startswith('-'): # Check for exclusion.
f = f[1:]
isExclusion = True
else:
isExclusion = False
bounds = [int(b) for b in f.split('-') if b]
if not bounds:
continue
if len(bounds) > 2: # Fix numbers not in proper x-y range format.
del bounds[2:]
elif len(bounds) == 1:
bounds.append( bounds[0] )
bounds[0] = min(bounds[0], self.MaxBib) # Keep the numbers in a reasonable range to avoid performance issues.
bounds[1] = min(bounds[1], self.MaxBib)
if bounds[0] > bounds[1]: # Swap the range if out of order.
bounds[0], bounds[1] = bounds[1], bounds[0]
if isExclusion:
self.exclude.update( range(bounds[0], bounds[1]+1) )
else:
self.intervals.append( tuple(bounds) )
except Exception as e:
# Ignore any parsing errors.
pass
self.intervals.sort()
catStr = property(_getStr, _setStr)
def getMask( self ):
''' Return the common number prefix for all intervals (None if non-existent). '''
mask = None
for i in self.intervals:
for k in i:
num = '{}'.format(k)
if len(num) < 3: # No mask for 1 or 2-digit numbers
return None
if mask is None:
mask = num
elif len(mask) != len(num): # No mask for numbers of different lengths
return None
else:
cp = commonprefix([mask, num])
if not cp:
return None
mask = cp.ljust(len(mask), '.')
return mask
def __init__( self, active = True, name = 'Category 100-199', catStr = '100-199', startOffset = '00:00:00',
numLaps = None, sequence = 0,
raceLaps = None, raceMinutes = None,
distance = None, distanceType = None, firstLapDistance = None,
gender = 'Open', lappedRidersMustContinue = False,
catType = CatWave, publishFlag = True, uploadFlag = True, seriesFlag = True ):
self.name = '{}'.format(name).strip()
self.catStr = '{}'.format(catStr).strip()
self.startOffset = startOffset if startOffset else '00:00:00'
self.catType = self.CatWave
catType = '{}'.format(catType).strip().lower()
try:
self.catType = int(catType)
except ValueError:
try:
if catType.startswith(u'component'):
self.catType = self.CatComponent
elif catType.startswith(u'custom'):
self.catType = self.CatCustom
except:
pass
def toBool( v ):
return u'{}'.format(v).strip()[:1] in u'TtYy1'
self.active = toBool( active )
self.publishFlag = toBool( publishFlag )
self.uploadFlag = toBool( uploadFlag )
self.seriesFlag = toBool( seriesFlag )
try:
self._numLaps = int(numLaps)
if self._numLaps < 1:
self._numLaps = None
except (ValueError, TypeError):
self._numLaps = None
try:
self.raceMinutes = int( raceMinutes )
except (ValueError, TypeError):
self.raceMinutes = None
try:
self.sequence = int(sequence)
except (ValueError, TypeError):
self.sequence = 0
try:
self.distance = float(distance) if distance else None
except (ValueError, TypeError):
self.distance = None
if self.distance is not None and self.distance <= 0.0:
self.distance = None
try:
self.distanceType = int(distanceType)
except (ValueError, TypeError):
self.distanceType = None
if self.distanceType not in (Category.DistanceByLap, Category.DistanceByRace):
self.distanceType = Category.DistanceByLap
try:
self.firstLapDistance = float(firstLapDistance) if firstLapDistance else None
except (ValueError, TypeError):
self.firstLapDistance = None
if self.firstLapDistance is not None and self.firstLapDistance <= 0.0:
self.firstLapDistance = None
self.gender = 'Open'
try:
genderFirstChar = six.text_type(gender or u'Open').strip()[:1].lower()
if genderFirstChar in 'mhu':
self.gender = 'Men'
elif genderFirstChar in 'wfld':
self.gender = 'Women'
except:
pass
self.lappedRidersMustContinue = False
lappedRidersMustContinue = u'{}'.format(lappedRidersMustContinue).strip()
if lappedRidersMustContinue[:1] in u'TtYy1':
self.lappedRidersMustContinue = True
def __setstate( self, d ):
self.__dict__.update(d)
i = getattr( self, 'intervals', None )
if i:
i.sort()
def getLapDistance( self, lap ):
if lap is None or self.distanceType != Category.DistanceByLap:
return None
if lap <= 0:
return 0
return self.firstLapDistance if lap == 1 and self.firstLapDistance else self.distance
def getDistanceAtLap( self, lap ):
if lap is None or self.distanceType != Category.DistanceByLap:
return None
if lap == 1 and not (self.firstLapDistance or self.distance):
return None
if lap <= 0:
return 0
return (self.firstLapDistance or self.distance or 0.0) + (self.distance or 0.0) * (lap-1)
@staticmethod
def getFullName( name, gender ):
GetTranslation = _
return u'{} ({})'.format(name, GetTranslation(gender))
@property
def fullname( self ):
return Category.getFullName( self.name.strip(), getattr(self, 'gender', u'Open') )
@property
def firstLapRatio( self ):
if self.distanceType == Category.DistanceByLap and self.firstLapDistance and self.distance:
return self.firstLapDistance / self.distance
else:
return 1.0
@property
def distanceIsByLap( self ):
return self.distanceType == Category.DistanceByLap
@property
def distanceIsByRace( self ):
return self.distanceType == Category.DistanceByRace
def getNumLaps( self ):
laps = getattr( self, '_numLaps', None )
if (race and race.isTimeTrial) and ((laps or 0) < 1 and not self.raceMinutes):
laps = 1
if laps or not self.raceMinutes or not race or race.isTimeTrial:
return laps
# Estimate the number of laps based on the wave category leader's time.
entries = race.interpolateCategory( self )
if not entries:
return None
tFinish = self.raceMinutes * 60.0 + race.getStartOffset(entries[0].num)
lapCur = 1
tLeader = []
for e in entries:
if e.lap == lapCur:
tLeader.append( e.t )
if e.t > tFinish:
break
lapCur += 1
if len(tLeader) <= 1:
return 1
# Check if the expected overlap exceeds race time by less than half a lap.
if (tLeader[-1] - tFinish) < (tLeader[-1] - tLeader[-2]) / 2.0:
return len(tLeader)
return len(tLeader) - 1
def setNumLaps( self, numLaps ):
try:
numLaps = int(numLaps)
except (TypeError, ValueError):
numLaps = None
self._numLaps = numLaps if numLaps else None
numLaps = property(getNumLaps, setNumLaps)
def isNumLapsLocked( self ):
return getattr(self, '_numLaps', None) is not None
def matches( self, num, ignoreActiveFlag = False ):
if not ignoreActiveFlag:
if not self.active:
return False
return False if num in self.exclude else InSortedIntervalList( self.intervals, num )
def getMatchSet( self ):
matchSet = IntervalsToSet( self.intervals )
matchSet.difference_update( self.exclude )
return matchSet
key_attr = ['sequence', 'name', 'active', 'startOffset', '_numLaps', 'raceMinutes', 'catStr',
'distance', 'distanceType', 'firstLapDistance',
'gender', 'lappedRidersMustContinue', 'catType', 'publishFlag', 'uploadFlag', 'seriesFlag']
def key( self ):
return tuple( getattr(self, attr, None) for attr in self.key_attr )
def copy( self, c ):
for attr in self.key_attr:
setattr( self, attr, getattr(c, attr) )
def removeNum( self, num ):
if not self.matches(num, True):
return
# Remove any singleton intervals.
for j in range(len(self.intervals)-1, -1, -1):
interval = self.intervals[j]
if num == interval[0] == interval[1]:
self.intervals.pop( j )
# If we still match, add to the exclude set.
if self.matches(num, True):
self.exclude.add( num )
def addNum( self, num ):
self.exclude.discard( num )
if self.matches(num, True):
return
self.intervals.append( (num, num) )
self.intervals.sort()
def resetNums( self ):
self.intervals = []
self.exclude = set()
self.catStr = ''
def normalize( self ):
# Combine any consecutive or overlapping intervals.
all_nums = IntervalsToSet( self.intervals )
# Remove unnecessary excludes.
needlessExcludes = []
for num in self.exclude:
if num not in all_nums:
needlessExcludes.append( num )
self.exclude.difference_update( needlessExcludes )
self.intervals = SetToIntervals( all_nums )
def __repr__( self ):
return u'Category(active={}, name="{}", catStr="{}", startOffset="{}", numLaps={}, raceMinutes={}, sequence={}, distance={}, distanceType={}, gender="{}", lappedRidersMustContinue="{}", catType="{}")'.format(
self.active,
self.name,
self.catStr,
self.startOffset,
self._numLaps,
self.raceMinutes,
self.sequence,
getattr(self,'distance',None),
getattr(self,'distanceType', Category.DistanceByLap),
getattr(self,'gender',''),
getattr(self,'lappedRidersMustContinue',False),
['Wave', 'Component', 'Custom'][self.catType],
)
def getStartOffsetSecs( self ):
return Utils.StrToSeconds( self.startOffset )
def setFromSet( self, s ):
self.exclude = set()
self.intervals = SetToIntervals( s )
#------------------------------------------------------------------------------------------------------------------
class Entry(object):
__slots__ = ('num', 'lap', 't', 'interp') # Suppress the default dictionary to save space.
def __init__( self, num, lap, t, interp ):
self.num = num
self.lap = lap
self.t = t
self.interp = interp
def __lt__( self, e ):
return (
((self.t > e.t) - (self.t < e.t)) or
-((self.lap > e.lap) - (self.lap < e.lap)) or
((self.num > e.num) - (self.num < e.num)) or
((self.interp > e.interp) - (self.interp < e.interp))
) < 0
def __eq__( self, e ):
return self.num == e.num and self.lap == e.lap and self.t == e.t and self.interp == e.interp
def __ne__( self, e ):
return not (self.num == e.num and self.lap == e.lap and self.t == e.t and self.interp == e.interp)
def key( self ):
return (self.t, -self.lap, self.num, self.interp)
def keyTT( self ):
return (0 if self.lap == 0 else 1, self.t, -self.lap, self.num, self.interp)
def set( self, e ):
self.num = e.num
self.lap = e.lap
self.t = e.t
self.interp = e.interp
def __hash__( self ):
return (self.num<<16) ^ (self.lap<<8) ^ hash(self.t) ^ ((1<<20) if self.interp else 0)
def isGap( self ):
return self.num <= 0
def setGroupCountGap( self, groupCount, gapTime ):
self.num = -groupCount
self.t = gapTime
@property
def gap( self ):
return self.t
@gap.setter
def gap( self, gt ):
self.t = gt
@property
def groupCount( self ):
return -self.num
@groupCount.setter
def groupCount( self, gc ):
self.num = -gc
def __repr__( self ):
return u'Entry(num={}, lap={}, interp={}, t={})'.format(self.num, self.lap, self.interp, self.t)
class Rider(object):
# Rider Status.
Finisher = 0
DNF = 1
Pulled = 2
DNS = 3
DQ = 4
OTL = 5
NP = 6
statusNames = ['Finisher', 'DNF', 'PUL', 'DNS', 'DQ', 'OTL', 'NP']
statusSortSeq = { 'Finisher':1, Finisher:1,
'PUL':2, Pulled:2,
'OTL':6, OTL:6,
'DNF':3, DNF:3,
'DQ':4, DQ:4,
'DNS':5, DNS:5,
'NP':7, NP:7 }
# Factors for range of acceptable lap times.
pMin, pMax = 0.85, 1.20
# Maximum entries generated by interpolation.
entriesMax = 200
firstTime = None # Used for time trial mode. Also used to flag the first start time.
relegatedPosition = None
autocorrectLaps = True
alwaysFilterMinPossibleLapTime = True # If True, short laps will always be filtered even if autocorrectLaps is off.
pulledLapsToGo = None
pulledSequence = None
def __init__( self, num ):
self.num = num
self.times = []
self.status = Rider.Finisher
self.tStatus = None
def clearCache( self ):
for attr in ('_iTimesLast', '_entriesLast'):
try:
delattr( self, attr )
except AttributeError:
pass
def swap( a, b ):
a.clearCache()
b.clearCache()
# Swap all attributes except the num.
for attr in ('times', 'status', 'tStatus', 'autocorrectLaps', 'firstTime', 'relegatedPosition'):
aVal = getattr( a, attr )
bVal = getattr( b, attr )
setattr( a, attr, bVal )
setattr( b, attr, aVal )
def __getstate__( self ):
# Don't pickle cached entries.
state = self.__dict__.copy()
state.pop( '_iTimesLast', None )
state.pop( '_entriesLast', None )
return state
def __repr__( self ):
return u'{} ({})'.format( self.num, self.statusNames[self.status] )
def setAutoCorrect( self, on = True ):
self.autocorrectLaps = on
def addTime( self, t ):
# All times in race time seconds.
if t < 0.0: # Don't add negative race times.
return
try:
if t > self.times[-1]:
self.times.append( t )
return
except IndexError:
self.times.append( t )
return
i = bisect.bisect_left(self.times, t)
if i >= len(self.times) or self.times[i] != t:
self.times.insert( i, t )
def deleteTime( self, t ):
try:
self.times.remove( t )
except ValueError:
pass
def getTimeCount( self ):
# Make sure we don't include times that exceed the number of laps.
try:
numLaps = min( race.getCategory(self.num)._numLaps or 999999, len(self.times) )
except Exception as e:
numLaps = len(self.times)
if not numLaps:
return 0.0, 0 # No times, no count.
elif numLaps == 1:
# If we only have one lap, make sure we consider the start offset.
try:
startOffset = race.getStartOffset( self.num ) if not race.isTimeTrial else 0.0
except:
startOffset = 0.0
return self.times[0] - startOffset, 1
else:
# Otherwise ignore the first lap.
return self.times[numLaps-1] - self.times[0], numLaps-1
def getLastKnownTime( self ):
# Make sure we don't include times that exceed the number of laps.
try:
numLaps = min( race.getCategory(self.num)._numLaps or 999999, len(self.times) )
except Exception as e:
numLaps = len(self.times)
try:
return self.times[numLaps-1]
except IndexError:
return 0.0
def getFirstKnownTime( self ):
t = self.firstTime
if t is None:
try:
t = self.times[0]
except IndexError:
pass
return t
def isDNF( self ): return self.status == Rider.DNF
def isDNS( self ): return self.status == Rider.DNS
def isPulled( self ): return self.status == Rider.Pulled
def isRelegated( self ): return self.status == Rider.Finisher and bool(self.relegatedPosition)
def setStatus( self, status, tStatus = None ):
if status in (Rider.Finisher, Rider.DNS, Rider.DQ):
tStatus = None
elif status in (Rider.Pulled, Rider.DNF):
if tStatus is None:
tStatus = race.lastRaceTime() if race else None
self.status = status
self.tStatus = tStatus
def getMustBeRepeatInterval( self ):
minPossibleLapTime = race.minPossibleLapTime
medianLapTime = race.getMedianLapTime( race.getCategory(self.num) )
if race.enableJChipIntegration:
medianLapTime /= 10.0
mustBeRepeatInterval = max( minPossibleLapTime, medianLapTime * 0.4 )
return mustBeRepeatInterval
def getCleanLapTimes( self ):
if not self.times or self.status in (Rider.DNS, Rider.DQ) or not race:
return None
# Create a separate working list.
# Add the start offset for the beginning of the start wave.
# This avoids special cases later.
iTimes = [race.getStartOffset(self.num)]
# Clean up spurious reads based on minumum possible lap time.
# Also removes early times.
mustBeRepeatInterval = self.getMustBeRepeatInterval()
for t in self.times:
if t - iTimes[-1] > mustBeRepeatInterval:
iTimes.append( t )
try:
numLaps = min( race.getCategory(self.num)._numLaps or 999999, len(iTimes) )
except Exception as e:
numLaps = len(iTimes)
'''
medianLapTime = race.getMedianLapTime() if race else (iTimes[-1] - iTimes[0]) / float(len(iTimes) - 1)
mustBeRepeatInterval = medianLapTime * 0.5
# Remove duplicate entries.
while len(iTimes) > 2:
try:
# Don't correct the last lap - assume the rider looped around and cross the finish again.
i = next(i for i in range(len(iTimes) - 1, 0, -1) \
if iTimes[i] - iTimes[i-1] < mustBeRepeatInterval)
if i == 1:
iDelete = i # if the short interval is the first one, delete the next entry.
elif i == len(iTimes) - 1:
iDelete = i # if the short interval is the last one, delete the last entry.
else:
#
# Delete the entry that equalizes the time on each side.
# -------g-------h---i---------j---------
#
g = i - 2
h = i - 1
j = i + 1
gh = iTimes[h] - iTimes[g]
ij = iTimes[j] - iTimes[i]
iDelete = i - 1 if gh < ij else i
del iTimes[iDelete]
except StopIteration:
break
'''
# Ensure that there are no more times after the deleted ones.
iTimes = iTimes[:numLaps+1]
return iTimes if len(iTimes) >= 2 else []
def getExpectedLapTime( self, iTimes = None ):
if iTimes is None:
iTimes = self.getCleanLapTimes()
if iTimes is None:
return None
# If only 2 times, return a second lap adjusted for lap distance.
if len(iTimes) == 2:
d = iTimes[1] - iTimes[0]
category = race.getCategory( self.num )
return d / category.firstLapRatio if category else d
# Return the median of the lap times ignoring the first lap.
dTimes = sorted( b-a for b, a in zip(iTimes[2:], iTimes[1:]) )
if not dTimes:
return None
dTimesLen = len(dTimes)
return dTimes[dTimesLen // 2] if dTimesLen & 1 else (dTimes[dTimesLen//2-1] + dTimes[dTimesLen//2]) / 2.0
def removeEarlyTimes( self, times ):
try:
startOffset = race.getStartOffset(self.num) if race else 0.0
if startOffset:
times = [t for t in times if t >= startOffset]
if len(times) <= 1:
return []
except (ValueError, AttributeError):
pass
assert len(times) == 0 or len(times) >= 2
return times
def removeLateTimes( self, iTimes, dnfPulledTime ):
if iTimes and dnfPulledTime is not None:
i = bisect.bisect_right( iTimes, (dnfPulledTime,True) )
if i < len(iTimes):
while i > 1 and iTimes[i-1][0] > dnfPulledTime:
i -= 1
del iTimes[i:]
if len(iTimes) < 2:
iTimes = []
return iTimes
def countEarlyTimes( self ):
count = 0
try:
startOffset = race.getStartOffset(self.num)
if startOffset:
for t in self.times:
if t < startOffset:
count += 1
except Exception as e:
pass
return count
def getEntries( self, iTimes ):
try:
if self._iTimesLast == iTimes:
return self._entriesLast
except AttributeError:
pass
num = self.num
self._entriesLast = tuple(Entry(num, lap, it[0], it[1]) for lap, it in enumerate(iTimes))
self._iTimesLast = iTimes
return self._entriesLast
def interpolate( self, stopTime = maxInterpolateTime ):
if not self.times or self.status in (Rider.DNS, Rider.DQ):
return self.getEntries( [] )
# Adjust the stop time.
st = stopTime
dnfPulledTime = None
if self.status in (Rider.DNF, Rider.Pulled):
# If no given time, use the last recorded time for DNF and Pulled riders.
dnfPulledTime = self.tStatus if self.tStatus is not None else self.times[-1]
st = min(st, dnfPulledTime + 0.01)
# Check if we need to do any interpolation or if the user wants the raw data.
if not self.autocorrectLaps:
if not self.times:
return self.getEntries( [] )
# Add the start time for the beginning of the rider.
# This avoids a whole lot of special cases later.
iTimes = [race.getStartOffset(self.num) if race else 0.0]
mustBeRepeatInterval = self.getMustBeRepeatInterval() if self.alwaysFilterMinPossibleLapTime else 0.0
for t in self.times:
if t - iTimes[-1] > mustBeRepeatInterval:
iTimes.append( t )
iTimes = [(t, False) for t in iTimes]
if dnfPulledTime is not None:
iTimes = self.removeLateTimes( iTimes, dnfPulledTime )
return self.getEntries( iTimes )
iTimes = self.getCleanLapTimes()
if not iTimes:
return self.getEntries( [] )
lapTimes = [tb-ta for tb, ta in (zip(iTimes[2:], iTimes[1:]) if len(iTimes) > 1 else zip(iTimes[1:], iTimes))]
# Flag that these are not interpolated times.
expected = self.getExpectedLapTime( iTimes )
iTimes = [(t, False) for t in iTimes]
if len(iTimes) > 2:
# Check for missing lap data and fill it in.
pDown, pUp = 1.0-Rider.pMin, Rider.pMax-1.0
missingMinMax = [(missing, expected * (missing-pDown), expected * (missing+pUp)) for missing in range(2, 5)]
# lapStats = LapStats.LapStats( lapTimes )
# missingMinMax = lapStats.probable_lap_ranges( 5, 0.75 )
for j in range(len(iTimes)-1, 0, -1): # Traverse backwards so we can add missing times as we go.
tDur = iTimes[j][0] - iTimes[j-1][0]
for missing, mMin, mMax in missingMinMax:
if tDur < mMin:
break
if mMin <= tDur < mMax:
tStart = iTimes[j-1][0]
interp = float(iTimes[j][0] - tStart) / float(missing)
iTimes[j:j] = [(tStart + interp * m, True) for m in range(1, missing)]
break
# Pad out to one entry exceeding stop time if we are less than it.
tBegin = iTimes[-1][0]
if tBegin < st and len(iTimes) < Rider.entriesMax:
expected = self.getExpectedLapTime( [t for t, i in iTimes] )
tBegin += expected
iMax = max( 1, int(math.ceil(st - tBegin) / expected) if expected > 0 else 1 )
iMax = min( iMax, Rider.entriesMax - len(iTimes) )
iTimes.extend( [(tBegin + expected * i, True) for i in range(iMax)] )
# Remove any entries exceeding the dnfPulledTime.
if dnfPulledTime is not None:
iTimes = self.removeLateTimes( iTimes, dnfPulledTime )
if len(iTimes) <= 1:
iTimes = []
return self.getEntries( iTimes )
def hasInterpolatedTime( self, tMax ):
interpolate = self.interpolate()
try:
return any( e.interp for e in interpolate if e.t <= tMax )
except (ValueError, StopIteration):
return False
def hasTimes( self ):
return self.times
def getLapTimesForMedian( self ):
# Prevent multi-reader multiple reads from overwhelming the sample.
iTimes = [race.getStartOffset(self.num) if race else 0.0]
for t in self.times:
if t - iTimes[-1] >= 2.0:
iTimes.append( t )
if len(iTimes) == 1:
return []
try:
numLaps = min( race.getCategory(self.num)._numLaps or 999999, len(iTimes)-1 )
except Exception as e:
numLaps = len(iTimes)-1
iTimes = iTimes[:numLaps+1]
if len(iTimes) > 2: # Ignore the first lap.
del iTimes[0]
return [b-a for b, a in zip(iTimes[1:], iTimes)]
def getEarlyStartOffset( self ):
if (not race or
race.isTimeTrial or
self.firstTime is None or
not (race.enableJChipIntegration and race.resetStartClockOnFirstTag)
):
return None
# If the rider is already in the first start wave then it is impossible to be in an earlier one.
startOffset = race.getStartOffset( self.num )
if not startOffset:
return None
StartGapBefore = 2.0
# Check if the first read is at or after the rider's offset. If so, this start is good.
if (startOffset - StartGapBefore) <= self.firstTime:
return None
# Try to find an earlier wave that the rider started in.
startOffsets = race.getStartOffsets()
for startOffsetCur, startOffsetNext in zip(startOffsets, startOffsets[1:]):
if startOffsetCur >= startOffset:
break
if (startOffsetCur - StartGapBefore) <= self.firstTime < startOffsetNext:
return startOffsetCur
return None
class NumTimeInfo(object):
Original = 0
Add = 1
Edit = 2
Delete = 3
Swap = 4
Split = 5
MaxReason = 6
ReasonName = {
Original: _('Original'),
Add: _('Add'),
Edit: _('Edit'),
Delete: _('Delete'),
Swap: _('Swap'),
Split: _('Split'),