aind-dynamic-foraging-basic-analysis 0.3.0__py3-none-any.whl → 0.3.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.3.0"
3
+ __version__ = "0.3.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,159 @@
1
+ """
2
+ Tools for annotation of lick bouts
3
+ df_licks = annotate_lick_bouts(nwb)
4
+ df_licks = annotate_rewards(nwb)
5
+ df_licks = annotate_cue_response(nwb)
6
+ """
7
+
8
+ import numpy as np
9
+
10
+
11
+ def annotate_lick_bouts(nwb, bout_threshold=0.7):
12
+ """
13
+ returns a dataframe of lick times with annotations
14
+ pre_ili, the elapsed time since the last lick (on either side)
15
+ post_ili, the time until the next lick (on either side)
16
+ bout_start (bool), whether this was the start of a lick bout
17
+ bout_end (bool), whether this was the end of a lick bout)
18
+ bout_number (int), what lick bout this was a part of
19
+
20
+ nwb, an nwb-like object with attributes: df_events
21
+ bout_threshold is the ILI that determines bout segmentation
22
+ """
23
+
24
+ if not hasattr(nwb, "df_events"):
25
+ print("You need to compute df_events: nwb_utils.create_events_df(nwb)")
26
+ return
27
+ df_licks = nwb.df_events.query('event in ["right_lick_time","left_lick_time"]').copy()
28
+ df_licks.reset_index(drop=True, inplace=True)
29
+
30
+ # Computing ILI for each lick
31
+ df_licks["pre_ili"] = np.concatenate([[np.nan], np.diff(df_licks.timestamps.values)])
32
+ df_licks["post_ili"] = np.concatenate([np.diff(df_licks.timestamps.values), [np.nan]])
33
+
34
+ # Assign licks into bouts
35
+ df_licks["bout_start"] = df_licks["pre_ili"] > bout_threshold
36
+ df_licks["bout_end"] = df_licks["post_ili"] > bout_threshold
37
+ df_licks.loc[df_licks["pre_ili"].isnull(), "bout_start"] = True
38
+ df_licks.loc[df_licks["post_ili"].isnull(), "bout_end"] = True
39
+ df_licks["bout_number"] = np.cumsum(df_licks["bout_start"])
40
+
41
+ # Check that bouts start and stop
42
+ num_bout_start = df_licks["bout_start"].sum()
43
+ num_bout_end = df_licks["bout_end"].sum()
44
+ num_bouts = df_licks["bout_number"].max()
45
+ assert num_bout_start == num_bout_end, "Bout Starts and Bout Ends don't align"
46
+ assert num_bout_start == num_bouts, "Number of bouts is incorrect"
47
+
48
+ return df_licks
49
+
50
+
51
+ def annotate_rewards(nwb):
52
+ """
53
+ Annotates df_licks with which lick triggered each reward
54
+ nwb, an nwb-lick object with attributes: df_licks, df_events
55
+ """
56
+
57
+ LICK_TO_REWARD_TOLERANCE = 0.25
58
+
59
+ if not hasattr(nwb, "df_events"):
60
+ print("You need to compute df_events: nwb_utils.create_events_df(nwb)")
61
+ return
62
+
63
+ # ensure we have df_licks
64
+ if not hasattr(nwb, "df_licks"):
65
+ print("annotating lick bouts")
66
+ nwb.df_licks = annotate_lick_bouts(nwb)
67
+
68
+ # make a copy of df licks
69
+ df_licks = nwb.df_licks.copy()
70
+
71
+ # set default to false
72
+ df_licks["rewarded"] = False
73
+
74
+ # Iterate right rewards, and find most recent lick within tolerance
75
+ right_rewards = nwb.df_events.query('event == "right_reward_delivery_time"').copy()
76
+ for index, row in right_rewards.iterrows():
77
+ this_reward_lick_times = np.where(
78
+ (df_licks.timestamps <= row.timestamps)
79
+ & (df_licks.timestamps > (row.timestamps - LICK_TO_REWARD_TOLERANCE))
80
+ & (df_licks.event == "right_lick_time")
81
+ )[0]
82
+ if len(this_reward_lick_times) > 0:
83
+ df_licks.at[this_reward_lick_times[-1], "rewarded"] = True
84
+ # TODO, should check for licks that happened before the last go cue
85
+ # TODO, if we can't find a matching lick, should ensure this is manual or auto water
86
+
87
+ # Iterate left rewards, and find most recent lick within tolerance
88
+ left_rewards = nwb.df_events.query('event == "left_reward_delivery_time"').copy()
89
+ for index, row in left_rewards.iterrows():
90
+ this_reward_lick_times = np.where(
91
+ (df_licks.timestamps <= row.timestamps)
92
+ & (df_licks.timestamps > (row.timestamps - LICK_TO_REWARD_TOLERANCE))
93
+ & (df_licks.event == "left_lick_time")
94
+ )[0]
95
+ if len(this_reward_lick_times) > 0:
96
+ df_licks.at[this_reward_lick_times[-1], "rewarded"] = True
97
+
98
+ # Annotate lick bouts as rewarded or unrewarded
99
+ x = (
100
+ df_licks.groupby("bout_number")
101
+ .any("rewarded")
102
+ .rename(columns={"rewarded": "bout_rewarded"})["bout_rewarded"]
103
+ )
104
+ df_licks["bout_rewarded"] = False
105
+ temp = df_licks.reset_index().set_index("bout_number").copy()
106
+ temp.update(x)
107
+ temp = temp.reset_index().set_index("index")
108
+ df_licks["bout_rewarded"] = temp["bout_rewarded"]
109
+
110
+ return df_licks
111
+
112
+
113
+ def annotate_cue_response(nwb):
114
+ """
115
+ Annotates df_licks with which lick was immediately after a go cue
116
+ nwb, an nwb-lick object with attributes: df_licks, df_events
117
+ """
118
+
119
+ CUE_TO_LICK_TOLERANCE = 1
120
+
121
+ if not hasattr(nwb, "df_events"):
122
+ print("You need to compute df_events: nwb_utils.create_events_df(nwb)")
123
+ return
124
+
125
+ # ensure we have df_licks
126
+ if not hasattr(nwb, "df_licks"):
127
+ print("annotating lick bouts")
128
+ nwb.df_licks = annotate_lick_bouts(nwb)
129
+
130
+ # make a copy of df licks
131
+ df_licks = nwb.df_licks.copy()
132
+
133
+ # set default to false
134
+ df_licks["cue_response"] = False
135
+
136
+ # Iterate go cues, and find most recent lick within tolerance
137
+ cues = nwb.df_events.query('event == "goCue_start_time"').copy()
138
+ for index, row in cues.iterrows():
139
+ this_lick_times = np.where(
140
+ (df_licks.timestamps > row.timestamps)
141
+ & (df_licks.timestamps <= (row.timestamps + CUE_TO_LICK_TOLERANCE))
142
+ & ((df_licks.event == "right_lick_time") | (df_licks.event == "left_lick_time"))
143
+ )[0]
144
+ if len(this_lick_times) > 0:
145
+ df_licks.at[this_lick_times[0], "cue_response"] = True
146
+
147
+ # Annotate lick bouts as cue_responsive, or unresponsive
148
+ x = (
149
+ df_licks.groupby("bout_number")
150
+ .any("cue_response")
151
+ .rename(columns={"cue_response": "bout_cue_response"})["bout_cue_response"]
152
+ )
153
+ df_licks["bout_cue_response"] = False
154
+ temp = df_licks.reset_index().set_index("bout_number").copy()
155
+ temp.update(x)
156
+ temp = temp.reset_index().set_index("index")
157
+ df_licks["bout_cue_response"] = temp["bout_cue_response"]
158
+
159
+ return df_licks
@@ -10,7 +10,7 @@ from aind_dynamic_foraging_data_utils import nwb_utils as nu
10
10
  from aind_dynamic_foraging_basic_analysis.plot.style import STYLE, FIP_COLORS
11
11
 
12
12
 
13
- def plot_fip_psth_compare_alignments(nwb, alignments, channel, tw=[-4, 4]):
13
+ def plot_fip_psth_compare_alignments(nwb, alignments, channel, tw=[-4, 4], censor=True):
14
14
  """
15
15
  Compare the same FIP channel aligned to multiple event types
16
16
  nwb, nwb object for the session
@@ -54,12 +54,20 @@ def plot_fip_psth_compare_alignments(nwb, alignments, channel, tw=[-4, 4]):
54
54
  )
55
55
  return
56
56
 
57
+ censor_times = []
58
+ for key in align_dict:
59
+ censor_times.append(align_dict[key])
60
+ censor_times = np.sort(np.concatenate(censor_times))
61
+
57
62
  align_label = "Time (s)"
58
63
 
59
64
  fig, ax = plt.subplots()
65
+
60
66
  for alignment in align_dict:
61
- etr = fip_psth_inner_compute(nwb, align_dict[alignment], channel, True, tw)
62
- fip_psth_inner_plot(ax, etr, FIP_COLORS.get(alignment, "k"), alignment)
67
+ etr = fip_psth_inner_compute(
68
+ nwb, align_dict[alignment], channel, True, tw, censor, censor_times
69
+ )
70
+ fip_psth_inner_plot(ax, etr, FIP_COLORS.get(alignment, ""), alignment)
63
71
 
64
72
  plt.legend()
65
73
  ax.set_xlabel(align_label, fontsize=STYLE["axis_fontsize"])
@@ -69,6 +77,7 @@ def plot_fip_psth_compare_alignments(nwb, alignments, channel, tw=[-4, 4]):
69
77
  ax.set_xlim(tw)
70
78
  ax.axvline(0, color="k", alpha=0.2)
71
79
  ax.tick_params(axis="both", labelsize=STYLE["axis_ticks_fontsize"])
80
+ ax.set_title(nwb.session_id, fontsize=STYLE["axis_fontsize"])
72
81
  plt.tight_layout()
73
82
  return fig, ax
74
83
 
@@ -85,15 +94,13 @@ def plot_fip_psth_compare_channels(
85
94
  "Iso_1_preprocessed",
86
95
  "Iso_2_preprocessed",
87
96
  ],
97
+ censor=True,
88
98
  ):
89
99
  """
90
- TODO, need to censor by next event
91
- todo, clean up plots
92
- todo, figure out a modular system for comparing alignments, and channels
93
- todo, annotate licks into bouts, start of bout, etc
94
-
100
+ nwb, the nwb object for the session of interest
95
101
  align should either be a string of the name of an event type in nwb.df_events,
96
102
  or a list of timepoints
103
+ channels should be a list of channel names (strings)
97
104
  EXAMPLE
98
105
  ********************
99
106
  plot_fip_psth(nwb, 'goCue_start_time')
@@ -119,10 +126,10 @@ def plot_fip_psth_compare_channels(
119
126
 
120
127
  fig, ax = plt.subplots()
121
128
 
122
- colors = [FIP_COLORS.get(c, "k") for c in channels]
129
+ colors = [FIP_COLORS.get(c, "") for c in channels]
123
130
  for dex, c in enumerate(channels):
124
131
  if c in nwb.fip_df["event"].values:
125
- etr = fip_psth_inner_compute(nwb, align_timepoints, c, True, tw)
132
+ etr = fip_psth_inner_compute(nwb, align_timepoints, c, True, tw, censor)
126
133
  fip_psth_inner_plot(ax, etr, colors[dex], c)
127
134
  else:
128
135
  print("No data for channel: {}".format(c))
@@ -135,6 +142,7 @@ def plot_fip_psth_compare_channels(
135
142
  ax.set_xlim(tw)
136
143
  ax.axvline(0, color="k", alpha=0.2)
137
144
  ax.tick_params(axis="both", labelsize=STYLE["axis_ticks_fontsize"])
145
+ ax.set_title(nwb.session_id)
138
146
  plt.tight_layout()
139
147
  return fig, ax
140
148
 
@@ -147,11 +155,16 @@ def fip_psth_inner_plot(ax, etr, color, label):
147
155
  color, the line color to plot
148
156
  label, the label for the etr
149
157
  """
158
+ if color == "":
159
+ cmap = plt.get_cmap("tab20")
160
+ color = cmap(np.random.randint(20))
150
161
  ax.fill_between(etr.index, etr.data - etr["sem"], etr.data + etr["sem"], color=color, alpha=0.2)
151
- ax.plot(etr.index, etr.data, color, label=label)
162
+ ax.plot(etr.index, etr.data, color=color, label=label)
152
163
 
153
164
 
154
- def fip_psth_inner_compute(nwb, align_timepoints, channel, average, tw=[-1, 1]):
165
+ def fip_psth_inner_compute(
166
+ nwb, align_timepoints, channel, average, tw=[-1, 1], censor=True, censor_times=None
167
+ ):
155
168
  """
156
169
  helper function that computes the event triggered response
157
170
  nwb, nwb object for the session of interest, should have fip_df attribute
@@ -170,6 +183,8 @@ def fip_psth_inner_compute(nwb, align_timepoints, channel, average, tw=[-1, 1]):
170
183
  t_start=tw[0],
171
184
  t_end=tw[1],
172
185
  output_sampling_rate=40,
186
+ censor=censor,
187
+ censor_times=censor_times,
173
188
  )
174
189
 
175
190
  if average:
@@ -12,11 +12,7 @@ from aind_dynamic_foraging_basic_analysis.data_model.foraging_session import (
12
12
  ForagingSessionData,
13
13
  PhotostimData,
14
14
  )
15
- from aind_dynamic_foraging_basic_analysis.plot.style import (
16
- STYLE,
17
- PHOTOSTIM_EPOCH_MAPPING,
18
- FIP_COLORS,
19
- )
15
+ from aind_dynamic_foraging_basic_analysis.plot.style import PHOTOSTIM_EPOCH_MAPPING
20
16
 
21
17
 
22
18
  def moving_average(a, n=3):
@@ -311,205 +307,3 @@ def plot_foraging_session( # noqa: C901
311
307
  ax.remove()
312
308
 
313
309
  return ax_choice_reward.get_figure(), [ax_choice_reward, ax_reward_schedule]
314
-
315
-
316
- def plot_session_scroller( # noqa: C901 pragma: no cover
317
- df_events, ax=None, adjust_time=True, fip_df=None
318
- ):
319
- """
320
- Creates an interactive plot of the session.
321
- Plots left/right licks/rewards, and go cues
322
-
323
- pressing "left arrow" scrolls backwards in time
324
- pressing "right arrow" scrolls forwards in time
325
- pressing "up arrow" zooms out, in time
326
- pressing "down arrow" zooms in, in time
327
-
328
- df_events, is a tidy dataframe of session events generated by
329
- aind_dynamic_foraging_data_utils.nwb_utils.create_events_df
330
-
331
- ax is a pyplot figure axis. If None, a new figure is created
332
-
333
- adjust_time (bool). If True, resets time=0 to the first event of the session
334
-
335
- fip_df is a tidy dataframe of FIP measurements generated by
336
- aind_dynamic_foraging_data_utils.nwb_utils.create_fib_df(tidy=True)
337
-
338
- EXAMPLES:
339
- df_events = nwb_utils.create_events_df(nwb_object)
340
- plot_foraging_session.plot_session_scroller(df_events)
341
-
342
- df_events = nwb_utils.create_events_df(nwb_object)
343
- fip_df = nwb_utils.create_fib_df(nwb_object, tidy=True)
344
- plot_foraging_session.plot_session_scroller(df_events,fip_df=fip_df)
345
- """
346
- if ax is None:
347
- if fip_df is None:
348
- fig, ax = plt.subplots(figsize=(15, 3))
349
- else:
350
- fig, ax = plt.subplots(figsize=(15, 8))
351
-
352
- if adjust_time:
353
- start_time = df_events.iloc[0]["timestamps"]
354
- df_events = df_events.copy()
355
- df_events["timestamps"] = df_events["timestamps"] - start_time
356
-
357
- if fip_df is not None:
358
- fip_df = fip_df.copy()
359
- fip_df["timestamps"] = fip_df["timestamps"] - start_time
360
-
361
- xmin = df_events.iloc[0]["timestamps"]
362
- xmax = xmin + 20
363
- ax.set_xlim(xmin, xmax)
364
-
365
- params = {
366
- "left_lick_bottom": 0,
367
- "left_lick_top": 0.25,
368
- "right_lick_bottom": 0.75,
369
- "right_lick_top": 1,
370
- "left_reward_bottom": 0.25,
371
- "left_reward_top": 0.5,
372
- "right_reward_bottom": 0.5,
373
- "right_reward_top": 0.75,
374
- "go_cue_bottom": 0,
375
- "go_cue_top": 1,
376
- "G_1_preprocessed_bottom": 1,
377
- "G_1_preprocessed_top": 2,
378
- "G_2_preprocessed_bottom": 2,
379
- "G_2_preprocessed_top": 3,
380
- "R_1_preprocessed_bottom": 3,
381
- "R_1_preprocessed_top": 4,
382
- "R_2_preprocessed_bottom": 4,
383
- "R_2_preprocessed_top": 5,
384
- }
385
- yticks = [
386
- (params["left_lick_top"] - params["left_lick_bottom"]) / 2 + params["left_lick_bottom"],
387
- (params["right_lick_top"] - params["right_lick_bottom"]) / 2 + params["right_lick_bottom"],
388
- (params["left_reward_top"] - params["left_reward_bottom"]) / 2
389
- + params["left_reward_bottom"],
390
- (params["right_reward_top"] - params["right_reward_bottom"]) / 2
391
- + params["right_reward_bottom"],
392
- ]
393
- ylabels = ["left licks", "right licks", "left reward", "right reward"]
394
- ycolors = ["k", "k", "r", "r"]
395
-
396
- if fip_df is not None:
397
- fip_channels = [
398
- "G_2_preprocessed",
399
- "G_1_preprocessed",
400
- "R_2_preprocessed",
401
- "R_1_preprocessed",
402
- ]
403
- present_channels = fip_df["event"].unique()
404
- for index, channel in enumerate(fip_channels):
405
- if channel in present_channels:
406
- yticks.append(
407
- (params[channel + "_top"] - params[channel + "_bottom"]) / 2
408
- + params[channel + "_bottom"]
409
- )
410
- ylabels.append(channel)
411
- color = FIP_COLORS.get(channel, "k")
412
- ycolors.append(color)
413
- C = fip_df.query("event == @channel").copy()
414
- C["data"] = C["data"] - C["data"].min()
415
- C["data"] = C["data"].values / C["data"].max()
416
- C["data"] += params[channel + "_bottom"]
417
- ax.plot(C.timestamps.values, C.data.values, color)
418
- ax.axhline(params[channel + "_bottom"], color="k", linewidth=0.5, alpha=0.25)
419
-
420
- left_licks = df_events.query('event == "left_lick_time"')
421
- left_times = left_licks.timestamps.values
422
- ax.vlines(
423
- left_times,
424
- params["left_lick_bottom"],
425
- params["left_lick_top"],
426
- alpha=1,
427
- linewidth=2,
428
- color="k",
429
- )
430
-
431
- right_licks = df_events.query('event == "right_lick_time"')
432
- right_times = right_licks.timestamps.values
433
- ax.vlines(
434
- right_times,
435
- params["right_lick_bottom"],
436
- params["right_lick_top"],
437
- alpha=1,
438
- linewidth=2,
439
- color="k",
440
- )
441
-
442
- left_reward_deliverys = df_events.query('event == "left_reward_delivery_time"')
443
- left_times = left_reward_deliverys.timestamps.values
444
- ax.vlines(
445
- left_times,
446
- params["left_reward_bottom"],
447
- params["left_reward_top"],
448
- alpha=1,
449
- linewidth=2,
450
- color="r",
451
- )
452
-
453
- right_reward_deliverys = df_events.query('event == "right_reward_delivery_time"')
454
- right_times = right_reward_deliverys.timestamps.values
455
- ax.vlines(
456
- right_times,
457
- params["right_reward_bottom"],
458
- params["right_reward_top"],
459
- alpha=1,
460
- linewidth=2,
461
- color="r",
462
- )
463
-
464
- go_cues = df_events.query('event == "goCue_start_time"')
465
- go_cue_times = go_cues.timestamps.values
466
- ax.vlines(
467
- go_cue_times,
468
- params["go_cue_bottom"],
469
- params["go_cue_top"],
470
- alpha=0.75,
471
- linewidth=1,
472
- color="b",
473
- )
474
-
475
- # Clean up plot
476
- ax.set_yticks(yticks)
477
- ax.set_yticklabels(ylabels, fontsize=STYLE["axis_ticks_fontsize"])
478
-
479
- for tick, color in zip(ax.get_yticklabels(), ycolors):
480
- tick.set_color(color)
481
- ax.set_xlabel("time (s)", fontsize=STYLE["axis_fontsize"])
482
- if fip_df is None:
483
- ax.set_ylim(0, 1)
484
- else:
485
- ax.set_ylim(0, 5)
486
- ax.spines["top"].set_visible(False)
487
- ax.spines["right"].set_visible(False)
488
- plt.tight_layout()
489
-
490
- def on_key_press(event):
491
- """
492
- Define interaction resonsivity
493
- """
494
- x = ax.get_xlim()
495
- xmin = x[0]
496
- xmax = x[1]
497
- xStep = (xmax - xmin) / 4
498
- if event.key == "<" or event.key == "," or event.key == "left":
499
- xmin -= xStep
500
- xmax -= xStep
501
- elif event.key == ">" or event.key == "." or event.key == "right":
502
- xmin += xStep
503
- xmax += xStep
504
- elif event.key == "up":
505
- xmin -= xStep
506
- xmax += xStep
507
- elif event.key == "down":
508
- xmin += xStep * (2 / 3)
509
- xmax -= xStep * (2 / 3)
510
- ax.set_xlim(xmin, xmax)
511
- plt.draw()
512
-
513
- kpid = fig.canvas.mpl_connect("key_press_event", on_key_press) # noqa: F841
514
-
515
- return fig, ax
@@ -0,0 +1,305 @@
1
+ """Plot foraging session in a standard format.
2
+ This is supposed to be reused in plotting real data or simulation data to ensure
3
+ a consistent visual representation.
4
+ """
5
+
6
+ import numpy as np
7
+ from matplotlib import pyplot as plt
8
+
9
+ from aind_dynamic_foraging_data_utils import nwb_utils as nu
10
+ from aind_dynamic_foraging_basic_analysis.licks import annotation as a
11
+ from aind_dynamic_foraging_basic_analysis.plot.style import (
12
+ STYLE,
13
+ FIP_COLORS,
14
+ )
15
+
16
+
17
+ def plot_session_scroller( # noqa: C901 pragma: no cover
18
+ nwb, ax=None, plot_bouts=False, processing="bright"
19
+ ):
20
+ """
21
+ Creates an interactive plot of the session.
22
+ Plots left/right licks/rewards, and go cues
23
+
24
+ pressing "left arrow" scrolls backwards in time
25
+ pressing "right arrow" scrolls forwards in time
26
+ pressing "up arrow" zooms out, in time
27
+ pressing "down arrow" zooms in, in time
28
+
29
+ nwb, an nwb like object that contains attributes: df_events, session_id
30
+ and optionally contains attributes fip_df, df_licks
31
+
32
+ ax is a pyplot figure axis. If None, a new figure is created
33
+
34
+ plot_bouts (bool), if True, plot licks colored by segmented lick bouts
35
+
36
+ EXAMPLES:
37
+ plot_foraging_session.plot_session_scroller(nwb)
38
+ plot_foraging_session.plot_session_scroller(nwb, plot_bouts=True)
39
+ """
40
+
41
+ if not hasattr(nwb, "df_events"):
42
+ print("computing df_events first")
43
+ nwb.df_events = nu.create_events_df(nwb)
44
+ df_events = nwb.df_events
45
+ else:
46
+ df_events = nwb.df_events
47
+ if hasattr(nwb, "fip_df"):
48
+ fip_df = nwb.fip_df
49
+ else:
50
+ fip_df = None
51
+ if hasattr(nwb, "df_licks") & plot_bouts:
52
+ df_licks = nwb.df_licks
53
+ elif plot_bouts:
54
+ print("computing df_licks first")
55
+ nwb.df_licks = a.annotate_lick_bouts(nwb)
56
+ nwb.df_licks = a.annotate_rewards(nwb)
57
+ df_licks = nwb.df_licks
58
+ else:
59
+ df_licks = None
60
+
61
+ if ax is None:
62
+ if fip_df is None:
63
+ fig, ax = plt.subplots(figsize=(15, 3))
64
+ else:
65
+ fig, ax = plt.subplots(figsize=(15, 8))
66
+
67
+ xmin = df_events.iloc[0]["timestamps"]
68
+ xmax = xmin + 20
69
+ ax.set_xlim(xmin, xmax)
70
+
71
+ params = {
72
+ "left_lick_bottom": 0,
73
+ "left_lick_top": 0.25,
74
+ "right_lick_bottom": 0.75,
75
+ "right_lick_top": 1,
76
+ "left_reward_bottom": 0.25,
77
+ "left_reward_top": 0.5,
78
+ "right_reward_bottom": 0.5,
79
+ "right_reward_top": 0.75,
80
+ "go_cue_bottom": 0,
81
+ "go_cue_top": 1,
82
+ "G_1_dff-bright_bottom": 1,
83
+ "G_1_dff-bright_top": 2,
84
+ "G_2_dff-bright_bottom": 2,
85
+ "G_2_dff-bright_top": 3,
86
+ "R_1_dff-bright_bottom": 3,
87
+ "R_1_dff-bright_top": 4,
88
+ "R_2_dff-bright_bottom": 4,
89
+ "R_2_dff-bright_top": 5,
90
+ "G_1_dff-poly_bottom": 1,
91
+ "G_1_dff-poly_top": 2,
92
+ "G_2_dff-poly_bottom": 2,
93
+ "G_2_dff-poly_top": 3,
94
+ "R_1_dff-poly_bottom": 3,
95
+ "R_1_dff-poly_top": 4,
96
+ "R_2_dff-poly_bottom": 4,
97
+ "R_2_dff-poly_top": 5,
98
+ "G_1_dff-exp_bottom": 1,
99
+ "G_1_dff-exp_top": 2,
100
+ "G_2_dff-exp_bottom": 2,
101
+ "G_2_dff-exp_top": 3,
102
+ "R_1_dff-exp_bottom": 3,
103
+ "R_1_dff-exp_top": 4,
104
+ "R_2_dff-exp_bottom": 4,
105
+ "R_2_dff-exp_top": 5,
106
+ }
107
+ yticks = [
108
+ (params["left_lick_top"] - params["left_lick_bottom"]) / 2 + params["left_lick_bottom"],
109
+ (params["right_lick_top"] - params["right_lick_bottom"]) / 2 + params["right_lick_bottom"],
110
+ (params["left_reward_top"] - params["left_reward_bottom"]) / 2
111
+ + params["left_reward_bottom"],
112
+ (params["right_reward_top"] - params["right_reward_bottom"]) / 2
113
+ + params["right_reward_bottom"],
114
+ ]
115
+ ylabels = ["left licks", "right licks", "left reward", "right reward"]
116
+ ycolors = ["k", "k", "r", "r"]
117
+
118
+ if fip_df is not None:
119
+ fip_channels = [
120
+ "G_2_dff-{}".format(processing),
121
+ "G_1_dff-{}".format(processing),
122
+ "R_2_dff-{}".format(processing),
123
+ "R_1_dff-{}".format(processing),
124
+ ]
125
+ present_channels = fip_df["event"].unique()
126
+ for index, channel in enumerate(fip_channels):
127
+ if channel in present_channels:
128
+ yticks.append(
129
+ (params[channel + "_top"] - params[channel + "_bottom"]) * 1
130
+ + params[channel + "_bottom"]
131
+ )
132
+ ylabels.append(channel)
133
+ color = FIP_COLORS.get(channel, "k")
134
+ ycolors.append(color)
135
+ C = fip_df.query("event == @channel").copy()
136
+ d_min = C["data"].min()
137
+ d_max = C["data"].max()
138
+ d_range = d_max - d_min
139
+ t1 = 0.25
140
+ t2 = 0.5
141
+ t3 = 0.75
142
+ p1 = d_min + t1 * d_range
143
+ p2 = d_min + t2 * d_range
144
+ p3 = d_min + t3 * d_range
145
+ yticks.append(
146
+ params[channel + "_bottom"]
147
+ + (params[channel + "_top"] - params[channel + "_bottom"]) * t1
148
+ )
149
+ yticks.append(
150
+ params[channel + "_bottom"]
151
+ + (params[channel + "_top"] - params[channel + "_bottom"]) * t2
152
+ )
153
+ yticks.append(
154
+ params[channel + "_bottom"]
155
+ + (params[channel + "_top"] - params[channel + "_bottom"]) * t3
156
+ )
157
+ ylabels.append(str(round(p1, 3)))
158
+ ylabels.append(str(round(p2, 3)))
159
+ ylabels.append(str(round(p3, 3)))
160
+ ycolors.append("darkgray")
161
+ ycolors.append("darkgray")
162
+ ycolors.append("darkgray")
163
+ C["data"] = C["data"] - d_min
164
+ C["data"] = C["data"].values / (d_max - d_min)
165
+ C["data"] += params[channel + "_bottom"]
166
+ ax.plot(C.timestamps.values, C.data.values, color)
167
+ ax.axhline(params[channel + "_bottom"], color="k", linewidth=0.5, alpha=0.25)
168
+
169
+ if df_licks is None:
170
+ left_licks = df_events.query('event == "left_lick_time"')
171
+ left_times = left_licks.timestamps.values
172
+ ax.vlines(
173
+ left_times,
174
+ params["left_lick_bottom"],
175
+ params["left_lick_top"],
176
+ alpha=1,
177
+ linewidth=2,
178
+ color="k",
179
+ )
180
+
181
+ right_licks = df_events.query('event == "right_lick_time"')
182
+ right_times = right_licks.timestamps.values
183
+ ax.vlines(
184
+ right_times,
185
+ params["right_lick_bottom"],
186
+ params["right_lick_top"],
187
+ alpha=1,
188
+ linewidth=2,
189
+ color="k",
190
+ )
191
+ else:
192
+ cmap = plt.get_cmap("tab20")
193
+ bouts = df_licks.bout_number.unique()
194
+ for b in bouts:
195
+ bout_left_licks = df_licks.query(
196
+ '(bout_number == @b)&(event=="left_lick_time")'
197
+ ).timestamps.values
198
+ bout_right_licks = df_licks.query(
199
+ '(bout_number == @b)&(event=="right_lick_time")'
200
+ ).timestamps.values
201
+ ax.vlines(
202
+ bout_left_licks,
203
+ params["left_lick_bottom"],
204
+ params["left_lick_top"],
205
+ alpha=1,
206
+ linewidth=2,
207
+ color=cmap(np.mod(b, 20)),
208
+ )
209
+ ax.vlines(
210
+ bout_right_licks,
211
+ params["right_lick_bottom"],
212
+ params["right_lick_top"],
213
+ alpha=1,
214
+ linewidth=2,
215
+ color=cmap(np.mod(b, 20)),
216
+ )
217
+ left_rewarded_licks = df_licks.query(
218
+ '(event == "left_lick_time")&(rewarded)'
219
+ ).timestamps.values
220
+ ax.plot(left_rewarded_licks, [params["left_lick_top"]] * len(left_rewarded_licks), "ro")
221
+ right_rewarded_licks = df_licks.query(
222
+ '(event == "right_lick_time")&(rewarded)'
223
+ ).timestamps.values
224
+ ax.plot(
225
+ right_rewarded_licks, [params["right_lick_bottom"]] * len(right_rewarded_licks), "ro"
226
+ )
227
+
228
+ left_reward_deliverys = df_events.query('event == "left_reward_delivery_time"')
229
+ left_times = left_reward_deliverys.timestamps.values
230
+ ax.vlines(
231
+ left_times,
232
+ params["left_reward_bottom"],
233
+ params["left_reward_top"],
234
+ alpha=1,
235
+ linewidth=2,
236
+ color="r",
237
+ )
238
+
239
+ right_reward_deliverys = df_events.query('event == "right_reward_delivery_time"')
240
+ right_times = right_reward_deliverys.timestamps.values
241
+ ax.vlines(
242
+ right_times,
243
+ params["right_reward_bottom"],
244
+ params["right_reward_top"],
245
+ alpha=1,
246
+ linewidth=2,
247
+ color="r",
248
+ )
249
+
250
+ go_cues = df_events.query('event == "goCue_start_time"')
251
+ go_cue_times = go_cues.timestamps.values
252
+ ax.vlines(
253
+ go_cue_times,
254
+ params["go_cue_bottom"],
255
+ params["go_cue_top"],
256
+ alpha=0.75,
257
+ linewidth=1,
258
+ color="b",
259
+ )
260
+
261
+ # Clean up plot
262
+ ax.set_yticks(yticks)
263
+ ax.set_yticklabels(ylabels, fontsize=STYLE["axis_ticks_fontsize"])
264
+
265
+ for tick, color in zip(ax.get_yticklabels(), ycolors):
266
+ tick.set_color(color)
267
+ ax.set_xlabel("time (s)", fontsize=STYLE["axis_fontsize"])
268
+ if fip_df is None:
269
+ ax.set_ylim(0, 1)
270
+ else:
271
+ ax.set_ylim(0, 5)
272
+ ax.spines["top"].set_visible(False)
273
+ ax.spines["right"].set_visible(False)
274
+ if fip_df is not None:
275
+ ax.set_title(nwb.session_id + ", FIP processing: {}".format(processing))
276
+ else:
277
+ ax.set_title(nwb.session_id)
278
+ plt.tight_layout()
279
+
280
+ def on_key_press(event):
281
+ """
282
+ Define interaction resonsivity
283
+ """
284
+ x = ax.get_xlim()
285
+ xmin = x[0]
286
+ xmax = x[1]
287
+ xStep = (xmax - xmin) / 4
288
+ if event.key == "<" or event.key == "," or event.key == "left":
289
+ xmin -= xStep
290
+ xmax -= xStep
291
+ elif event.key == ">" or event.key == "." or event.key == "right":
292
+ xmin += xStep
293
+ xmax += xStep
294
+ elif event.key == "up":
295
+ xmin -= xStep
296
+ xmax += xStep
297
+ elif event.key == "down":
298
+ xmin += xStep * (2 / 3)
299
+ xmax -= xStep * (2 / 3)
300
+ ax.set_xlim(xmin, xmax)
301
+ plt.draw()
302
+
303
+ kpid = fig.canvas.mpl_connect("key_press_event", on_key_press) # noqa: F841
304
+
305
+ return fig, ax
@@ -16,17 +16,29 @@ PHOTOSTIM_EPOCH_MAPPING = {
16
16
  # Colorscheme for FIP channels
17
17
  FIP_COLORS = {
18
18
  "G_1": "g",
19
- "G_1_preprocessed": "g",
19
+ "G_1_dff-bright": "g",
20
+ "G_1_dff-exp": "g",
21
+ "G_1_dff-poly": "g",
20
22
  "G_2": "darkgreen",
21
- "G_2_preprocessed": "darkgreen",
23
+ "G_2_dff-bright": "darkgreen",
24
+ "G_2_dff-exp": "darkgreen",
25
+ "G_2_dff-poly": "darkgreen",
22
26
  "R_1": "r",
23
- "R_1_preprocessed": "r",
27
+ "R_1_dff-bright": "r",
28
+ "R_1_dff-exp": "r",
29
+ "R_1_dff-poly": "r",
24
30
  "R_2": "darkred",
25
- "R_2_preprocessed": "darkred",
31
+ "R_2_dff-bright": "darkred",
32
+ "R_2_dff-exp": "darkred",
33
+ "R_2_dff-poly": "darkred",
26
34
  "Iso_1": "gray",
27
- "Iso_1_preprocessed": "gray",
35
+ "Iso_1_dff-bright": "gray",
36
+ "Iso_1_dff-exp": "gray",
37
+ "Iso_1_dff-poly": "gray",
28
38
  "Iso_2": "k",
29
- "Iso_2_preprocessed": "k",
39
+ "Iso_2_dff-bright": "k",
40
+ "Iso_2_dff-exp": "k",
41
+ "Iso_2_dff-poly": "k",
30
42
  "goCue_start_time": "b",
31
43
  "left_lick_time": "m",
32
44
  "right_lick_time": "r",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aind-dynamic-foraging-basic-analysis
3
- Version: 0.3.0
3
+ Version: 0.3.2
4
4
  Summary: Generated from aind-library-template
5
5
  Author: Allen Institute for Neural Dynamics
6
6
  License: MIT
@@ -0,0 +1,15 @@
1
+ aind_dynamic_foraging_basic_analysis/__init__.py,sha256=6BHc0q6Dvew_VVVzYJv9Xa8ZTRIPNQif1j8GGVII2c0,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/licks/annotation.py,sha256=HGK9t0WGPtkj8NzUR-4r2PeOIvtPE_5dfW_8i-6Zs0w,6019
5
+ aind_dynamic_foraging_basic_analysis/licks/lick_analysis.py,sha256=tgFqowzXHMRW2aCXhDi5SFE3Lfj_VMuMG1QPggkW9WE,20158
6
+ aind_dynamic_foraging_basic_analysis/plot/plot_fip.py,sha256=_KiEAonrsDrV-ReipDzKEPoKFTgV_E9IUCwVJTR5jac,8414
7
+ aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py,sha256=yfxqEu522DkBaD20R8BBBAmII4asu3mZ3psGUdUxqEQ,11534
8
+ aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session_plotly.py,sha256=wE-kl1W6KZjaMX08bjawWfSuse6KW6YNSxDbdph3XK0,6715
9
+ aind_dynamic_foraging_basic_analysis/plot/plot_session_scroller.py,sha256=GDPLIXl2y3JCvRwaiY2YFJXlubvgwzCwpPvjtd2_j-c,10430
10
+ aind_dynamic_foraging_basic_analysis/plot/style.py,sha256=VtGdmdxPEBt4dBrKRrYbscZE94-3wGfp564BphacF0I,1147
11
+ aind_dynamic_foraging_basic_analysis-0.3.2.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
12
+ aind_dynamic_foraging_basic_analysis-0.3.2.dist-info/METADATA,sha256=jNsT6dAvnUosSpVC_FaF0EqSiVwk8aDxTfdMadtJDLI,6737
13
+ aind_dynamic_foraging_basic_analysis-0.3.2.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
14
+ aind_dynamic_foraging_basic_analysis-0.3.2.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
15
+ aind_dynamic_foraging_basic_analysis-0.3.2.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (74.1.1)
2
+ Generator: setuptools (75.1.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,13 +0,0 @@
1
- aind_dynamic_foraging_basic_analysis/__init__.py,sha256=CJo5C4AvgEygUeRKFNBsBn1cC9PlkAQmKOxGY6O2YwE,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=tgFqowzXHMRW2aCXhDi5SFE3Lfj_VMuMG1QPggkW9WE,20158
4
- aind_dynamic_foraging_basic_analysis/data_model/foraging_session.py,sha256=7PFHfEIXP3QcjFS9Fk88S7PzBBYnUYw81WBjjEu_UKo,3536
5
- aind_dynamic_foraging_basic_analysis/plot/plot_fip.py,sha256=mvzFK48WY5KIfkl7odjVQulJ9F3wM-VNRdk3A8fjZ_Y,7968
6
- aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py,sha256=9_l5dUZtQnaOwEMkridwe3EKg9V9u4oDcGzsvIOixKU,18256
7
- aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session_plotly.py,sha256=wE-kl1W6KZjaMX08bjawWfSuse6KW6YNSxDbdph3XK0,6715
8
- aind_dynamic_foraging_basic_analysis/plot/style.py,sha256=vmrUdlCWeTDH9XJJKz7UBTchKlIP_8lhagjtwjjBPEc,823
9
- aind_dynamic_foraging_basic_analysis-0.3.0.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
10
- aind_dynamic_foraging_basic_analysis-0.3.0.dist-info/METADATA,sha256=I0ttIuhUN5tmuIlgjmsPja5FRJRtQpt4_4yPlC9H3UA,6737
11
- aind_dynamic_foraging_basic_analysis-0.3.0.dist-info/WHEEL,sha256=uCRv0ZEik_232NlR4YDw4Pv3Ajt5bKvMH13NUU7hFuI,91
12
- aind_dynamic_foraging_basic_analysis-0.3.0.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
13
- aind_dynamic_foraging_basic_analysis-0.3.0.dist-info/RECORD,,