aind-dynamic-foraging-basic-analysis 0.2.1__py3-none-any.whl → 0.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  """Init package"""
2
2
 
3
- __version__ = "0.2.1"
3
+ __version__ = "0.2.3"
4
4
 
5
5
  from .foraging_efficiency import compute_foraging_efficiency # noqa: F401
6
6
  from .plot.plot_foraging_session import plot_foraging_session # noqa: F401
@@ -1,22 +1,34 @@
1
1
  """Load packages."""
2
+ import os
2
3
  import numpy as np
3
4
  import matplotlib.pyplot as plt
4
5
  import matplotlib.gridspec as gridspec
5
6
  from aind_ephys_utils import align
6
7
  from pynwb import NWBHDF5IO
8
+ from hdmf_zarr import NWBZarrIO
7
9
  from scipy.stats import norm
8
10
 
9
11
 
10
12
  def load_nwb(nwb_file):
11
13
  """Load NWB file."""
12
- io = NWBHDF5IO(nwb_file, mode="r")
13
- nwb = io.read()
14
- return nwb
14
+ if os.path.isdir(nwb_file):
15
+ io = NWBZarrIO(nwb_file, mode="r")
16
+ nwb = io.read()
17
+ return nwb
18
+ elif os.path.isfile(nwb_file):
19
+ io = NWBHDF5IO(nwb_file, mode="r")
20
+ nwb = io.read()
21
+ return nwb
22
+ else:
23
+ print("nwb file does not exist.")
24
+ return None
15
25
 
16
26
 
17
27
  def plot_lick_analysis(nwb):
18
28
  """Plot lick distributions."""
19
29
  tbl_trials = nwb.trials.to_dataframe()
30
+ session_id = nwb.session_id
31
+ session_id = session_id.split(".")[0]
20
32
  gs = gridspec.GridSpec(
21
33
  2,
22
34
  6,
@@ -26,227 +38,182 @@ def plot_lick_analysis(nwb):
26
38
  fig = plt.figure(figsize=(15, 8))
27
39
  plt.subplots_adjust(hspace=0.5, wspace=0.5)
28
40
 
29
- left_licks = nwb.acquisition["left_lick_time"].timestamps[:]
30
- right_licks = nwb.acquisition["right_lick_time"].timestamps[:]
31
- all_licks = np.sort(np.concatenate((right_licks, left_licks)))
32
- sort_ind = np.argsort(np.concatenate((right_licks, left_licks)))
33
- all_licks_id = np.concatenate(
34
- (np.ones_like(right_licks), np.zeros_like(left_licks))
35
- )
36
- all_licks_id = all_licks_id[sort_ind]
37
- all_lick_diffs = np.diff(all_licks)
38
- # ILI_L-L
39
- plot_ILI(
40
- all_lick_diffs[(all_licks_id[:-1] == 0) & (all_licks_id[1:] == 0)],
41
- "ILI_L-L",
42
- gs[0, 0],
43
- fig,
44
- )
45
- # ILI_R-R
46
- plot_ILI(
47
- all_lick_diffs[(all_licks_id[:-1] == 1) & (all_licks_id[1:] == 1)],
48
- "ILI_R-R",
49
- gs[0, 1],
50
- fig,
51
- )
52
- # ILI_R-L
53
- plot_ILI(
54
- all_lick_diffs[(all_licks_id[:-1] == 1) & (all_licks_id[1:] == 0)],
55
- "ILI_R-l",
56
- gs[0, 2],
57
- fig,
58
- )
59
- # ILI_L-R
60
- plot_ILI(
61
- all_lick_diffs[(all_licks_id[:-1] == 0) & (all_licks_id[1:] == 1)],
62
- "ILI_l-R",
63
- gs[0, 3],
64
- fig,
65
- )
66
- # ILI_all
67
- plot_ILI(all_lick_diffs, "ILI_all", gs[0, 4], fig)
68
- # Pre-trial lick punishment
69
- lick_delay = (
70
- tbl_trials["goCue_start_time"]
71
- - tbl_trials["start_time"]
72
- - tbl_trials["ITI_duration"]
73
- )
74
- bins = np.arange(
75
- np.min(lick_delay),
76
- np.max(lick_delay),
77
- (np.max(lick_delay) - np.min(lick_delay)) / 20,
78
- )
79
- ax = fig.add_subplot(gs[0, 5])
80
- ax.hist(
81
- lick_delay[tbl_trials["animal_response"] == 1],
82
- alpha=0.5,
83
- label="R",
84
- bins=bins,
85
- # density=True,
86
- )
87
- ax.hist(
88
- lick_delay[tbl_trials["animal_response"] == 0],
89
- alpha=0.5,
90
- label="L",
91
- bins=bins,
92
- # density=True,
93
- )
94
- ax.hist(
95
- lick_delay[tbl_trials["animal_response"] == 2],
96
- alpha=0.5,
97
- label="0",
98
- bins=bins,
99
- # density=True,
100
- )
101
- p_early = 1 - np.mean(lick_delay < tbl_trials["delay_duration"] + 0.05)
102
- ax.set_title(f"Time out punishment prop {p_early:.2f}")
103
- ax.set_xlabel("s")
104
- ax.legend()
105
-
106
- # Pre-trial licks
107
-
108
- sort_ind_l = np.argsort(
109
- tbl_trials.loc[tbl_trials["animal_response"] == 0, "delay_duration"]
110
- )
111
- sort_ind_r = np.argsort(
112
- tbl_trials.loc[tbl_trials["animal_response"] == 1, "delay_duration"]
113
- )
114
- l_align = tbl_trials.loc[
115
- tbl_trials["animal_response"] == 0, "goCue_start_time"
116
- ].values
117
- r_align = tbl_trials.loc[
118
- tbl_trials["animal_response"] == 1, "goCue_start_time"
119
- ].values
120
- l_align = l_align[sort_ind_l.values]
121
- r_align = r_align[sort_ind_r.values]
122
-
123
- if len(l_align) > 0:
124
- # Left lick aligned to left choices
125
- fig, ax1, ax2 = plot_raster_rate(
126
- left_licks, l_align, fig, gs[1, 0], "L licks on L choice trials"
41
+ if len(tbl_trials) < 10:
42
+ """No enough trials to plot lick analysis."""
43
+ title_str = f"{session_id} has less than 10 trials"
44
+ plt.suptitle(title_str)
45
+ else:
46
+ left_licks = nwb.acquisition["left_lick_time"].timestamps[:]
47
+ right_licks = nwb.acquisition["right_lick_time"].timestamps[:]
48
+ all_licks = np.sort(np.concatenate((right_licks, left_licks)))
49
+ sort_ind = np.argsort(np.concatenate((right_licks, left_licks)))
50
+ all_licks_id = np.concatenate((np.ones_like(right_licks), np.zeros_like(left_licks)))
51
+ all_licks_id = all_licks_id[sort_ind]
52
+ all_lick_diffs = np.diff(all_licks)
53
+ # ILI_L-L
54
+ plot_ILI(
55
+ all_lick_diffs[(all_licks_id[:-1] == 0) & (all_licks_id[1:] == 0)],
56
+ "ILI_L-L",
57
+ gs[0, 0],
58
+ fig,
127
59
  )
128
- ax1.scatter(
129
- -np.sort(
130
- tbl_trials.loc[
131
- tbl_trials["animal_response"] == 0, "delay_duration"
132
- ]
133
- ),
134
- range(
135
- len(
136
- tbl_trials.loc[
137
- tbl_trials["animal_response"] == 0, "delay_max"
138
- ]
139
- )
140
- ),
141
- c="b",
142
- marker="|",
143
- s=1,
144
- zorder=1,
60
+ # ILI_R-R
61
+ plot_ILI(
62
+ all_lick_diffs[(all_licks_id[:-1] == 1) & (all_licks_id[1:] == 1)],
63
+ "ILI_R-R",
64
+ gs[0, 1],
65
+ fig,
145
66
  )
146
- ax2.set_ylabel("Licks/s")
147
-
148
- # Right licks aligned to left choices
149
- fig, ax1, _ = plot_raster_rate(
150
- right_licks, l_align, fig, gs[1, 2], "R licks on L choice trials"
67
+ # ILI_R-L
68
+ plot_ILI(
69
+ all_lick_diffs[(all_licks_id[:-1] == 1) & (all_licks_id[1:] == 0)],
70
+ "ILI_R-l",
71
+ gs[0, 2],
72
+ fig,
151
73
  )
152
- ax1.scatter(
153
- -np.sort(
154
- tbl_trials.loc[
155
- tbl_trials["animal_response"] == 0, "delay_duration"
156
- ]
157
- ),
158
- range(
159
- len(
160
- tbl_trials.loc[
161
- tbl_trials["animal_response"] == 0, "delay_max"
162
- ]
163
- )
164
- ),
165
- c="b",
166
- marker="|",
167
- s=1,
168
- zorder=1,
74
+ # ILI_L-R
75
+ plot_ILI(
76
+ all_lick_diffs[(all_licks_id[:-1] == 0) & (all_licks_id[1:] == 1)],
77
+ "ILI_l-R",
78
+ gs[0, 3],
79
+ fig,
169
80
  )
170
-
171
- if len(r_align) > 0:
172
- # right licks aligned to right choices
173
- fig, ax1, _ = plot_raster_rate(
174
- right_licks, r_align, fig, gs[1, 1], "R licks on R choice trials"
81
+ # ILI_all
82
+ plot_ILI(all_lick_diffs, "ILI_all", gs[0, 4], fig)
83
+ # Pre-trial lick punishment
84
+ lick_delay = (
85
+ tbl_trials["goCue_start_time"] - tbl_trials["start_time"] - tbl_trials["ITI_duration"]
175
86
  )
176
87
 
177
- ax1.scatter(
178
- -np.sort(
179
- tbl_trials.loc[
180
- tbl_trials["animal_response"] == 1, "delay_duration"
181
- ]
182
- ),
183
- range(
184
- len(
185
- tbl_trials.loc[
186
- tbl_trials["animal_response"] == 1, "delay_max"
187
- ]
188
- )
189
- ),
190
- c="b",
191
- marker="|",
192
- s=1,
193
- zorder=1,
88
+ bins = np.arange(
89
+ np.min(lick_delay),
90
+ np.max(lick_delay),
91
+ (np.max(lick_delay) - np.min(lick_delay)) / 20,
194
92
  )
195
93
 
196
- # left licks aligned to right choices
197
- fig, ax1, _ = plot_raster_rate(
198
- left_licks, r_align, fig, gs[1, 3], "L licks on R choice trials"
94
+ ax = fig.add_subplot(gs[0, 5])
95
+ ax.hist(
96
+ lick_delay[tbl_trials["animal_response"] == 1],
97
+ alpha=0.5,
98
+ label="R",
99
+ bins=bins,
100
+ # density=True,
199
101
  )
200
-
201
- ax1.scatter(
202
- -np.sort(
203
- tbl_trials.loc[
204
- tbl_trials["animal_response"] == 1, "delay_duration"
205
- ]
206
- ),
207
- range(
208
- len(
209
- tbl_trials.loc[
210
- tbl_trials["animal_response"] == 1, "delay_max"
211
- ]
212
- )
213
- ),
214
- c="b",
215
- marker="|",
216
- s=1,
217
- zorder=1,
102
+ ax.hist(
103
+ lick_delay[tbl_trials["animal_response"] == 0],
104
+ alpha=0.5,
105
+ label="L",
106
+ bins=bins,
107
+ # density=True,
218
108
  )
109
+ ax.hist(
110
+ lick_delay[tbl_trials["animal_response"] == 2],
111
+ alpha=0.5,
112
+ label="0",
113
+ bins=bins,
114
+ # density=True,
115
+ )
116
+ p_early = 1 - np.mean(lick_delay < tbl_trials["delay_duration"] + 0.05)
117
+ ax.set_title(f"Time out punishment prop {p_early:.2f}")
118
+ ax.set_xlabel("s")
119
+ ax.legend()
219
120
 
220
- session_id = nwb.session_id
221
- session_id = session_id.split(".")[0]
222
- box = nwb.scratch["metadata"][0].box.values
223
- plt.suptitle(f"{session_id} in {box}")
121
+ # Pre-trial licks
224
122
 
225
- # Response latency
226
- ax = fig.add_subplot(gs[1, 4:6])
227
- lick_lat = (
228
- tbl_trials["reward_outcome_time"] - tbl_trials["goCue_start_time"]
229
- )
230
- bins = np.arange(0, 1, 0.05)
231
- ax.hist(
232
- lick_lat[tbl_trials["animal_response"] == 1],
233
- bins=bins,
234
- alpha=0.5,
235
- label="R",
236
- density=True,
237
- )
238
- ax.hist(
239
- lick_lat[tbl_trials["animal_response"] == 0],
240
- bins=bins,
241
- alpha=0.5,
242
- label="L",
243
- density=True,
244
- )
245
- ax.legend()
246
- ax.set_title("lickLat by lick side")
247
- ax.set_xlabel("s")
248
- ax.set_ylabel("density %")
249
- plt.suptitle(session_id)
123
+ sort_ind_l = np.argsort(
124
+ tbl_trials.loc[tbl_trials["animal_response"] == 0, "delay_duration"]
125
+ )
126
+ sort_ind_r = np.argsort(
127
+ tbl_trials.loc[tbl_trials["animal_response"] == 1, "delay_duration"]
128
+ )
129
+ l_align = tbl_trials.loc[tbl_trials["animal_response"] == 0, "goCue_start_time"].values
130
+ r_align = tbl_trials.loc[tbl_trials["animal_response"] == 1, "goCue_start_time"].values
131
+ l_align = l_align[sort_ind_l.values]
132
+ r_align = r_align[sort_ind_r.values]
133
+
134
+ if len(l_align) > 0:
135
+ # Left lick aligned to left choices
136
+ fig, ax1, ax2 = plot_raster_rate(
137
+ left_licks, l_align, fig, gs[1, 0], "L licks on L choice trials"
138
+ )
139
+ ax1.scatter(
140
+ -np.sort(tbl_trials.loc[tbl_trials["animal_response"] == 0, "delay_duration"]),
141
+ range(len(tbl_trials.loc[tbl_trials["animal_response"] == 0, "delay_max"])),
142
+ c="b",
143
+ marker="|",
144
+ s=1,
145
+ zorder=1,
146
+ )
147
+ ax2.set_ylabel("Licks/s")
148
+
149
+ # Right licks aligned to left choices
150
+ fig, ax1, _ = plot_raster_rate(
151
+ right_licks, l_align, fig, gs[1, 2], "R licks on L choice trials"
152
+ )
153
+ ax1.scatter(
154
+ -np.sort(tbl_trials.loc[tbl_trials["animal_response"] == 0, "delay_duration"]),
155
+ range(len(tbl_trials.loc[tbl_trials["animal_response"] == 0, "delay_max"])),
156
+ c="b",
157
+ marker="|",
158
+ s=1,
159
+ zorder=1,
160
+ )
161
+
162
+ if len(r_align) > 0:
163
+ # right licks aligned to right choices
164
+ fig, ax1, _ = plot_raster_rate(
165
+ right_licks, r_align, fig, gs[1, 1], "R licks on R choice trials"
166
+ )
167
+
168
+ ax1.scatter(
169
+ -np.sort(tbl_trials.loc[tbl_trials["animal_response"] == 1, "delay_duration"]),
170
+ range(len(tbl_trials.loc[tbl_trials["animal_response"] == 1, "delay_max"])),
171
+ c="b",
172
+ marker="|",
173
+ s=1,
174
+ zorder=1,
175
+ )
176
+
177
+ # left licks aligned to right choices
178
+ fig, ax1, _ = plot_raster_rate(
179
+ left_licks, r_align, fig, gs[1, 3], "L licks on R choice trials"
180
+ )
181
+
182
+ ax1.scatter(
183
+ -np.sort(tbl_trials.loc[tbl_trials["animal_response"] == 1, "delay_duration"]),
184
+ range(len(tbl_trials.loc[tbl_trials["animal_response"] == 1, "delay_max"])),
185
+ c="b",
186
+ marker="|",
187
+ s=1,
188
+ zorder=1,
189
+ )
190
+
191
+ box = nwb.scratch["metadata"][0].box.values
192
+ plt.suptitle(f"{session_id} in {box}")
193
+
194
+ # Response latency
195
+ ax = fig.add_subplot(gs[1, 4:6])
196
+ lick_lat = tbl_trials["reward_outcome_time"] - tbl_trials["goCue_start_time"]
197
+ bins = np.arange(0, 1, 0.05)
198
+ ax.hist(
199
+ lick_lat[tbl_trials["animal_response"] == 1],
200
+ bins=bins,
201
+ alpha=0.5,
202
+ label="R",
203
+ density=True,
204
+ )
205
+ ax.hist(
206
+ lick_lat[tbl_trials["animal_response"] == 0],
207
+ bins=bins,
208
+ alpha=0.5,
209
+ label="L",
210
+ density=True,
211
+ )
212
+ ax.legend()
213
+ ax.set_title("lickLat by lick side")
214
+ ax.set_xlabel("s")
215
+ ax.set_ylabel("density %")
216
+ plt.suptitle(session_id)
250
217
 
251
218
  return fig, session_id
252
219
 
@@ -254,13 +221,12 @@ def plot_lick_analysis(nwb):
254
221
  def load_data(nwb):
255
222
  """Load data from NWB file."""
256
223
  session_id = nwb.session_id
224
+ session_id = session_id.split(".")[0]
257
225
  tbl_trials = nwb.trials.to_dataframe()
258
226
  left_licks = nwb.acquisition["left_lick_time"].timestamps[:]
259
227
  right_licks = nwb.acquisition["right_lick_time"].timestamps[:]
260
228
  all_licks = np.sort(np.concatenate((right_licks, left_licks)))
261
- lick_lat = (
262
- tbl_trials["reward_outcome_time"] - tbl_trials["goCue_start_time"]
263
- )
229
+ lick_lat = tbl_trials["reward_outcome_time"] - tbl_trials["goCue_start_time"]
264
230
  lick_lat_r = lick_lat[tbl_trials["animal_response"] == 1]
265
231
  lick_lat_l = lick_lat[tbl_trials["animal_response"] == 0]
266
232
  thresh = [0.05, 0.5, 1.0]
@@ -303,60 +269,72 @@ def cal_metrics(data):
303
269
  win_go = data["win_go"]
304
270
  win_bl = data["win_bl"]
305
271
 
306
- lick_percent_l = [
307
- np.sum(lick_lat_l <= thresh_curr) / np.shape(lick_lat_l)[0]
308
- for thresh_curr in thresh
309
- ]
310
- lick_percent_r = [
311
- np.sum(lick_lat_r <= thresh_curr) / np.shape(lick_lat_r)[0]
312
- for thresh_curr in thresh
313
- ]
314
- finish = tbl_trials["animal_response"] != 2
315
- ref = np.ones_like(finish)
316
- ref_kernel = np.convolve(ref, kernel)
317
- finish_kernel = np.convolve(finish.astype(float), kernel)
318
- finish_kernel = np.divide(finish_kernel, ref_kernel)
319
- finish_kernel = finish_kernel[
320
- int(0.5 * len(kernel)): -int(0.5 * len(kernel))
321
- ]
322
- all_go_no_rwd = tbl_trials.loc[
323
- (tbl_trials["animal_response"] != 2)
324
- & (tbl_trials["rewarded_historyL"] == 0)
325
- & (tbl_trials["rewarded_historyR"] == 0),
326
- "goCue_start_time",
327
- ].values
328
- all_pre_nolick = (
329
- tbl_trials.loc[
330
- tbl_trials["animal_response"] != 2, "goCue_start_time"
272
+ if tbl_trials.shape[0] < 10:
273
+ """Not enough trials to calculate lick metrics."""
274
+ return {
275
+ "session_id": session_id,
276
+ "bl_lick": 0,
277
+ "bl_lick_lr": [0, 0],
278
+ "resp_lick": 0,
279
+ "bl_lick_trial": 0,
280
+ "resp_lick_trial": 0,
281
+ "peak_ratio": [0, 0],
282
+ "peak_lat": [0, 0],
283
+ "lick_cdf": {
284
+ "thresh": thresh,
285
+ "l": [0, 0, 0],
286
+ "r": [0, 0, 0],
287
+ },
288
+ "resp_score": 0,
289
+ "finish_ratio": 0,
290
+ }
291
+ else: # calculate lick metrics
292
+ lick_percent_l = [
293
+ np.sum(lick_lat_l <= thresh_curr) / np.shape(lick_lat_l)[0] for thresh_curr in thresh
294
+ ]
295
+ lick_percent_r = [
296
+ np.sum(lick_lat_r <= thresh_curr) / np.shape(lick_lat_r)[0] for thresh_curr in thresh
297
+ ]
298
+ finish = tbl_trials["animal_response"] != 2
299
+ ref = np.ones_like(finish)
300
+ ref_kernel = np.convolve(ref, kernel)
301
+ finish_kernel = np.convolve(finish.astype(float), kernel)
302
+ finish_kernel = np.divide(finish_kernel, ref_kernel)
303
+ finish_kernel = finish_kernel[int(0.5 * len(kernel)): -int(0.5 * len(kernel))]
304
+ all_go_no_rwd = tbl_trials.loc[
305
+ (tbl_trials["animal_response"] != 2)
306
+ & (tbl_trials["rewarded_historyL"] == 0)
307
+ & (tbl_trials["rewarded_historyR"] == 0),
308
+ "goCue_start_time",
331
309
  ].values
332
- - tbl_trials.loc[
333
- tbl_trials["animal_response"] != 2, "delay_duration"
334
- ].values
335
- )
336
- respond_mean = np.mean(rate_align(all_licks, all_go_no_rwd, win_go))
337
- bl_mean = np.mean(rate_align(all_licks, all_pre_nolick, win_bl))
338
- bl_mean_l = np.mean(rate_align(left_licks, all_pre_nolick, win_bl))
339
- bl_mean_r = np.mean(rate_align(right_licks, all_pre_nolick, win_bl))
340
- l_major, l_major_perc = slide_mode(lick_lat_l, bin_width, bin_steps)
341
- r_major, r_major_perc = slide_mode(lick_lat_r, bin_width, bin_steps)
342
- lick_met = {
343
- "session_id": session_id,
344
- "bl_lick": bl_mean,
345
- "bl_lick_lr": [bl_mean_l, bl_mean_r],
346
- "resp_lick": respond_mean,
347
- "bl_lick_trial": rate_align(all_licks, all_pre_nolick, win_bl),
348
- "resp_lick_trial": rate_align(all_licks, all_go_no_rwd, win_go),
349
- "peak_ratio": [l_major_perc, r_major_perc],
350
- "peak_lat": [l_major, r_major],
351
- "lick_cdf": {
352
- "thresh": thresh,
353
- "l": lick_percent_l,
354
- "r": lick_percent_r,
355
- },
356
- "resp_score": respond_mean - bl_mean,
357
- "finish_ratio": finish_kernel,
358
- }
359
- return lick_met
310
+ all_pre_nolick = (
311
+ tbl_trials.loc[tbl_trials["animal_response"] != 2, "goCue_start_time"].values
312
+ - tbl_trials.loc[tbl_trials["animal_response"] != 2, "delay_duration"].values
313
+ )
314
+ respond_mean = np.mean(rate_align(all_licks, all_go_no_rwd, win_go))
315
+ bl_mean = np.mean(rate_align(all_licks, all_pre_nolick, win_bl))
316
+ bl_mean_l = np.mean(rate_align(left_licks, all_pre_nolick, win_bl))
317
+ bl_mean_r = np.mean(rate_align(right_licks, all_pre_nolick, win_bl))
318
+ l_major, l_major_perc = slide_mode(lick_lat_l, bin_width, bin_steps)
319
+ r_major, r_major_perc = slide_mode(lick_lat_r, bin_width, bin_steps)
320
+ lick_met = {
321
+ "session_id": session_id,
322
+ "bl_lick": bl_mean,
323
+ "bl_lick_lr": [bl_mean_l, bl_mean_r],
324
+ "resp_lick": respond_mean,
325
+ "bl_lick_trial": rate_align(all_licks, all_pre_nolick, win_bl),
326
+ "resp_lick_trial": rate_align(all_licks, all_go_no_rwd, win_go),
327
+ "peak_ratio": [l_major_perc, r_major_perc],
328
+ "peak_lat": [l_major, r_major],
329
+ "lick_cdf": {
330
+ "thresh": thresh,
331
+ "l": lick_percent_l,
332
+ "r": lick_percent_r,
333
+ },
334
+ "resp_score": respond_mean - bl_mean,
335
+ "finish_ratio": finish_kernel,
336
+ }
337
+ return lick_met
360
338
 
361
339
 
362
340
  def plot_met(data, lick_met):
@@ -370,144 +348,141 @@ def plot_met(data, lick_met):
370
348
  all_licks = data["all_licks"]
371
349
  tbl_trials = data["tbl_trials"]
372
350
 
373
- edges = np.arange(
374
- np.min(lick_lat_l),
375
- np.max(lick_lat_l),
376
- 0.02,
377
- )
378
351
  fig = plt.figure(figsize=(8, 4))
379
- gs = fig.add_gridspec(
380
- 2,
381
- 2,
382
- width_ratios=[1, 1],
383
- height_ratios=[2, 1],
384
- wspace=0.5,
385
- hspace=0.5,
386
- )
387
- ax1 = fig.add_subplot(gs[0, 0])
388
- ax1.hist(
389
- lick_lat_l, bins=edges, alpha=0.5, density=True, label="lick hist"
390
- )
391
- ax1.set_xlabel("s")
392
- ax1.set_ylabel("density %")
393
- ax1.legend(loc="upper left", bbox_to_anchor=(0, 1), ncol=1)
394
- ax1t = ax1.twinx()
395
- ax1t.set_ylabel("CDF")
396
- plot_cdf(lick_lat_l, {"label": "lick cdf"})
397
- # ax1t.plot(np.array(thresh), lick_met["lick_cdf"]["l"], "k")
398
- l_major = lick_met["peak_lat"][0]
399
- l_major_ratio = lick_met["peak_ratio"][0]
400
- ax1t.fill(
401
- [
402
- l_major - 0.5 * bin_width,
403
- l_major + 0.5 * bin_width,
404
- l_major + 0.5 * bin_width,
405
- l_major - 0.5 * bin_width,
406
- ],
407
- [0, 0, 1, 1],
408
- "r",
409
- alpha=0.2,
410
- )
411
- ax1t.set_title(f"Lick Latency: L {l_major_ratio:.2f}")
412
- ax1t.set_ylim(0, 1.1)
413
- ax1t.legend(loc="upper left", bbox_to_anchor=(0, 0.8), ncol=1)
414
- ax1.plot(
415
- [win_bl[0], 0],
416
- np.ones_like(win_bl) * lick_met["bl_lick"],
417
- color=[0.3, 0.3, 0.3],
418
- lw=4,
419
- )
420
- ax1.plot(
421
- win_go,
422
- np.ones_like(win_bl) * lick_met["resp_lick"],
423
- color=[0.3, 0.3, 0.3],
424
- lw=4,
425
- )
352
+ if data["tbl_trials"].shape[0] < 10:
353
+ """Not enough trials to plot lick metrics."""
354
+ plt.suptitle(f"{session_id} has less than 10 trials")
355
+ else:
356
+ edges = np.arange(
357
+ np.min(lick_lat_l),
358
+ np.max(lick_lat_l),
359
+ 0.02,
360
+ )
361
+ gs = fig.add_gridspec(
362
+ 2,
363
+ 2,
364
+ width_ratios=[1, 1],
365
+ height_ratios=[2, 1],
366
+ wspace=0.5,
367
+ hspace=0.5,
368
+ )
369
+ ax1 = fig.add_subplot(gs[0, 0])
370
+ ax1.hist(lick_lat_l, bins=edges, alpha=0.5, density=True, label="lick hist")
371
+ ax1.set_xlabel("s")
372
+ ax1.set_ylabel("density %")
373
+ ax1.legend(loc="upper left", bbox_to_anchor=(0, 1), ncol=1)
374
+ ax1t = ax1.twinx()
375
+ ax1t.set_ylabel("CDF")
376
+ plot_cdf(lick_lat_l, {"label": "lick cdf"})
377
+ # ax1t.plot(np.array(thresh), lick_met["lick_cdf"]["l"], "k")
378
+ l_major = lick_met["peak_lat"][0]
379
+ l_major_ratio = lick_met["peak_ratio"][0]
380
+ ax1t.fill(
381
+ [
382
+ l_major - 0.5 * bin_width,
383
+ l_major + 0.5 * bin_width,
384
+ l_major + 0.5 * bin_width,
385
+ l_major - 0.5 * bin_width,
386
+ ],
387
+ [0, 0, 1, 1],
388
+ "r",
389
+ alpha=0.2,
390
+ )
391
+ ax1t.set_title(f"Lick Latency: L {l_major_ratio:.2f}")
392
+ ax1t.set_ylim(0, 1.1)
393
+ ax1t.legend(loc="upper left", bbox_to_anchor=(0, 0.8), ncol=1)
394
+ ax1.plot(
395
+ [win_bl[0], 0],
396
+ np.ones_like(win_bl) * lick_met["bl_lick"],
397
+ color=[0.3, 0.3, 0.3],
398
+ lw=4,
399
+ )
400
+ ax1.plot(
401
+ win_go,
402
+ np.ones_like(win_bl) * lick_met["resp_lick"],
403
+ color=[0.3, 0.3, 0.3],
404
+ lw=4,
405
+ )
426
406
 
427
- ax2 = fig.add_subplot(gs[0, 1])
428
- ax2.hist(lick_lat_r, bins=edges, alpha=0.5, density=True)
429
- ax2.set_xlabel("s")
430
- ax2t = ax2.twinx()
431
- plot_cdf(lick_lat_r, {"label": "lick cdf"})
432
- # ax2t.plot(np.array(thresh), lick_met["lick_cdf"]["r"], "k")
433
- r_major = lick_met["peak_lat"][1]
434
- r_major_ratio = lick_met["peak_ratio"][1]
435
- ax2t.fill(
436
- [
437
- r_major - 0.5 * bin_width,
438
- r_major + 0.5 * bin_width,
439
- r_major + 0.5 * bin_width,
440
- r_major - 0.5 * bin_width,
441
- ],
442
- [0, 0, 1, 1],
443
- "r",
444
- alpha=0.2,
445
- )
446
- ax2t.set_title(f"R {r_major_ratio:.2f}")
447
- ax2t.set_ylim(0, 1.1)
448
- ax2.plot(
449
- [win_bl[0], 0],
450
- np.ones_like(win_bl) * lick_met["bl_lick"],
451
- color=[0.3, 0.3, 0.3],
452
- lw=4,
453
- )
454
- ax2.plot(
455
- win_go,
456
- np.ones_like(win_bl) * lick_met["resp_lick"],
457
- color=[0.3, 0.3, 0.3],
458
- lw=4,
459
- )
407
+ ax2 = fig.add_subplot(gs[0, 1])
408
+ ax2.hist(lick_lat_r, bins=edges, alpha=0.5, density=True)
409
+ ax2.set_xlabel("s")
410
+ ax2t = ax2.twinx()
411
+ plot_cdf(lick_lat_r, {"label": "lick cdf"})
412
+ # ax2t.plot(np.array(thresh), lick_met["lick_cdf"]["r"], "k")
413
+ r_major = lick_met["peak_lat"][1]
414
+ r_major_ratio = lick_met["peak_ratio"][1]
415
+ ax2t.fill(
416
+ [
417
+ r_major - 0.5 * bin_width,
418
+ r_major + 0.5 * bin_width,
419
+ r_major + 0.5 * bin_width,
420
+ r_major - 0.5 * bin_width,
421
+ ],
422
+ [0, 0, 1, 1],
423
+ "r",
424
+ alpha=0.2,
425
+ )
426
+ ax2t.set_title(f"R {r_major_ratio:.2f}")
427
+ ax2t.set_ylim(0, 1.1)
428
+ ax2.plot(
429
+ [win_bl[0], 0],
430
+ np.ones_like(win_bl) * lick_met["bl_lick"],
431
+ color=[0.3, 0.3, 0.3],
432
+ lw=4,
433
+ )
434
+ ax2.plot(
435
+ win_go,
436
+ np.ones_like(win_bl) * lick_met["resp_lick"],
437
+ color=[0.3, 0.3, 0.3],
438
+ lw=4,
439
+ )
460
440
 
461
- ax3 = fig.add_subplot(gs[1, :])
462
- all_go_no_rwd = tbl_trials.loc[
463
- (tbl_trials["animal_response"] != 2)
464
- & (tbl_trials["rewarded_historyL"] == 0)
465
- & (tbl_trials["rewarded_historyR"] == 0),
466
- "goCue_start_time",
467
- ].values
468
- all_go_rwd = tbl_trials.loc[
469
- (tbl_trials["animal_response"] != 2)
470
- & (tbl_trials["rewarded_historyL"] == 1)
471
- | (tbl_trials["rewarded_historyR"] == 1),
472
- "goCue_start_time",
473
- ].values
474
- all_pre_nolick = (
475
- tbl_trials.loc[
476
- tbl_trials["animal_response"] != 2, "goCue_start_time"
441
+ ax3 = fig.add_subplot(gs[1, :])
442
+ all_go_no_rwd = tbl_trials.loc[
443
+ (tbl_trials["animal_response"] != 2)
444
+ & (tbl_trials["rewarded_historyL"] == 0)
445
+ & (tbl_trials["rewarded_historyR"] == 0),
446
+ "goCue_start_time",
477
447
  ].values
478
- - tbl_trials.loc[
479
- tbl_trials["animal_response"] != 2, "delay_duration"
448
+ all_go_rwd = tbl_trials.loc[
449
+ (tbl_trials["animal_response"] != 2) & (tbl_trials["rewarded_historyL"] == 1)
450
+ | (tbl_trials["rewarded_historyR"] == 1),
451
+ "goCue_start_time",
480
452
  ].values
481
- )
482
- rate_go_rwd = rate_align(all_licks, all_go_rwd, win_go)
453
+ all_pre_nolick = (
454
+ tbl_trials.loc[tbl_trials["animal_response"] != 2, "goCue_start_time"].values
455
+ - tbl_trials.loc[tbl_trials["animal_response"] != 2, "delay_duration"].values
456
+ )
457
+ rate_go_rwd = rate_align(all_licks, all_go_rwd, win_go)
483
458
 
484
- ax3.plot(
485
- all_go_no_rwd,
486
- lick_met["resp_lick_trial"],
487
- label="Resp-noRwd",
488
- color="r",
489
- )
490
- ax3.plot(
491
- all_pre_nolick,
492
- lick_met["bl_lick_trial"],
493
- label="baseline",
494
- color="grey",
495
- )
496
- ax3.plot(all_go_rwd, rate_go_rwd, label="Resp-Rwd", color="b")
497
- ax3.set_ylabel("lick rate")
498
- ax3t = ax3.twinx()
499
- ax3t.plot(
500
- tbl_trials["goCue_start_time"],
501
- lick_met["finish_ratio"],
502
- color="g",
503
- label="finish",
504
- )
505
- ax3t.set_ylabel("Ratio")
506
- temp = lick_met["resp_score"]
507
- ax3.set_title(f"Resp score {temp:.2f}")
508
- ax3.legend()
509
- ax3t.legend()
510
- plt.suptitle(session_id)
459
+ ax3.plot(
460
+ all_go_no_rwd,
461
+ lick_met["resp_lick_trial"],
462
+ label="Resp-noRwd",
463
+ color="r",
464
+ )
465
+ ax3.plot(
466
+ all_pre_nolick,
467
+ lick_met["bl_lick_trial"],
468
+ label="baseline",
469
+ color="grey",
470
+ )
471
+ ax3.plot(all_go_rwd, rate_go_rwd, label="Resp-Rwd", color="b")
472
+ ax3.set_ylabel("lick rate")
473
+ ax3t = ax3.twinx()
474
+ ax3t.plot(
475
+ tbl_trials["goCue_start_time"],
476
+ lick_met["finish_ratio"],
477
+ color="g",
478
+ label="finish",
479
+ )
480
+ ax3t.set_ylabel("Ratio")
481
+ temp = lick_met["resp_score"]
482
+ ax3.set_title(f"Resp score {temp:.2f}")
483
+ ax3.legend()
484
+ ax3t.legend()
485
+ plt.suptitle(session_id)
511
486
  return fig, session_id
512
487
 
513
488
 
@@ -540,9 +515,8 @@ def rate_align(x, events, win):
540
515
 
541
516
  def plot_ILI(ili, title, subplot_spec, fig):
542
517
  """Plot ILI."""
543
- nested_gs = gridspec.GridSpecFromSubplotSpec(
544
- 2, 1, subplot_spec=subplot_spec
545
- )
518
+ nested_gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=subplot_spec)
519
+ nested_gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=subplot_spec)
546
520
  bins = np.arange(0, 2500, 20)
547
521
  ax1 = fig.add_subplot(nested_gs[0, 0])
548
522
  ax2 = fig.add_subplot(nested_gs[1, 0])
@@ -572,9 +546,8 @@ def plot_raster_rate(
572
546
  ):
573
547
  """Plot raster and rate aligned to events"""
574
548
  edges = np.arange(tb + 0.5 * bin_size, tf - 0.5 * bin_size, step_size)
575
- nested_gs = gridspec.GridSpecFromSubplotSpec(
576
- 2, 1, subplot_spec=subplot_spec
577
- )
549
+ nested_gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=subplot_spec)
550
+ nested_gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=subplot_spec)
578
551
  ax1 = fig.add_subplot(nested_gs[0, 0])
579
552
  ax2 = fig.add_subplot(nested_gs[1, 0])
580
553
 
@@ -584,12 +557,10 @@ def plot_raster_rate(
584
557
  ax1.set_title(title)
585
558
  ax1.set_xlim(tb, tf)
586
559
 
587
- counts_pre = np.searchsorted(
588
- np.sort(df.time.values), edges - 0.5 * bin_size
589
- )
590
- counts_post = np.searchsorted(
591
- np.sort(df.time.values), edges + 0.5 * bin_size
592
- )
560
+ counts_pre = np.searchsorted(np.sort(df.time.values), edges - 0.5 * bin_size)
561
+ counts_post = np.searchsorted(np.sort(df.time.values), edges + 0.5 * bin_size)
562
+ counts_pre = np.searchsorted(np.sort(df.time.values), edges - 0.5 * bin_size)
563
+ counts_post = np.searchsorted(np.sort(df.time.values), edges + 0.5 * bin_size)
593
564
  lick_rate = (counts_post - counts_pre) / (bin_size * len(align_events))
594
565
  ax2.plot(edges, lick_rate)
595
566
  ax2.set_title("lickRate")
@@ -601,14 +572,12 @@ def plot_raster_rate(
601
572
 
602
573
  # example use
603
574
  if __name__ == "__main__":
604
- import os
605
575
  from pathlib import Path
606
576
 
607
577
  """Example."""
608
578
  data_dir = Path(os.path.dirname(__file__)).parent.parent
609
- nwbfile = os.path.join(
610
- data_dir, "tests/data/689514_2024-02-01_18-06-43.nwb"
611
- )
579
+ nwbfile = os.path.join(data_dir, "tests/data/705599_2024-05-31_14-06-54.nwb")
580
+ nwbfile = os.path.join(data_dir, "tests/data/705599_2024-05-31_14-06-54.nwb")
612
581
  # use of load_data depends on data structure
613
582
  nwb = load_nwb(nwbfile)
614
583
  fig, session_id = plot_lick_analysis(nwb)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aind-dynamic-foraging-basic-analysis
3
- Version: 0.2.1
3
+ Version: 0.2.3
4
4
  Summary: Generated from aind-library-template
5
5
  Author: Allen Institute for Neural Dynamics
6
6
  License: MIT
@@ -16,6 +16,7 @@ Requires-Dist: pynwb
16
16
  Requires-Dist: aind-ephys-utils
17
17
  Requires-Dist: pathlib
18
18
  Requires-Dist: pydantic
19
+ Requires-Dist: hdmf-zarr
19
20
  Provides-Extra: dev
20
21
  Requires-Dist: aind-dynamic-foraging-basic-analysis ; extra == 'dev'
21
22
  Requires-Dist: black ; extra == 'dev'
@@ -0,0 +1,10 @@
1
+ aind_dynamic_foraging_basic_analysis/__init__.py,sha256=pzXja6QJMzGyrEjymtaqBJc9MIUFJDi-0uTzCmP62II,194
2
+ aind_dynamic_foraging_basic_analysis/foraging_efficiency.py,sha256=9IhMqQo_aU_RFsDu8D2P3-Qu3J72bo7sASC3dkUQ2YE,8634
3
+ aind_dynamic_foraging_basic_analysis/lick_analysis.py,sha256=Du6sP-Dfr6hBdRS98gc9Gp_kOq5TV_L80pDyj2WYctQ,20120
4
+ aind_dynamic_foraging_basic_analysis/data_model/foraging_session.py,sha256=7PFHfEIXP3QcjFS9Fk88S7PzBBYnUYw81WBjjEu_UKo,3536
5
+ aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py,sha256=X-gLffs8tau2Eeh_fF8tlU-KDkYiyRrtbO_jZnTyPxo,11580
6
+ aind_dynamic_foraging_basic_analysis-0.2.3.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
7
+ aind_dynamic_foraging_basic_analysis-0.2.3.dist-info/METADATA,sha256=5lXBY3eJw6ZyU2k4QySUXIanpWkbe5whu4ZjG8WpjYY,6715
8
+ aind_dynamic_foraging_basic_analysis-0.2.3.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
9
+ aind_dynamic_foraging_basic_analysis-0.2.3.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
10
+ aind_dynamic_foraging_basic_analysis-0.2.3.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (70.2.0)
2
+ Generator: setuptools (72.1.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,10 +0,0 @@
1
- aind_dynamic_foraging_basic_analysis/__init__.py,sha256=9eee3SXxbiJ_U7VbhoMxyRs7mH3m3VCgOY8EBx6qPM4,194
2
- aind_dynamic_foraging_basic_analysis/foraging_efficiency.py,sha256=9IhMqQo_aU_RFsDu8D2P3-Qu3J72bo7sASC3dkUQ2YE,8634
3
- aind_dynamic_foraging_basic_analysis/lick_analysis.py,sha256=WCfSmG7g57f5o7u3gsYoYTipyH7hyqf61R4zWKbDIhI,18136
4
- aind_dynamic_foraging_basic_analysis/data_model/foraging_session.py,sha256=7PFHfEIXP3QcjFS9Fk88S7PzBBYnUYw81WBjjEu_UKo,3536
5
- aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py,sha256=X-gLffs8tau2Eeh_fF8tlU-KDkYiyRrtbO_jZnTyPxo,11580
6
- aind_dynamic_foraging_basic_analysis-0.2.1.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
7
- aind_dynamic_foraging_basic_analysis-0.2.1.dist-info/METADATA,sha256=aliacxrmrBmHlozX0qgJ2mn2MhC0fnzQEMriTZI_mX4,6690
8
- aind_dynamic_foraging_basic_analysis-0.2.1.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91
9
- aind_dynamic_foraging_basic_analysis-0.2.1.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
10
- aind_dynamic_foraging_basic_analysis-0.2.1.dist-info/RECORD,,