Skip to content

Commit 48891f6

Browse files
committed
Fixing errors in RS sessions
1 parent 6c2ab5b commit 48891f6

File tree

3 files changed

+22
-7
lines changed

3 files changed

+22
-7
lines changed

brainbox/behavior/dlc.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ def insert_idx(array, values):
4141
idx[np.where(abs(values - array[idx - 1]) < abs(values - array[idx]))] -= 1
4242
# If 0 index was reduced, revert
4343
idx[idx == -1] = 0
44+
if np.all(idx == 0):
45+
raise ValueError('Something is wrong, all values to insert are outside of the array.')
4446
return idx
4547

4648

@@ -121,7 +123,7 @@ def get_feature_event_times(dlc, dlc_t, features):
121123

122124
def get_licks(dlc, dlc_t):
123125
"""
124-
Compute lick times from the toungue dlc points
126+
Compute lick times from the tongue dlc points
125127
:param dlc: dlc pqt table
126128
:param dlc_t: dlc times
127129
:return:
@@ -216,6 +218,9 @@ def get_smooth_pupil_diameter(diameter_raw, camera, std_thresh=5, nan_thresh=1):
216218
else:
217219
raise NotImplementedError("camera has to be 'left' or 'right")
218220

221+
# Raise error if too many NaN time points, in this case it doesn't make sense to interpolate
222+
if np.mean(np.isnan(diameter_raw)) > 0.9:
223+
raise ValueError(f"Raw pupil diameter for {camera} is too often NaN, cannot smooth.")
219224
# run savitzy-golay filter on non-nan time points to denoise
220225
diameter_smoothed = smooth_interpolate_savgol(diameter_raw, window=window, order=3, interp_kind='linear')
221226

@@ -488,6 +493,8 @@ def plot_speed_hist(dlc_df, cam_times, trials_df, feature='paw_r', cam='left', l
488493
"""
489494
# Threshold the dlc traces
490495
dlc_df = likelihood_threshold(dlc_df)
496+
# For pre-GPIO sessions, remove the first few timestamps to match the number of frames
497+
cam_times = cam_times[-len(dlc_df):]
491498
# Get speeds
492499
speeds = get_speed(dlc_df, cam_times, camera=cam, feature=feature)
493500
# Windows aligned to align_to
@@ -506,7 +513,7 @@ def plot_speed_hist(dlc_df, cam_times, trials_df, feature='paw_r', cam='left', l
506513
plt.plot(times, pd.DataFrame.from_dict(dict(zip(incorrect.index, incorrect.values))).mean(axis=1),
507514
c='gray', label='incorrect trial')
508515
plt.axvline(x=0, label='stimOn', linestyle='--', c='r')
509-
plt.title(f'{feature.split("_")[0].capitalize()} speed')
516+
plt.title(f'{feature.split("_")[0].capitalize()} speed ({cam} cam)')
510517
plt.xticks([-0.5, 0, 0.5, 1, 1.5])
511518
plt.xlabel('time [sec]')
512519
plt.ylabel('speed [px/sec]')
@@ -542,7 +549,7 @@ def plot_pupil_diameter_hist(pupil_diameter, cam_times, trials_df, cam='left'):
542549
plt.plot(times, pupil_mean, label=align_to.split("_")[0], color=color)
543550
plt.fill_between(times, pupil_mean + pupil_std, pupil_mean - pupil_std, color=color, alpha=0.5)
544551
plt.axvline(x=0, linestyle='--', c='k')
545-
plt.title('Pupil diameter')
552+
plt.title(f'Pupil diameter ({cam} cam)')
546553
plt.xlabel('time [sec]')
547554
plt.xticks([-0.5, 0, 0.5, 1, 1.5])
548555
plt.ylabel('pupil diameter [px]')

ibllib/pipes/ephys_preprocessing.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -922,8 +922,13 @@ def _run(self, overwrite=False, run_qc=True, plot_qc=True):
922922
# Compute pupil diameter, raw and smoothed
923923
_logger.info(f"Computing raw pupil diameter for {cam} camera.")
924924
features['pupilDiameter_raw'] = get_pupil_diameter(dlc_thresh)
925-
_logger.info(f"Computing smooth pupil diameter for {cam} camera.")
926-
features['pupilDiameter_smooth'] = get_smooth_pupil_diameter(features['pupilDiameter_raw'], cam)
925+
try:
926+
_logger.info(f"Computing smooth pupil diameter for {cam} camera.")
927+
features['pupilDiameter_smooth'] = get_smooth_pupil_diameter(features['pupilDiameter_raw'],
928+
cam)
929+
except BaseException:
930+
_logger.error(f"Computing smooth pupil diameter for {cam} camera failed, saving all NaNs.")
931+
features['pupilDiameter_smooth'] = np.nan
927932
# Safe to pqt
928933
features_file = Path(self.session_path).joinpath('alf', f'_ibl_{cam}Camera.features.pqt')
929934
features.to_parquet(features_file)
@@ -962,6 +967,7 @@ def _run(self, overwrite=False, run_qc=True, plot_qc=True):
962967
fig_path.parent.mkdir(parents=True, exist_ok=True)
963968
fig = dlc_qc_plot(self.one.path2eid(self.session_path), one=self.one)
964969
fig.savefig(fig_path)
970+
fig.clf()
965971
snp = ReportSnapshot(self.session_path, session_id, one=self.one)
966972
snp.outputs = [fig_path]
967973
snp.register_images(widths=['orig'],

ibllib/plots/figures.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,7 @@ def dlc_qc_plot(eid, one=None):
299299
logger.warning(f"Could not load _ibl_{cam}Camera.{feat} some DLC QC plots have to be skipped.")
300300
data[f'{cam}_{feat}'] = None
301301
# Sometimes there is a file but the object is empty
302-
if len(data[f'{cam}_{feat}']) == 0:
302+
if data[f'{cam}_{feat}'] is not None and len(data[f'{cam}_{feat}']) == 0:
303303
logger.warning(f"Object loaded from _ibl_{cam}Camera.{feat} is empty, some plots have to be skipped.")
304304
data[f'{cam}_{feat}'] = None
305305

@@ -317,7 +317,9 @@ def dlc_qc_plot(eid, one=None):
317317
data[f'{alf_object}'] = None
318318
# Simplify to what we actually need
319319
data['licks'] = data['licks'].times if data['licks'] else None
320-
data['left_pupil'] = data['left_features'].pupilDiameter_smooth if data['left_features'] is not None else None
320+
data['left_pupil'] = data['left_features'].pupilDiameter_smooth if (
321+
data['left_features'] is not None and not np.all(np.isnan(data['left_features'].pupilDiameter_smooth))
322+
) else None
321323
data['wheel_time'] = data['wheel'].timestamps if data['wheel'] is not None else None
322324
data['wheel_position'] = data['wheel'].position if data['wheel'] is not None else None
323325
if data['trials']:

0 commit comments

Comments
 (0)