Skip to content

Commit 0915c4f

Browse files
committed
Fixing some errors related to missing times data
1 parent 7d39ba4 commit 0915c4f

File tree

3 files changed

+33
-19
lines changed

3 files changed

+33
-19
lines changed

brainbox/behavior/dlc.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -440,26 +440,37 @@ def plot_motion_energy_hist(camera_dict, trials_df):
440440
'body': '#035382'}
441441

442442
start_window, end_window = plt_window(trials_df['stimOn_times'])
443+
missing_data = []
443444
for cam in camera_dict.keys():
444-
try:
445-
motion_energy = zscore(camera_dict[cam]['motion_energy'], nan_policy='omit')
446-
start_idx = insert_idx(camera_dict[cam]['times'], start_window)
447-
end_idx = np.array(start_idx + int(WINDOW_LEN * SAMPLING[cam]), dtype='int64')
448-
me_all = [motion_energy[start_idx[i]:end_idx[i]] for i in range(len(start_idx))]
449-
times = np.arange(len(me_all[0])) / SAMPLING[cam] + WINDOW_LAG
450-
me_mean = np.mean(me_all, axis=0)
451-
me_std = np.std(me_all, axis=0) / np.sqrt(len(me_all))
452-
plt.plot(times, me_mean, label=f'{cam} cam', color=colors[cam], linewidth=2)
453-
plt.fill_between(times, me_mean + me_std, me_mean - me_std, color=colors[cam], alpha=0.2)
454-
except AttributeError:
455-
logger.warning(f"Cannot load motion energy AND times data for {cam} camera")
445+
if (camera_dict[cam]['motion_energy'] is not None and len(camera_dict[cam]['motion_energy']) > 0
446+
and camera_dict[cam]['times'] is not None and len(camera_dict[cam]['times']) > 0):
447+
try:
448+
motion_energy = zscore(camera_dict[cam]['motion_energy'], nan_policy='omit')
449+
start_idx = insert_idx(camera_dict[cam]['times'], start_window)
450+
end_idx = np.array(start_idx + int(WINDOW_LEN * SAMPLING[cam]), dtype='int64')
451+
me_all = [motion_energy[start_idx[i]:end_idx[i]] for i in range(len(start_idx))]
452+
times = np.arange(len(me_all[0])) / SAMPLING[cam] + WINDOW_LAG
453+
me_mean = np.mean(me_all, axis=0)
454+
me_std = np.std(me_all, axis=0) / np.sqrt(len(me_all))
455+
plt.plot(times, me_mean, label=f'{cam} cam', color=colors[cam], linewidth=2)
456+
plt.fill_between(times, me_mean + me_std, me_mean - me_std, color=colors[cam], alpha=0.2)
457+
except AttributeError:
458+
logger.warning(f"Cannot load motion energy and/or times data for {cam} camera")
459+
missing_data.append(cam)
460+
else:
461+
logger.warning(f"Data missing or empty for motion energy and/or times data for {cam} camera")
462+
missing_data.append(cam)
456463

457464
plt.xticks([-0.5, 0, 0.5, 1, 1.5])
458465
plt.ylabel('z-scored motion energy [a.u.]')
459466
plt.xlabel('time [sec]')
460467
plt.axvline(x=0, label='stimOn', linestyle='--', c='k')
461468
plt.legend(loc='lower right')
462469
plt.title('Motion Energy')
470+
if len(missing_data) > 0:
471+
ax = plt.gca()
472+
ax.text(.95, .35, f"Data incomplete for\n{' and '.join(missing_data)} camera", color='r', fontsize=10,
473+
horizontalalignment='right', verticalalignment='center', transform=ax.transAxes)
463474
return plt.gca()
464475

465476

ibllib/pipes/ephys_preprocessing.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -903,15 +903,13 @@ def _run(self, overwrite=False, run_qc=True, plot_qc=True):
903903
dlc = pd.read_parquet(dlc_file)
904904
dlc_thresh = likelihood_threshold(dlc, 0.9)
905905
# try to load respective camera times
906-
try:
907-
dlc_t = np.load(next(Path(self.session_path).joinpath('alf').glob(f'_ibl_{cam}Camera.times.*npy')))
908-
times = True
909-
except StopIteration:
910-
_logger.error(f'No camera.times found for {cam} camera. '
906+
dlc_t = np.load(next(Path(self.session_path).joinpath('alf').glob(f'_ibl_{cam}Camera.times.*npy')))
907+
times = True
908+
if dlc_t.shape[0] == 0:
909+
_logger.error(f'camera.times empty for {cam} camera. '
911910
f'Computations using camera.times will be skipped')
912911
self.status = -1
913912
times = False
914-
915913
# These features are only computed from left and right cam
916914
if cam in ('left', 'right'):
917915
features = pd.DataFrame()

ibllib/plots/figures.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,11 @@ def dlc_qc_plot(eid, one=None):
297297
else:
298298
logger.warning(f"Could not load _ibl_{cam}Camera.{feat} some DLC QC plots have to be skipped.")
299299
data[f'{cam}_{feat}'] = None
300+
# Sometimes there is a file but the object is empty
301+
if len(data[f'{cam}_{feat}']) == 0:
302+
logger.warning(f"Object loaded from _ibl_{cam}Camera.{feat} is empty, some plots have to be skipped.")
303+
data[f'{cam}_{feat}'] = None
304+
300305
# Session data
301306
for alf_object in ['trials', 'wheel', 'licks']:
302307
try:
@@ -349,7 +354,7 @@ def dlc_qc_plot(eid, one=None):
349354
ax = plt.subplot(2, 5, i + 1)
350355
ax.text(-0.1, 1.15, ascii_uppercase[i], transform=ax.transAxes, fontsize=16, fontweight='bold')
351356
# Check if any of the inputs is None
352-
if any([v is None for v in panel[1].values()]):
357+
if any([v is None for v in panel[1].values()]) or any([v.values() is None for v in panel[1].values() if isinstance(v, dict)]):
353358
ax.text(.5, .5, f"Data incomplete\n{panel[0].__name__}", color='r', fontweight='bold',
354359
fontsize=12, horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
355360
plt.axis('off')

0 commit comments

Comments
 (0)