-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
executable file
·1935 lines (1658 loc) · 95.2 KB
/
run.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
print("Importing modules...")
import os # Used for analyzing file paths and directories
import csv # Needed to read in and write out data
import argparse # Used to parse optional command-line arguments
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
# https://stackoverflow.com/questions/15777951/how-to-suppress-pandas-future-warning
# https://stackoverflow.com/questions/18603270/progress-indicator-during-pandas-operations
# https://pypi.org/project/tqdm/#pandas-integration
# Gives warning if tqdm version <4.33.0. Ignore.
# https://github.com/tqdm/tqdm/issues/780
import pandas as pd # Series and DataFrame structures
import numpy as np
import traceback
import time
from datetime import datetime
import getpass
from PIL import Image
import hashlib
import glob
from tqdm import tqdm
import copy
import re
try:
import matplotlib
matplotlib.use("Agg") # no UI backend for use w/ WSL
# https://stackoverflow.com/questions/43397162/show-matplotlib-plots-and-other-gui-in-ubuntu-wsl1-wsl2
import matplotlib.pyplot as plt # Needed for optional data plotting.
PLOT_LIB_PRESENT = True
except ImportError:
PLOT_LIB_PRESENT = False
# https://stackoverflow.com/questions/3496592/conditional-import-of-modules-in-python
print("...done\n")
# global constants: directory structure
RAW_INCA_DIR = "./raw_data/INCA"
RAW_EDAQ_DIR = "./raw_data/eDAQ"
SYNC_DIR = "./sync_data"
PLOT_DIR = "./figs"
# Find Desktop path, default destination for log files.
username = getpass.getuser()
# https://stackoverflow.com/questions/842059/is-there-a-portable-way-to-get-the-current-username-in-python
home = os.path.join("/mnt/c/Users", "%s" % username)
onedrives = [folder for folder in os.listdir(home) if "OneDrive -" in folder][0]
assert len(onedrives) == 1, "Found more than one OneDrive folder. Unhandled exception"
onedrive = onedrives[0]
LOG_DIR = os.path.join(home, "%s", "Desktop" % (username, onedrive))
# global constants: raw data format
INCA_CHANNELS = ["time", "pedal_sw", "engine_spd", "throttle"]
EDAQ_CHANNELS_5 = ["time", "pedal_v", "gnd_speed", "pedal_sw"]
EDAQ_CHANNELS_6 = ["time", "pedal_v", "wtq_RR", "wspd_RR", "wtq_LR", "wspd_LR",
"pedal_sw"]
CHANNEL_UNITS = {"time": "s",
"pedal_sw": "off/on",
"pedal_v": "V",
"engine_spd": "rpm",
"gnd_speed": "mph",
"throttle": "deg",
"wtq_RR": "ft-lb",
"wtq_LR": "ft-lb",
"wspd_RR": "rpm",
"wspd_LR": "rpm"
}
INCA_HEADER_HT = 5 # how many non-data rows at top of raw INCA file.
EDAQ_HEADER_HT = 1 # how many non-data rows at top of raw eDAQ file.
SAMPLING_FREQ = 100 # Hz
# global constants: vehicle parameters
ROLLING_RADIUS_FACTOR = 0.965
TIRE_DIAM_IN = 18 # inches
AXLE_RATIO = 11.47
GEARBOX_RATIO = 1.95
# Some case-specific constants stored in class definitions
class FilenameError(Exception):
pass
class DataReadError(Exception):
pass
class DataSyncError(Exception):
pass
class RunGroup(object):
"""Represents a collection of runs from the raw_data directory."""
def __init__(self, process_all=False, start_run=False, verbose=False, warn=False):
self.verbosity = verbose
self.warn_p = warn
# create SingleRun object for each run but don't read in data yet.
self.build_run_dict()
self.process_runs(process_all, start_run)
def build_run_dict(self):
"""Creates dictionary with an entry for each INCA run in raw_data dir."""
if not os.path.exists(RAW_INCA_DIR):
raise DataReadError("No raw INCA directory found. Put data in this "
"folder: %s" % RAW_INCA_DIR)
INCA_files = os.listdir(RAW_INCA_DIR)
INCA_files.sort()
self.run_dict = {}
for i, file in enumerate(INCA_files):
if os.path.isdir(os.path.join(RAW_INCA_DIR, file)):
continue # ignore any directories found
if re.findall(r"(dec{1,2}el)|(downhill)", file, flags=re.IGNORECASE):
try:
ThisRun = self.create_downhill_run(file)
except FilenameError as exception_text:
print(exception_text)
# https://stackoverflow.com/questions/1483429/how-to-print-an-exception-in-python
input("\nRun creation failed with file '%s'.\n"
"Press Enter to skip this run." % (file))
print("") # blank line
continue # Don't add to run dict
else:
try:
ThisRun = self.create_ss_run(file)
except FilenameError as exception_text:
print(exception_text)
# https://stackoverflow.com/questions/1483429/how-to-print-an-exception-in-python
input("\nRun creation failed with file '%s'.\n"
"Press Enter to skip this run." % (file))
print("") # blank line
continue # Don't add to run dict
if ThisRun.get_run_label() in self.run_dict:
# catch duplicate run nums.
dup_answ = ""
while dup_answ.lower() not in ["1", "2"]:
print("More than one run %s found in %s:\n"
"\t1. '%s'\n"
"\t2. '%s'\n"
"Which one should be used as run %s? (1/2)"
% (ThisRun.get_run_label(), RAW_INCA_DIR,
self.run_dict[ThisRun.get_run_label()].get_inca_filename(),
file, ThisRun.get_run_label()))
dup_answ = input("> ")
if dup_answ.lower() == "1":
print("") # blank line
continue
if dup_answ.lower() == "2":
# fall through
pass
self.run_dict[ThisRun.get_run_label()] = ThisRun
def create_ss_run(self, filename):
return SSRun(os.path.join(RAW_INCA_DIR, filename), self.verbosity,
self.warn_p)
def create_downhill_run(self, filename):
return DownhillRun(os.path.join(RAW_INCA_DIR, filename), self.verbosity,
self.warn_p)
def process_runs(self, process_all, start_run):
"""Processes runs in RunGroup."""
if process_all:
# automatically process all INCA runs (below)
self.runs_to_process = dict(self.run_dict) # avoids aliasing.
if start_run:
if not self.validate_run_num(start_run):
raise FileNameError("Cannot find matching INCA run for -s "
"argument %s" % start_run)
# Remove earlier runs
for run_num in self.run_dict.keys():
if run_num < start_run:
self.runs_to_process.pop(run_num)
else:
# prompt user for single run to process.
OnlyRun = self.prompt_for_run()
self.runs_to_process = {OnlyRun.get_run_label(): OnlyRun}
bad_runs = []
for run_num in self.runs_to_process:
RunObj = self.runs_to_process[run_num]
try:
RunObj.process_data()
except Exception:
RunObj.log_exception("Processing")
# Stage for removal from run dict.
bad_runs.append(run_num)
continue
if bad_runs:
for bad_run in bad_runs:
# Remove any errored runs from run dict so they aren't included
# in later calls.
self.runs_to_process.pop(bad_run)
def plot_runs(self, overwrite=False, desc_str=""):
"""Creates plots for all runs in RunGroup."""
if not self.runs_to_process:
print("\nNo valid runs to plot.\n")
return
bad_runs = []
# If only one run in group is to be processed, this will only loop once.
for run_num in self.runs_to_process:
RunObj = self.runs_to_process[run_num]
try:
RunObj.plot_data(overwrite, desc_str)
except Exception:
RunObj.log_exception("Plotting")
# Stage for removal from run dict.
bad_runs.append(run_num)
continue
if bad_runs:
for bad_run in bad_runs:
# Remove any errored runs from run dict so they aren't included
# in later calls.
self.runs_to_process.pop(bad_run)
def export_runs(self, overwrite=False, desc_str=""):
"""Exports data for all runs in RunGroup."""
if not self.runs_to_process:
print("\nNo valid runs to export.\n")
return
bad_runs = []
# If only one run in group is to be processed, this will only loop once.
for run_num in self.runs_to_process:
RunObj = self.runs_to_process[run_num]
try:
RunObj.export_data(overwrite, desc_str)
except Exception:
RunObj.log_exception("Exporting")
# Stage for removal from run dict.
bad_runs.append(run_num)
continue
if bad_runs:
for bad_run in bad_runs:
# Remove any errored runs from run dict so they aren't included
# in later calls.
self.runs_to_process.pop(bad_run)
def prompt_for_run(self):
"""Prompts user for what run to process
Returns SingleRun object."""
run_prompt = "Enter run num (four digits)\n> "
target_run_num = input(run_prompt)
while not self.validate_run_num(target_run_num):
target_run_num = input(run_prompt)
return self.run_dict.get(target_run_num)
def validate_run_num(self, target_run_num):
"""Check if user-entered run num is valid."""
if len(target_run_num) != 4:
print("Need a four-digit number.")
return False
elif self.run_dict.get(target_run_num):
return True
else:
print("No valid INCA file found matching that run.")
return False
class SingleRun(object):
"""Represents a single run from the raw_data directory.
No data is read in until read_data() method called.
"""
def __init__(self, INCA_path, verbose=False, warn_prompt=False):
# Create a new object to store and print output info
self.Doc = Output(verbose, warn_prompt)
self.INCA_path = INCA_path
self.INCA_filename = os.path.basename(self.INCA_path)
self.parse_run_num()
def parse_run_num(self):
run_num_match = re.findall(r"(?<=_)\d{4}(?=-)", self.INCA_filename):
if run_num_match:
self.run_label = run_num_match[0]
else:
raise FilenameError("INCA filename '%s' not in correct format.\n"
"Expected format is "
"'[pretext]_[four-digit run num][anything else]'.\nNeed the four "
"characters that follow the first underscore to be run num."
% self.INCA_filename)
# Create metadata string to document in outuput file
self.meta_str = "INCA_file: '%s' | " % self.INCA_filename
def process_data(self):
"""Run all processing methods on run data."""
self.read_data()
self.sync_data()
if int(self.run_label[:2]) > 5:
# only needed for torque-meter runs.
self.combine_torque()
self.calc_gnd_speed()
self.abridge_data()
self.add_math_channels()
def find_edaq_path(self, eDAQ_file_num):
"""Locate path to eDAQ file corresponding to INCA run num."""
if not os.path.exists(RAW_EDAQ_DIR):
raise DataReadError("No raw eDAQ directory found. Put data in this"
"folder: %s" % RAW_EDAQ_DIR)
all_eDAQ_runs = os.listdir(RAW_EDAQ_DIR)
found_eDAQ = False # initialize to false. Will change if file is found.
for eDAQ_run in all_eDAQ_runs:
if os.path.isdir(os.path.join(RAW_EDAQ_DIR, eDAQ_run)):
continue # ignore any directories found
run_num_match = re.findall(r"(?<=\d{8}_)\d{2}(?=[.-])", eDAQ_run)
if run_num_match:
run_num_i = run_num_match[0]
else:
raise FilenameError("eDAQ filename '%s' not in correct format."
"\nExpected format is "
"'[pretext]_[two-digit file num][anything else]'.\nNeed the "
"two characters that follow the first underscore to be file "
"num.\nThis will cause problems with successive runs until you "
"fix the filename or remove the offending file from %s."
% (eDAQ_run, RAW_EDAQ_DIR))
if run_num_i == eDAQ_file_num and not found_eDAQ:
target_edaq_run = eDAQ_run
found_eDAQ = True
elif run_num_i == eDAQ_file_num:
# Duplicate found
raise FilenameError("More than one eDAQ file with '%s' "
"designation. This will cause problems with successive runs "
"until you remove duplicate files from %s."
% (eDAQ_file_num, RAW_EDAQ_DIR))
if found_eDAQ:
self.eDAQ_path = os.path.join(RAW_EDAQ_DIR, target_edaq_run)
# Document in metadata string for later file output.
self.meta_str += "eDAQ file: '%s' | " % target_edaq_run
else:
raise FilenameError("No eDAQ file found for run %s" % eDAQ_file_num)
def read_data(self):
"""Read in both INCA and eDAQ data from raw_data directory."""
eDAQ_file_num = self.run_label[0:2]
self.find_edaq_path(eDAQ_file_num)
# Channels changed starting with eDAQ file "06"
if int(eDAQ_file_num) > 5:
self.edaq_channels = EDAQ_CHANNELS_6
else:
self.edaq_channels = EDAQ_CHANNELS_5
# Read in both eDAQ and INCA data for specific run.
# Read INCA data first
# File automatically closed at end of "with/as" block.
with open(self.INCA_path, "r") as inca_ascii_file:
self.Doc.print("\nReading INCA data from %s" % self.INCA_path)
INCA_file_in = csv.reader(inca_ascii_file, delimiter="\t")
# https://stackoverflow.com/questions/7856296/parsing-csv-tab-delimited-txt-file-with-python
raw_inca_dict = {}
for channel in INCA_CHANNELS:
raw_inca_dict[channel] = []
for i, INCA_row in enumerate(INCA_file_in):
if i == 2:
# print channel order for debugging
self.Doc.print("\tINCA file channels:\t" +
" - ".join([str(c) for c in INCA_row]), True)
self.Doc.print("\tAssumed channel order:\t" +
" - ".join([str(c) for c in INCA_CHANNELS]), True)
# Explicitly check for improper channel order:
if ("time" not in INCA_row[INCA_CHANNELS.index("time")] or
"SW_PEDAL" not in INCA_row[INCA_CHANNELS.index("pedal_sw")] or
"NE" not in INCA_row[INCA_CHANNELS.index("engine_spd")] or
"THagr" not in INCA_row[INCA_CHANNELS.index("throttle")]):
raise DataReadError("Bad channel order in INCA file.")
continue
elif i < INCA_HEADER_HT:
# ignore headers
continue
else:
for n, channel in enumerate(INCA_CHANNELS):
raw_inca_dict[channel].append(float(INCA_row[n]))
# Convert the dict to a pandas DataFrame for easier manipulation
# and analysis.
self.raw_inca_df = pd.DataFrame(data=raw_inca_dict,
index=raw_inca_dict["time"])
self.Doc.print("...done")
self.Doc.print("\nraw_inca_df after reading in data:", True)
self.Doc.print(self.raw_inca_df.to_string(max_rows=10, max_cols=7,
show_dimensions=True), True)
self.Doc.print("", True)
# Now read eDAQ data
with open(self.eDAQ_path, "r") as edaq_ascii_file:
self.Doc.print("Reading eDAQ data from %s" % self.eDAQ_path)
eDAQ_file_in = csv.reader(edaq_ascii_file, delimiter="\t")
raw_edaq_dict = {}
for channel in self.edaq_channels:
raw_edaq_dict[channel] = []
for j, eDAQ_row in enumerate(eDAQ_file_in):
if j < EDAQ_HEADER_HT-1:
pass
elif j == EDAQ_HEADER_HT-1:
# The first row is a list of channel names.
# Converting to int and back to str strips zero padding
sub_run_num = int(self.run_label[2:4])
edaq_sub_run = "RN_"+str(sub_run_num)
# Loop through and find the first channel for this run.
for n, col in enumerate(eDAQ_row):
if edaq_sub_run in col:
edaq_run_start_col = n
break
if n == len(eDAQ_row) - 1:
# Got to end of row and didn't find the run in any
# column heading
raise DataReadError("Can't find %s in any eDAQ file" %
edaq_sub_run)
elif eDAQ_row[edaq_run_start_col+1]:
# Need to make sure we haven't reached end of channel strm.
# Time vector may keep going past a channel's data, so look
# at a run-specific channel to see if the run's ended.
# Time is always in 1st column.
raw_edaq_dict["time"].append(float(eDAQ_row[0]))
for n, channel in enumerate(self.edaq_channels[1:]):
# Only add this run's channels to our data list.
raw_edaq_dict[channel].append(
float(eDAQ_row[edaq_run_start_col+n]))
self.raw_edaq_df = pd.DataFrame(data=raw_edaq_dict,
index=raw_edaq_dict["time"])
self.Doc.print("...done")
self.Doc.print("\nraw_edaq_df after reading in data:", True)
self.Doc.print(self.raw_edaq_df.to_string(max_rows=10, max_cols=7,
show_dimensions=True), True)
def sync_data(self):
# Create copies of the raw dfs to modify and merge.
inca_df = self.raw_inca_df.copy(deep=True)
edaq_df = self.raw_edaq_df.copy(deep=True)
# Convert index from seconds to hundredths of a second
# It's simple for eDAQ data.
edaq_df.set_index(pd.Index([int(round(ti * SAMPLING_FREQ))
for ti in edaq_df.index]), inplace=True)
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html
# Offset time series to start at zero.
self.shift_time_series(edaq_df, zero=True)
# INCA time increments are slightly off, so error accumulates and
# can eventually cause issues (alternating 0.00 and 0.02s periods
# after rounding).
# Convert INCA to deltas by subtracting each time value from previous
# one, rounding the delta and adding to the previous (rounded) value.
# Calculate the rolling difference (delta) between each pair of vals.
deltas = inca_df["time"].diff()
# https://stackoverflow.com/questions/13114512/calculating-difference-between-two-rows-in-python-pandas
deltas[0] = 0 # first val was NaN
# Round the series then do a cumulative summation:
deltas = pd.Series([round(ti * SAMPLING_FREQ) for ti in deltas])
rolling_delt_times = deltas.cumsum()
# Assign as the index now (converting to int)
inca_df.set_index(pd.Index(rolling_delt_times.astype(int)), inplace=True)
# Check if any pedal events exist
if inca_df.loc[inca_df["pedal_sw"] == 1].empty:
raise DataSyncError("No pedal event found in INCA data (looking for"
" value of 1 in pedal switch column). Check input pedal data and "
"ordering of input file's columns.")
if edaq_df.loc[edaq_df["pedal_sw"] == 1].empty:
raise DataSyncError("No pedal event found in eDAQ data (looking for"
" value of 1 in pedal switch column). Check input pedal data and "
"ordering of input file's columns.")
# Find first pedal switch event.
# https://stackoverflow.com/questions/16683701/in-pandas-how-to-get-the-index-of-a-known-value
inca_high_start_t = inca_df.loc[inca_df["pedal_sw"] == 1].index[0]
edaq_high_start_t = edaq_df.loc[edaq_df["pedal_sw"] == 1].index[0]
self.Doc.print("\nStart times (inca, edaq): %.2fs, %.2fs"
% (inca_high_start_t / SAMPLING_FREQ,
edaq_high_start_t / SAMPLING_FREQ), True)
# Test first to see if either data set has first pedal event earlier
# than 1s. If so, that's the new time for both files to align on.
start_buffer = min([1 * SAMPLING_FREQ, inca_high_start_t,
edaq_high_start_t])
self.Doc.print("Start buffer: %0.2fs"
% (start_buffer/SAMPLING_FREQ), True)
# Shift time values, leaving negative values in early part of file that
# will be trimmed off below.
inca_target_t = inca_high_start_t - start_buffer
edaq_target_t = edaq_high_start_t - start_buffer
self.shift_time_series(inca_df, offset_val=-inca_target_t)
self.shift_time_series(edaq_df, offset_val=-edaq_target_t)
self.Doc.print("First INCA sample shifted to time %0.2fs"
% (inca_df.index[0]/SAMPLING_FREQ), True)
self.Doc.print("First eDAQ sample shifted to time %0.2fs"
% (edaq_df.index[0]/SAMPLING_FREQ), True)
# Unify datasets into one DataFrame/
# Slice out values before t=0 (1s before first pedal press)
# Truncate file with extra time vals at end. Will not happen during
# join() because of the "outer" option creating union to catch any
# time gaps in either dataset (has happened in INCA runs).
end_time = min(inca_df.index[-1], edaq_df.index[-1])
# Leave out redundant channels in eDAQ data.
# Carry over raw time for debugging purposes.
# The suffix options keep the two DFs' time columns from conflicting.
self.sync_df = inca_df.loc[0:end_time].join(
edaq_df.loc[0:end_time, edaq_df.drop(
columns=["pedal_v", "pedal_sw"]).columns],
lsuffix="_raw_inca", rsuffix="_raw_edaq", how="outer")
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html#pandas.DataFrame.join
self.Doc.print("\nsync_df at end of sync:", True)
self.Doc.print(self.sync_df.to_string(max_rows=10, max_cols=7,
show_dimensions=True), True)
def shift_time_series(self, df, zero=False, offset_val=None):
"""If offset_val param specified, add this signed value to all time
values.
If zero param passed, offset all such that first val is 0."""
if zero:
offset_val = -df.index[0]
elif offset_val==None:
raise DataSyncError("shift_time_series needs either zero or "
"offset_val param.")
df.set_index(df.index + offset_val, inplace=True)
def combine_torque(self):
"""Sums LR and RR wheel torque readings.
Used when processing runs 06xx+ that use torque meters."""
tq_sum = wspd_avg = self.sync_df[["wtq_RR", "wtq_LR"]].sum(axis=1)
# Remove original columns and replace with combined one.
self.sync_df.drop(columns=["wtq_RR", "wtq_LR"], inplace=True)
self.sync_df["rear_wtq_combined"] = tq_sum
CHANNEL_UNITS["rear_wtq_combined"] = CHANNEL_UNITS["wtq_RR"]
def calc_gnd_speed(self):
"""Averages LR and RR angular wheel speeds.
Used when processing runs 06xx+ that use torque meters."""
wspd_avg = self.sync_df[["wspd_RR", "wspd_LR"]].mean(axis=1)
# Remove wheel speed channels since we don't want them written to sync file.
self.sync_df.drop(columns=["wspd_RR", "wspd_LR"], inplace=True)
# Convert to linear speed.
tire_circ = np.pi * TIRE_DIAM_IN * ROLLING_RADIUS_FACTOR # inches
gnd_spd_in_min = wspd_avg * tire_circ
self.sync_df["gnd_speed"] = gnd_spd_in_min / (5280 * 12/60) # inches/min to mph
def knit_pedal_gaps(self):
"""Finds any gaps in INCA pedal channel and fills them if pedal signal
is high before and after gap. Prevents false-negative in abridge
algo."""
na_times = self.sync_df["pedal_sw"][self.sync_df["pedal_sw"].isna()]
if len(na_times) == 0:
self.Doc.print("\nNo missing INCA times found.")
return
else:
self.Doc.print("\nMissing INCA times (len: %d):" % len(na_times), True)
self.Doc.print(na_times.to_string(max_rows=10), True)
# Filter trivial case of gap length 1 to avoid IndexError below.
if len(na_times) == 1:
# set variables used in reassignment loop below
gap_ranges = [na_times.index[0], na_times.index[0]]
elif len(na_times) > 1:
# Step through na_times and identify any discontinuities, indicating
# multiple gaps in the data.
gap_ranges = []
current_range = [na_times.index[0]]
for i, time in enumerate(na_times.index[1:]):
prev_time = na_times.index[i] # i is behind by one.
if time - prev_time > 1:
current_range.append(prev_time)
gap_ranges.append(current_range)
# Reset range
current_range = [time]
# Add last value to end of last range
current_range.append(time)
gap_ranges.append(current_range)
self.Doc.print("\nContinuous INCA sample gaps: ")
for range in gap_ranges:
self.Doc.print("\t%0.2f\t->\t%0.2f"
% (range[0] / SAMPLING_FREQ, range[1] / SAMPLING_FREQ))
# https://stackoverflow.com/questions/973568/convert-nested-lists-to-string
for range in gap_ranges:
# Find time values before and after gap
pre_time_i = self.sync_df.index.get_loc(range[0]) - 1
post_time_i = self.sync_df.index.get_loc(range[-1]) + 1
pre_time = self.sync_df.index[pre_time_i]
post_time = self.sync_df.index[post_time_i]
# https://stackoverflow.com/questions/28837633/pandas-get-position-of-a-given-index-in-dataframe
knit = False
if (self.sync_df.at[pre_time, "pedal_sw"]
and self.sync_df.at[post_time, "pedal_sw"]):
# Only need to knit gap if pedal was actuated before gap and
# still actuated after. Assume no interruption during gap.
self.Doc.print("\nKnitting pedal event in gap %0.2f -> %0.2f"
% (range[0] / SAMPLING_FREQ, range[-1] / SAMPLING_FREQ))
self.sync_df.at[range[0]:range[1]+1, "pedal_sw"] = 1
knit = True
self.Doc.print("\nsync_df after knitting pedal event:", True)
self.Doc.print(self.sync_df[range[0]-2:range[1]+3].to_string(
max_rows=10, max_cols=7, show_dimensions=True), True)
if not knit:
self.Doc.print("\nNo pedal events to knit.")
def abridge_data(self):
# Implemented in child classes
# Different version of this function in SSRun vs. DownhillRun
pass
def add_math_channels(self):
# Implemented in child classes
# Different version of this function in SSRun vs. DownhillRun
pass
def add_cvt_ratio(self):
"""Calculate instantaneous CVT ratio and include in abridged dataframe."""
tire_circ = np.pi * TIRE_DIAM_IN * ROLLING_RADIUS_FACTOR # inches
if self.get_run_type() == "SSRun":
gnd_spd_in_min = self.abr_df["gnd_speed"] * 5280 * 12/60 # inches/min
elif self.get_run_type() == "DownhillRun":
# Downhill run already has rolling avg available.
# Using this more stable data to generate CVT ratio for plot.
gnd_spd_in_min = self.math_df["gs_rolling_avg"] * 5280 * 12/60 # inches/min
tire_ang_spd = gnd_spd_in_min / tire_circ
self.math_df["input_shaft_ang_spd"] = tire_ang_spd * AXLE_RATIO * GEARBOX_RATIO
self.math_df["cvt_ratio"] = (self.abr_df["engine_spd"]
/ self.math_df["input_shaft_ang_spd"])
# # Remove any values that are zero or > 5 (including infinite).
self.math_df["cvt_ratio_mskd"] = self.math_df["cvt_ratio"].mask(
(self.math_df["cvt_ratio"] > 5) | (self.math_df["cvt_ratio"] <= 0))
# Transcribe to main DF for export
self.abr_df["CVT_ratio_calc"] = self.math_df["cvt_ratio_mskd"].copy()
CHANNEL_UNITS["CVT_ratio_calc"] = "rpm/rpm"
def plot_data(self, overwrite=False, description=""):
"""Plot various raw and calculated data from run.
Child classes add to this."""
self.overwrite = overwrite
self.description = description
self.Doc.print("") # blank line
self.plot_abridge_compare()
self.plot_cvt_ratio()
def plot_abridge_compare(self):
# Implemented in child classes
# Different version of this function in SSRun vs. DownhillRun
pass
def plot_cvt_ratio(self):
"""Plot calculated CVT ratio along with other data for evaluation."""
ax1 = plt.subplot(311)
# https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.subplot.html
plt.plot(self.math_df.index/SAMPLING_FREQ,
self.math_df["gs_rolling_avg"], color="lightgrey", zorder=2)
plt.plot(self.math_df.index/SAMPLING_FREQ,
self.math_df["gs_rol_avg_mskd"], color="r", zorder=3)
ax1.set_ylabel("Speed (mph)")
if self.get_run_type() == "SSRun" and ~np.isnan(self.math_df.at[0, "SS_gnd_spd_avg"]):
# plot average for steady-state run
avg = self.math_df.at[0, "SS_gnd_spd_avg"]
color="lightcoral"
ax1.axhline(avg, color=color, zorder=1)
if avg > ax1.get_ylim()[1]*2/10:
y_pos = avg - ax1.get_ylim()[1]/8
else:
y_pos = avg + ax1.get_ylim()[1]/10
ax1.text(ax1.get_xlim()[0], y_pos, str(round(avg, 1)), color=color,
fontsize="x-small")
elif self.get_run_type() == "DownhillRun":
# Plot slopes for downhill run
# Restore existing y-axis limits after adding slopes because slopes
# may extend beyond optimal window limits.
ylims = ax1.get_ylim()
color = "lightcoral"
plt.plot(self.math_df.index/SAMPLING_FREQ,
self.math_df["trendlines"], color=color, zorder=1, scaley=False)
ax1.set_ylim(ylims)
ax1.text(ax1.get_xlim()[0], ax1.get_ylim()[1]*9/10,
" Eng-on: %.2f" % self.math_df.at[0, "accel_avg_calc_eng_on"],
color=color, fontsize="x-small")
ax1.text(ax1.get_xlim()[0], ax1.get_ylim()[1]*8/10,
" Eng-off: %.2f" % self.math_df.at[0, "accel_avg_calc_eng_off"],
color=color, fontsize="x-small")
# https://stackoverflow.com/questions/7386872/make-matplotlib-autoscaling-ignore-some-of-the-plots
# https://matplotlib.org/3.1.1/gallery/misc/zorder_demo.html
plt.title("Run %s - CVT Ratio (Abridged Data)" % self.run_label, loc="left")
plt.setp(ax1.get_xticklabels(), visible=False) # x labels only on bottom
ax2 = plt.subplot(312, sharex=ax1)
if self.get_run_type() == "SSRun":
es_rolling_avg = self.math_df["es_rolling_avg"]
engine_spd_mskd = self.math_df["es_rol_avg_mskd"]
elif self.get_run_type() == "DownhillRun":
es_rolling_avg = self.abr_df["engine_spd"]
engine_spd_mskd = self.abr_df["engine_spd"].mask(~self.math_df["downhill_filter"])
plt.plot(self.abr_df.index/SAMPLING_FREQ, es_rolling_avg, color="lightgrey", zorder=2)
plt.plot(self.abr_df.index/SAMPLING_FREQ, engine_spd_mskd, color="tab:blue", zorder=3)
if self.get_run_type() == "SSRun" and ~np.isnan(self.math_df.at[0, "SS_eng_spd_avg"]):
# plot average for steady-state run
avg = self.math_df.at[0, "SS_eng_spd_avg"]
color = "lightsteelblue"
ax2.axhline(avg, color=color, zorder=1)
if avg > ax2.get_ylim()[1]*2/10:
y_pos = avg - ax2.get_ylim()[1]/10
else:
y_pos = avg + ax2.get_ylim()[1]/10
ax2.text(ax2.get_xlim()[0], y_pos, "%.0f" % avg, color=color,
fontsize="x-small")
ax2.set_ylabel("Engine Speed (rpm)")
plt.setp(ax2.get_xticklabels(), visible=False) # x labels only on bottom
ax3 = plt.subplot(313, sharex=ax1)
plt.plot(self.math_df.index/SAMPLING_FREQ, self.math_df["cvt_ratio"],
color="lightgrey", zorder=2)
plt.plot(self.math_df.index/SAMPLING_FREQ, self.math_df["cvt_ratio_mskd"],
color="tab:green", zorder=3)
ax3.set_ylim([-0.2, 4])
ax3.set_yticks([0, 1, 2, 3, 4])
if self.get_run_type() == "SSRun" and ~np.isnan(self.math_df.at[0, "SS_cvt_ratio_avg"]):
# plot average for steady-state run
avg = self.math_df.at[0, "SS_cvt_ratio_avg"]
color="lightgreen"
ax3.axhline(avg, color=color, zorder=1)
if avg > ax3.get_ylim()[1]*2/10:
y_pos = avg - ax3.get_ylim()[1]/10
else:
y_pos = avg + ax3.get_ylim()[1]/25
ax3.text(ax3.get_xlim()[0], y_pos, " " + str(round(avg, 1)),
color=color, fontsize="x-small")
ax3.set_ylabel("CVT Ratio Calc")
ax3.set_xlabel("Time (s)")
# plt.show() # can't use w/ WSL. Export instead.
# https://stackoverflow.com/questions/43397162/show-matplotlib-plots-and-other-gui-in-ubuntu-wsl1-wsl2
self.export_plot("cvt")
plt.clf()
# https://stackoverflow.com/questions/8213522/when-to-use-cla-clf-or-close-for-clearing-a-plot-in-matplotlib
def export_plot(self, type):
"""Exports plot that's already been created with another method.
Assumes caller method will clear figure afterward."""
if self.description:
fig_filepath = ("%s/%s_%s-%s.png"
% (PLOT_DIR, self.run_label, type, self.description))
else:
fig_filepath = "%s/%s_%s.png" % (PLOT_DIR, self.run_label, type)
short_hash_len = 6
# Check for existing fig with same filename including description but
# EXCLUDING hash.
wildcard_filename = (os.path.splitext(fig_filepath)[0]
+ "-#" + "?"*short_hash_len
+ os.path.splitext(fig_filepath)[1])
if glob.glob(wildcard_filename) and not self.overwrite:
ow_answer = ""
while ow_answer.lower() not in ["y", "n"]:
self.Doc.print("\n%s already exists in figs folder. Overwrite? (Y/N)"
% os.path.basename(wildcard_filename))
ow_answer = input("> ")
if ow_answer.lower() == "y":
for filepath in glob.glob(wildcard_filename):
os.remove(filepath)
# continue with rest of function
elif ow_answer.lower() == "n":
# plot will be cleared in caller function.
return
elif glob.glob(wildcard_filename) and self.overwrite:
for filepath in glob.glob(wildcard_filename):
os.remove(filepath)
# Must manually remove because if figure hash changes, it will
# not overwrite original.
plt.savefig(fig_filepath)
# Calculate unique hash value (like a fingerprint) to output in CSV's
# meta_str. Put in img filename too.
img_hash = hashlib.sha1(Image.open(fig_filepath).tobytes())
# https://stackoverflow.com/questions/24126596/print-md5-hash-of-an-image-opened-with-pythons-pil
hash_text = img_hash.hexdigest()[:short_hash_len]
fig_filepath_hash = (os.path.splitext(fig_filepath)[0] + "-#"
+ hash_text + os.path.splitext(fig_filepath)[1])
os.rename(fig_filepath, fig_filepath_hash)
self.Doc.print("Exported plot as %s." % fig_filepath_hash)
self.meta_str += ("Corresponding %s fig hash: '%s' | "
% (type, hash_text))
def export_data(self, overwrite=False, description=""):
"""Output CSV file with synced and abridged data, including some
calculated channels and aggregated values."""
self.overwrite = overwrite
self.description = description
export_df = self.abr_df.drop(columns=["time_raw_inca", "time_raw_edaq"])
# https://stackoverflow.com/questions/29763620/how-to-select-all-columns-except-one-column-in-pandas
if self.get_run_type() == "SSRun":
# Pad the columns to not overlap Downhill-specific columns.
speed_index = export_df.columns.get_loc("gnd_speed")
export_df.insert(speed_index + 1, "gnd_speed_reg_slope", np.nan)
CHANNEL_UNITS["gnd_speed_reg_slope"] = CHANNEL_UNITS["gnd_speed"] + "/s"
# Add some channels from math_df
export_df["SS_gnd_spd_avg_calc"] = self.math_df["SS_gnd_spd_avg"]
export_df["SS_eng_spd_avg_calc"] = self.math_df["SS_eng_spd_avg"]
export_df["SS_cvt_ratio_avg_calc"] = self.math_df["SS_cvt_ratio_avg"]
CHANNEL_UNITS["SS_gnd_spd_avg_calc"] = CHANNEL_UNITS["gnd_speed"]
CHANNEL_UNITS["SS_eng_spd_avg_calc"] = CHANNEL_UNITS["engine_spd"]
CHANNEL_UNITS["SS_cvt_ratio_avg_calc"] = CHANNEL_UNITS["CVT_ratio_calc"]
elif self.get_run_type() == "DownhillRun":
# Pad the columns to not overlap SS-specific columns.
export_df[" "] = np.nan
export_df[" "] = np.nan
export_df[" "] = np.nan
CHANNEL_UNITS[" "] = ""
CHANNEL_UNITS[" "] = ""
CHANNEL_UNITS[" "] = ""
# Add some channels from math_df
export_df["accel_avg_calc_eng_on"] = self.math_df["accel_avg_calc_eng_on"]
export_df["accel_avg_calc_eng_off"] = self.math_df["accel_avg_calc_eng_off"]
CHANNEL_UNITS["accel_avg_calc_eng_on"] = CHANNEL_UNITS["gnd_speed"] + "/s"
CHANNEL_UNITS["accel_avg_calc_eng_off"] = CHANNEL_UNITS["accel_avg_calc_eng_on"]
# More column-padding, but only needed for runs w/o torque meters.
if int(self.run_label[:2]) < 6:
speed_index = export_df.columns.get_loc("gnd_speed")
export_df.insert(speed_index, "rear_wtq_combined", np.nan)
CHANNEL_UNITS["rear_wtq_combined"] = CHANNEL_UNITS["wtq_RR"]
# Replace any NaNs with blanks
export_df.fillna("", inplace=True)
# https://stackoverflow.com/questions/26837998/pandas-replace-nan-with-blank-empty-string
# Convert to list of lists for easier writing out
sync_array = export_df.values.tolist()
# https://stackoverflow.com/questions/28006793/pandas-dataframe-to-list-of-lists
# Convert time values from hundredths of a second to seconds
time_series = [round(ti/SAMPLING_FREQ,2)
for ti in export_df.index.tolist()]
for line_no, line in enumerate(sync_array):
# prepend time values
sync_array[line_no].insert(0, time_series[line_no])
# https://stackoverflow.com/questions/8537916/whats-the-idiomatic-syntax-for-prepending-to-a-short-python-list
# Format header rows
channel_list = ["time"] + export_df.columns.tolist()
header_rows = [channel_list, [CHANNEL_UNITS[c] for c in channel_list]]
# Add headers to array
sync_array.insert(0, header_rows[1])
sync_array.insert(0, header_rows[0])
# Add metadata string
sync_array.insert(0, [self.get_meta_str()])
if self.description:
sync_basename = "%s_Sync-%s.csv" % (self.run_label, self.description)
else:
sync_basename = "%s_Sync.csv" % self.run_label
sync_filename = "%s/%s" % (SYNC_DIR, sync_basename)
# Check if file exists already. Prompt user for overwrite decision.
if os.path.exists(sync_filename) and not self.overwrite:
ow_answer = ""
while ow_answer.lower() not in ["y", "n"]:
self.Doc.print("\n%s already exists in sync_data folder. Overwrite? (Y/N)"
% sync_basename)
ow_answer = input("> ")
if ow_answer.lower() == "n":
return
# Create new CSV file and write out. Closes automatically at end of
# with/as block.
# This block does not run if answered no to overwrite above.
with open(sync_filename, 'w+') as sync_file:
sync_file_csv = csv.writer(sync_file, dialect="excel")
self.Doc.print("\nWriting combined data to %s..." % sync_filename)
sync_file_csv.writerows(sync_array)
self.Doc.print("...done")
def log_exception(self, operation):
"""Write output file for later debugging upon encountering exception."""
exception_trace = traceback.format_exc()
# https://stackoverflow.com/questions/1483429/how-to-print-an-exception-in-python
timestamp = datetime.now().strftime("%Y-%m-%dT%H%M%S")
# https://stackoverflow.com/questions/415511/how-to-get-the-current-time-in-python
filename = "%s_Run%s_%s_error.txt" % (timestamp, self.get_run_label(),
operation.lower())
self.Doc.print(exception_trace)
# Wait one second to prevent overwriting previous error if it occurred less
# than one second ago.
time.sleep(1)
full_path = os.path.join(LOG_DIR, filename)
with open(full_path, "w") as log_file:
log_file.write(self.get_output().get_log_dump())
input("\n%s failed on run %s.\nOutput and exception "
"trace written to '%s'.\nPress Enter to skip this run."
% (operation, self.get_run_label(), full_path))
print("") # blank line
def get_run_label(self):
return self.run_label
def get_inca_filename(self):
return self.INCA_filename
def get_meta_str(self):
# Remove trailing delimiter
return self.meta_str[:-3]
def get_output(self):
return self.Doc
def __str__(self):
return self.run_label
def __repr__(self):
return ("SingleRun object for INCA run %s" % self.run_label)
class SSRun(SingleRun):
"""Represents a single run with steady-state operation. INCA file name
determines SS vs. Downhill."""
def abridge_data(self):
"""Isolates important events in data by removing any long stretches of
no pedal input or pedal events during which the throttle position not
sustained above threshold for enough time.
"""
# Define constants used to isolating valid events.
thrtl_thresh = 45 # degrees ("throttle threshold")
thrtl_t_thresh = 2 # seconds ("throttle time threshold")
# Need to repair any gaps in INCA samples. If pedal was actuated
# when sampling cut out, and it was still actuated when the sampling
# resumed, the abridge_data() algorithmm will treat that as a pedal lift
# when it likely wasn't.
self.knit_pedal_gaps()
# list of start and end times for pedal-down events meeting criteria.
valid_event_times = []
# maintain a buffer of candidate pedal-down and throttle time vals.
ped_buffer = []
high_throttle_time = [0, 0]
self.Doc.print("\nSteady-state event parsing:")
pedal_down = False
counting = False
keep = False
for i, ti in enumerate(self.sync_df.index):
# Main loop evaluates pedal-down event. Stores event start and end
# times if inner loop finds criteria met during event.
if self.sync_df["pedal_sw"][ti] == 1: