-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary.py
1502 lines (1273 loc) · 46.2 KB
/
binary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
import getopt
import glob
import logging
import os
import subprocess
import sys
import numpy as np
import pandas as pd
from guizero import (
App,
Box,
CheckBox,
Combo,
ListBox,
PushButton,
Text,
TextBox,
TitleBox,
Window,
)
from pandas.api.types import is_integer_dtype
import common
from parameter import *
# Constants:
ZERO_TO_ONE = "0 to 1"
ONE_TO_ZERO = "1 to 0"
# output columns
OUTPUT_COL0_TS = "timestamps"
OUTPUT_COL1_MI = "Motion Index"
OUTPUT_COL2_MI_AVG = "Avg of MI"
OUTPUT_COL3_FREEZE_TP = "Freezing TurnPoints"
# output directory and file names
OUTPUT_DIR_NAME = "_output"
OUTPUT_BASE = "_base.csv"
MIN_DURATION = "_min_duration.csv"
TW_FILTER = "_tw_filter.csv"
UNDERSCORE = "_"
EMPTY = "_EMPTY"
# output file name formats:
OUTPUT_NO_PARAMETERS = "_outside-parameters"
OUTPUT_ZERO_TO_ONE_CSV_NAME = "01"
OUTPUT_ONE_TO_ZERO_CSV_NAME = "10"
OUTPUT_LOG_FILE = "binary_output.log"
# UI related constants
INPUT_FOLDER_NAME_BOX_MAX_WIDTH = 26
PARAM_UI_TIME_WINDOW_START_TIMES = "Time window start (secs):"
PARAM_UI_MIN_TIME_DURATION_CRITERIA_TEXT = "Min time duration criteria (secs):"
PARAM_UI_MIN_BEFORE_TIME_DURATION_CRITERIA_TEXT = "\t\t before: "
PARAM_UI_MIN_AFTER_TIME_DURATION_CRITERIA_TEXT = "after: "
PARAM_UI_TIME_WINDOW_DURATION_TEXT = "Time window duration (secs): "
# globals
r_log_box = None
output_dir = None
OUTPUT_COLUMN_SCHEMA = {
OUTPUT_COL0_TS: 'float64',
OUTPUT_COL1_MI: 'float64',
OUTPUT_COL2_MI_AVG: 'float64',
OUTPUT_COL3_FREEZE_TP: 'str',
}
out_file_zero_to_one = ""
out_file_zero_to_one_ts = ""
out_file_zero_to_one_un = ""
out_file_zero_to_one_un_ts = ""
out_file_one_to_zero = ""
out_file_one_to_zero_ts = ""
out_file_one_to_zero_un = ""
out_file_one_to_zero_un_ts = ""
param_file_exists = False
parameter_obj = Parameters()
param_min_time_duration_before = 0
param_min_time_duration_after = 0
param_window_duration = 0
# When set to True, only the currently selected parameter is processed instead
# of all the parameters. Default is to process all parameters.
only_process_cur_param = False
# When set to True, create output folder with the csv file name.
create_output_folder_with_file_name = True
# When set to True, add the csv file name to the output file names.
add_csv_file_name_to_output = False
files_without_timeshift = []
def apply_duration_criteria(
ts_series, param_min_time_duration_before, param_min_time_duration_after
):
it = ts_series.items()
prev_ts = 0
for i, (idx, ts) in enumerate(it):
# Query the timestamp of the next element in the series.
# Default behavior is to drop the last element.
if i == ts_series.size - 1:
break
next_ts = ts_series.iat[i + 1]
if (ts - prev_ts >= param_min_time_duration_before) and (
next_ts - ts >= param_min_time_duration_after
):
yield idx
prev_ts = ts
def apply_timewindow_filter(ts_series, timstamp_filter_series, duration):
it = ts_series.items()
for idx, val in it:
for filter_idx, filter_val in timstamp_filter_series.items():
if val < filter_val:
break
if val >= filter_val and val <= filter_val + duration:
yield idx
break
def apply_special_emtpy_ts_logic(file_name_with_path, df):
"""
This function will generate a new name for the file if the supplied
DataFrame is empty
"""
if df.empty:
dir_namm = os.path.dirname(file_name_with_path)
file_name_without_ext, ext = os.path.splitext(
os.path.basename(file_name_with_path)
)
return os.path.join(dir_namm, file_name_without_ext + EMPTY + ext)
return file_name_with_path
def split_df_and_output(
out_df,
timeshift_val,
out_file_zero_to_one,
out_file_one_to_zero,
out_file_zero_to_one_ts,
out_file_one_to_zero_ts,
):
"""
Split the DataFrame based on whether it is a [0->1] or [1->0] transitions
and output to respective files.
Timestamps file should have the header
"""
# Create a copy of the DataFrame so that the original is not affected
output_df = out_df[:]
output_df[OUTPUT_COL0_TS] = output_df[OUTPUT_COL0_TS] + timeshift_val
# Round up to two decimals
output_df[OUTPUT_COL0_TS] = output_df[OUTPUT_COL0_TS].astype(
float).round(decimals=2)
common.logger.debug("Removing all entries with timestamp < 10 secs")
# Remove all entries with timestamps less than 10 seconds
output_df = output_df[output_df[OUTPUT_COL0_TS] > 10]
out_zero_to_one_df = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
out_one_to_zero_df = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
out_zero_to_one_df = output_df.loc[output_df[OUTPUT_COL3_FREEZE_TP] == ZERO_TO_ONE]
out_zero_to_one_ts_df = out_zero_to_one_df.loc[:, OUTPUT_COL0_TS]
out_one_to_zero_df = output_df.loc[output_df[OUTPUT_COL3_FREEZE_TP] == ONE_TO_ZERO]
out_one_to_zero_ts_df = out_one_to_zero_df.loc[:, OUTPUT_COL0_TS]
out_zero_to_one_df.to_csv(out_file_zero_to_one, index=False)
out_file_zero_to_one_ts = apply_special_emtpy_ts_logic(
out_file_zero_to_one_ts, out_zero_to_one_ts_df
)
out_zero_to_one_ts_df.to_csv(
out_file_zero_to_one_ts, index=False, header=True)
out_one_to_zero_df.to_csv(out_file_one_to_zero, index=False)
out_file_one_to_zero_ts = apply_special_emtpy_ts_logic(
out_file_one_to_zero_ts, out_one_to_zero_ts_df
)
out_one_to_zero_ts_df.to_csv(
out_file_one_to_zero_ts, index=False, header=True)
def out_base(input_file, output_folder):
input_file_without_ext = os.path.splitext(os.path.basename(input_file))[0]
return os.path.join(output_folder, input_file_without_ext + OUTPUT_BASE)
def out_min_duration_file(input_file, output_folder):
input_file_without_ext = os.path.splitext(os.path.basename(input_file))[0]
return os.path.join(output_folder, input_file_without_ext + MIN_DURATION)
def out_tw_filter_file(input_file, param_name, output_folder):
input_file_without_ext = os.path.splitext(os.path.basename(input_file))[0]
return os.path.join(
output_folder, input_file_without_ext + UNDERSCORE + param_name + TW_FILTER
)
def format_out_name_with_param_val(
param_min_time_duration_before, param_min_time_duration_after
):
global param_file_exists
if param_file_exists == False or (
param_min_time_duration_before == 0 and param_min_time_duration_after == 0
):
return ""
else:
return (
UNDERSCORE
+ str(int(param_min_time_duration_before))
+ "-"
+ str(int(param_min_time_duration_after))
+ "s"
)
def format_out_nop_file_name(
input_file,
param_names,
param_min_time_duration_before,
param_min_time_duration_after,
output_folder,
):
"""
Format the 'no parameter' output file name
"""
global out_file_zero_to_one_un, out_file_zero_to_one_un_ts
global out_file_one_to_zero_un, out_file_one_to_zero_un_ts
output_no_parameter = ""
if param_names:
output_no_parameter = OUTPUT_NO_PARAMETERS
input_file_without_ext = os.path.splitext(os.path.basename(input_file))[0]
out_file_zero_to_one_un = os.path.join(
output_folder,
input_file_without_ext
+ UNDERSCORE
+ OUTPUT_ZERO_TO_ONE_CSV_NAME
+ output_no_parameter
+ common.CSV_EXT,
)
min_time_before_after = format_out_name_with_param_val(
param_min_time_duration_before, param_min_time_duration_after
)
if add_csv_file_name_to_output:
out_file_zero_to_one_un_ts = os.path.join(
output_folder,
OUTPUT_ZERO_TO_ONE_CSV_NAME
+ UNDERSCORE
+ input_file_without_ext
+ min_time_before_after
+ output_no_parameter
+ common.CSV_EXT,
)
else:
out_file_zero_to_one_un_ts = os.path.join(
output_folder,
OUTPUT_ZERO_TO_ONE_CSV_NAME
+ min_time_before_after
+ output_no_parameter
+ common.CSV_EXT,
)
out_file_one_to_zero_un = os.path.join(
output_folder,
input_file_without_ext
+ UNDERSCORE
+ OUTPUT_ONE_TO_ZERO_CSV_NAME
+ output_no_parameter
+ common.CSV_EXT,
)
if add_csv_file_name_to_output:
out_file_one_to_zero_un_ts = os.path.join(
output_folder,
OUTPUT_ONE_TO_ZERO_CSV_NAME
+ UNDERSCORE
+ input_file_without_ext
+ min_time_before_after
+ output_no_parameter
+ common.CSV_EXT,
)
else:
out_file_one_to_zero_un_ts = os.path.join(
output_folder,
OUTPUT_ONE_TO_ZERO_CSV_NAME
+ min_time_before_after
+ output_no_parameter
+ common.CSV_EXT,
)
common.logger.debug("\tOutput files:")
common.logger.debug("\t\tNOp [0->1]: %s",
os.path.basename(out_file_zero_to_one_un))
common.logger.debug("\t\tNOp [1->0]: %s",
os.path.basename(out_file_one_to_zero_un))
common.logger.debug(
"\t\tNOp [0->1] TimeStamps Only: %s",
os.path.basename(out_file_zero_to_one_un_ts),
)
common.logger.debug(
"\t\tNOp [1->0] TimeStamps Only: %s",
os.path.basename(out_file_one_to_zero_un_ts),
)
def format_out_file_names(
input_file,
param_name,
param_min_time_duration_before,
param_min_time_duration_after,
output_folder,
):
"""
Format the output file names
"""
global out_file_zero_to_one, out_file_zero_to_one_ts
global out_file_one_to_zero, out_file_one_to_zero_ts
global add_csv_file_name_to_output
param_ext = ""
if param_name:
param_ext = "_" + param_name
input_file_without_ext = os.path.splitext(os.path.basename(input_file))[0]
out_file_zero_to_one = os.path.join(
output_folder,
input_file_without_ext
+ UNDERSCORE
+ OUTPUT_ZERO_TO_ONE_CSV_NAME
+ param_ext
+ common.CSV_EXT,
)
min_time_before_after = format_out_name_with_param_val(
param_min_time_duration_before, param_min_time_duration_after
)
if add_csv_file_name_to_output:
out_file_zero_to_one_ts = os.path.join(
output_folder,
OUTPUT_ZERO_TO_ONE_CSV_NAME
+ UNDERSCORE
+ input_file_without_ext
+ min_time_before_after
+ param_ext
+ common.CSV_EXT,
)
else:
out_file_zero_to_one_ts = os.path.join(
output_folder,
OUTPUT_ZERO_TO_ONE_CSV_NAME
+ min_time_before_after
+ param_ext
+ common.CSV_EXT,
)
out_file_one_to_zero = os.path.join(
output_folder,
input_file_without_ext
+ UNDERSCORE
+ OUTPUT_ONE_TO_ZERO_CSV_NAME
+ param_ext
+ common.CSV_EXT,
)
if add_csv_file_name_to_output:
out_file_one_to_zero_ts = os.path.join(
output_folder,
OUTPUT_ONE_TO_ZERO_CSV_NAME
+ UNDERSCORE
+ input_file_without_ext
+ min_time_before_after
+ param_ext
+ common.CSV_EXT,
)
else:
out_file_one_to_zero_ts = os.path.join(
output_folder,
OUTPUT_ONE_TO_ZERO_CSV_NAME
+ min_time_before_after
+ param_ext
+ common.CSV_EXT,
)
common.logger.debug("\tOutput files:")
common.logger.debug(
"\t\t[0->1]: %s", os.path.basename(out_file_zero_to_one))
common.logger.debug(
"\t\t[1->0]: %s", os.path.basename(out_file_one_to_zero))
common.logger.debug(
"\t\t[0->1] TimeStamps Only: %s", os.path.basename(
out_file_zero_to_one_ts)
)
common.logger.debug(
"\t\t[1->0] TimeStamps Only: %s", os.path.basename(
out_file_one_to_zero_ts)
)
def parse_param_folder(parameter_obj):
"""
Parse parameter folder and create a list of parameter DataFrame(s)
out of it.
"""
input_dir = common.get_input_dir()
try:
parameter_obj.parse(input_dir)
except ValueError as e:
common.logger.warning(e)
def get_param_min_time_duration(parameter_obj):
"""
Returns the value of the min parameter time duration value.
"""
global param_file_exists
(
param_file_exists,
t_duration_before,
t_duration_after,
) = parameter_obj.get_min_time_duration_values()
return t_duration_before, t_duration_after
def reset_all_parameters():
global param_min_time_duration_before, param_window_duration
global param_min_time_duration_after
param_min_time_duration_before = param_min_time_duration_before
param_window_duration = param_min_time_duration_after
def parse_cur_param_file(parameter_obj):
"""
Parse the paramter file
"""
global param_min_time_duration_before, param_min_time_duration_after
update_min_t_in_file(
min_time_duration_before_box.value, min_time_duration_after_box.value
)
param_min_time_duration_before = min_time_duration_before_box.value
param_min_time_duration_after = min_time_duration_after_box.value
currently_selected_param = parameter_obj.get_currently_selected_param()
if not currently_selected_param:
return
try:
parameter_obj.parse(common.get_input_dir())
parameter_obj.set_currently_selected_param(currently_selected_param)
(
param_window_duration,
param_start_timestamp_series,
) = parameter_obj.get_param_values(currently_selected_param)
except ValueError as e:
common.logger.error(e)
refresh_param_values_ui(param_window_duration,
param_start_timestamp_series)
def process_param(parameter_obj, param_name, out_df, nop_df):
"""
Processes the DataFrame for the parameter name specified using
the parameter name.
Returns:
- DataFrame after applying the time window criteria
- 'not in parameter' DataFrame - i.e. everything in the input DataFrame after removing
entries that were selected by the parameter criteria's
p.s - This parameter allows continuation from a previous 'nop_df'
"""
# Make a copy by value
temp_out_df = out_df[:]
(
param_window_duration,
param_start_timestamp_series,
) = parameter_obj.get_param_values(param_name)
# Apply time window filter
if not param_start_timestamp_series.empty:
filter_list = list(
apply_timewindow_filter(
temp_out_df.iloc[:, 0],
param_start_timestamp_series,
param_window_duration,
)
)
temp_out_df = temp_out_df.loc[filter_list]
# Build a consolidated (for each parameter) 'not in parameter' DataFrame
# after starting from original set and by removing entries that are in the parameter.
# This is done by doing an right outer join of the two DataFrames where the right
# DataFrame is 'not in parameter' DataFrame.
nop_df = (
pd.merge(temp_out_df, nop_df, how="outer", indicator=True)
.query("_merge == 'right_only'")
.drop("_merge", axis=1)
.reset_index(drop=True)
)
return temp_out_df, nop_df
def process_input_df(input_df):
"""
Process an input DataFrame and return an output base DataFrame (i.e. without
any of the criteria's or parameters applied)
"""
sum = 0
itr = 0
prev_idx = 0
# p.s - start with a freeze value of 1 as that will make the very first row
# with freeze value of 0 look like a transition to avoid special
# case handle for row 0.
prev_freeze = 1
out_df = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
freeze_0_ts = 0
freeze_0_mi = 0
# Iterate over all the rows
for idx, row in input_df.iterrows():
# All row's with freeze value of '0' are valuable and need to
# be summed up (until a transition)
if row.values[2] == 0:
sum += row.values[1]
itr += 1
# On transition from [1->0], record the row values which will
# be later used for output
if row.values[2] != prev_freeze and row.values[2] == 0:
freeze_0_ts = row.values[0]
freeze_0_mi = row.values[1]
# For output, we only care about rows where there is a transition
# of freeze value from [0->1]
if row.values[2] != prev_freeze and row.values[2] == 1:
# Divide by zero exceptional condition. Capture the details
# for troubleshooting.
if itr == 0:
common.logger.error("Current index: %s", str(idx + 4))
common.logger.error("Row value: %s", row.to_string())
common.logger.error("Previous index: %s", str(prev_idx + 4))
return False, None
# On transition from [0->1], we need to capture two entries:
# One for the row which has the freeze value of 0 (that was previously captured)
# and for the row with the freeze value of 1 (current idx)
df_o = pd.DataFrame(
{
OUTPUT_COL0_TS: freeze_0_ts,
OUTPUT_COL1_MI: freeze_0_mi,
OUTPUT_COL2_MI_AVG: [sum / itr],
OUTPUT_COL3_FREEZE_TP: [ONE_TO_ZERO],
}
)
out_df = pd.concat(
[out_df.astype(df_o.dtypes), df_o.astype(out_df.dtypes)],
ignore_index=True,
sort=False,
)
df_o = pd.DataFrame(
{
OUTPUT_COL0_TS: [row.values[0]],
OUTPUT_COL1_MI: [row.values[1]],
OUTPUT_COL2_MI_AVG: [sum / itr],
OUTPUT_COL3_FREEZE_TP: [ZERO_TO_ONE],
}
)
out_df = pd.concat(
[out_df.astype(df_o.dtypes), df_o.astype(out_df.dtypes)],
ignore_index=True,
sort=False,
)
# On transition, reset the values.
sum = 0
itr = 0
prev_idx = idx
freeze_0_ts = 0
freeze_0_mi = 0
prev_freeze = row.values[2]
return True, out_df
def apply_min_time_duration_criteria(min_t_before, min_t_after, df):
"""
This will apply minimum time duration criteria on the provided
DataFrame and return the DataFrame.
"""
if min_t_before > 0 or min_t_after > 0:
df = df.loc[
list(apply_duration_criteria(
df.iloc[:, 0], min_t_before, min_t_after))
]
return df
def process_input_file(input_file, output_folder):
"""
Main logic routine to parse the input and spit out the output
"""
global out_file_zero_to_one, out_file_zero_to_one_un
global out_file_zero_to_one_ts, out_file_zero_to_one_un_ts
global out_file_one_to_zero, out_file_one_to_zero_un
global out_file_one_to_zero_ts, out_file_one_to_zero_un_ts
global param_min_time_duration_before, param_window_duration
global param_min_time_duration_after, files_without_timeshift
global param_file_exists, parameter_obj
common.logger.debug("Processing input file: %s",
os.path.basename(input_file))
timeshift_val, num_rows_processed = common.get_timeshift_from_input_file(
input_file)
if timeshift_val:
common.logger.debug(
"\tUsing timeshift value of: %s", str(timeshift_val))
else:
if timeshift_val is None:
timeshift_val = 0
common.logger.warning("\tNo timeshift value specified")
else:
common.logger.warning(
"\tIncorrect timeshift value of zero specified")
files_without_timeshift.append(input_file)
# Parse the input file
success, df = common.parse_input_file_into_df(
input_file, common.NUM_INITIAL_ROWS_TO_SKIP + num_rows_processed
)
if not success:
return False
# Parse all the parameter files.
reset_all_parameters()
parse_param_folder(parameter_obj)
# Get a base output DataFrame without any criteria's applied
result, out_df = process_input_df(df)
if result == False or out_df.empty:
return False
out_base_file = out_base(input_file, output_folder)
common.logger.debug(
"\tAfter initial parsing (without any criteria or filter): %s",
os.path.basename(out_base_file),
)
out_df.to_csv(out_base_file, index=False)
(
param_min_time_duration_before,
param_min_time_duration_after,
) = get_param_min_time_duration(parameter_obj)
if param_file_exists:
common.logger.debug(
"\tUsing min time duration (secs): %s", str(
param_min_time_duration_before)
)
# Apply any minimum time duration criteria
out_df = apply_min_time_duration_criteria(
param_min_time_duration_before, param_min_time_duration_after, out_df
)
min_duration_file = out_min_duration_file(input_file, output_folder)
common.logger.debug(
"\tAfter applying min time duration " "criteria: %s",
os.path.basename(min_duration_file),
)
out_df.to_csv(min_duration_file, index=False)
# 'nop' -> not in parameter. This is the left over of the original data
# after all the parameters have been processed. 'no' starts with
# the original set (after the min time duration) and as each parameter
# gets process the set gets subtracted by that.
# Make a copy of out DataFrame 'by value' and not by reference.
nop_df = out_df[:]
params_name = ""
cur_selected_param = parameter_obj.get_currently_selected_param()
# Iterate through the parameters and apply each one of them
param_name_list = parameter_obj.get_param_name_list()
for idx, param_name in enumerate(param_name_list):
common.logger.debug("\tProcessing parameter: %s", param_name)
if only_process_cur_param and param_name != cur_selected_param:
continue
params_name += UNDERSCORE + param_name
# process the DataFrame for the parameter with the given index.
temp_out_df, nop_df = process_param(
parameter_obj, param_name, out_df, nop_df)
# Format the file names of the output files using the parameter name
format_out_file_names(
input_file,
param_name,
param_min_time_duration_before,
param_min_time_duration_after,
output_folder,
)
tw_filter_file = out_tw_filter_file(
input_file, param_name, output_folder)
common.logger.debug(
"\tAfter applying time window duration filter: %s",
os.path.basename(tw_filter_file),
)
temp_out_df.to_csv(tw_filter_file, index=False)
split_df_and_output(
temp_out_df,
timeshift_val,
out_file_zero_to_one,
out_file_one_to_zero,
out_file_zero_to_one_ts,
out_file_one_to_zero_ts,
)
format_out_nop_file_name(
input_file,
params_name,
param_min_time_duration_before,
param_min_time_duration_after,
output_folder,
)
split_df_and_output(
nop_df,
timeshift_val,
out_file_zero_to_one_un,
out_file_one_to_zero_un,
out_file_zero_to_one_un_ts,
out_file_one_to_zero_un_ts,
)
return True
def print_help():
"""
Display help
"""
print("\nHelp/Usage:\n")
print(
"python binary.py -i <input folder or .csv file> -o <output_directory> -v -h -c\n"
)
print("where:")
print("-i (required): input folder or .csv file.")
print("-o (optional): output folder.")
print("-v (optional): run in verbose mode")
print("-h (optional): print this help")
print("-c (optional): run in console (no UI) mode")
print("\nExamples:\n")
print("\nProcess input file:")
print("\tpython binary.py -i input.csv")
print("\nProcess all the csv files from the input folder:")
print("\tpython binary.py -i c:\\data\\input")
print(
"\nProcess all the csv files from the input folder and use the output folder:"
)
print("\tpython binary.py -i c:\\data\\input -d c:\\data\\output")
print("\nNotes:")
print("\tClose the output file prior to running.")
sys.exit()
def get_input_files(input_dir):
input_files = []
# Normalize the path to deal with backslash/frontslash
input_folder_or_file = os.path.normpath(input_dir)
search_path = os.path.join(input_folder_or_file, "*.csv")
for file in glob.glob(search_path):
input_files.append(file)
return input_files
def main(input_folder_or_file, separate_files, output_folder):
global output_dir, create_output_folder_with_file_name
input_dir = ""
input_files = []
output_folder = ""
# strip the quotes at the start and end, else
# paths with white spaces won't work.
input_folder_or_file = input_folder_or_file.strip('"')
# get the input file if one is not provided.
if not input_folder_or_file:
input_folder_or_file = input(
"Provide an input folder or .csv file name: ")
input_folder_or_file = os.path.normpath(input_folder_or_file)
if os.path.isdir(input_folder_or_file):
input_dir = input_folder_or_file
input_files = get_input_files(input_dir)
elif os.path.isfile(input_folder_or_file):
input_dir = os.path.dirname(input_folder_or_file)
input_files.append(input_folder_or_file)
else:
common.logger.error(
"The input path is not a valid directory or file: %s", input_folder_or_file
)
print_help()
output_folder = common.get_output_dir(
input_dir, output_folder, separate_files)
common.set_input_dir(input_dir)
common.logger.debug("Input folder: %s", os.path.normpath(input_dir))
output_dir = os.path.normpath(output_folder)
successfully_parsed_files = []
unsuccessfully_parsed_files = []
for input_file in input_files:
# Create a different output folder for each input file
if separate_files or create_output_folder_with_file_name:
output_folder = os.path.join(
output_dir, os.path.splitext(os.path.basename(input_file))[0]
)
common.logger.debug("Output folder: %s", output_folder)
if not os.path.isdir(output_folder):
os.mkdir(output_folder)
if separate_files:
parsed = separate_input_file(input_file, output_folder)
else:
parsed = process_input_file(input_file, output_folder)
if parsed:
successfully_parsed_files.append(input_file)
else:
unsuccessfully_parsed_files.append(input_file)
return successfully_parsed_files, unsuccessfully_parsed_files
def separate_input_file(input_file, output_folder):
"""
Main logic routine to separate input file into multiple files.
"""
global files_without_timeshift
timeshift_val, num_rows_processed = common.get_timeshift_from_input_file(
input_file)
if timeshift_val:
common.logger.debug(
"\tUsing timeshift value of: %s", str(timeshift_val))
else:
if timeshift_val is None:
timeshift_val = 0
common.logger.warning("\tNo timeshift value specified")
else:
common.logger.warning(
"\tIncorrect timeshift value of zero specified")
files_without_timeshift.append(input_file)
# Parse the input file
df = pd.read_csv(input_file, header=0, skiprows=num_rows_processed)
columns = df.columns.str.lower().to_list()
try:
time_col_index = columns.index("time")
except ValueError:
common.logger.warning(
"Time column is not present in the file. Skipping file")
return False
for i, col in enumerate(df):
if i == time_col_index:
continue
# Binary whole numbers only
if is_integer_dtype(df[col]) and df[col].min() == 0 and df[col].max() == 1:
out_df_frame = pd.DataFrame(
[
*zip(
[common.TIMESHIFT_HEADER_ALT, common.INPUT_COL0_TS],
[int(timeshift_val), common.INPUT_COL1_MI],
[np.nan, common.INPUT_COL2_FREEZE],
)
]
)
output_file_name = os.path.join(
output_folder, col.replace(" ", "_") + common.CSV_EXT
)
out_df_freeze = df[col]
# Empty motion index columns
out_mi = pd.DataFrame(index=range(
out_df_freeze.size), columns=range(1))
out_df_time = df.iloc[:, time_col_index]
out_df = pd.concat(
[out_df_time, out_mi, out_df_freeze],
axis=1,
ignore_index=True,
sort=False,
)
out_df = pd.concat([out_df_frame, out_df],
ignore_index=True, sort=False)
out_df.to_csv(output_file_name, index=False, header=False)
# print(out_df)
return True
"""
------------------------------------------------------------
UI related stuff
------------------------------------------------------------
"""
def line():
"""
Line for the main app
"""
Text(
app,
"------------------------------------------------------------------------------------------------------",
)
def line_r(rwin):
"""
Line for results window
"""
Text(
rwin,
"-------------------------------------------------------------------------------------",
)
def select_input_dir(parameter_obj):
global param_min_time_duration_before, param_min_time_duration_after
input_dir = common.select_input_dir(app)
if input_dir is None:
common.logger.debug("No input folder selected.")
return
try:
parameter_obj.parse(input_dir)
except ValueError as e:
common.logger.warning(e)
input_dir_text_box.value = os.path.basename(input_dir)
input_dir_text_box.width = min(
len(input_dir_text_box.value), INPUT_FOLDER_NAME_BOX_MAX_WIDTH
)
# Reset all current values of the parameters and refresh the parameter
# UI section with the reset values (this will ensure the UI will show
# the default values even in cases when there are no parameters specified
# in the input folder).
(
param_window_duration,
param_start_timestamp_series,
) = parameter_obj.get_default_parameter_values()
refresh_param_values_ui(param_window_duration,
param_start_timestamp_series)
(
param_min_time_duration_before,
param_min_time_duration_after,
) = get_param_min_time_duration(parameter_obj)
param_name_list = parameter_obj.get_param_name_list()
refresh_param_names_combo_box(parameter_obj)
if len(param_name_list):
(
param_window_duration,
param_start_timestamp_series,
) = parameter_obj.get_param_values(parameter_obj.get_currently_selected_param())
refresh_param_values_ui(param_window_duration,
param_start_timestamp_series)
def open_output_folder():
global output_dir