-
Notifications
You must be signed in to change notification settings - Fork 3
/
create_non_wear_method.py
1749 lines (1352 loc) · 71.5 KB
/
create_non_wear_method.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
IMPORT PACKAGES
"""
import os
import re
import numpy as np
import pandas as pd
import datetime
import time
from multiprocessing import cpu_count
from joblib import Parallel
from joblib import delayed
from scipy import stats
from sklearn.utils import shuffle
"""
IMPORTED FUNCTIONS
"""
from functions.helper_functions import set_start, set_end, load_yaml, read_directory, create_directory, get_subjects_with_invalid_data, save_pickle, load_pickle,\
calculate_vector_magnitude, get_subject_counters_for_correction, get_subject_counter_to_merge, get_random_number_between,\
delete_directory
from functions.datasets_functions import get_actigraph_acc_data
from functions.hdf5_functions import save_data_to_group_hdf5, get_all_subjects_hdf5, read_dataset_from_group, get_datasets_from_group
from functions.raw_non_wear_functions import find_candidate_non_wear_segments_from_raw, find_consecutive_index_ranges, group_episodes
from functions.plot_functions import plot_merged_episodes, plot_cnn_classification_performance, plot_training_results_per_epoch,\
plot_baseline_performance, plot_start_stop_segments,\
plot_baseline_performance_compare_f1, plot_overview_all_raw_nw_methods
from functions.datasets_functions import get_actigraph_acc_data, get_actiwave_acc_data, get_actiwave_hr_data
from functions.ml_functions import get_confusion_matrix, calculate_classification_performance
from functions.dl_functions import create_1d_cnn_non_wear_episodes, load_tf_model
"""
PREPROCESSING
"""
def merge_close_episodes_from_training_data(read_folder, save_folder):
"""
Merge epsisodes that are close to each other. Two close episodes could for instance have some artificial movement between them.
Note that this merging is done on our labeled gold standard dataset, and this merging is only for training purposes.
Note that the words merge and group are used here interchangably
Parameters
-----------
read_folder : os.path()
folder location of start and stop labels for non-wear time
save_folder : os.path()
folder where to save the merged episodes to
"""
# read all files to process
F = [f for f in read_directory(read_folder) if f[-4:] == '.csv']
# process each file
for f_idx, f in enumerate(F):
# extract subject from file
subject = re.search('[0-9]{8}', f)[0]
logging.info(f'=== Processing subject {subject}, file {f_idx}/{len(F)} ===')
# read csv file as dataframe
episodes = pd.read_csv(f)
# empty dataframe for grouped episodes
grouped_episodes = pd.DataFrame()
# check if episodes is not empty
if not episodes.empty:
"""
MERGE NON-WEAR EPISODES
"""
# group the following episodes (note that we work with counters here, so first episode is counter 0, second episode is counter 1 etc)
group_nw_episodes = get_subject_counter_to_merge(subject)
# empty list for episodes to group
group_nw_episodes_list = [] if group_nw_episodes is None else range(group_nw_episodes[0], group_nw_episodes[1] + 1)
# start grouping nw episodes based on get_subject_counter_to_merge
if group_nw_episodes is not None:
# create the combination of counters, for example '1-4'
counter_label = f'{group_nw_episodes[0]}-{group_nw_episodes[1]}'
# grouped non-wear time
grouped_episodes[counter_label] = pd.Series({ 'counter' : counter_label,
'start' : episodes.iloc[group_nw_episodes[0]]['start'],
'start_index' : episodes.iloc[group_nw_episodes[0]]['start_index'],
'stop' : episodes.iloc[group_nw_episodes[1]]['stop'],
'stop_index' : episodes.iloc[group_nw_episodes[1]]['stop_index'],
'label' : episodes.iloc[group_nw_episodes[0]]['label']})
# add non-wear time that not need be grouped
for _, row in episodes[episodes['label'] == 0].iterrows():
if row.loc['counter'] not in group_nw_episodes_list:
# save to new dataframe
grouped_episodes[row.loc['counter']] = pd.Series({ 'counter' : row.loc['counter'],
'start_index' : row.loc['start_index'],
'start' : row.loc['start'],
'stop_index' : row.loc['stop_index'],
'stop' : row.loc['stop'],
'label' : row.loc['label'],
})
"""
GROUP WEAR EPISODES
"""
grouped_wear_episodes = group_episodes(episodes = episodes[episodes['label'] == 1], distance_in_min = 3, correction = 3, hz = 100, training = True)
"""
COMBINE TWO DATAFRAMES
"""
if not grouped_wear_episodes.empty:
# combine two dataframes
grouped_episodes = pd.concat([grouped_episodes, grouped_wear_episodes], axis=1, sort = True)
# create the save folder if not exists
create_directory(save_folder)
# save to file + transpose
grouped_episodes.T.to_csv(os.path.join(save_folder, f'{subject}.csv'))
def process_calculate_true_nw_time_from_labeled_episodes(merged_episodes_folder, hdf5_read_file, hdf5_save_file, std_threshold = 0.004):
"""
Read labeled episodes and create a non-wear vector with gold standard labels.
These labels have a start and stop timestamp with a 1 minute resolution. We also extend the edges to obtain a resolution on a 1-second level.
This extension is done by incrementally extending the edges with 1-second intervals. If the intervals are below the std_threshold, then include that interval into
the non-wear episode.
Paramaters
-------------
merged_episodes_folder : os.path
folder location where episodes are stored that have undergone the merged function. See function merge_close_episodes_from_training_data
hdf5_read_file : os.path
file location of the HDF5 file that contains all the raw data
hdf5_save_file : os.path
file name to create a new HDF5 file for
std_threshold : float (optional)
standard deviation threshold that is used to calculate if the acceleration is below this value. The 0.004 threshold is used to find episodes where the acceleration
is flat (i.e., no activity)
"""
# get all the subjects from the hdf5 file (subjects are individuals who participated in the Tromso Study #7
subjects = get_all_subjects_hdf5(hdf5_file = hdf5_read_file)
# exclude subjects that have issues with their data
subjects = [s for s in subjects if s not in get_subjects_with_invalid_data()]
# loop over each subject
for i, subject in enumerate(subjects):
logging.info(f'=== Processing subject {subject}, file {i}/{len(subjects)} ===')
# get file that contains merged episodes data for subject
f = os.path.join(merged_episodes_folder, f'{subject}.csv')
# read file as dataframe
episodes = pd.read_csv(f)
# read actigraph raw data for subject
actigraph_acc, *_ = get_actigraph_acc_data(subject, hdf5_file = hdf5_read_file)
# create new nw_vector
nw_vector = np.zeros((actigraph_acc.shape[0], 1)).astype('uint8')
# loop over each episode, extend the edges, and then record the non-wear time
for _, row in episodes.iterrows():
# only continue if the episode is non-wear time ( in the csv file , non wear time is encoded as 0. Note that we will flip this encoding in later stages so as to encode nw-time as 1)
if row.loc['label'] == 0:
# extract start and stop index
start_index = row.loc['start_index']
stop_index = row.loc['stop_index']
# forward search to extend stop index
stop_index = _forward_search_episode(actigraph_acc, stop_index, hz = 100, max_search_min = 5, std_threshold = std_threshold, verbose = False)
# backwar search to extend start index
start_index = _backward_search_episode(actigraph_acc, start_index, hz = 100, max_search_min = 5, std_threshold = std_threshold, verbose = False)
# now update the non-wear vector
nw_vector[start_index:stop_index] = 1
# save non-wear vector to to HDF5 file
save_data_to_group_hdf5(group = 'true_nw_time', data = nw_vector, data_name = subject, overwrite = True, hdf5_file = hdf5_save_file)
def process_plot_merged_episodes(episodes_folder, grouped_episodes_folder, hdf5_file):
"""
Plot original non-merged episodes with merged episodes to see if the merging went ok.
Parameters
-----------
episodes_folder : os.path()
folder location of start and stop labels for non-wear time
grouped_episodes_folder : os.path()
folder location with episodes that have been merged when to appear close to each other
hdf5_file : os.path
location of HDF5 file that contains the raw activity data for actigraph and actiwave
"""
# read all files to process
F = [f for f in read_directory(episodes_folder) if f[-4:] == '.csv']
# process each file
for f_idx, f in enumerate(F):
# extract subject from file
subject = re.search('[0-9]{8}', f)[0]
logging.info(f'=== Processing subject {subject}, file {f_idx}/{len(F)} ===')
# read csv file as dataframe
episodes = pd.read_csv(f, index_col = 0)
# read grouped episodes
grouped_episodes = pd.read_csv(os.path.join(grouped_episodes_folder, f'{subject}.csv'), index_col = 0)
"""
READ ACCELERATION DATA
"""
# actigraph acceleration data
actigraph_acc, _, actigraph_time = get_actigraph_acc_data(subject = subject, hdf5_file = hdf5_file)
# actiwave acceleration data
actiwave_acc, _, actiwave_time = get_actiwave_acc_data(subject = subject, hdf5_file = hdf5_file)
# create dataframe
df_actigraph_acc = pd.DataFrame(actigraph_acc, index = actigraph_time, columns = ['Y', 'X', 'Z'])
df_actiwave_acc = pd.DataFrame(actiwave_acc, index = actiwave_time, columns = ['Y', 'X', 'Z'])
# plot merged episode
plot_merged_episodes(df_actigraph_acc, df_actiwave_acc, episodes, grouped_episodes, subject)
"""
GRID SEARCH CNN
"""
def perform_grid_search_1d_cnn(label_folder, hdf5_read_file, save_data_location, save_model_folder, file_limit = None):
"""
A total of four 1D CNN architectures were constructed and trained for the binary classification of our features as either belonging
to true non-wear time or to wear time; Figure 2 shows the four proposed architectures labelled V1, V2, V3, and V4. The input feature
is a vector of w x 3 (i.e. three orthogonal axes), where w is the window size ranging from 2–10 seconds. In total, 10 x 4 = 40 different
CNN models were trained. CNN V1 can be considered a basic CNN with only a single convolutional layer followed by a single fully connected
layer. CNN V2 and V3 contain additional convolutional layers with different kernel sizes and numbers of filters. Stacking convolutional
layers enables the detection of high-level features, unlike single convolutional layers. CNN V4 contains a max pooling layer after each
convolutional layer to merge semantically similar features while reducing the data dimensionality.(LeCun et al., 2015) A CNN architecture
with max pooling layers has shown varying results, from increased classification performance (Song-Mi Lee et al., 2017) to pooling layers
interfering with the convolutional layer’s ability to learn to down sample the raw sensor data.(Ordóñez & Roggen, 2016) All proposed CNN
architectures have a single neuron in the output layer with a sigmoid activation function for binary classification.
Training was performed on 60% of the data, with 20% used for validation and another 20% used for testing. All models were trained for up to 250
epochs with the Adam optimiser (Kingma & Ba, 2014) and a learning rate of 0.001. Loss was calculated with binary cross entropy and, additionally,
early stopping was implemented to monitor the validation loss with a patience of 25 epochs and restore weights of the lowest validation loss.
This means that training would terminate if the validation loss did not improve for 25 epochs, and the best model weights would be restored. All
models were trained on 2 x Nvidia RTX 2080TI graphics cards with the Python library TensorFlow (v2.0).
Parameters
----------
label_folder : os.path
folder location where gold standard labels are saved
hdf5_read_file : os.path
location of HDF5 file that contains the raw activity data for actigraph and actiwave
save_data_location : os.path
folder location where to save the training features to
save_model_folder : os.path
folder location where to save the trained CNN model to
file_limit : int (optional)
can be used for debugging/testing since it limits the number of features to be created
"""
# read all files to process
F = [f for f in read_directory(label_folder) if f[-4:] == '.csv'][:file_limit]
"""
GRID SEARCH VARIABLES
"""
# episode window in seconds
EW = [2, 3, 4, 5, 6, 7, 8, 9, 10]
# cnn architectures (see dl_functions about the actual architecture of these types)
CNN = ['v1', 'v2', 'v3', 'v4']
"""
DEEP LEARNING SETTINGS
"""
# define number of epochs
epoch = 250
# training proportion of the data
train_split = 0.6
# development proportion of the data (test size will be the remainder of train + dev)
dev_split = 0.2
"""
OTHER SETTNGS
"""
# set to true if created features need to be stored to disk (this can then be used to read from disk which is much faster)
save_features = False
# load features from disk, can only be done if created first (see save_features Boolean value)
load_features_from_disk = True
# perform combinations
for idx, episode_window_sec in enumerate(EW):
"""
CREATE START AND STOP EPISODES
"""
try:
# verbose
logging.info(f'Processing combination {idx}/{len(EW)}')
# verbose
logging.debug(f'Episode window sec : {str(episode_window_sec)}')
# calculate features if load_features_from_disk is set to False, otherwise read from disk (remember to have created them first)
if not load_features_from_disk:
# create the feature data
executor = Parallel(n_jobs = cpu_count(), backend = 'multiprocessing')
# create tasks so we can execute them in parallel
tasks = (delayed(get_start_and_stop_episodes)(file = f, label_folder = label_folder, hdf5_read_file = hdf5_read_file, idx = i, total = len(F), episode_window_sec = episode_window_sec) for i, f in enumerate(F))
# empty lists to hold x_0 and x_1
new_data = {'x_0' : [], 'x_1' : []}
# execute task
for data in executor(tasks):
# data contains x_0 and x_1 arrays
for key, value in data.items():
if len(value) > 0:
new_data[key].append(value)
# vstack all the arrays within new_data
for key, value in new_data.items():
new_data[key] = np.vstack(value)
# define X_0 and X_1 as new variables and convert to float 32
X_0 = np.array(new_data['x_0']).astype('float32')
X_1 = np.array(new_data['x_1']).astype('float32')
# upscale X_1
X_1 = np.repeat(X_1, len(X_0) // len(X_1), 0)
# create the Y features
Y_0 = np.zeros((X_0.shape[0], 1))
Y_1 = np.ones((X_1.shape[0], 1))
# now stack features
X = np.vstack([X_0, X_1])
Y = np.vstack([Y_0, Y_1])
# shuffle the dataset (necessary before we split into train, dev, test)
X, Y = shuffle(X, Y, random_state = 42)
if save_features:
# construct save location
save_features_location = os.path.join(save_data_location, str(episode_window_sec))
# create directory if not exists
create_directory(save_features_location)
# save data as npz file
np.savez(os.path.join(save_features_location, 'data.npz'), x = X, y = Y)
else:
# load features from disk
features = np.load(os.path.join(save_data_location, str(episode_window_sec), 'data.npz'))
X = features['x']
Y = features['y']
logging.debug(f'X shape : {X.shape}')
logging.debug(f'Y shape : {Y.shape}')
"""
CREATE CNN MODEL
"""
for cnn_type in CNN:
logging.info(f'Processing cnn_type : {cnn_type}')
# dynamically create model name
model_name = f'cnn_{cnn_type}_{episode_window_sec}.h5'
# create 1D cnn
create_1d_cnn_non_wear_episodes(X, Y, save_model_folder, model_name, cnn_type, epoch = epoch, train_split = train_split, dev_split = dev_split, return_model = False)
except Exception as e:
logging.error(f'Unable to create 1D CNN model with EP: {episode_window_sec}, error : {e}')
def get_start_and_stop_episodes(file, label_folder, hdf5_read_file, episode_window_sec, idx = 1, total = 1, hz = 100, save_location = os.path.join(os.sep, 'users', 'shaheensyed', 'hdf5', 'start_stop_data')):
"""
Get start and stop episodes from activity data
Parameters
-----------
file : string
file location of csv file that contains episodes
label_folder : os.path
folder location of start and stop labels for non-wear time
hdf5_read_file : os.path
location of HDF5 file that contains raw acceleration data per participant
episode_window_sec : int
window size in seconds that will determine how long the preceding and following features will be
idx : int (optional)
index of the file to process, only used for verbose and can be usefull when multiprocessing is one
total : int (optional)
total number of fies to be processed, only used for verbose and can be usefull when multiprocessing is one
save_location : os.path
folder location where to save the labels to for each subject together with type, window, subject, label, index, and counter information
Returns
---------
data : dict()
dictionary that will hold episodes by label
"""
# extract subject from file
subject = re.search('[0-9]{8}', file)[0]
logging.info(f'=== Processing subject {subject}, file {idx}/{total} ===')
# logging.info(f'episode window sec : {episode_window_sec}, feature_window_ms : {feature_window_ms}, feature step ms : {feature_step_ms}')
# read csv file with episodes
episodes = pd.read_csv(file)
# read actigraph raw data for subject
actigraph_acc, *_ = get_actigraph_acc_data(subject, hdf5_file = hdf5_read_file)
# empty list that will hold all the data
data = {'x_0' : [], 'x_1' : []}
# loop over each label and get start and stop episode
for _, row in episodes.iterrows():
# parse out variables from dataframe row
start_index = row.loc['start_index']
stop_index = row.loc['stop_index']
# note that we flip the encoding here. so labels with 0 become 1, and labels that are 1 become zero. This is basically changing how we define the positive class
label = 1 - row.loc['label']
# forward search to extend stop index
stop_index = _forward_search_episode(actigraph_acc, stop_index, hz = 100, max_search_min = 5, std_threshold = 0.004, verbose = False)
# backwar search to extend start index
start_index = _backward_search_episode(actigraph_acc, start_index, hz = 100, max_search_min = 5, std_threshold = 0.004, verbose = False)
# get start episode
start_episode = actigraph_acc[start_index - (episode_window_sec * hz) : start_index]
# get stop episode
stop_episode = actigraph_acc[stop_index : stop_index + (episode_window_sec * hz)]
# check if episode is right size
if start_episode.shape[0] == episode_window_sec * hz:
data[f'x_{label}'].append(start_episode)
if stop_episode.shape[0] == episode_window_sec * hz:
data[f'x_{label}'].append(stop_episode)
return data
"""
CREATE NON-WEAR TIME BY USING CNN MODEL
"""
def batch_process_get_nw_time_from_raw(hdf5_acc_file, hdf5_nw_file, limit = None, skip_n = 0, hz = 100):
"""
Grid search approach to calculate non-wear time from raw data by using the CNN model and trying out different hyperparameter values
Parameters
-----------
hdf5_read_file : os.path
location of HDF5 file that contains the raw activity data for actigraph and actiwave
hdf5_nw_file : os.path
location of HDF5 file where to save the inferred non-wear to
limit : int (optional)
limit the number of subjects to be processed
skip_n : int (optional)
skip first N subjects
hz : int (optional)
sampling frequency of the raw acceleration data (defaults to 100HZ)
"""
# which CNN model to use
model_folder = os.path.join('files', 'models', 'nw', 'cnn1d_60_20_20_early_stopping')
# define architecture type
cnn_type = 'v2'
# define window length
episode_window_sec = 3
"""
GRID SEARCH PARAMETERS
"""
# standard deviation threshold
std_range = [0.004]
# default classification when an episode does not have a starting or stop feature window (happens at t=0 or at the end of the data)
edge_true_or_false_range = [True, False]
# logical operator to see if both sides need to be classified as non-wear time (AND) or just a single side (OR)
start_stop_label_decision_range = ['or', 'and']
# merging of two candidate non-wear episodes that are 'distance_in_min_range' minutes apart from each other
distance_in_min_range = [1, 2, 3, 4, 5]
# loop over each standard deviation
for std_threshold in std_range:
# loop over each default setting
for edge_true_or_false in edge_true_or_false_range:
# loop over logical operator
for start_stop_label_decision in start_stop_label_decision_range:
# loop over each merging distance
for distance_in_min in distance_in_min_range:
# get all the subjects from the hdf5 file (subjects are individuals who participated in the Tromso Study #7
subjects = get_all_subjects_hdf5(hdf5_file = hdf5_acc_file)[0 + skip_n:limit]
# exclude subjects that have issues with their data
subjects = [s for s in subjects if s not in get_subjects_with_invalid_data()]
# use parallel processing to speed up processing time
executor = Parallel(n_jobs = cpu_count(), backend = 'multiprocessing')
# create tasks so we can execute them in parallel
tasks = (delayed(process_get_nw_time_from_raw)(subject, model_folder, hdf5_acc_file, hdf5_nw_file, cnn_type, std_threshold, episode_window_sec, start_stop_label_decision, distance_in_min, edge_true_or_false, hz, i, len(subjects)) for i, subject in enumerate(subjects))
# execute task
executor(tasks)
def process_get_nw_time_from_raw(subject, model_folder, hdf5_read_file, hdf5_save_file, cnn_type, std_threshold, episode_window_sec, start_stop_label_decision, distance_in_min, edge_true_or_false, hz, idx, total):
"""
Get non-wear time from raw acceleration data by using a trained cnn model
Parameters
-----------
subject : string
subject ID to process
model_folder : os.path
folder location where different CNN models are stored
hdf5_read_file : os.path
file location of HDF5 that contains raw acceleration data
hdf5_save_file : os.path
file location where to save the inferred non-wear time to
cnn_type : string
what type of CNN architecture to use (v1, v2, v3 or v4 for example)
std_threshold : float
standard deviation threshold
episode_window_sec : int
define window length (for example 3 seconds)
start_stop_label_decision : string
logical operator to see if both sides need to be classified as non-wear time (AND) or just a single side (OR)
distance_in_min : int
number of minutes that will be used to merg two candidate non-wear episodes that are 'distance_in_min_range' minutes apart from each other
edge_true_or_false : Boolen
default classification when an episode does not have a starting or stop feature window (happens at t=0 or at the end of the data)
hz : int
sample frequency of the raw data
idx : int (optional)
index of the file to process, only used for verbose and can be usefull when multiprocessing is one
total : int (optional)
total number of files to be processed, only used for verbose and can be usefull when multiprocessing is one
"""
# verbose
logging.info('{style} Processing subject: {} {}/{} {style}'.format(subject, idx, total, style = '='*10))
# load cnn model
cnn_model = load_tf_model(model_location = os.path.join(model_folder, cnn_type, f'cnn_{cnn_type}_{episode_window_sec}.h5'))
# read actigraph raw data for subject
actigraph_acc, _, actigraph_time = get_actigraph_acc_data(subject, hdf5_file = hdf5_read_file)
# create new nw_vector
nw_vector = np.zeros((actigraph_acc.shape[0], 1)).astype('uint8')
"""
FIND CANDIDATE NON-WEAR SEGMENTS ACTIGRAPH ACCELERATION DATA
"""
# get candidate non-wear episodes (note that these are on a minute resolution)
nw_episodes = find_candidate_non_wear_segments_from_raw(actigraph_acc, std_threshold = std_threshold, min_segment_length = 1, sliding_window = 1, hz = hz)
# flip the candidate episodes, we want non-wear time to be encoded as 1, and wear time encoded as 0
nw_episodes = 1 - nw_episodes
"""
GET START AND END TIME OF NON WEAR SEGMENTS
"""
# find all indexes of the numpy array that have been labeled non-wear time
nw_indexes = np.where(nw_episodes == 1)[0]
# find consecutive ranges
non_wear_segments = find_consecutive_index_ranges(nw_indexes)
# empty dictionary where we can store the start and stop times
dic_segments = {}
# check if segments are found
if len(non_wear_segments[0]) > 0:
# find start and stop times (the indexes of the edges and find corresponding time)
for i, row in enumerate(non_wear_segments):
# find start and stop
start, stop = np.min(row), np.max(row)
# add the start and stop times to the dictionary
dic_segments[i] = {'counter' : i, 'start': actigraph_time[start], 'stop' : actigraph_time[stop], 'start_index': start, 'stop_index' : stop}
# create dataframe from segments
episodes = pd.DataFrame.from_dict(dic_segments)
"""
MERGE EPISODES THAT ARE CLOSE TO EACH OTHER
"""
grouped_episodes = group_episodes(episodes = episodes.T, distance_in_min = distance_in_min, correction = 3, hz = hz, training = False).T
"""
FOR EACH EPISODE, EXTEND THE EDGES, CREATE FEATURES, AND INFER LABEL
"""
for _, row in grouped_episodes.iterrows():
start_index = row.loc['start_index']
stop_index = row.loc['stop_index']
logging.info(f'Start_index : {start_index}, Stop_index: {stop_index}')
# forward search to extend stop index
stop_index = _forward_search_episode(actigraph_acc, stop_index, hz = hz, max_search_min = 5, std_threshold = std_threshold, verbose = False)
# backwar search to extend start index
start_index = _backward_search_episode(actigraph_acc, start_index, hz = hz, max_search_min = 5, std_threshold = std_threshold, verbose = False)
logging.info(f'Start_index : {start_index}, Stop_index: {stop_index}')
# get start episode
start_episode = actigraph_acc[start_index - (episode_window_sec * hz) : start_index]
# get stop episode
stop_episode = actigraph_acc[stop_index : stop_index + (episode_window_sec * hz)]
# label for start and stop combined
start_stop_label = [False, False]
"""
START EPISODE
"""
if start_episode.shape[0] == episode_window_sec * hz:
# reshape into num feature x time x axes
start_episode = start_episode.reshape(1, start_episode.shape[0], start_episode.shape[1])
# get binary class from model
start_label = cnn_model.predict_classes(start_episode).squeeze()
# if the start label is 1, this means that it is wear time, and we set the first start_stop_label to 1
if start_label == 1:
start_stop_label[0] = True
else:
# there is an episode right at the start of the data, since we cannot obtain a full epsisode_window_sec array
# here we say that True for nw-time and False for wear time
start_stop_label[0] = edge_true_or_false
"""
STOP EPISODE
"""
if stop_episode.shape[0] == episode_window_sec * hz:
# reshape into num feature x time x axes
stop_episode = stop_episode.reshape(1, stop_episode.shape[0], stop_episode.shape[1])
# get binary class from model
stop_label = cnn_model.predict_classes(stop_episode).squeeze()
# if the start label is 1, this means that it is wear time, and we set the first start_stop_label to 1
if stop_label == 1:
start_stop_label[1] = True
else:
# there is an episode right at the END of the data, since we cannot obtain a full epsisode_window_sec array
# here we say that True for nw-time and False for wear time
start_stop_label[1] = edge_true_or_false
if start_stop_label_decision == 'or':
# use logical OR to determine if episode is true non-wear time
if any(start_stop_label):
# true non-wear time, record start and stop in nw-vector
nw_vector[start_index:stop_index] = 1
elif start_stop_label_decision == 'and':
# use logical and to determine if episode is true non-wear time
if all(start_stop_label):
# true non-wear time, record start and stop in nw-vector
nw_vector[start_index:stop_index] = 1
else:
logging.error(f'Start/Stop decision unknown, can only use or/and, given: {start_stop_label_decision}')
# save nw_vector to HDF5
group_name = f'{cnn_type}_{episode_window_sec}_{start_stop_label_decision}_{distance_in_min}_{std_threshold}_{edge_true_or_false}'
# save to HDF5 file
save_data_to_group_hdf5(group = group_name, data = nw_vector, data_name = subject, overwrite = True, hdf5_file = hdf5_save_file)
def calculate_cnn_classification_performance(hdf5_read_file):
"""
Calculate the classification performance metrics of several CNN models
Parameters
----------
hdf5_read_file : os.path
file location of the HDF5 file that contains the inferred non-wear time data and true non-wear time
Note that the function batch_process_get_nw_time_from_raw will need to be executed first to obtain inferred non-wear time vectors
This function only calculates performance measures based on the inferred and true non-wear time
"""
# define architecture type
cnn_type = 'v2'
# define window length
episode_window_sec = 3
"""
PARAMETERS
"""
# standard deviation threshold
std_threshold_range = [0.004]
# default classification when an episode does not have a starting or stop feature window (happens at t=0 or at the end of the data)
edge_true_or_false_range = [True, False]
# logical operator to see if both sides need to be classified as non-wear time (AND) or just a single side (OR)
start_stop_label_decision_range = ['or', 'and']
# merging of two candidate non-wear episodes that are 'distance_in_min_range' minutes apart from each other
distance_in_min_range = [1, 2, 3, 4, 5]
for std_threshold in std_threshold_range:
for edge_true_or_false in edge_true_or_false_range:
for start_stop_label_decision in start_stop_label_decision_range:
for distance_in_min in distance_in_min_range:
# verbose
logging.info(f'Processing CNN_TYPE : {cnn_type}, EPISODE WINDOW SEC : {episode_window_sec}, STD RANGE : {std_threshold}, EDGE : {edge_true_or_false}, START/STOP LABEL : {start_stop_label_decision}, DISTANCE : {distance_in_min}')
# empty dictionary to hold all the data
data = {}
"""
TRUE NON WEAR TIME
"""
logging.info('Reading true non-wear time')
# read data of true non-wear time
for subject in get_datasets_from_group(group_name = 'true_nw_time', hdf5_file = hdf5_read_file):
# read dataset
nw_time = read_dataset_from_group(group_name = 'true_nw_time', dataset = subject, hdf5_file = hdf5_read_file)
data[subject] = {'y' : nw_time, 'y_hat' : None}
"""
INFERRED NON WEAR TIME
"""
# group name of inferred non-wear time
inferred_nw_time_group_name = f'{cnn_type}_{episode_window_sec}_{start_stop_label_decision}_{distance_in_min}_{std_threshold}_{edge_true_or_false}'
logging.info('Reading inferred non-wear time')
# read data of true non-wear time
for subject in data.keys():
# read dataset
inferred_nw_time = read_dataset_from_group(group_name = inferred_nw_time_group_name, dataset = subject, hdf5_file = hdf5_read_file)
data[subject]['y_hat'] = inferred_nw_time
"""
CALCULATE tn, fp, fn, tp
"""
# empty dataframe to hold values
all_results = pd.DataFrame()
logging.info('Calculating classification performance')
# create the feature data
executor = Parallel(n_jobs = cpu_count(), backend = 'multiprocessing')
# create tasks so we can execute them in parallel
tasks = (delayed(_calculate_confusion_matrix)(key, value) for key, value in data.items())
# execute task
for key, series in executor(tasks):
all_results[key] = pd.Series(series)
# tranpose dataframe
all_results = all_results.T
# create subfolder based on cnn type and seconds used
subfolder = f'{cnn_type}_{episode_window_sec}'
# create subfolder if not exists
create_directory(os.path.join('files', 'cnn_nw_performance', subfolder))
# save to CSV
all_results.to_csv(os.path.join('files', 'cnn_nw_performance', subfolder, f'{inferred_nw_time_group_name}_per_subject.csv'))
tn = all_results['tn'].sum()
fp = all_results['fp'].sum()
fn = all_results['fn'].sum()
tp = all_results['tp'].sum()
logging.debug('tn: {}, fp: {}, fn: {}, tp: {}'.format(tn, fp, fn, tp))
# calculate classification performance such as precision, recall, f1 etc.
classification_performance = calculate_classification_performance(tn, fp, fn, tp)
df_classification_performance = pd.DataFrame(pd.Series(classification_performance))
df_classification_performance.to_csv(os.path.join('files', 'cnn_nw_performance', subfolder, f'{inferred_nw_time_group_name}_all_subjects.csv'))
"""
EVALUATE BASELINE MODELS
"""
def batch_evaluate_baseline_models(hdf5_acc_file, hdf5_nw_file):
"""
Calculate non-wear time with two baseline algorithms. See paper description below
Description from paper:
Our proposed non-wear algorithm was compared to several baseline algorithms and existing non-wear detection algorithms to evaluate its
performance (van Hees et al., 2011, 2013) These baseline algorithms employ a similar analytical approach commonly found in count-based
algorithms(L. Choi et al., 2011; Hecht et al., 2009; Troiano et al., 2007), that is, detecting episodes of no activity by using an interval
of varying length. The first baseline algorithm detected episodes of no activity when the raw acceleration data was below a SD threshold
of 0.004g, 0.005g, 0.006g, and 0.007g and the duration did not exceed an interval length of 15, 30, 45, 60, 75, 90, 105, or 120 minutes.
A similar approach was proposed in another recent study as the SD_XYZ method,(Ahmadi et al., 2020) although the authors fixed the
threshold to 13mg and the interval to 30 minutes for a wrist worn accelerometer. Throughout this paper, the first baseline algorithm is
referred to as the XYZ algorithm. The second baseline algorithm was similar to the first baseline algorithm, albeit that the SD threshold
was applied to the vector magnitude unit (VMU) of the three axes, where VMU is calculated as √(〖acc〗_x^2+〖acc〗_y^2+ 〖acc〗_z^2 ),
with accx, accy, and accz referring to each of the orthogonal axes. A similar approach has recently been proposed as the SD_VMU
algorithm (Ahmadi et al., 2020). Throughout this paper, this baseline algorithm is referred to as the VMU algorithm.
Parameters
-------------
hdf5_acc_file
file location of the HDF5 file that contains the raw acceleration data
hdf5_nw_file : os.path
file location of the HDF5 file that contains the inferred non-wear time data and true non-wear time
"""
# standard deviation range
std_threshold_range = [0.004, 0.005, 0.006, 0.007]
# episode length
episode_length_range = [15, 30, 45, 60, 75, 90, 105, 120]
# create combinations
combinations = [ (std_threshold, episode_length) for std_threshold in std_threshold_range for episode_length in episode_length_range]
# get all the subjects from the hdf5 file (subjects are individuals who participated in the Tromso Study #7
subjects = get_all_subjects_hdf5(hdf5_file = hdf5_acc_file)
# exclude subjects that have issues with their data
subjects = [s for s in subjects if s not in get_subjects_with_invalid_data()]
# create parallel executor
executor = Parallel(n_jobs = cpu_count(), backend = 'multiprocessing')
# create tasks so we can execute them in parallel
tasks = (delayed(_read_true_non_wear_time_from_hdf5)(subject, hdf5_nw_file, i, len(subjects)) for i, subject in enumerate(subjects))
# empty dictionary to hold true non wear time
true_nw_time = {}
logging.info('Reading true non-wear time')
# execute task and return data
for subject, nw_time_vector in executor(tasks):
# add true non wear time to dictionary
true_nw_time[subject] = nw_time_vector
# evaluate each combination
for i, combination in enumerate(combinations):
# unpack tuple variables
std_threshold, episode_length = combination
# verbose
logging.info(f'Processing std_treshold : {std_threshold}, episode length : {episode_length} {i}/{len(combinations)}')
# call evaluate function
evaluate_baseline_models(subjects, hdf5_acc_file, true_nw_time, std_threshold, episode_length)
def evaluate_baseline_models(subjects, hdf5_acc_file, true_nw_time, std_threshold, episode_length, use_vmu = True, save_folder = os.path.join('files', 'baseline_performance_vmu')):
"""
Function that is part of the batch_evaluate_baseline_models function.
Here we calculate the performance of a single parameterized baseline model.
Parameters
------------
subjects : list
list of all subject ID that we want to include when calculating the performance of this baseline algorithm. Typically all available subjects will be used
hdf5_acc_file
file location of the HDF5 file that contains the raw acceleration data
hdf5_nw_file : os.path
file location of the HDF5 file that contains the inferred non-wear time data and true non-wear time
std_threshold : float
standard deviation threshold used inside this baseline algorithm
episode_length : int
this can be seen as the interval. The interval is used as a minimum window in which the 'std_threshold' need to be below in order to classify as non-wear time.
"""
# create the feature data
executor = Parallel(n_jobs = cpu_count(), backend = 'multiprocessing')
# create tasks so we can execute them in parallel
tasks = (delayed(_evaluate_baseline)(hdf5_acc_file, subject, std_threshold, episode_length, use_vmu, i, len(subjects)) for i, subject in enumerate(subjects))
# new dictionary to keep all data
data = {}
# execute task and return data
for subject, y_hat in executor(tasks):
y = true_nw_time[subject]
# keep y and y_hat in dictionary
data[subject] = {'y' : y, 'y_hat' : y_hat}
"""
CALCULATE tn, fp, fn, tp
"""
# empty dataframe to hold values
all_results = pd.DataFrame()
logging.info('Calculating classification performance')
# create the feature data
executor = Parallel(n_jobs = cpu_count(), backend = 'multiprocessing')
# create tasks so we can execute them in parallel
tasks = (delayed(_calculate_confusion_matrix)(key, value) for key, value in data.items())
# execute task
for key, series in executor(tasks):
all_results[key] = pd.Series(series)
# transpose dataframe
all_results = all_results.T
# create save folder if not exists
create_directory(save_folder)
# save to CSV
all_results.to_csv(os.path.join(save_folder, f'{std_threshold}_{episode_length}_per_subject.csv'))
# count occurences of true negatives (tn), false positives (fp), false negatives (fn), and true positives (tp)
tn = all_results['tn'].sum()
fp = all_results['fp'].sum()
fn = all_results['fn'].sum()
tp = all_results['tp'].sum()
logging.debug('tn: {}, fp: {}, fn: {}, tp: {}'.format(tn, fp, fn, tp))
# calculate classification performance such as precision, recall, f1 etc.
classification_performance = calculate_classification_performance(tn, fp, fn, tp)
# create dataframe
df_classification_performance = pd.DataFrame(pd.Series(classification_performance))
# store dataframe as CSV file
df_classification_performance.to_csv(os.path.join(save_folder, f'{std_threshold}_{episode_length}_all.csv'))
"""
FUNCTIONS THAT WILL CREATE PLOTS THAT ARE USED WITHIN THE PAPER:
A novel algorithm to detect non-wear time from raw accelerometer data using convolutional neural networks
"""
def process_plot_start_stop_segments(merged_episodes_folder, hdf5_acc_file, plot_folder, hz = 100, std_threshold = 0.004):
"""
Start or the stop segments of candidate non-wear episodes where features of a length of 2-10 seconds were extracted
This basically shows raw acceleration data of candidate non-wear episodes from where we extracted preceding and following features
[FIGURE 1] Start or the stop segments of candidate non-wear episodes where features of a length of 2-10 seconds were extracted;
(a) start or stop episodes of true non-wear time, (b) start or stop episodes of wear time.
Parameters
-----------
merged_episodes_folder : os.path
folder location that contain candidate non-wear episodes with start and stop timestamps (these have been merged, meaning, that two episodes
in close proximity have been merged together to from a larger one)
hdf5_acc_file : os.path
file location of the HDF5 file that contains the raw acceleration data
hz : int (optional)
sample frequency of the data. Basically to know how many data samples we have within a single second. Defaults to 100Hz
std_threshold : float (optional)
standard deviation threshold to find candidate non-wear episodes. This is used to extend the edges of an episode to go from 1-min resolution to 1-sec resolution
"""
# dictionary to hold plot data
plot_data = {'0' : [], '1' : []}