-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSS01_inspect_predictions_N_run_onlybad.py
executable file
·279 lines (214 loc) · 9.9 KB
/
SS01_inspect_predictions_N_run_onlybad.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 10:46:38 2020
@author: adonay
"""
import os.path as op
import numpy as np
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import utils_io as uio
import utils_signal_processing as sig_proc
import utils_visualization as viz
import utils_retraining as retrn
def run_step(step, subj):
"check if step done, if overwrite true or inspected"
sj_vals = res.subj_vals(step, subj)
if "inspected" in sj_vals and any(sj_vals["inspected"] == "no"):
return True
if sj_vals.shape[0] > 0 and OVERWRT[step]:
res.remove_vals(step, subj)
return sj_vals.shape[0] == 0 or OVERWRT[step]
def saved_TS_data(paths, TS_predictions=None):
"Save TS_predictions if not None or load them/create dict"
if TS_predictions is not None:
with open(paths['out_TS'], 'wb') as f:
pickle.dump(TS_predictions, f)
return
if op.exists(paths['out_TS']):
with open(paths['out_TS'], 'rb') as f:
TS_predictions = pickle.load(f)
else:
TS_predictions = {}
return TS_predictions
# Path definitions
root_dir = '/home/adonay/Desktop/projects/Ataxia'
pat_dlc = '/data/databases/Finger_tapping/FingerTapping-Adonay-2020-01-29/'
pat_dlc_vids = [pat_dlc + i for i in ['videos/', "new_videos/"]]
lab_csv_name = "CollectedData_Adonay.csv"
pat_dlc_labs= op.join(pat_dlc, "labeled-data")
extension = "_Finger_Tapping"
model_name = '_resnet152_FingerTappingJan29shuffle1_650000'
pat_sbjs, subjs = uio.get_sbj_folders(pat_dlc_vids, name_len=16,
sufix=f'*{model_name}.csv')
paths = uio.get_paths(model_name, root_dir)
df_beh = pd.read_csv(paths['beh'], index_col=0)
# CSV files storing results
res = uio.results_dic(paths)
OVERWRT = {"subj_done" :False,
'pred_qual':False,
'times':False,
"outliers":False,
"bad_pred":False,
"good_pred":False,
"nans_pred":False}
TS_predictions = saved_TS_data(paths)
# Load results and predictions from previous run
previous_model_name = '_resnet152_FingerTappingJan29shuffle1_740000'
PREV_RUN = True#True if previous_model_name else False
path_old = uio.get_paths(previous_model_name, root_dir)
res_old = uio.results_dic(path_old)
TS_predictions_old = saved_TS_data(path_old)
subjs_in = [i for i, s in enumerate(subjs) if s not in TS_predictions.keys()]
pat_sbjs, subjs = [[l[p] for p in subjs_in] for l in [pat_sbjs, subjs]]
# Remove subj from list
missing_timestamps = []
bad_record_fname = f"{path_old['out']}Subj_comments__resnet152_FingerTappingJan29shuffle2_550000.csv"
bad_recordings = pd.read_csv(bad_record_fname)['subj']
out_subj = missing_timestamps + list(bad_recordings)
subjs_in = [i for i, s in enumerate(subjs) if s not in out_subj]
pat_sbjs, subjs = [[l[p] for p in subjs_in] for l in [pat_sbjs, subjs]]
n=6
isb, path_s, subj = n, pat_sbjs[n], subjs[n]
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(20, 10))
for isb, (path_s, subj) in enumerate(zip(pat_sbjs, subjs)):
# if res_old.subj_vals("pred_qual", subj)["quality"] == "good":
prev_bad = res_old.subj_vals("bad_pred", subj).values.tolist()
if len(prev_bad) == 0 or (len(prev_bad) == 1 and np.isnan(prev_bad[0][1])):
TS_predictions[subj] = TS_predictions_old[subj]
print(f"{subj} good subject, using previous run data")
continue
extension = op.splitext(op.basename(path_s))[0]
extension = extension.replace('DLC'+model_name,'').replace(subj, '')
subj_data={}
subj_diag = df_beh.loc[subj,'gen_diagnosis']
print(f'Doing s: {subj}, {isb}/{len(subjs)}')
old_frames = retrn.get_res_frames(subj, res_old)
if old_frames.size == 0:
old_frames = None
fingers, prob = uio.load_finger_pred(path_s, pred_theshold=.1)
subj_data['raw'] = fingers
# Load time stamps & finger positions
timestmp = uio.load_timestamps(subj, paths)
diff_time_frames = fingers.shape[2] - timestmp.size
if diff_time_frames < 0: # Last GoPro videos
print(f"Time length and frames not matching by {diff_time_frames}")
timestmp = timestmp[:fingers.shape[2]]
subj_data['timestamp'] = timestmp
if PREV_RUN and subj in TS_predictions_old.keys():
ts_old = TS_predictions_old[subj]['TS']
else:
ts_old = None
# preprocess TS
if PREV_RUN and len(res_old.get_times(subj)):
times = res_old.get_times(subj)
else:
times = None
int1, int2, out = sig_proc.ts_prepro(fingers, timestmp, times, Outl=False)
relab = []
# Do quality control prediction: good or bad
if run_step("pred_qual", subj):
if PREV_RUN and len(res_old.subj_vals("pred_qual", subj)["quality"]):
res_qc = res_old.subj_vals("pred_qual", subj)["quality"].to_list()[0]
viz.resp_corr_fig_bkg(fig, res_qc)
res_qc, relab = viz.plot_check_quality(fingers, int1, int2, out, timestmp,
axes, fig, subj, subj_diag, path_s, ts_old, old_frames)
print(f"{subj} : {res_qc}")
res.add_vals("pred_qual", [subj, res_qc])
else:
res_qc = res.subj_vals("pred_qual", subj)["quality"].to_list()[0]
viz.resp_corr_fig_bkg(fig, res_qc)
subj_data['pred_qual'] = res_qc
if res_qc == "good":
# Get beginning and end right & left tapping
if run_step("times", subj) and times is None:
res_tms, res_lg = viz.plot_get_times(fingers, int2,timestmp, axes,
fig, subj, subj_diag)
tms_vals = np.hstack((subj, res_tms, 'yes', res_lg))
print(f"R/L beg-end: {res_tms[:2]}, {res_tms[2:]}, length: " +
f"{res_lg.astype(int)} secs")
res.add_vals("times", list(tms_vals))
elif times is not None:
tms_vals = res_old.subj_vals('times', subj).to_numpy()[:,:-1]
res.add_vals("times", [i for i in tms_vals[0]])
times = res.get_times(subj)
int1, int2, out = sig_proc.ts_prepro(fingers, timestmp, times, Outl=False)
subj_data['times'] = times
# Check and select good outliers
if PREV_RUN and len(res.subj_vals("outliers", subj)) == 0:
out_checked = []
else:
cols_v = ['finger', 'x_y_ax', 'frames', 'pos', 'inspected']
out_checked = res.subj_vals("outliers", subj)[cols_v].values.tolist()
# change int2 good outliers
int2 = sig_proc.restore_bad_outliers(out_checked, int1, int2)
out_good = [o for o in out_checked if 'good' in o]
# Selects nans for retraining
bd_relab = []
if run_step("nans_pred", subj):
nans_pred = sig_proc.get_dist_nans(fingers, int2, max_nans=5)
print(f"{subj}: num nans is {len(nans_pred)}")
gd_nan_pred, bd_relab, relab = viz.nan_inspec(nans_pred, path_s,
subj,fingers, int2, relab)
res.add_vals('nans_pred', [subj, gd_nan_pred])
else:
gd_nan_pred, = res.subj_vals("nans_pred",
subj)['frames'].values.tolist()
gd_nan_pred = eval(str(gd_nan_pred)) if gd_nan_pred else []
# update relabels
relab.extend(bd_relab)
for rlb in bd_relab:
if not np.isnan(int2[int(rlb[1]), 0, int(rlb[0])]):
int2[int(rlb[1]), :, int(rlb[0])] = rlb[2:]
# inspect suspicious
relabeled= []
if run_step("bad_pred", subj):
# load previous relabels
cols_v = ['frames', 'finger', 'x', 'y']
relabeled = res.subj_vals("bad_pred", subj)[cols_v].values.tolist()
relabeled = [] if np.all(np.isnan(relabeled)) else relabeled
for rlb in relabeled:
if not np.all(np.isnan(rlb)):
int2[int(rlb[1]), :, int(rlb[0])] = rlb[2:]
relabeled, _ = viz.plot_ts_inspection(
[], timestmp, int1, int2, path_s, subj, subj_diag, axes, fig, [], ts_old)
n_relab = np.unique([r[0] for r in relabeled]).size
print(f"{subj}: {n_relab} relabeled")
relabeled.extend(relab)
res.add_bad_pred(relabeled, subj)
else:
if len(relab):
res.add_bad_pred(relab, subj)
cols_v = ['frames', 'finger', 'x', 'y']
relabeled = res.subj_vals("bad_pred", subj)[cols_v].values.tolist()
relabeled = [] if np.all(np.isnan(relabeled)) else relabeled
elif res_qc == "bad":
# int1, int2, out = sig_proc.ts_prepro(fingers, timestmp)
if run_step("good_pred", subj) or run_step("bad_pred", subj): ##TODO fix with a proper step
ttl = "SELECT GOOD and BAD PREDICTIONS for retraining"
relabeled, good_pred = viz.plot_ts_inspection(
[], timestmp, int1, int2, path_s, subj, subj_diag, axes, fig, ttl, ts_old)
n_relab = np.unique([r[0] for r in relabeled]).size
n_gd = len(good_pred)
print(f"{subj}: {n_relab} relabeled, {n_gd} good")
# res.add_vals('good_pred', [subj, good_pred])
res.add_bad_pred(relabeled, subj)
else:
cols_v = ['frames', 'finger', 'x', 'y']
relabeled = res.subj_vals("bad_pred", subj)[cols_v].values.tolist()
relabeled = [] if np.all(np.isnan(relabeled)) else relabeled
else:
ValueError("No prediction quality information")
for rlb in relabeled:
if not np.all(np.isnan(rlb)):
int2[int(rlb[1]), :, int(rlb[0])] = rlb[2:]
axes[0].clear(); axes[1].clear(); fig.patch.set_facecolor('w')
plt.show()
subj_data['TS'] = int2
TS_predictions[subj] = subj_data
retrn.save_labeled_data(int2, res, subj, path_s, pat_dlc_labs, extension,
lab_csv_name)
saved_TS_data(paths, TS_predictions)
plt.pause(.01)