-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdff.py
More file actions
1165 lines (1010 loc) · 37.8 KB
/
dff.py
File metadata and controls
1165 lines (1010 loc) · 37.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import concurrent
import getopt
import glob
import logging
import os
import subprocess
import sys
import time
from concurrent.futures import ProcessPoolExecutor
import h5py
import numpy as np
import pandas as pd
from guizero import (
App,
Box,
Combo,
ListBox,
PushButton,
Text,
TextBox,
TitleBox,
Window,
)
from pandas.api.types import is_integer_dtype
import common
from parameter import *
# UI related constants
INPUT_FOLDER_NAME_BOX_MAX_WIDTH = 26
# Parameter UI strings
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): "
# Other constants
OUTPUT_LOG_FILE = "dff_output.log"
OUTPUT_COL0_TS = "Start time (sec)"
OUTPUT_COL1_LEN = "Bout length (sec)"
OUTPUT_COL2_MI_AVG = "Motion Index (avg)"
OUTPUT_COL3_DATA_AUC = "AUC (dff)"
OUTPUT_COL4_DATA_AVG = "dff"
OUTPUT_COLUMN_SCHEMA = {
OUTPUT_COL0_TS: 'float64',
OUTPUT_COL1_LEN: 'float64',
OUTPUT_COL2_MI_AVG: 'float64',
OUTPUT_COL3_DATA_AUC: 'float64',
OUTPUT_COL4_DATA_AVG: 'float64',
}
# Number of decimal precision
OUTPUT_VALUE_PRECISION = 5
# output file names
OUTPUT_ZEROS = "0_"
OUTPUT_ONES = "1_"
OUTPUT_DFF = "dff_"
OUTPUT_AUC = "AUC (sum)"
OUTPUT_Z_SCORE = "dff (avg)"
OUTPUT_SUMMARY_COLUMN_SCHEMA = {
OUTPUT_AUC: 'float64', OUTPUT_Z_SCORE: 'float64'}
# Globals
parameter_obj = Parameters()
r_log_box = None
files_without_timeshift = []
result_success_list_box = None
result_unsuccess_list_box = None
output_dir = None
custom_log_handler = None
def initialize(log_level: int):
global custom_log_handler
logging.basicConfig(filename=OUTPUT_LOG_FILE,
level=log_level, format="")
common.logger = logging.getLogger(__name__)
custom_log_handler = common.loghandler()
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
custom_log_handler.setFormatter(formatter)
common.logger.addHandler(custom_log_handler)
def main(input_dir: str, parameter_obj: Parameters):
global result_success_list_box, result_unsuccess_list_box, files_without_timeshift
path = glob.glob(os.path.join(input_dir, "dff_*"))
output_dir = common.get_output_dir(input_dir, "", False)
futures = []
futures_dict = {}
log_level = common.logger.getEffectiveLevel()
with ProcessPoolExecutor(initializer=initialize, initargs=(log_level, )) as executor:
for i in range(len(path)):
basename = (os.path.basename(path[i])).split(".")[0]
name_1 = basename.split("_")[-1]
ts = read_hdf5("timeCorrection_" + name_1, input_dir, "timestampNew")
if np.isnan(ts).any():
common.logger.warning(
"%s file has NaN (not a number) values. Currently, unsupported",
("timeCorrection_" + name_1),
)
continue
z_score = read_hdf5("", path[i], "data")
nan = np.isnan(z_score)
if nan.any():
cleaned_z_score = []
cleaned_ts = []
common.logger.warning(
"%s file has NaN (not a number) values. Discarding those values.",
path[i],
)
for idx, v in enumerate(nan):
# Discard NaN
if v == False:
cleaned_z_score.append(z_score[idx])
cleaned_ts.append(ts[idx])
z_score = cleaned_z_score
ts = cleaned_ts
if len(ts) == 0:
common.logger.warning(
"No timestamp values left in the series. Skipping file: %s",
os.path.basename(path[i]))
continue
csv_path = glob.glob(os.path.join(input_dir, "*.csv"))
for csv_file in csv_path:
f = executor.submit(__process_csv_file, parameter_obj,
csv_file, z_score, ts, output_dir)
common.logger.info('Processing csv file: %s', csv_file)
futures.append(f)
futures_dict[f] = csv_file
for f in concurrent.futures.as_completed(futures):
common.logger.info('Finished processing csv file: %s', futures_dict[f])
result = f.result()
if result_success_list_box is not None:
result_success_list_box.append(result[0])
if result_unsuccess_list_box is not None:
result_unsuccess_list_box.append(result[1])
if files_without_timeshift is not None:
files_without_timeshift.append(result[2])
custom_log_handler.flush_logs(result[3])
# ----------------------------------------------------------------------------
# Routines in the below section are all parallelizable. Avoid taking any
# dependencies on globals.
# ----------------------------------------------------------------------------
# Read the values of the given 'key' from the HDF5 file
# into an numpy array. If an 'event' is provided, it will
# be appended to the filepath.
def read_hdf5(event, filepath, key):
if event:
event = event.replace("\\", "_")
event = event.replace("/", "_")
op = os.path.join(filepath, event + ".hdf5")
else:
op = filepath
if os.path.exists(op):
with h5py.File(op, "r") as f:
arr = np.asarray(f[key])
else:
common.logger.error(f"{op}.hdf5 file does not exist")
raise Exception("{}.hdf5 file does not exist".op)
return arr
def compute_avg(sum, cnt):
avg = round(sum / cnt, OUTPUT_VALUE_PRECISION)
return avg
def generate_output_file(sum, cnt, out_df, out_file):
avg = compute_avg(sum, cnt)
df_summary = pd.DataFrame(columns=OUTPUT_SUMMARY_COLUMN_SCHEMA.keys()).astype(
OUTPUT_SUMMARY_COLUMN_SCHEMA)
df_summary.loc[len(df_summary.index)] = [sum, avg]
df_summary.to_csv(out_file, mode="w", index=False, header=True)
out_df.to_csv(out_file, mode="a", index=False, header=True)
def __process_csv_file(
parameter_obj: Parameters,
csv_file: str,
data: np.asarray,
ts: np.asarray,
output_dir: str,
):
without_timeshift_list = []
unsuccess_list = []
success_list = []
common.logger.info("Processing input file: %s", csv_file)
timeshift_val, num_rows_processed = common.get_timeshift_from_input_file(
csv_file
)
if timeshift_val:
common.logger.info(
"Using 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"
)
without_timeshift_list.append(os.path.basename(csv_file))
success, binary_df = common.parse_input_file_into_df(
csv_file, common.NUM_INITIAL_ROWS_TO_SKIP + num_rows_processed
)
if not success:
common.logger.warning(
"Skipping CSV file (%s) as it is not well formed", csv_file)
unsuccess_list.append(os.path.basename(csv_file))
return
success_list.append(os.path.basename(csv_file))
binary_ts_splits = get_ts_split_for_binary(
binary_df, timeshift_val)
csv_basename = (os.path.basename(csv_file)).split(".")[0]
# Create output folder specific for this csv file.
this_output_dir = os.path.join(output_dir, csv_basename)
common.logger.info("Output folder: %s", this_output_dir)
if not os.path.isdir(this_output_dir):
os.mkdir(this_output_dir)
# We want to generate without any parameters as well. So start with
# no parameters and append the parameter list.
param_name_list = [""]
param_list = parameter_obj.get_param_name_list()
# If there are more than one parameter, generate output for combined
# parameter and ~(combined parameter). A `None` value is used to
# represent 'combined parameters'
if len(param_list) > 1:
param_name_list.append(None)
param_name_list.extend(param_list)
futures = []
futures_dict = {}
log_level = common.logger.getEffectiveLevel()
with ProcessPoolExecutor(initializer=initialize, initargs=(log_level, )) as executor:
for param_name in param_name_list:
f = executor.submit(__process_param_with_output, parameter_obj, param_name,
binary_df, timeshift_val, binary_ts_splits, data, ts,
this_output_dir, csv_basename)
common.logger.info('Processing, param: %s', param_name)
futures.append(f)
futures_dict[f] = param_name
for f in concurrent.futures.as_completed(futures):
common.logger.info('Finished processing param: %s', futures_dict[f])
return success_list, unsuccess_list, without_timeshift_list, common.logs
def __process_param_with_output(
parameter_obj: Parameters,
param_name: str,
binary_df: pd.DataFrame,
timeshift_val: float,
binary_ts_splits: list,
data: np.asarray,
ts: np.asarray,
output_dir: str,
csv_basename: str,
):
# Process the data and write out the results
common.logger.info("processing param: %s", param_name)
success, results = process(
parameter_obj, param_name, binary_df, timeshift_val, binary_ts_splits, data, ts
)
if not success:
return
auc_0s_sum = results[0]
auc_0s_cnt = results[1]
out_df_0s = results[2]
auc_0s_sum_not = results[3]
auc_0s_cnt_not = results[4]
out_df_0s_not = results[5]
auc_1s_sum = results[6]
auc_1s_cnt = results[7]
out_df_1s = results[8]
auc_1s_sum_not = results[9]
auc_1s_cnt_not = results[10]
out_df_1s_not = results[11]
auc_sum = results[12]
auc_cnt = results[13]
out_df = results[14]
auc_sum_not = results[15]
auc_cnt_not = results[16]
out_df_not = results[17]
param_ext = ""
if param_name == None:
param_ext = "_outside-parameters"
elif not param_name == "":
param_ext = "_" + param_name
# 0's
out_0_file = os.path.join(
output_dir,
OUTPUT_ZEROS + csv_basename + param_ext + common.CSV_EXT,
)
if auc_0s_cnt > 0 and param_name is not None:
generate_output_file(
auc_0s_sum, auc_0s_cnt, out_df_0s, out_0_file)
if auc_0s_cnt_not > 0 and param_name is None:
generate_output_file(
auc_0s_sum_not, auc_0s_cnt_not, out_df_0s_not, out_0_file
)
# 1's
out_1_file = os.path.join(
output_dir,
OUTPUT_ONES + csv_basename + param_ext + common.CSV_EXT,
)
if auc_1s_cnt > 0 and param_name is not None:
generate_output_file(
auc_1s_sum, auc_1s_cnt, out_df_1s, out_1_file)
if auc_1s_cnt_not > 0 and param_name is None:
generate_output_file(
auc_1s_sum_not, auc_1s_cnt_not, out_df_1s_not, out_1_file
)
# Data independent of 0 or 1
out_not_file = os.path.join(
output_dir,
OUTPUT_DFF + csv_basename + param_ext + common.CSV_EXT,
)
if auc_cnt > 0 and param_name is not None:
generate_output_file(
auc_sum, auc_cnt, out_df, out_not_file)
if auc_cnt_not > 0 and param_name is None:
generate_output_file(
auc_sum_not, auc_cnt_not, out_df_not, out_not_file
)
def process(
parameter_obj,
param_name: str,
binary_df: pd.DataFrame,
timeshift_val: float,
binary_ts_splits: list,
data: np.asarray,
ts: np.asarray,
) -> (bool, list):
"""Process the parameter.
Parameters
----------
param_name : str
The name of the parameter to process.
"" -> Indicates a parameter that represents the full duration.
None -> Indicates combining all the parameters
binary_df : pd.DataFrame
The freeze frame binary DataFrame.
timeshift_val - float
The timeshift value to apply to the timestamps from the binary_df
binary_ts_splits -> list
Binary timestamp splits to use. If `None`, then this routine
will compute the splits.
data: np.asarray
The data values
ts: np.asarray
The timestamps corresponding to the data values. The ts array should
have a 1:1 correspondence to the data array.
Returns
------
(bool, list)
bool -> True if the routine successfully process the parameter; False otherwise.
list:
list[0] -> Sum of data values within the parameters, for the freeze frame 0s.
list[1] -> Count of data values within the parameters, for the freeze frame 0s.
list[2] -> Summarized DataFrame of data values within the parameters, for the freeze frame 0s.
list[3] -> Sum of data values outside the parameters, for the freeze frame 0s.
list[4] -> Count of data values outside the parameters, for the freeze frame 0s.
list[5] -> Summarized DataFrame of data values outside the parameters, for the freeze frame 0s.
list[6] -> Sum of data values within the parameters, for the freeze frame 1s.
list[7] -> Count of data values within the parameters, for the freeze frame 1s.
list[8] -> Summarized DataFrame of data values within the parameters, for the freeze frame 1s.
list[9] -> Sum of data values outside the parameters, for the freeze frame 1s.
list[10] -> Count of data values outside the parameters, for the freeze frame 1s.
list[11] -> Summarized DataFrame of data values outside the parameters, for the freeze frame 1s.
list[12] -> Sum of data values within the parameters.
list[13] -> Count of data values within the parameters.
list[14] -> Summarized DataFrame of data values within the parameters.
list[15] -> Sum of data values outside the parameters.
list[16] -> Count of data values outside the parameters.
list[17] -> Summarized DataFrame of data values outside the parameters.
"""
# Perform some basic checks on the data sets.
if len(ts) != len(data):
common.logger.error(
"Timestamp series length(%d) does not match data series length(%d)",
len(ts),
len(data),
)
return False
if not binary_df[common.INPUT_COL0_TS].is_monotonic_increasing:
common.logger.error("Binary timestamp values are not sorted.")
return False, []
# Make sure the 'binary' column is actually binary.
if not (
is_integer_dtype(binary_df[common.INPUT_COL2_FREEZE])
and binary_df[common.INPUT_COL2_FREEZE].min() == 0
and binary_df[common.INPUT_COL2_FREEZE].max() == 1
):
common.logger.error("Binary column contains non-binary data.")
return False, []
# Timestamp series should be sorted.
if not np.all(np.diff(ts) >= 0):
common.logger.error("Timestamp series is not sorted.")
return False, []
index_start = -1
index_end = 0
auc_sum = 0
auc_cnt = 0
mi_sum = 0
mi_cnt = 0
out_df = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
auc_sum_not = 0
auc_cnt_not = 0
mi_sum_not = 0
mi_cnt_not = 0
out_df_not = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
auc_0s_sum = 0
auc_0s_cnt = 0
mi_0s_sum = 0
mi_0s_cnt = 0
out_df_0s = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
auc_0s_sum_not = 0
auc_0s_cnt_not = 0
mi_0s_sum_not = 0
mi_0s_cnt_not = 0
out_df_0s_not = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
auc_1s_sum = 0
auc_1s_cnt = 0
mi_1s_sum = 0
mi_1s_cnt = 0
out_df_1s = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
auc_1s_sum_not = 0
auc_1s_cnt_not = 0
mi_1s_sum_not = 0
mi_1s_cnt_not = 0
out_df_1s_not = pd.DataFrame(columns=OUTPUT_COLUMN_SCHEMA.keys()).astype(
OUTPUT_COLUMN_SCHEMA)
splits = []
if binary_ts_splits == None:
binary_ts_splits = get_ts_split_for_binary(binary_df, timeshift_val)
for binary_split in binary_ts_splits:
ts_start = binary_split[0]
ts_end = binary_split[1]
cur_binary_value = binary_split[2]
common.logger.debug("ts_start: %f, ts_end: %f", ts_start, ts_end)
splits.append([ts_start, ts_end])
if param_name is None:
ts_split = parameter_obj.get_ts_series_for_combined_param(
ts_start, ts_end, timeshift_val
)
else:
ts_split = parameter_obj.get_ts_series_for_timestamps(
param_name, ts_start, ts_end, timeshift_val
)
common.logger.debug("ts_split: %s", ts_split)
for element in ts_split:
ts_start = element[0]
ts_end = element[1]
is_inside = element[2]
binary_df_ts = binary_df[common.INPUT_COL0_TS]
ts_start_without_shift = round(
ts_start - timeshift_val, Parameters.TIMESTAMP_ROUND_VALUE
)
# Find the `index` such that binary_df_ts[index] >= ts_start_without_shift
index_start = np.searchsorted(binary_df_ts, ts_start_without_shift)
ts_end_without_shift = round(
ts_end - timeshift_val, Parameters.TIMESTAMP_ROUND_VALUE
)
# Find the 'index' such that binary_df_ts[index] > ts_end_without_shift
index_end = np.searchsorted(binary_df_ts, ts_end_without_shift, side='right')
if index_start == index_end:
index_end += 1
if index_end == 0:
index_end = len(binary_df_ts)
ts_start = round(
binary_df.iloc[index_start][common.INPUT_COL0_TS] +
timeshift_val,
Parameters.TIMESTAMP_ROUND_VALUE,
)
ts_end = round(
binary_df.iloc[index_end -
1][common.INPUT_COL0_TS] + timeshift_val,
Parameters.TIMESTAMP_ROUND_VALUE,
)
# Find the `index` such that ts[index] >= ts_start
ts_index_start_for_val = np.searchsorted(ts, ts_start)
if ts_index_start_for_val == 0 and ts_start > ts[len(ts) - 1]:
common.logger.debug(
"ts start is out of bounds. ts_start: %f, ts[last]: %f",
ts_start,
ts[len(ts) - 1],
)
break
# Find the `index` such that ts[index] > ts_end
ts_index_end_for_val = np.searchsorted(ts, ts_end, side='right')
# If there is only one element, then include it.
if ts_index_start_for_val == ts_index_end_for_val:
ts_index_end_for_val += 1
if ts_index_end_for_val == 0:
ts_index_end_for_val = len(ts)
bout_length = round(ts_end - ts_start,
Parameters.TIMESTAMP_ROUND_VALUE)
motion_index_slice = binary_df.iloc[index_start:index_end][
common.INPUT_COL1_MI
]
sum_mi = sum(motion_index_slice)
cnt_mi = len(motion_index_slice)
mi_avg = round(sum_mi / cnt_mi, OUTPUT_VALUE_PRECISION)
data_slice = data[ts_index_start_for_val:ts_index_end_for_val]
sum_data = round(sum(data_slice), OUTPUT_VALUE_PRECISION)
cnt_data = len(data_slice)
data_avg = round(sum_data / cnt_data, OUTPUT_VALUE_PRECISION)
if cnt_data == 0:
common.logger.debug("ts split with no elements:")
common.logger.debug(
"\tindex start: %d, index end: %d, length: %d",
index_start,
index_end,
index_end - index_start + 1,
)
common.logger.debug(
"\tts index start: %d, end: %d, length: %d",
ts_index_start_for_val,
ts_index_end_for_val,
ts_index_end_for_val - ts_index_start_for_val + 1,
)
continue
if is_inside:
auc_sum += sum_data
auc_cnt += cnt_data
mi_sum += sum_mi
mi_cnt += cnt_mi
out_df.loc[len(out_df.index)] = [
ts_start,
bout_length,
mi_avg,
sum_data,
data_avg,
]
else:
auc_sum_not += sum_data
auc_cnt_not += cnt_data
mi_sum_not += sum_mi
mi_cnt_not += cnt_mi
out_df_not.loc[len(out_df_not.index)] = [
ts_start,
bout_length,
mi_avg,
sum_data,
data_avg,
]
if cur_binary_value == 0:
if is_inside:
auc_0s_sum += sum_data
auc_0s_cnt += cnt_data
mi_0s_sum += sum_mi
mi_0s_cnt += cnt_mi
out_df_0s.loc[len(out_df_0s.index)] = [
ts_start,
bout_length,
mi_avg,
sum_data,
data_avg,
]
else:
auc_0s_sum_not += sum_data
auc_0s_cnt_not += cnt_data
mi_0s_sum_not += sum_mi
mi_0s_cnt_not += cnt_mi
out_df_0s_not.loc[len(out_df_0s_not.index)] = [
ts_start,
bout_length,
mi_avg,
sum_data,
data_avg,
]
else:
if is_inside:
auc_1s_sum += sum_data
auc_1s_cnt += cnt_data
mi_1s_sum += sum_mi
mi_1s_cnt += cnt_mi
out_df_1s.loc[len(out_df_1s.index)] = [
ts_start,
bout_length,
mi_avg,
sum_data,
data_avg,
]
else:
auc_1s_sum_not += sum_data
auc_1s_cnt_not += cnt_data
mi_1s_sum_not += sum_mi
mi_1s_cnt_not += cnt_mi
out_df_1s_not.loc[len(out_df_1s_not.index)] = [
ts_start,
bout_length,
mi_avg,
sum_data,
data_avg,
]
# Reset the index to indicate the start of a new dataset.
index_start = -1
return True, [
round(auc_0s_sum, OUTPUT_VALUE_PRECISION),
auc_0s_cnt,
out_df_0s,
round(auc_0s_sum_not, OUTPUT_VALUE_PRECISION),
auc_0s_cnt_not,
out_df_0s_not,
round(auc_1s_sum, OUTPUT_VALUE_PRECISION),
auc_1s_cnt,
out_df_1s,
round(auc_1s_sum_not, OUTPUT_VALUE_PRECISION),
auc_1s_cnt_not,
out_df_1s_not,
round(auc_sum, OUTPUT_VALUE_PRECISION),
auc_cnt,
out_df,
round(auc_sum_not, OUTPUT_VALUE_PRECISION),
auc_cnt_not,
out_df_not,
]
def get_ts_split_for_binary(
binary_df: pd.DataFrame,
timeshift_val: float,
) -> list:
if not binary_df[common.INPUT_COL0_TS].is_monotonic_increasing:
common.logger.error("Binary timestamp values are not sorted.")
return False, []
# Make sure the 'binary' column is actually binary.
if not (
is_integer_dtype(binary_df[common.INPUT_COL2_FREEZE])
and binary_df[common.INPUT_COL2_FREEZE].min() == 0
and binary_df[common.INPUT_COL2_FREEZE].max() == 1
):
common.logger.error("Binary column contains non-binary data.")
return False, []
index_start = -1
index_end = 0
row_count = binary_df.shape[0]
splits = []
for index, row in binary_df.iterrows():
if index_end == row_count:
break
if index_start == -1:
index_start = index
cur_binary_value = binary_df.iloc[index_start][common.INPUT_COL2_FREEZE]
if cur_binary_value == row[common.INPUT_COL2_FREEZE]:
index_end = index
# If there is a transition of the freeze value, compute the variables.
# Note: The last row is also considered as the end of transition.
if index < row_count - 1 and (
cur_binary_value == binary_df.iloc[index +
1][common.INPUT_COL2_FREEZE]
):
continue
ts_start_without_shift = binary_df.iloc[index_start][common.INPUT_COL0_TS]
ts_start = round(
ts_start_without_shift + timeshift_val, Parameters.TIMESTAMP_ROUND_VALUE
)
ts_end_without_shift = binary_df.iloc[index_end][common.INPUT_COL0_TS]
ts_end = round(
ts_end_without_shift + timeshift_val, Parameters.TIMESTAMP_ROUND_VALUE
)
splits.append([ts_start, ts_end, cur_binary_value])
# Reset the index to indicate the start of a new dataset.
index_start = -1
return splits
# ----------------------------------------------------------------------------
# End of parallelizable section.
# ----------------------------------------------------------------------------
def print_help():
"""
Display help
"""
print("\nHelp/Usage:\n")
print(
"python dff.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 dff.py -i input.csv")
print("\nProcess all the csv files from the input folder:")
print("\tpython dff.py -i c:\\data\\input")
print(
"\nProcess all the csv files from the input folder and use the output folder:"
)
print("\tpython dff.py -i c:\\data\\input -o c:\\data\\output")
print("\nNotes:")
print("\tClose the output file prior to running.")
sys.exit()
# ----------------------------------------------------------------------------
# UI related stuff
# ----------------------------------------------------------------------------
INPUT_FOLDER_NAME_BOX_MAX_WIDTH = 26
def refresh_param_names_combo_box(parameter_obj):
param_name_list = parameter_obj.get_param_name_list()
param_names_combo_box.clear()
for param_name in param_name_list:
param_names_combo_box.append(param_name)
param_names_combo_box.show()
def select_input_dir(parameter_obj):
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_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
if output_dir is None:
app.warn(
"Uh oh!",
"Output folder dose not exist! Select input folder and process first.",
)
return
# Normalize the path to deal with backslash/frontslash
norm_path = os.path.normpath(output_dir)
if sys.platform == "win32":
subprocess.Popen(f"explorer /open,{norm_path}")
elif sys.platform == "darwin":
subprocess.Popen(["open", norm_path])
else:
subprocess.Popen(["xdg-open", norm_path])
def reset_result_box():
result_success_list_box.clear()
result_unsuccess_list_box.clear()
result_withoutshift_list_box.clear()
files_without_timeshift.clear()
r_log_box.clear()
def ui_process_cmd(parameter_obj):
if not common.get_input_dir():
app.warn(
"Uh oh!",
"No input folder specified. Please select an input folder and run again!",
)
return
reset_result_box()
main(common.get_input_dir(), parameter_obj)
rwin.show()
def open_params_file(parameter_obj):
param_file = parameter_obj.get_param_file_from_name(
parameter_obj.get_currently_selected_param()
)
if not os.path.isfile(param_file):
app.warn("Uh oh!", "Parameters file " + param_file + " is not a file!")
return
common.open_file(param_file)
def parse_cur_param_file(parameter_obj):
"""
Parse the paramter file
"""
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 set_time_window_duration_box_value(param_window_duration):
time_window_duration_box.value = param_window_duration
def refresh_ts_list_box(ts_series):
ts_series_list_box.clear()
for val in ts_series:
ts_series_list_box.append(val)
def refresh_param_values_ui(param_window_duration, param_start_timestamp_series):
set_time_window_duration_box_value(param_window_duration)
refresh_ts_list_box(param_start_timestamp_series)
def select_param(selected_param_value):
"""
This method is called when the user selects a parameter from the parameter
name drop down box.
"""
global parameter_obj
if not selected_param_value:
return
cur_selected_param = selected_param_value
try:
parameter_obj.set_currently_selected_param(selected_param_value)
except:
common.logger.error("Parameter name(%s) not found in list; unexpected")
(
param_window_duration,
param_start_timestamp_series,
) = parameter_obj.get_param_values(cur_selected_param)
refresh_param_values_ui(param_window_duration,
param_start_timestamp_series)
def line():
"""
Line for the main app
"""
Text(
app,
"------------------------------------------------------------------------------------------------------",
)
def line_r(rwin):
"""
Line for results window
"""
Text(
rwin,
"-------------------------------------------------------------------------------------",
)
if __name__ == "__main__":
"""
Main entry point
"""
custom_log_handler = common.loghandler()
logging.basicConfig(filename=OUTPUT_LOG_FILE,
level=logging.INFO, format="")
common.logger = logging.getLogger(__name__)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
custom_log_handler.setFormatter(formatter)
common.logger.addHandler(custom_log_handler)
argv = sys.argv[1:]
console_mode = False
separate_files = False
output_folder = None
try:
opts, args = getopt.getopt(argv, "i:vhco:")
except getopt.GetoptError as e:
common.logger.error("USAGE ERROR: %s", e)
print_help()
for opt, arg in opts:
if opt == "-h":
print_help()
elif opt in ("-i"):
input_dir = arg
elif opt in ("-o"):
output_folder = arg
elif opt in ("-v"):
logging.getLogger().setLevel(logging.DEBUG)
elif opt in ("-c"):
console_mode = True
else:
print_help()
if console_mode:
main(input_dir, parameter_obj)
sys.exit()
# Main app
app = App("", height=650, width=900)
# App name box