aind-dynamic-foraging-basic-analysis 0.2.4__py3-none-any.whl → 0.2.6__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.4"
3
+ __version__ = "0.2.6"
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,223 @@
1
+ """
2
+ Tools for plotting FIP data
3
+ """
4
+
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+
8
+ from aind_dynamic_foraging_data_utils import alignment as an
9
+ from aind_dynamic_foraging_data_utils import nwb_utils as nu
10
+ from aind_dynamic_foraging_basic_analysis.plot.style import STYLE, FIP_COLORS
11
+
12
+
13
+ def plot_fip_psth_compare_alignments(nwb, alignments, channel, tw=[-4, 4]):
14
+ """
15
+ Compare the same FIP channel aligned to multiple event types
16
+ nwb, nwb object for the session
17
+ alignments, either a list of event types in df_events, or a dictionary
18
+ whose keys are event types and values are a list of timepoints
19
+ channel, (str) the name of the FIP channel
20
+ tw, time window for the PSTH
21
+
22
+ EXAMPLE
23
+ *******************
24
+ plot_fip_psth_compare_alignments(nwb,['left_reward_delivery_time',
25
+ 'right_reward_delivery_time'],'G_1_preprocessed')
26
+ """
27
+ if not hasattr(nwb, "fip_df"):
28
+ print("You need to compute the fip_df first")
29
+ print("running `nwb.fip_df = create_fib_df(nwb,tidy=True)`")
30
+ nwb.fip_df = nu.create_fib_df(nwb, tidy=True)
31
+ if not hasattr(nwb, "df_events"):
32
+ print("You need to compute the df_events first")
33
+ print("run `nwb.df_events = create_events_df(nwb)`")
34
+ nwb.df_events = nu.create_events_df(nwb)
35
+
36
+ if channel not in nwb.fip_df["event"].values:
37
+ print("channel {} not in fip_df".format(channel))
38
+
39
+ if isinstance(alignments, list):
40
+ align_dict = {}
41
+ for a in alignments:
42
+ if a not in nwb.df_events["event"].values:
43
+ print("{} not found in the events table".format(a))
44
+ return
45
+ else:
46
+ align_dict[a] = nwb.df_events.query("event == @a")["timestamps"].values
47
+ elif isinstance(alignments, dict):
48
+ align_dict = alignments
49
+ else:
50
+ print(
51
+ "alignments must be either a list of events in nwb.df_events, "
52
+ + "or a dictionary where each key is an event type, "
53
+ + "and the value is a list of timepoints"
54
+ )
55
+ return
56
+
57
+ align_label = "Time (s)"
58
+
59
+ fig, ax = plt.subplots()
60
+ 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)
63
+
64
+ plt.legend()
65
+ ax.set_xlabel(align_label, fontsize=STYLE["axis_fontsize"])
66
+ ax.set_ylabel("df/f", fontsize=STYLE["axis_fontsize"])
67
+ ax.spines["top"].set_visible(False)
68
+ ax.spines["right"].set_visible(False)
69
+ ax.set_xlim(tw)
70
+ ax.axvline(0, color="k", alpha=0.2)
71
+ ax.tick_params(axis="both", labelsize=STYLE["axis_ticks_fontsize"])
72
+ plt.tight_layout()
73
+ return fig, ax
74
+
75
+
76
+ def plot_fip_psth_compare_channels(
77
+ nwb,
78
+ align,
79
+ tw=[-4, 4],
80
+ channels=[
81
+ "G_1_preprocessed",
82
+ "G_2_preprocessed",
83
+ "R_1_preprocessed",
84
+ "R_2_preprocessed",
85
+ "Iso_1_preprocessed",
86
+ "Iso_2_preprocessed",
87
+ ],
88
+ ):
89
+ """
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
+
95
+ align should either be a string of the name of an event type in nwb.df_events,
96
+ or a list of timepoints
97
+ EXAMPLE
98
+ ********************
99
+ plot_fip_psth(nwb, 'goCue_start_time')
100
+ """
101
+ if not hasattr(nwb, "fip_df"):
102
+ print("You need to compute the fip_df first")
103
+ print("running `nwb.fip_df = create_fib_df(nwb,tidy=True)`")
104
+ nwb.fip_df = nu.create_fib_df(nwb, tidy=True)
105
+ if not hasattr(nwb, "df_events"):
106
+ print("You need to compute the df_events first")
107
+ print("run `nwb.df_events = create_events_df(nwb)`")
108
+ nwb.df_events = nu.create_events_df(nwb)
109
+
110
+ if isinstance(align, str):
111
+ if align not in nwb.df_events["event"].values:
112
+ print("{} not found in the events table".format(align))
113
+ return
114
+ align_timepoints = nwb.df_events.query("event == @align")["timestamps"].values
115
+ align_label = "Time from {} (s)".format(align)
116
+ else:
117
+ align_timepoints = align
118
+ align_label = "Time (s)"
119
+
120
+ fig, ax = plt.subplots()
121
+
122
+ colors = [FIP_COLORS.get(c, "k") for c in channels]
123
+ for dex, c in enumerate(channels):
124
+ if c in nwb.fip_df["event"].values:
125
+ etr = fip_psth_inner_compute(nwb, align_timepoints, c, True, tw)
126
+ fip_psth_inner_plot(ax, etr, colors[dex], c)
127
+ else:
128
+ print("No data for channel: {}".format(c))
129
+
130
+ plt.legend()
131
+ ax.set_xlabel(align_label, fontsize=STYLE["axis_fontsize"])
132
+ ax.set_ylabel("df/f", fontsize=STYLE["axis_fontsize"])
133
+ ax.spines["top"].set_visible(False)
134
+ ax.spines["right"].set_visible(False)
135
+ ax.set_xlim(tw)
136
+ ax.axvline(0, color="k", alpha=0.2)
137
+ ax.tick_params(axis="both", labelsize=STYLE["axis_ticks_fontsize"])
138
+ plt.tight_layout()
139
+ return fig, ax
140
+
141
+
142
+ def fip_psth_inner_plot(ax, etr, color, label):
143
+ """
144
+ helper function that plots an event triggered response
145
+ ax, the pyplot axis to plot on
146
+ etr, the dataframe that contains the event triggered response
147
+ color, the line color to plot
148
+ label, the label for the etr
149
+ """
150
+ 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)
152
+
153
+
154
+ def fip_psth_inner_compute(nwb, align_timepoints, channel, average, tw=[-1, 1]):
155
+ """
156
+ helper function that computes the event triggered response
157
+ nwb, nwb object for the session of interest, should have fip_df attribute
158
+ align_timepoints, an iterable list of the timepoints to compute the ETR aligned to
159
+ channel, what channel in the fip_df dataframe to use
160
+ average(bool), whether to return the average, or all individual traces
161
+ tw, time window before and after each event
162
+ """
163
+
164
+ data = nwb.fip_df.query("event == @channel")
165
+ etr = an.event_triggered_response(
166
+ data,
167
+ "timestamps",
168
+ "data",
169
+ align_timepoints,
170
+ t_start=tw[0],
171
+ t_end=tw[1],
172
+ output_sampling_rate=40,
173
+ )
174
+
175
+ if average:
176
+ mean = etr.groupby("time").mean()
177
+ sem = etr.groupby("time").sem()
178
+ mean["sem"] = sem["data"]
179
+ return mean
180
+ return etr
181
+
182
+
183
+ def plot_histogram(nwb, preprocessed=True, edge_percentile=2):
184
+ """
185
+ Generates a histogram of values of each FIP channel
186
+ preprocessed (Bool), if True, uses the preprocessed channel
187
+ edge_percentile (float), displays only the (2, 100-2) percentiles of the data
188
+
189
+ EXAMPLE
190
+ ***********************
191
+ plot_histogram(nwb)
192
+ """
193
+ if not hasattr(nwb, "fip_df"):
194
+ print("You need to compute the fip_df first")
195
+ print("running `nwb.fip_df = create_fib_df(nwb,tidy=True)`")
196
+ nwb.fip_df = nu.create_fib_df(nwb, tidy=True)
197
+ return
198
+
199
+ fig, ax = plt.subplots(3, 2, sharex=True)
200
+ channels = ["G", "R", "Iso"]
201
+ mins = []
202
+ maxs = []
203
+ for i, c in enumerate(channels):
204
+ for j, count in enumerate(["1", "2"]):
205
+ if preprocessed:
206
+ dex = c + "_" + count + "_preprocessed"
207
+ else:
208
+ dex = c + "_" + count
209
+ df = nwb.fip_df.query("event == @dex")
210
+ ax[i, j].hist(df["data"], bins=1000, color=FIP_COLORS.get(dex, "k"))
211
+ ax[i, j].spines["top"].set_visible(False)
212
+ ax[i, j].spines["right"].set_visible(False)
213
+ if preprocessed:
214
+ ax[i, j].set_xlabel("df/f")
215
+ else:
216
+ ax[i, j].set_xlabel("f")
217
+ ax[i, j].set_ylabel("count")
218
+ ax[i, j].set_title(dex)
219
+ mins.append(np.percentile(df["data"].values, edge_percentile))
220
+ maxs.append(np.percentile(df["data"].values, 100 - edge_percentile))
221
+ ax[0, 0].set_xlim(np.min(mins), np.max(maxs))
222
+ fig.suptitle(nwb.session_id)
223
+ plt.tight_layout()
@@ -12,26 +12,18 @@ from aind_dynamic_foraging_basic_analysis.data_model.foraging_session import (
12
12
  ForagingSessionData,
13
13
  PhotostimData,
14
14
  )
15
-
16
- PHOTOSTIM_EPOCH_MAPPING = {
17
- "after iti start": "cyan",
18
- "before go cue": "cyan",
19
- "after go cue": "green",
20
- "whole trial": "blue",
21
- }
22
-
23
- """
24
- Define a dictionary of plotting styles
25
- This allows rapid regeneration of figures
26
- """
27
- STYLE = {"axis_ticks_fontsize": 12, "axis_fontsize": 16}
15
+ from aind_dynamic_foraging_basic_analysis.plot.style import (
16
+ STYLE,
17
+ PHOTOSTIM_EPOCH_MAPPING,
18
+ FIP_COLORS,
19
+ )
28
20
 
29
21
 
30
22
  def moving_average(a, n=3):
31
23
  """Compute moving average of a list or array."""
32
24
  ret = np.nancumsum(a, dtype=float)
33
25
  ret[n:] = ret[n:] - ret[:-n]
34
- return ret[(n - 1):] / n
26
+ return ret[(n - 1) :] / n # noqa: E203
35
27
 
36
28
 
37
29
  def plot_foraging_session( # noqa: C901
@@ -321,7 +313,9 @@ def plot_foraging_session( # noqa: C901
321
313
  return ax_choice_reward.get_figure(), [ax_choice_reward, ax_reward_schedule]
322
314
 
323
315
 
324
- def plot_session_scroller(df_events, ax=None, adjust_time=True): # pragma: no cover
316
+ def plot_session_scroller( # noqa: C901 pragma: no cover
317
+ df_events, ax=None, adjust_time=True, fip_df=None
318
+ ):
325
319
  """
326
320
  Creates an interactive plot of the session.
327
321
  Plots left/right licks/rewards, and go cues
@@ -338,16 +332,31 @@ def plot_session_scroller(df_events, ax=None, adjust_time=True): # pragma: no c
338
332
 
339
333
  adjust_time (bool). If True, resets time=0 to the first event of the session
340
334
 
341
- EXAMPLE:
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:
342
339
  df_events = nwb_utils.create_events_df(nwb_object)
343
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)
344
345
  """
345
346
  if ax is None:
346
- fig, ax = plt.subplots(figsize=(15, 3))
347
+ if fip_df is None:
348
+ fig, ax = plt.subplots(figsize=(15, 3))
349
+ else:
350
+ fig, ax = plt.subplots(figsize=(15, 8))
347
351
 
348
352
  if adjust_time:
353
+ start_time = df_events.iloc[0]["timestamps"]
349
354
  df_events = df_events.copy()
350
- df_events["timestamps"] = df_events["timestamps"] - df_events.iloc[0]["timestamps"]
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
351
360
 
352
361
  xmin = df_events.iloc[0]["timestamps"]
353
362
  xmax = xmin + 20
@@ -364,6 +373,14 @@ def plot_session_scroller(df_events, ax=None, adjust_time=True): # pragma: no c
364
373
  "right_reward_top": 0.75,
365
374
  "go_cue_bottom": 0,
366
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,
367
384
  }
368
385
  yticks = [
369
386
  (params["left_lick_top"] - params["left_lick_bottom"]) / 2 + params["left_lick_bottom"],
@@ -374,6 +391,31 @@ def plot_session_scroller(df_events, ax=None, adjust_time=True): # pragma: no c
374
391
  + params["right_reward_bottom"],
375
392
  ]
376
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)
377
419
 
378
420
  left_licks = df_events.query('event == "left_lick_time"')
379
421
  left_times = left_licks.timestamps.values
@@ -433,11 +475,14 @@ def plot_session_scroller(df_events, ax=None, adjust_time=True): # pragma: no c
433
475
  # Clean up plot
434
476
  ax.set_yticks(yticks)
435
477
  ax.set_yticklabels(ylabels, fontsize=STYLE["axis_ticks_fontsize"])
436
- colors = ["k", "k", "r", "r"]
437
- for tick, color in zip(ax.get_yticklabels(), colors):
478
+
479
+ for tick, color in zip(ax.get_yticklabels(), ycolors):
438
480
  tick.set_color(color)
439
481
  ax.set_xlabel("time (s)", fontsize=STYLE["axis_fontsize"])
440
- ax.set_ylim(0, 1)
482
+ if fip_df is None:
483
+ ax.set_ylim(0, 1)
484
+ else:
485
+ ax.set_ylim(0, 5)
441
486
  ax.spines["top"].set_visible(False)
442
487
  ax.spines["right"].set_visible(False)
443
488
  plt.tight_layout()
@@ -0,0 +1,35 @@
1
+ """
2
+ Defines a dictionary of styles
3
+ """
4
+
5
+ # General plotting style
6
+ STYLE = {"axis_ticks_fontsize": 12, "axis_fontsize": 16}
7
+
8
+ # Colorscheme for photostim
9
+ PHOTOSTIM_EPOCH_MAPPING = {
10
+ "after iti start": "cyan",
11
+ "before go cue": "cyan",
12
+ "after go cue": "green",
13
+ "whole trial": "blue",
14
+ }
15
+
16
+ # Colorscheme for FIP channels
17
+ FIP_COLORS = {
18
+ "G_1": "g",
19
+ "G_1_preprocessed": "g",
20
+ "G_2": "darkgreen",
21
+ "G_2_preprocessed": "darkgreen",
22
+ "R_1": "r",
23
+ "R_1_preprocessed": "r",
24
+ "R_2": "darkred",
25
+ "R_2_preprocessed": "darkred",
26
+ "Iso_1": "gray",
27
+ "Iso_1_preprocessed": "gray",
28
+ "Iso_2": "k",
29
+ "Iso_2_preprocessed": "k",
30
+ "goCue_start_time": "b",
31
+ "left_lick_time": "m",
32
+ "right_lick_time": "r",
33
+ "left_reward_delivery_time": "b",
34
+ "right_reward_delivery_time": "r",
35
+ }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aind-dynamic-foraging-basic-analysis
3
- Version: 0.2.4
3
+ Version: 0.2.6
4
4
  Summary: Generated from aind-library-template
5
5
  Author: Allen Institute for Neural Dynamics
6
6
  License: MIT
@@ -0,0 +1,12 @@
1
+ aind_dynamic_foraging_basic_analysis/__init__.py,sha256=Qg0Rfawo0JuRdGTLdWCzNu5URAopGjIOMNY2jEJ9pko,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_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/style.py,sha256=vmrUdlCWeTDH9XJJKz7UBTchKlIP_8lhagjtwjjBPEc,823
8
+ aind_dynamic_foraging_basic_analysis-0.2.6.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
9
+ aind_dynamic_foraging_basic_analysis-0.2.6.dist-info/METADATA,sha256=1g5OBig6QzfmhXb4cr5WkIVDjpvnEzTUcyYjXXUsu-g,6715
10
+ aind_dynamic_foraging_basic_analysis-0.2.6.dist-info/WHEEL,sha256=UvcQYKBHoFqaQd6LKyqHw9fxEolWLQnlzP0h_LgJAfI,91
11
+ aind_dynamic_foraging_basic_analysis-0.2.6.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
12
+ aind_dynamic_foraging_basic_analysis-0.2.6.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (73.0.1)
2
+ Generator: setuptools (74.0.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=ti2seCRcOdLN6XHXb1oId4MB7ghsQp5ScK7kSEs889k,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=xvOCDutonCDmPBfzeVL49pkV_nqsTiLZPxT5Obn5s6w,16388
6
- aind_dynamic_foraging_basic_analysis-0.2.4.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
7
- aind_dynamic_foraging_basic_analysis-0.2.4.dist-info/METADATA,sha256=4cqyS-byYZFLPvZ3GxO7JiJ6MaE3T7aixFMmvNmp-ps,6715
8
- aind_dynamic_foraging_basic_analysis-0.2.4.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91
9
- aind_dynamic_foraging_basic_analysis-0.2.4.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
10
- aind_dynamic_foraging_basic_analysis-0.2.4.dist-info/RECORD,,