/
Dakar_Rally_2021.py
1781 lines (1411 loc) · 63.8 KB
/
Dakar_Rally_2021.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
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# ## Dakar Rally Scraper
#
# This notebook provides a case study in retrieving, cleaning, organising and processing data obtained from a third party website, specifically, timing and results data from the 2019 Dakar Rally.
#
# Another way of thinking of it is as a series of marks created during an exploratory data analysis performance.
#
# Or palaver.
#
# Whatever.
#
# Shall we begin?
# +
#Use requests cache so we can keep an archive of the results HTML
import requests
import pandas as pd
from numpy import nan as NaN
# -
import requests_cache
requests_cache.install_cache('dakar_cache21', backend='sqlite', expire_after=300)
# Timing data is provided in two forms:
#
# - time at waypoint / split;
# - gap to leader at that waypoint;
#
# Ranking data for the stage and overall at end of stage is also available.
#
# Timing and ranking data is available for:
#
# - car
# - moto (motorbike)
# - quad
# - ssv
# - truck
#
YEAR = 2021 #2019
STAGE = 1
VTYPE = 'car'
# ## Stage Info
#
# Retrieve some basic information about a stage.
def get_stage_stats(stage, year=YEAR):
#stage_stats_url='https://gaps.dakar.com/2019/dakar/index_info.php?l=ukie&s={stage}&vh=a'
stage_stats_url=f'https://gaps.dakar.com/{year}/dakar/index_info.php?l=ukie&s={stage}&vh=a'
html = requests.get(stage_stats_url.format(stage=STAGE)).content
stage_stats_df=pd.read_html(html)[0]
return stage_stats_df#.rename(columns=stage_stats_df.iloc[0]).drop(stage_stats_df.index[0])
# + tags=["active-ipynb"]
# get_stage_stats(STAGE)
# -
# ## Timing Data
#
# Typical of many rallies, the live timing pages return several sorts of data:
#
# - times and gaps for each stage;
# - stage and overall results for each stage.
# +
URL_PATTERN='https://gaps.dakar.com/2019/dakar/?s={stage}&c=aso&l=ukie&vi={tab}&sv={timerank}&vh={vtype}&sws=99'
URL_PATTERN='https://gaps.dakar.com/2020/dakar/?s={stage}&c=aso&l=ukie&vi={tab}&sv={timerank}&vh={vtype}&sws=99'
URL_PATTERN='https://gaps.dakar.com/2021/dakar/?s={stage}&c=aso&l=ukie&vi={tab}&sv={timerank}&vh={vtype}&sws=99'
#sws - selected waypoint?
# +
#Vehicle types
VTYPE_ ={ 'car':'a','moto':'m','quad':'q','ssv':'s','truck':'c', 'lightweight vehicle':'s'}
VTYPE_ ={ 'car':'a','moto':'m','quad':'q', 'truck':'c', 'lightweight vehicle':'s'}
#Screen / tab selection
TAB_ = {'timing':0,'news':1,'ranking':2}
#Options for timing data
TIMING_ = {'gap':0,'time':1}
#Options for ranking data
RANKING_ = {'stage':0, 'general':1}
# -
# ## Previewing the data
#
# Let's see what the data looks like...
#
# *Uncomment and run the following to preview / inspect the data that's avaliable.*
# +
#pd.read_html(URL_PATTERN.format(stage=STAGE,tab=TAB_['timing'],vtype=VTYPE_['car'],timerank='time'))
# +
#pd.read_html(URL_PATTERN.format(stage=STAGE,tab=TAB_['ranking'],vtype=VTYPE_['car'],timerank='stage'))
# -
# By inspection, we note that:
#
# - several tables are returned by each page;
# - there are common identifier columns (`['Pos','Bib','Crew','Brand']`);
# - there are irrelevant columns (`['View details','Select']`);
# - the raw timing data columns (timig data at each waypoint) include information about split rank and how it compares to the rank at the previous split / waypoint; this needs to be cleaned before we can convert timestrings to timedeltas.
#TIMING = RANKING = 0 #deprecate these
TIME = RANK = 0
CREWTEAM = 1
BRANDS = 2
COUNTRIES = 3
# ## Retrieving the Data Tables
#
# We can define helper functions to pull back tables associated with the timing or ranking pages.
# +
#Retrieve a page
#Should we also return the stage so that tables stand alone as items with complete information?
def _data(stage,vtype='car',tab='timing', timerank='time', showstage=False):
''' Retrieve timing or ranking HTML page and scrape HTML tables. '''
timerank = RANKING_[timerank] if tab=='ranking' else TIMING_[timerank]
url = URL_PATTERN.format(stage=stage,tab=TAB_[tab],vtype=VTYPE_[vtype],timerank=timerank)
html = requests.get(url).content
_tmp = pd.read_html(html, na_values=['-'])
if showstage:
#This is a hack - elsewhere we use TIME, RANK etc in case there are more tables?
_tmp[0].insert(0, 'Stage', stage)
return _tmp
def _fetch_timing_data(stage,vtype='car', timerank='time', showstage=False):
''' Return data tables from timing page. '''
_tmp = _data(stage,vtype=vtype, tab='timing', timerank=timerank, showstage=showstage)
if 'View details' not in _tmp[TIME]:
return []
_tmp[TIME].drop(columns=['View details','Select'], inplace=True)
return _tmp
def _fetch_ranking_data(stage,vtype='car', timerank='stage', showstage=False):
''' Return data tables from ranking page. '''
rank_cols = ['Pos','Bib','Crew','Brand','Time','Gap','Penalty']
_tmp = _data(stage,vtype=vtype, tab='ranking', timerank=timerank, showstage=showstage)
if 'View details' not in _tmp[RANK]:
return []
_tmp[RANK].drop(columns=['View details','Select'], inplace=True)
#if timerank=='general':
# _tmp[RANK].rename(columns={'Pos':'Overall Position'}, inplace=True)
return _tmp
# + active=""
# #cache grab - grab all the HTML pages into a SQLite cache without expiry
#
# #The news tab returns news items as a list rather than in a table
# def _get_news(stage,vtype='car',):
# _tmp = _data(stage,vtype=vtype, tab='news')
# # return _tmp
#
# for stage in [1,2,3,4,5,6,7, 8, 9, 10]:
# for v in VTYPE_:
# _get_news(stage,vtype=v)
# get_stage_stats(stage)
# for timing in TIMING_:
# _fetch_timing_data(stage,vtype=v, timerank=timing)
# for ranking in RANKING_:
# _fetch_ranking_data(stage,vtype=v, timerank=ranking)
#
# -
# ## Ranking Data
#
# Process the ranking data...
#
# So what have we got to work with?
# + tags=["active-ipynb"]
# rdata = _fetch_ranking_data(STAGE, vtype=VTYPE, timerank='general', showstage=True)
#
# rdata[RANK].head()
# + tags=["active-ipynb"]
# rdata[RANK].dtypes
# -
# The basic retrieval returns a table with timing data as strings, and the `Bib` identifier as an integer.
#
# The `Bib` identifer, We could also regard it as a string so that we aren't tempted to treat it as a number, inwhich case we should also ensure that any extraneous whitespace is stripped if the `Bib` was already a string:
#
# ```python
# rdata[RANK]['Bib'] = rdata[RANK]['Bib'].astype(str).str.strip()
# ```
# + tags=["active-ipynb"]
# rdata[RANK]['Bib'] = rdata[RANK]['Bib'].astype(int)
# -
# ## Convert time to timedelta
#
# Several of the datasets return times, as strings, in the form: `HH:MM:SS`.
#
# We can convert these times to timedeltas.
#
# Timing related columns are all columns except those in `['Pos','Bib','Crew','Brand']`.
#
# We can also prefix timing columns in the timing data screens so we can recreate the order they should appear in:
#Prefix each split designator with a split count
timingcols=['dss','wp1','wp2','ass']
# + tags=["active-ipynb"]
# { x:'{}_{}'.format('{0:02d}'.format(i), x) for i, x in enumerate(timingcols, 0) }
# -
# One of the things we need to handle are timing columns where the timing data may be mixed with other sorts of data in the raw data table.
#
# Routines for cleaner the data are included in the timing handler function but they were actually "backfilled" into the function after creating them (originally) later on in the notebook.
# +
from pandas.api.types import is_string_dtype
#At first sight, this looks quite complicated, but a lot of it is backfilled
# to take into account some of the cleaning we need to do for the full (messy) timing data
def _get_timing(df, typ=TIME, kind='simple'):
''' Convert times to time deltas and
prefix waypoint / timing columns with a two digit counter. '''
#kind: simple, full, raw
#Some of the exclusion column names are backfilled into this function
# from columns introduced later in the notebook
# What we're trying to do is identify columns that aren't timing related
timingcols = [c for c in df[typ].columns if c not in ['Pos','Overall Position','Bib','Crew','Brand',
'Refuel', 'Road Position', 'Stage'] ]
#Clean up the data in a timing column, then cast to timedelta
for col in timingcols:
#A column of NAs may be incorrectly typed
#print(df[typ].columns)
df[typ][col] = df[typ][col].fillna('').str.strip()
#In the simple approach, we just grab the timing data and dump the mess
if kind!='full':
df[typ][col] = df[typ][col].str.extract(r'(\d{1,2}:\d{1,2}:\d{1,2})')
else:
#The full on extractor - try to parse out all the data
# that has been munged into a timing column
if col==timingcols[-1]:
#There's an end effect:
# the last column in the timing dataset doesn't have position embedded in it
# In this case, just pull out the position gained/maintained/lost flag
df[typ][[col,col+'_gain']] = df[typ][col].str.extract(r'(\d{1,2}:\d{1,2}:\d{1,2})(.*)', expand=True)
else:
#In the main body of the table, position gain as well as waypoint rank position are available
df[typ][[col,col+'_gain',col+'_pos']] = df[typ][col].str.extract(r'(\d{1,2}:\d{1,2}:\d{1,2})(.*)\((\d*)\)', expand=True)
#Ideally, the pos cols would be of int type, but int doesn't support NA
df[typ][col+'_pos'] = df[typ][col+'_pos'].astype(float)
#Cast the time string to a timedelta
if kind=='full' or kind=='raw':
df[typ]['{}_raw'.format(col)] = df[typ][col][:]
df[typ][col] = pd.to_timedelta( df[typ][col] )
#In timing screen, rename cols with a leading two digit index
#This allows us to report splits in order
#We only want to do this for the timing data columns, not the rank timing columns...
#Should really do this based on time type?
timingcols = [c for c in timingcols if c not in ['Time','Gap','Penalty'] and not c.endswith(('_raw','_pos','_gain'))]
timingcols_map = { x:'{}_{}'.format('{0:02d}'.format(i), x) for i, x in enumerate(timingcols, 0) }
df[typ].rename(columns=timingcols_map, inplace=True)
#TO_DO - need to number label the ..._raw, _pos and ..._gain cols
#This is overly complex because it handles ranking and timing frames
#Better to split out to separate ones?
for suffix in ['_raw','_pos','_gain']:
cols=[c for c in df[typ].columns if (not c.startswith(('Time','Gap','Penalty'))) and c.endswith(suffix)]
cols_map = { x:'{}_{}'.format(x,'{0:02d}'.format(i)) for i, x in enumerate(cols, 0) }
df[typ].rename(columns=cols_map, inplace=True)
#TO_DO - elsewhere: trap for start with 0/1 and not end _gain etc
return df
# -
# ## Ranking Data Redux
#
# Normalise the times as timedeltas.
#
# For timestrings of the form `HH:MM:SS`, this is as simple as passing the timestring column to the *pandas* `.to_timedelta()` function:
#
# ```python
# pd.to_timedelta( df[TIMESTRING_COLUMN] )
# ```
#
# We just need to ensure we pass it the correct columns...
def get_ranking_data(stage,vtype='car', timerank='stage', kind='simple'):
''' Retrieve rank timing data and return it in a form we can work directly with. '''
#kind: simple, raw
df = _fetch_ranking_data(stage,vtype=vtype, timerank=timerank)
df[RANK]['Bib'] = df[RANK]['Bib'].astype(int)
return _get_timing(df, typ=RANK, kind=kind)
# + tags=["active-ipynb"]
# get_ranking_data(STAGE, VTYPE, kind='raw')[RANK].head()
# + tags=["active-ipynb"]
# STAGE, VTYPE
# + tags=["active-ipynb"]
# #What changed?
# get_ranking_data(STAGE, VTYPE,timerank='general', kind='raw')[RANK].head()
# + tags=["active-ipynb"]
# ranking_data = get_ranking_data(STAGE, VTYPE)
#
# ranking_data[RANK].head()
# + tags=["active-ipynb"]
# ranking_data[RANK].dtypes
# -
# The `Crew` data is a bit of a mishmash. If we were to normalise this table, we'd have to split that data out...
#
# For now, let's leave it...
#
# ...because sometimes, it can be handy to be able to pull out a chunk of unnormalised data as a simple string.
# + tags=["active-ipynb"]
# ranking_data[RANK].dtypes
# -
# ## Timing Data
#
# The timing data needs some processing:
# + tags=["active-ipynb"]
# data = _fetch_timing_data(STAGE, VTYPE)
#
# data[TIME][60:70]
# -
# A full inspection of the time data shows that some additional metadata corresponding to whether in-stage refuelling is allowed may also be recorded in the `Bib` column (for example, `403 ⛽`).
#
# We can extract this information into a separate dataframe / table.
def get_refuel_status(df):
''' Parse the refuel status out of timing data Bib column.
Return extended dataframe with a clean Bib column and a new Refuel column. '''
#The .str.extract() function allows us to match separate groups using a regex
# and return the corresponding group data as distinct columns
#Force the Bin type to a str if it isn't created as such so we can regex it...
df[['Bib','_tmp']] = df['Bib'].astype(str).str.extract(r'(\d*)([^\d]*)', expand=True)
#Set the Refuel status as a Boolean
df.insert(2, 'Refuel', df['_tmp'])
df.drop('_tmp', axis=1, inplace=True)
df['Refuel'] = df['Refuel']!=''
#Set the Bib value as an int
df['Bib'] = df['Bib'].astype(int)
return df
# + tags=["active-ipynb"]
# data[TIME] = get_refuel_status(data[TIME])
# data[TIME][60:70]
# -
# We also notice that the raw timing data includes information about split rank and how it compares to the rank at the previous split / waypoint, with the raw data taking the form `08:44:00= (11)`. Which is to say, `HH:MM:DDx (NN?)` where `x` is a comparator showing whether the rank at that waypoint improved (▲), remained the same as (=), or worsened (▼) compared to the previous waypoint.
#
# Note that the final `ass` column does not include the rank.
#
# We can use a regular expression to separate the data out, with each regex group being expanded into a separate column:
# + tags=["active-ipynb"]
# data[TIME]['dss'].str.extract(r'(\d{2}:\d{2}:\d{2})(.*)\((\d*)\)', expand=True).head()
# -
# We can backfill an expression of that form into the timing data handler function above...
#
# Now we wrap several steps together into a function that gets us a clean set of timing data, with columns of an appropriate type:
def get_timing_data(stage,vtype='car', timerank='time', kind='simple'):
''' Get timing data in a form ready to use. '''
df = _fetch_timing_data(stage,vtype=vtype, timerank=timerank)
if not df:
return []
df[TIME] = get_refuel_status(df[TIME])
return _get_timing(df, typ=TIME, kind=kind)
# + tags=["active-ipynb"]
# get_timing_data(STAGE, VTYPE, kind='simple')[TIME].head()
# + tags=["active-ipynb"]
# data = get_timing_data(STAGE, VTYPE, kind='full')
# data[TIME].head()
# + tags=["active-ipynb"]
# data[TIME].dtypes
# -
# ## Parse Metadata
#
# Some of the scraped tables are used to provide selection lists, but we might be able to use them as metadata tables.
#
# For example, here's a pretty complete set, although mangled together, set of competititor names, nationalities, and team names:
# + tags=["active-ipynb"]
# data[ CREWTEAM ].head()
# -
# It'll probably be convenient to have the unique `Bib` values available as an index:
# + tags=["active-ipynb"]
# data[ CREWTEAM ] = data[ CREWTEAM ][['Bib', 'Names']].set_index('Bib')
# data[ CREWTEAM ].head()
# -
# The `Names` may have several `Name (Country)` values, followed by a team name. The original HTML uses `<span>` tags to separate out values but the *pandas* `.read_html()` function flattens cell contents.
#
# Let's have a go at pulling out the team names, which appear at the end of the string. If we can split each name, and the team name, into separate columns, and then metl those columns into separate rows, grouped by `Bib` number, we should be able to grab the last row, corrsponding to the team, in each group:
# + tags=["active-ipynb"]
# #Perhaps split on brackets?
# # At least one team has brackets in the name at the end of the name
# # So let's make that case, at least, a "not bracket" by setting a ) at the end to a :]:
# # so we don't (mistakenly) split on it as if it were a country-associated bracket.
# teams = data[ CREWTEAM ]['Names'].str.replace(r'\)$',':]:').str.split(')').apply(pd.Series).reset_index().melt(id_vars='Bib', var_name='Num').dropna()
#
# #Find last item in each group, which is to say: the team
# teamnames = teams.groupby('Bib').last()
# #Defudge any brackets at the end back
# teamnames = teamnames['value'].str.replace(':]:',')')
# teamnames.head()
# -
# Now let's go after the competitors. These are all *but* the last row in each group:
# + tags=["active-ipynb"]
# #Remove last row in group i.e. the team
# personnel = teams.groupby('Bib').apply(lambda x: x.iloc[:-1]).set_index('Bib').reset_index()
#
# personnel[['Name','Country']] = personnel['value'].str.split('(').apply(pd.Series)
#
# #Strip whitespace
# for c in ['Name','Country']:
# personnel[c] = personnel[c].str.strip()
#
# personnel[['Bib','Num','Name','Country']].head()
# -
# For convenience, we might want to reshape this long form back to a wide form, with a single string containing all the competitor names associated with a particular `Bib` identifier:
# + tags=["active-ipynb"]
# #Create a single name string for each vehicle
# #For each Bib number, group the rows associated with that number
# # and aggregate the names in those rows into a single, comma separated, joined string
# # indexed by the corresponding Bib number
# personnel.groupby('Bib')['Name'].agg(lambda col: ', '.join(col)).tail()
# + tags=["active-ipynb"]
# data[ BRANDS ].head()
# + tags=["active-ipynb"]
# data[ COUNTRIES ].head()
# + tags=["active-ipynb"]
# data[ COUNTRIES ][['Country','CountryCode']] = data[ COUNTRIES ]['Names'].str.extract(r'(.*) \((.*)\)',expand=True)
# data[ COUNTRIES ].head()
# -
# If we have a col with a lot of missing timing data, should we drop it early? A downside of this is we are working with live data, there is likely to be lots of missing data so we can't run live tables? The following `get_annotated_timing_data()` definition takes the *delete cols with missing data* approach...
def get_annotated_timing_data(stage, vtype='car',
timerank='time', kind='simple', MAXMISSING=10):
''' Return a timing dataset that's ready to use. '''
df = get_timing_data(stage, vtype, timerank, kind)
if not df:
return []
#TEST
df[TIME].dropna(thresh=MAXMISSING,axis=1,inplace=True)
col00 = [c for c in df[TIME].columns if c.startswith('00_')][0]
#Add in Road position
df[TIME].insert(2,'Road Position', df[TIME].sort_values(col00,ascending=True)[col00].rank())
return df
# + tags=["active-ipynb"]
# get_annotated_timing_data(STAGE,vtype=VTYPE, timerank='time', kind='full')[TIME].head()
# + tags=["active-ipynb"]
# t_data = get_annotated_timing_data(STAGE,vtype=VTYPE, timerank='time')[TIME]
# t_data.head(10)
# + tags=["active-ipynb"]
# not_timing_cols = ['Pos','Road Position','Refuel','Bib','Crew','Brand']
#
# driver_data = t_data[ not_timing_cols ]
# driver_data.head()
# -
def get_driver_data(stage, topN=None, vtype='car',):
driver_data = get_annotated_timing_data(stage, vtype=vtype,
timerank='time')[TIME]
driver_data = driver_data[['Bib','Pos','Road Position','Crew','Brand']]
driver_data.set_index('Bib', inplace=True)
if topN:
return driver_data[(driver_data['Pos']<=topN)]
return driver_data
# + tags=["active-ipynb"]
# get_driver_data(STAGE)
# -
# The number of waypoints differs across stages. If we cast the wide format waypoint data into a long form, we can more conveniently merge waypoint timing data from separate stages into the same dataframe.
# + tags=["active-ipynb"]
# pd.melt(t_data.head(),
# id_vars=not_timing_cols,
# var_name='Waypoint', value_name='Time').head()
# +
def _timing_long(df, nodss=True):
''' Cast timing data to long data frame. '''
df = pd.melt(df,
id_vars=[c for c in df.columns if not any(_c in c for _c in ['dss','wp','ass', 'km', 'pk'])],
var_name='Waypoint', value_name='Time')
if nodss:
return df[~df['Waypoint'].str.startswith('00')]
return df
#Should return cols: Pos Bib Road Position Refuel Crew Brand Waypoint Time
def _typ_long(df, typ='_pos_', nodss=False):
''' Cast wide data to long data frame. '''
df = pd.melt(df[['Bib']+[c for c in df.columns if typ in c]],
id_vars=['Bib'],
var_name='Waypoint', value_name=typ)
df['WaypointOrder'] = df['Waypoint'].str.slice(-2).astype(int)
if nodss:
return df[~df['Waypoint'].str.startswith('00')]
return df
#Should return cols: Bib Waypoint _gain_ Waypoint_idx
# + tags=["active-ipynb"]
# t_data_long = _timing_long(t_data)
# t_data_long.head()
# + tags=["active-ipynb"]
# t_data2 = get_annotated_timing_data(STAGE,vtype=VTYPE, timerank='time', kind='full')[TIME]
# display(_typ_long(t_data2, '_gain_').head())
# #_pos_, _raw_, _gain_
# #Clear down
# t_data2 = None
# +
def get_long_annotated_timing_data(stage, vtype='car', timerank='time', kind='simple'):
''' Get annotated timing dataframe and convert it to long format. '''
#TO DO: But for the db, we want the raw long, not the time long
_tmp = get_annotated_timing_data(stage, vtype, timerank, kind=kind)
if not _tmp:
return []
#I don't think this works for anything other than kind=simple
#TO DO: do we need to cope with the kind='full' stuff differently?
_tmp[TIME] = _timing_long(_tmp[TIME])
if kind=='simple':
#Should really be testing if starts with an int
_tmp[TIME]=_tmp[TIME][_tmp[TIME]['Waypoint'].str.startswith(('0','1'))]
#Find the total seconds for each split / waypoint duration
_tmp[TIME]['TimeInS'] = _tmp[TIME]['Time'].dt.total_seconds()
if timerank=='gap':
_tmp[TIME].rename(columns={'Time':'Gap', 'TimeInS':'GapInS'}, inplace=True)
return _tmp
#Should return cols:
#Pos Bib Road Position Refuel Crew Brand Section Gap GapInS
# +
#get_long_annotated_timing_data(3,vtype='quad', timerank='time')[TIME]
# + tags=["active-ipynb"]
# get_long_annotated_timing_data(STAGE, VTYPE)[TIME].head()
# + tags=["active-ipynb"]
# get_long_annotated_timing_data(STAGE, VTYPE, 'gap')[TIME].head()
# -
# ## Find the time between each waypoint
#
# That is, the time taken to get from one waypoint to the next. If we think of waypoints as splits, this is essentially a `timeInSplit` value. If we know this information, we can work out how much time each competitor made, or lost, relative to every other competitor in the same class, going between each waypoint.
#
# This means we may be able to work out which parts of the stage a particular competitor was pushing on, or had difficulties on.
# There's an issue with the following: if there is missing data at a waypoint, then the `nan` causes issues with the calculations. One fix might be to try to drop a column if there's lots of missing data in it, which is the approach used in `get_annotated_timing_data()`; another might be to try to fill just the occasional `nan` across from the previous stage; this would then give a 0 time from one stage to another which we might be able to catch as some sort of exception?
#
# In `_get_time_between_waypoints()` we go even more defensive and drop NA time rows from waypoints.
# +
def _get_time_between_waypoints(timing_data_long):
''' Find time taken to go from one waypoint to the next for each vehicle. '''
timing_data_long.dropna(subset=['TimeInS'], inplace=True)
#The timeInSplit is the time between waypoints.
#So find the diff between each consecutive waypoint time for each Crew
timing_data_long['timeInSplit'] = timing_data_long[['Crew','Time']].groupby('Crew').diff()
#Because we're using a diff(), the first row is set to NaN - there's nothing to diff to
#So use the time at the first split as the time from the start to the first waypoint.
timing_data_long.loc[timing_data_long.groupby('Crew')['timeInSplit'].head(1).index, 'timeInSplit'] = timing_data_long.loc[timing_data_long.groupby('Crew')['timeInSplit'].head(1).index,'Time']
#To finesse diff calculations on NaT, set diff with day!=0 to NaT
#This catches things where we get spurious times calculated as diff times against NaTs
timing_data_long.loc[timing_data_long['Time'].isna(),'timeInSplit'] = pd.NaT
timing_data_long.loc[timing_data_long['timeInSplit'].dt.days!=0,'timeInSplit'] = pd.NaT
#If there's been a reset, we can fill across
timing_data_long[['Time','timeInSplit']] = timing_data_long[['Time','timeInSplit']].fillna(method='ffill',axis=1)
#Find the total seconds for each split / waypoint duration
timing_data_long['splitS'] = timing_data_long['timeInSplit'].dt.total_seconds()
return timing_data_long
def get_timing_data_long_timeInSplit(stage, vtype='car', timerank='time'):
''' For a stage, get the data in long form, including timeInSplit times. '''
timing_data_long = get_long_annotated_timing_data(stage, vtype, timerank)[TIME]
timing_data_long = _get_time_between_waypoints(timing_data_long)
return timing_data_long
# + tags=["active-ipynb"]
# #Preview some data
# timing_data_long_insplit = get_timing_data_long_timeInSplit(STAGE, VTYPE)
# #timing_data_long_insplit[timing_data_long_insplit['Brand']=='PEUGEOT'].head()
# timing_data_long_insplit.head()
# + tags=["active-ipynb"]
# timing_data_long = get_long_annotated_timing_data(STAGE, VTYPE)[TIME]
# timing_data_long
# #timing_data_long[timing_data_long['Brand']=='PEUGEOT'].head()
# timing_data_long.head()
# + tags=["active-ipynb"]
# timing_data_long['Waypoint'].unique()
# -
# ## Saving the Data to a Database
#
# The data can be saved to a database directly in an unnormalised form, or we can tidy it up a bit and save it in a higher normal form.
#
# The table structure is far from best practice - it's pragmatic and in first instance intended simply to be useful...
# #!pip3 install sqlite-utils
from sqlite_utils import Database
# +
def cleardbtable(conn, table):
''' Clear the table whilst retaining the table definition '''
c = conn.cursor()
c.execute('DELETE FROM "{}"'.format(table))
def dbfy(conn, df, table, if_exists='append', index=False, clear=False, **kwargs):
''' Save a dataframe as a SQLite table.
Clearing or replacing a table will first empty the table of entries but retain the structure. '''
if if_exists=='replace':
clear=True
if_exists='append'
if clear: cleardbtable(conn, table)
df.to_sql(table,conn,if_exists=if_exists,index=index)
# +
#dbname='dakar_test_sql.sqlite'
# #!rm $dbname
# -
import sqlite3
# + tags=["active-ipynb"]
# dbname='dakar_sql-21.sqlite'
# !rm $dbname
#
# conn = sqlite3.connect(dbname)
#
# c = conn.cursor()
#
# setup_sql= 'dakar.sql'
# with open(setup_sql,'r') as f:
# txt = f.read()
# c.executescript(txt)
#
# db = Database(conn)
# + tags=["active-ipynb"]
# q="SELECT name FROM sqlite_master WHERE type = 'table';"
# pd.read_sql(q, conn)
# + tags=["active-ipynb"]
# tmp = teamnames.reset_index()
# tmp['Year'] = YEAR
# tmp.rename(columns={'value':'Team'}, inplace=True)
# dbfy(conn, tmp, "teams")
# + tags=["active-ipynb"]
# q="SELECT * FROM teams LIMIT 3;"
# pd.read_sql(q, conn)
# + tags=["active-ipynb"]
# tmp = personnel[['Bib','Num','Name','Country']]
# tmp['Year'] = YEAR
# dbfy(conn, tmp, "crew")
# + tags=["active-ipynb"]
# q="SELECT * FROM crew LIMIT 3;"
# pd.read_sql(q, conn)
# +
import os
def init_db(dbname='file::memory:', setup_sql='dakar.sql', clean=True):
if clean and os.path.exists(dbname):
# !rm $dbname
os.remove(dbname)
conn = sqlite3.connect(dbname)
c = conn.cursor()
with open(setup_sql,'r') as f:
txt = f.read()
c.executescript(txt)
db = Database(conn)
tmp = teamnames.reset_index()
tmp['Year'] = YEAR
tmp.rename(columns={'value':'Team'}, inplace=True)
dbfy(conn, tmp, "teams")
tmp = personnel[['Bib','Num','Name','Country']]
tmp['Year'] = YEAR
dbfy(conn, tmp, "crew")
return conn, db
# + tags=["active-ipynb"]
# stage=1
#
# tmp = get_stage_stats(STAGE).set_index('Special').T.reset_index()
# tmp.rename(columns={'Leader at latest WP':'LeaderLatestWP', 'index':'Vehicle', "Latest WP":'LatestWP',
# 'At start':'AtStart', 'Nb at latest WP':'NumLatestWP' }, inplace=True)
# tmp[['BibLatestWP', 'NameLatestWP']] = tmp['LeaderLatestWP'].str.extract(r'([^ ]*) (.*)',expand=True)
# tmp['BibLatestWP'] = tmp['BibLatestWP'].astype(int)
#
# tmp['Stage'] = stage
# tmp['Year'] = YEAR
#
# tmp['StageDist'] = tmp['Special'].str.extract(r'(?P<StageDist>.*)[pkm]{2}').astype(int)
#
# stagedists = tmp[['Stage', 'Vehicle', 'StageDist']]
# tmp
# + tags=["active-ipynb"]
# stagedists
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #1?
#
# v=VTYPE
#
# tmp = get_long_annotated_timing_data(stage,vtype=v, timerank='time')[TIME]
# tmp['Year'] = YEAR
# tmp['Stage'] = stage
#
# tmp.rename(columns={'Road Position':'RoadPos'}, inplace=True)
# #try:
# # t_stagemeta.upsert_all(tmp[['Year', 'Stage', 'Bib','RoadPos','Refuel']].to_dict(orient='records'))
# #except:
# # t_stagemeta.insert_all(tmp[['Year', 'Stage', 'Bib','RoadPos','Refuel']].to_dict(orient='records'))
# print(tmp['Waypoint'].unique())
# tmp.head()
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #2?
# tmp2 = get_long_annotated_timing_data(stage,vtype=v, timerank='gap')[TIME]
# tmp = pd.merge(tmp, tmp2[['Bib', 'Waypoint', 'Gap', 'GapInS']],
# on=['Bib', 'Waypoint'], how='left')
# tmp['WaypointOrder'] = tmp['Waypoint'].str.slice(0,2).astype(int)
#
# tmp['WaypointOrder'] = tmp['Waypoint'].str.slice(0,2).astype(int)
#
# print(tmp['Waypoint'].unique())
# tmp.head()
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #3?
# tmp['VehicleType'] = v
#
# #Add in the WaypointRank
# tmp3=get_annotated_timing_data(stage,vtype=v, timerank='time', kind='full')[TIME]
#
# tmp = pd.merge(tmp, _typ_long(tmp3, '_pos_')[['Bib','WaypointOrder', '_pos_']],
# on=['Bib','WaypointOrder'], how='left')
# tmp.rename(columns={'_pos_':'WaypointRank'}, inplace=True)
# print(tmp['Waypoint'].unique())
# tmp.head()
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #4?
# ## ADD IN
# #Way point pos
#
#
# waypoints = pd.DataFrame({'Waypoint':tmp['Waypoint'].unique().tolist()})
#
# waypoints['WaypointDist'] = waypoints['Waypoint'].str.extract(r'.*_[pkm]{2}(?P<Change>.*)?')
# stagedists[stagedists['Vehicle'].str.lower()==v]['StageDist'].iloc[0]
# #tmp
# waypoints
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #5?
# waypoints.loc[waypoints['Waypoint'].str.contains('_ass'),'WaypointDist'] = stagedists[stagedists['Vehicle'].str.lower()==v]['StageDist'].iloc[0]
# waypoints['WaypointDist'] = waypoints['WaypointDist'].astype(int)
# waypoints
#
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #6?
# tmp = pd.merge(tmp, waypoints, on=['Waypoint'], how='left')
# tmp
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #7?
# #TO DO: use Gap and Time as raw
# #print(tmp.columns, tmp.dtypes)
# _tcols = ["Time","Gap"]
# for t in _tcols:
# tmp['{}InS'.format(t)] = pd.to_timedelta( tmp[t] ).dt.total_seconds()
# tmp.drop(['RoadPos', 'Refuel', 'Brand', 'Crew'], axis=1, inplace=True)
# tmp.drop(['Time','Gap'], axis=1, inplace=True)
#
# tmp = pd.merge(tmp, _typ_long(tmp3, '_raw_')[['Bib','WaypointOrder', '_raw_']],
# on=['Bib','WaypointOrder'])
# tmp.rename(columns={'_raw_':'Time_raw'}, inplace=True)
#
# tmp = pd.merge(tmp, _typ_long(get_annotated_timing_data(stage,vtype=v, timerank='gap', kind='full')[TIME], '_raw_')[['Bib','WaypointOrder', '_raw_']],
# on=['Bib','WaypointOrder'])
# tmp.rename(columns={'_raw_':'Gap_raw'}, inplace=True)
#
# tmp
# + tags=["active-ipynb"]
# get_timing_data_long_timeInSplit(stage, VTYPE)[['Bib','Waypoint', 'timeInSplit','splitS']]
# + tags=["active-ipynb"]
# ### wtf is going on w/ waypoints #8?
# tmp = pd.merge(tmp, get_timing_data_long_timeInSplit(stage, v)[['Bib','Waypoint', 'timeInSplit','splitS']],
# on=['Bib','Waypoint'])
# tmp['WaypointPos'] = tmp.groupby(['Stage','Waypoint'])['splitS'].rank(ascending=True,
# method='dense')
# tmp.head(3)
# -
def create_waypoints_db_df(stage, v, stagedists):
tmp = get_long_annotated_timing_data(stage,vtype=v, timerank='time')
if not tmp:
return pd.DataFrame()
tmp = tmp[TIME]
tmp['Year'] = YEAR
tmp['Stage'] = stage
tmp.rename(columns={'Road Position':'RoadPos'}, inplace=True)
tmp2 = get_long_annotated_timing_data(stage,vtype=v, timerank='gap')[TIME]
tmp = pd.merge(tmp, tmp2[['Bib', 'Waypoint', 'Gap', 'GapInS']],
on=['Bib', 'Waypoint'], how='left')
tmp['WaypointOrder'] = tmp['Waypoint'].str.slice(0,2).astype(int)
tmp['VehicleType'] = v
#Add in the WaypointRank
tmp3=get_annotated_timing_data(stage,vtype=v, timerank='time', kind='full')[TIME]
tmp = pd.merge(tmp, _typ_long(tmp3, '_pos_')[['Bib','WaypointOrder', '_pos_']],
on=['Bib','WaypointOrder'], how='left')
tmp.rename(columns={'_pos_':'WaypointRank'}, inplace=True)
tmp['WaypointPos'] = tmp.groupby(['Stage','Waypoint'])['GapInS'].rank(ascending=True,
method='dense')
waypoints = pd.DataFrame({'Waypoint':tmp['Waypoint'].unique().tolist()})
waypoints['WaypointDist'] = waypoints['Waypoint'].str.extract(r'.*_[pkm]{2}(?P<Change>.*)?')
stagedists[stagedists['Vehicle'].str.lower()==v]['StageDist'].iloc[0]
waypoints.loc[waypoints['Waypoint'].str.contains('_ass'),'WaypointDist'] = stagedists[stagedists['Vehicle'].str.lower()==v]['StageDist'].iloc[0]
waypoints['WaypointDist'] = waypoints['WaypointDist'].astype(int)
tmp = pd.merge(tmp, waypoints, on=['Waypoint'], how='left')
_tcols = ["Time","Gap"]
for t in _tcols:
tmp['{}InS'.format(t)] = pd.to_timedelta( tmp[t] ).dt.total_seconds()
tmp.drop(['RoadPos', 'Refuel', 'Brand', 'Crew'], axis=1, inplace=True)
tmp.drop(['Time','Gap'], axis=1, inplace=True)
tmp = pd.merge(tmp, _typ_long(tmp3, '_raw_')[['Bib','WaypointOrder', '_raw_']],
on=['Bib','WaypointOrder'])
tmp.rename(columns={'_raw_':'Time_raw'}, inplace=True)
tmp = pd.merge(tmp, _typ_long(get_annotated_timing_data(stage,vtype=v, timerank='gap', kind='full')[TIME], '_raw_')[['Bib','WaypointOrder', '_raw_']],
on=['Bib','WaypointOrder'])
tmp.rename(columns={'_raw_':'Gap_raw'}, inplace=True)
tmp = pd.merge(tmp, get_timing_data_long_timeInSplit(stage, v)[['Bib','Waypoint', 'splitS']],
on=['Bib','Waypoint'])
tmp['WaypointPos'] = tmp.groupby(['Stage','Waypoint'])['splitS'].rank(ascending=True,
method='dense')
return tmp
# + tags=["active-ipynb"]
# stage=1
# + tags=["active-ipynb"]
# create_waypoints_db_df(stage, v, stagedists)
# + tags=["active-ipynb"]
# conn, db = init_db('dakar_2021.db')
# + tags=["active-ipynb"]
# # 'Year', 'Bib' is a sensible common key for several things?
#
# STAGESTATS = True
#
# for stage in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]:
#
# tmp = get_stage_stats(STAGE).set_index('Special').T.reset_index()