forked from april-tools/e4selflearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess_ds.py
252 lines (234 loc) · 8.59 KB
/
preprocess_ds.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
import argparse
import pickle
from functools import partial
from shutil import rmtree
import pandas as pd
from tqdm.contrib import concurrent
from timebase.data import preprocessing
from timebase.data import spreadsheet
from timebase.data import utils
from timebase.data.static import *
from timebase.utils import h5
from timebase.utils.utils import set_random_seed
def get_session_label(clinical_info: pd.DataFrame, session_id: str):
session = clinical_info[clinical_info.Session_Code == session_id]
if session.empty:
return None
else:
values = session.values[0]
values[LABEL_COLS.index("Session_Code")] = float(
os.path.basename(values[LABEL_COLS.index("Session_Code")])
)
return values.astype(np.float32)
def preprocess_session(
args, clinical_info: pd.DataFrame, session_id: str, labelled: bool
):
if labelled:
recording_dir = utils.unzip_session(
args.path2labelled_data, session_id=os.path.basename(session_id)
)
session_label = get_session_label(clinical_info, session_id=session_id)
if session_label is None:
raise ValueError(f"Cannot find session {session_id} in spreadsheet.")
session_data, session_info, short_section = preprocessing.preprocess_dir(
args,
recording_dir=recording_dir,
labelled=labelled,
)
else:
session_label = np.empty(len(LABEL_COLS), dtype=np.float32)
session_label.fill(np.nan)
session_data, session_info, short_section = preprocessing.preprocess_dir(
args,
recording_dir=session_id,
labelled=labelled,
)
if short_section:
return None
else:
session_data["labels"] = session_label
session_output_dir = os.path.join(args.output_dir, session_id).replace(
os.path.join(args.path2unlabelled_data, "recast/"), ""
)
if not os.path.isdir(session_output_dir):
os.makedirs(session_output_dir)
filename = os.path.join(session_output_dir, "channels.h5")
h5.write(filename=filename, content=session_data, overwrite=True)
return session_info
def preprocess_wrapper(args, clinical_info, session_id, labelled):
results = preprocess_session(
args,
clinical_info,
session_id,
labelled,
)
return results
def main(args):
if not args.e4selflearning:
if not os.path.isdir(args.path2labelled_data):
raise FileNotFoundError(
f"labelled data at {args.path2labelled_data} not found."
)
if not os.path.isdir(args.path2unlabelled_data):
raise FileNotFoundError(
f"path2unlabelled_data data at {args.path2unlabelled_data} " f"not found."
)
if os.path.isdir(args.output_dir):
if args.overwrite:
rmtree(args.output_dir)
else:
raise FileExistsError(
f"output_dir {args.output_dir} already exists. Add --overwrite "
f" flag to overwrite the existing preprocessed data."
)
os.makedirs(args.output_dir)
set_random_seed(args.seed)
unlabelled_sessions = preprocessing.recast_unlabelled_data(args)
all_sessions = dict(
zip(
unlabelled_sessions,
len(unlabelled_sessions) * [False],
)
)
recording_time = {
"unlabelled": {0.0: 0, 1.0: 0, 2.0: 0},
}
if not args.e4selflearning:
clinical_info = spreadsheet.read(args)
args.session_codes = list(clinical_info["Session_Code"])
clinical_info.replace({"status": DICT_STATE}, inplace=True)
clinical_info.replace({"time": DICT_TIME}, inplace=True)
for session in args.session_codes:
all_sessions[session] = False
recording_time["labelled"] = {0.0: 0, 1.0: 0, 2.0: 0}
assert os.sep.join(args.path2unlabelled_data.split(os.sep)[:-1]) == os.sep.join(
args.path2labelled_data.split(os.sep)[:-1]
)
else:
clinical_info = None
print(
f"\nPreprocessing recordings from {os.sep.join(args.path2unlabelled_data.split(os.sep)[:-1])}..."
)
results = concurrent.process_map(
partial(preprocess_wrapper, args, clinical_info),
all_sessions.keys(),
all_sessions.values(),
max_workers=args.num_workers,
chunksize=args.chunksize,
desc="Preprocessing",
)
sessions_info, invalid_sessions = {}, []
for i, (session_id, labelled) in enumerate(all_sessions.items()):
# session_info = preprocess_session(
# args,
# session_id=session_id,
# clinical_info=clinical_info,
# labelled=labelled,
# )
session_info = results[i]
session_id = session_id.replace(
os.path.join(args.path2unlabelled_data, "recast/"), ""
)
if session_info is None:
invalid_sessions.append(session_id)
continue
annotation_status = "labelled" if session_info["labelled"] else "unlabelled"
for k, v in session_info["seconds_per_status"].items():
recording_time[annotation_status][k] += v
# del session_info['minutes_by_status']
sessions_info[session_id] = session_info
res = {
"invalid_sessions": invalid_sessions,
"sessions_info": sessions_info,
"sleep_algorithm": args.sleep_algorithm,
}
if not args.e4selflearning:
numeric_columns = clinical_info.select_dtypes(include=[np.number]).columns
clinical_info[numeric_columns] = clinical_info[numeric_columns].astype(
np.float32
)
res["clinical_info"] = clinical_info
with open(os.path.join(args.output_dir, "metadata.pkl"), "wb") as file:
pickle.dump(
res,
file,
)
if args.verbose == 1:
for k, v in recording_time.items():
print(f"{k} recordings:\t")
for status, seconds in v.items():
hours = seconds // 3600
minutes = (seconds % 3600) // 60
remaining_seconds = seconds % 60
print(
f"{hours} hours, {minutes} minutes, and {remaining_seconds} "
f"seconds of recording as {SLEEP_DICT[status]}"
)
print(f"Saved processed data to {args.output_dir}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--path2unlabelled_data",
type=str,
default="data/raw_data/unlabelled_data",
help="path to directory with unlabelled data",
)
parser.add_argument(
"--path2labelled_data",
type=str,
default="data/raw_data/barcelona",
help="path to directory with raw data in zip files collected and "
"labelled in Barcelona, Hospital Clínic",
)
parser.add_argument(
"--e4selflearning",
action="store_true",
help="allows users with no access to INTREPIBD/TIMEBASE data to "
"carry out the pre-processing and the self-supervised "
"pre-training on the datasets forming the E4SelfLearning "
"unlabelled collection",
)
parser.add_argument(
"--output_dir",
type=str,
required=True,
help="path to directory to store dataset",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="overwrite existing preprocessed directory",
)
parser.add_argument(
"--overwrite_spreadsheet",
action="store_true",
help="read from timebase/data/TIMEBASE_database.xlsx",
)
parser.add_argument("--verbose", type=int, default=1, choices=[0, 1, 2])
parser.add_argument("--seed", type=int, default=1234)
# preprocessing configuration
parser.add_argument(
"--sleep_algorithm",
type=str,
default="van_hees",
choices=["van_hees", "scripps_clinic"],
help="algorithm used for sleep-wake detection",
)
parser.add_argument(
"--wear_minimum_minutes",
type=int,
default=5,
help="minimum duration (in minutes) recording periods within a session"
"marked as on-body have to meet in order to be included in further "
"analyses",
)
parser.add_argument(
"--minimum_recorded_time",
type=int,
default=15,
help="minimum duration (in minutes) a recording session has to meet in"
" order to be considered for further analyses",
)
parser.add_argument("--num_workers", type=int, default=6)
parser.add_argument("--chunksize", type=int, default=1)
main(parser.parse_args())