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