aind-dynamic-foraging-basic-analysis 0.1.0__tar.gz → 0.2.0__tar.gz

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.
Files changed (38) hide show
  1. {aind_dynamic_foraging_basic_analysis-0.1.0/src/aind_dynamic_foraging_basic_analysis.egg-info → aind_dynamic_foraging_basic_analysis-0.2.0}/PKG-INFO +3 -1
  2. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/pyproject.toml +3 -1
  3. aind_dynamic_foraging_basic_analysis-0.2.0/src/aind_dynamic_foraging_basic_analysis/__init__.py +6 -0
  4. aind_dynamic_foraging_basic_analysis-0.2.0/src/aind_dynamic_foraging_basic_analysis/data_model/foraging_session.py +107 -0
  5. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/src/aind_dynamic_foraging_basic_analysis/foraging_efficiency.py +14 -28
  6. aind_dynamic_foraging_basic_analysis-0.2.0/src/aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py +315 -0
  7. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0/src/aind_dynamic_foraging_basic_analysis.egg-info}/PKG-INFO +3 -1
  8. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/src/aind_dynamic_foraging_basic_analysis.egg-info/SOURCES.txt +3 -0
  9. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/src/aind_dynamic_foraging_basic_analysis.egg-info/requires.txt +2 -0
  10. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/tests/nwb_io.py +1 -1
  11. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/tests/test_foraging_efficiency.py +4 -10
  12. aind_dynamic_foraging_basic_analysis-0.2.0/tests/test_plot_foraging_session.py +136 -0
  13. aind_dynamic_foraging_basic_analysis-0.1.0/src/aind_dynamic_foraging_basic_analysis/__init__.py +0 -5
  14. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.flake8 +0 -0
  15. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  16. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  17. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.github/ISSUE_TEMPLATE/user-story.md +0 -0
  18. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.github/workflows/init.yml +0 -0
  19. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.github/workflows/tag_and_publish.yml +0 -0
  20. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.github/workflows/test_and_lint.yml +0 -0
  21. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/.gitignore +0 -0
  22. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/LICENSE +0 -0
  23. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/README.md +0 -0
  24. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/doc_template/Makefile +0 -0
  25. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/doc_template/make.bat +0 -0
  26. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/doc_template/source/_static/dark-logo.svg +0 -0
  27. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/doc_template/source/_static/favicon.ico +0 -0
  28. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/doc_template/source/_static/light-logo.svg +0 -0
  29. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/doc_template/source/conf.py +0 -0
  30. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/doc_template/source/index.rst +0 -0
  31. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/setup.cfg +0 -0
  32. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/setup.py +0 -0
  33. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/src/aind_dynamic_foraging_basic_analysis.egg-info/dependency_links.txt +0 -0
  34. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/src/aind_dynamic_foraging_basic_analysis.egg-info/top_level.txt +0 -0
  35. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/tests/__init__.py +0 -0
  36. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/tests/data/697929_2024-02-22_08-38-30.nwb +0 -0
  37. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/tests/data/703548_2024-03-01_08-51-32.nwb +0 -0
  38. {aind_dynamic_foraging_basic_analysis-0.1.0 → aind_dynamic_foraging_basic_analysis-0.2.0}/tests/data/727456_2024-06-12_11-10-53.nwb +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aind-dynamic-foraging-basic-analysis
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Generated from aind-library-template
5
5
  Author: Allen Institute for Neural Dynamics
6
6
  License: MIT
@@ -9,6 +9,8 @@ Requires-Python: >=3.7
9
9
  Description-Content-Type: text/markdown
10
10
  License-File: LICENSE
11
11
  Requires-Dist: numpy
12
+ Requires-Dist: matplotlib
13
+ Requires-Dist: pydantic
12
14
  Provides-Extra: dev
13
15
  Requires-Dist: aind-dynamic-foraging-basic-analysis; extra == "dev"
14
16
  Requires-Dist: black; extra == "dev"
@@ -17,7 +17,9 @@ readme = "README.md"
17
17
  dynamic = ["version"]
18
18
 
19
19
  dependencies = [
20
- 'numpy'
20
+ 'numpy',
21
+ 'matplotlib',
22
+ 'pydantic'
21
23
  ]
22
24
 
23
25
  [project.optional-dependencies]
@@ -0,0 +1,6 @@
1
+ """Init package"""
2
+
3
+ __version__ = "0.2.0"
4
+
5
+ from .foraging_efficiency import compute_foraging_efficiency # noqa: F401
6
+ from .plot.plot_foraging_session import plot_foraging_session # noqa: F401
@@ -0,0 +1,107 @@
1
+ """
2
+ Pydantic data model of foraging session data for shared validation.
3
+
4
+ Maybe this is an overkill...
5
+ """
6
+
7
+ from typing import List, Optional
8
+
9
+ import numpy as np
10
+ from pydantic import BaseModel, field_validator, model_validator
11
+
12
+
13
+ class PhotostimData(BaseModel):
14
+ """Photostimulation data"""
15
+
16
+ trial: List[int]
17
+ power: List[float]
18
+ stim_epoch: Optional[List[str]] = None
19
+
20
+ class Config:
21
+ """Allow np.ndarray as input"""
22
+
23
+ arbitrary_types_allowed = True
24
+
25
+
26
+ class ForagingSessionData(BaseModel):
27
+ """Shared validation for foraging session data"""
28
+
29
+ choice_history: np.ndarray
30
+ reward_history: np.ndarray
31
+ p_reward: Optional[np.ndarray] = None
32
+ random_number: Optional[np.ndarray] = None
33
+ autowater_offered: Optional[np.ndarray] = None
34
+ fitted_data: Optional[np.ndarray] = None
35
+ photostim: Optional[PhotostimData] = None
36
+
37
+ class Config:
38
+ """Allow np.ndarray as input"""
39
+
40
+ arbitrary_types_allowed = True
41
+
42
+ @field_validator(
43
+ "choice_history",
44
+ "reward_history",
45
+ "p_reward",
46
+ "random_number",
47
+ "autowater_offered",
48
+ "fitted_data",
49
+ mode="before",
50
+ )
51
+ @classmethod
52
+ def convert_to_ndarray(cls, v, info):
53
+ """Always convert to numpy array"""
54
+ return (
55
+ np.array(
56
+ v,
57
+ dtype=(
58
+ "bool"
59
+ if info.field_name in ["reward_history", "autowater_offered"] # Turn to bool
60
+ else None
61
+ ),
62
+ )
63
+ if v is not None
64
+ else None
65
+ )
66
+
67
+ @model_validator(mode="after")
68
+ def check_all_fields(cls, values): # noqa: C901
69
+ """Check consistency of all fields"""
70
+
71
+ choice_history = values.choice_history
72
+ reward_history = values.reward_history
73
+ p_reward = values.p_reward
74
+ random_number = values.random_number
75
+ autowater_offered = values.autowater_offered
76
+ fitted_data = values.fitted_data
77
+ photostim = values.photostim
78
+
79
+ if not np.all(np.isin(choice_history, [0.0, 1.0]) | np.isnan(choice_history)):
80
+ raise ValueError("choice_history must contain only 0, 1, or np.nan.")
81
+
82
+ if choice_history.shape != reward_history.shape:
83
+ raise ValueError("choice_history and reward_history must have the same shape.")
84
+
85
+ if p_reward.shape != (2, len(choice_history)):
86
+ raise ValueError("reward_probability must have the shape (2, n_trials)")
87
+
88
+ if random_number is not None and random_number.shape != p_reward.shape:
89
+ raise ValueError("random_number must have the same shape as reward_probability.")
90
+
91
+ if autowater_offered is not None and autowater_offered.shape != choice_history.shape:
92
+ raise ValueError("autowater_offered must have the same shape as choice_history.")
93
+
94
+ if fitted_data is not None and fitted_data.shape[0] != choice_history.shape[0]:
95
+ raise ValueError("fitted_data must have the same length as choice_history.")
96
+
97
+ if photostim is not None:
98
+ if len(photostim.trial) != len(photostim.power):
99
+ raise ValueError("photostim.trial must have the same length as photostim.power.")
100
+ if photostim.stim_epoch is not None and len(photostim.stim_epoch) != len(
101
+ photostim.power
102
+ ):
103
+ raise ValueError(
104
+ "photostim.stim_epoch must have the same length as photostim.power."
105
+ )
106
+
107
+ return values
@@ -4,6 +4,8 @@ from typing import List, Tuple, Union
4
4
 
5
5
  import numpy as np
6
6
 
7
+ from aind_dynamic_foraging_basic_analysis.data_model.foraging_session import ForagingSessionData
8
+
7
9
 
8
10
  def compute_foraging_efficiency(
9
11
  baited: bool,
@@ -74,38 +76,22 @@ def compute_foraging_efficiency(
74
76
  reward_optimal_func = _reward_optimal_forager_no_baiting
75
77
 
76
78
  # Formatting and sanity checks
77
- choice_history = np.array(choice_history, dtype=float) # Convert None to np.nan, if any
78
- reward_history = np.array(reward_history, dtype=float)
79
- p_reward = np.array(p_reward, dtype=float)
80
- random_number = np.array(random_number, dtype=float) if random_number is not None else None
81
- n_trials = len(choice_history)
82
-
83
- if not np.all(np.isin(choice_history, [0.0, 1.0]) | np.isnan(choice_history)):
84
- raise ValueError("choice_history must contain only 0, 1, or np.nan.")
85
-
86
- if not np.all(np.isin(reward_history, [0.0, 1.0])):
87
- raise ValueError("reward_history must contain only 0 (False) or 1 (True).")
88
-
89
- if choice_history.shape != reward_history.shape:
90
- raise ValueError("choice_history and reward_history must have the same shape.")
91
-
92
- if p_reward.shape != (2, n_trials):
93
- raise ValueError("reward_probability must have the shape (2, n_trials)")
94
-
95
- if random_number is not None and random_number.shape != p_reward.shape:
96
- raise ValueError("random_number must have the same shape as reward_probability.")
97
-
98
- if autowater_offered is not None and not autowater_offered.shape == choice_history.shape:
99
- raise ValueError("autowater_offered must have the same shape as choice_history.")
79
+ data = ForagingSessionData(
80
+ choice_history=choice_history,
81
+ reward_history=reward_history,
82
+ p_reward=p_reward,
83
+ random_number=random_number,
84
+ autowater_offered=autowater_offered,
85
+ )
100
86
 
101
87
  # Foraging_efficiency is calculated only on finished AND non-autowater trials
102
- ignored = np.isnan(choice_history)
88
+ ignored = np.isnan(data.choice_history)
103
89
  valid_trials = (~ignored & ~autowater_offered) if autowater_offered is not None else ~ignored
104
90
 
105
- choice_history = choice_history[valid_trials]
106
- reward_history = reward_history[valid_trials]
107
- p_reward = p_reward[:, valid_trials]
108
- random_number = random_number[:, valid_trials] if random_number is not None else None
91
+ choice_history = data.choice_history[valid_trials]
92
+ reward_history = data.reward_history[valid_trials]
93
+ p_reward = data.p_reward[:, valid_trials]
94
+ random_number = data.random_number[:, valid_trials] if data.random_number is not None else None
109
95
 
110
96
  # Compute reward of the optimal forager
111
97
  reward_optimal, reward_optimal_random_seed = reward_optimal_func(
@@ -0,0 +1,315 @@
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
+ from typing import List, Tuple, Union
7
+
8
+ import numpy as np
9
+ from matplotlib import pyplot as plt
10
+
11
+ from aind_dynamic_foraging_basic_analysis.data_model.foraging_session import (
12
+ ForagingSessionData,
13
+ PhotostimData,
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
+ def moving_average(a, n=3):
25
+ """Compute moving average of a list or array."""
26
+ ret = np.nancumsum(a, dtype=float)
27
+ ret[n:] = ret[n:] - ret[:-n]
28
+ return ret[n - 1:] / n
29
+
30
+
31
+ def plot_foraging_session( # noqa: C901
32
+ choice_history: Union[List, np.ndarray],
33
+ reward_history: Union[List, np.ndarray],
34
+ p_reward: Union[List, np.ndarray],
35
+ autowater_offered: Union[List, np.ndarray] = None,
36
+ fitted_data: Union[List, np.ndarray] = None,
37
+ photostim: dict = None,
38
+ valid_range: List = None,
39
+ smooth_factor: int = 5,
40
+ base_color: str = "y",
41
+ ax: plt.Axes = None,
42
+ vertical: bool = False,
43
+ ) -> Tuple[plt.Figure, List[plt.Axes]]:
44
+ """Plot dynamic foraging session.
45
+
46
+ Parameters
47
+ ----------
48
+ choice_history : Union[List, np.ndarray]
49
+ Choice history (0 = left choice, 1 = right choice, np.nan = ignored).
50
+ reward_history : Union[List, np.ndarray]
51
+ Reward history (0 = unrewarded, 1 = rewarded).
52
+ p_reward : Union[List, np.ndarray]
53
+ Reward probability for both sides. The size should be (2, len(choice_history)).
54
+ autowater_offered: Union[List, np.ndarray], optional
55
+ If not None, indicates trials where autowater was offered.
56
+ fitted_data : Union[List, np.ndarray], optional
57
+ If not None, overlay the fitted data (e.g. from RL model) on the plot.
58
+ photostim : Dict, optional
59
+ If not None, indicates photostimulation trials. It should be a dictionary with the keys:
60
+ - trial: list of trial numbers
61
+ - power: list of laser power
62
+ - stim_epoch: optional, list of stimulation epochs from
63
+ {"after iti start", "before go cue", "after go cue", "whole trial"}
64
+ valid_range : List, optional
65
+ If not None, add two vertical lines to indicate the valid range where animal was engaged.
66
+ smooth_factor : int, optional
67
+ Smoothing factor for the choice history, by default 5.
68
+ base_color : str, optional
69
+ Base color for the reward probability, by default "yellow".
70
+ ax : plt.Axes, optional
71
+ If not None, use the provided axis to plot, by default None.
72
+ vertical : bool, optional
73
+ If True, plot the session vertically, by default False.
74
+
75
+ Returns
76
+ -------
77
+ Tuple[plt.Figure, List[plt.Axes]]
78
+ fig, [ax_choice_reward, ax_reward_schedule]
79
+ """
80
+
81
+ # Formatting and sanity checks
82
+ data = ForagingSessionData(
83
+ choice_history=choice_history,
84
+ reward_history=reward_history,
85
+ p_reward=p_reward,
86
+ autowater_offered=autowater_offered,
87
+ fitted_data=fitted_data,
88
+ photostim=PhotostimData(**photostim) if photostim is not None else None,
89
+ )
90
+
91
+ choice_history = data.choice_history
92
+ reward_history = data.reward_history
93
+ p_reward = data.p_reward
94
+ autowater_offered = data.autowater_offered
95
+ fitted_data = data.fitted_data
96
+ photostim = data.photostim
97
+
98
+ if ax is None:
99
+ fig, ax = plt.subplots(1, 1, figsize=(15, 3) if not vertical else (3, 12), dpi=200)
100
+ plt.subplots_adjust(left=0.1, right=0.8, bottom=0.05, top=0.8)
101
+
102
+ if not vertical:
103
+ gs = ax._subplotspec.subgridspec(2, 1, height_ratios=[1, 0.2], hspace=0.1)
104
+ ax_choice_reward = ax.get_figure().add_subplot(gs[0, 0])
105
+ ax_reward_schedule = ax.get_figure().add_subplot(gs[1, 0], sharex=ax_choice_reward)
106
+ else:
107
+ gs = ax._subplotspec.subgridspec(1, 2, width_ratios=[0.2, 1], wspace=0.1)
108
+ ax_choice_reward = ax.get_figure().add_subplot(gs[0, 1])
109
+ ax_reward_schedule = ax.get_figure().add_subplot(gs[0, 0], sharey=ax_choice_reward)
110
+
111
+ # == Fetch data ==
112
+ n_trials = len(choice_history)
113
+
114
+ p_reward_fraction = p_reward[1, :] / (np.sum(p_reward, axis=0))
115
+
116
+ ignored = np.isnan(choice_history)
117
+
118
+ if autowater_offered is None:
119
+ rewarded_excluding_autowater = reward_history
120
+ autowater_collected = np.full_like(choice_history, False, dtype=bool)
121
+ autowater_ignored = np.full_like(choice_history, False, dtype=bool)
122
+ unrewarded_trials = ~reward_history & ~ignored
123
+ else:
124
+ rewarded_excluding_autowater = reward_history & ~autowater_offered
125
+ autowater_collected = autowater_offered & ~ignored
126
+ autowater_ignored = autowater_offered & ignored
127
+ unrewarded_trials = ~reward_history & ~ignored & ~autowater_offered
128
+
129
+ # == Choice trace ==
130
+ # Rewarded trials (real foraging, autowater excluded)
131
+ xx = np.nonzero(rewarded_excluding_autowater)[0] + 1
132
+ yy = 0.5 + (choice_history[rewarded_excluding_autowater] - 0.5) * 1.4
133
+ ax_choice_reward.plot(
134
+ *(xx, yy) if not vertical else [*(yy, xx)],
135
+ "|" if not vertical else "_",
136
+ color="black",
137
+ markersize=10,
138
+ markeredgewidth=2,
139
+ label="Rewarded choices",
140
+ )
141
+
142
+ # Unrewarded trials (real foraging; not ignored or autowater trials)
143
+ xx = np.nonzero(unrewarded_trials)[0] + 1
144
+ yy = 0.5 + (choice_history[unrewarded_trials] - 0.5) * 1.4
145
+ ax_choice_reward.plot(
146
+ *(xx, yy) if not vertical else [*(yy, xx)],
147
+ "|" if not vertical else "_",
148
+ color="gray",
149
+ markersize=6,
150
+ markeredgewidth=1,
151
+ label="Unrewarded choices",
152
+ )
153
+
154
+ # Ignored trials
155
+ xx = np.nonzero(ignored & ~autowater_ignored)[0] + 1
156
+ yy = [1.1] * sum(ignored & ~autowater_ignored)
157
+ ax_choice_reward.plot(
158
+ *(xx, yy) if not vertical else [*(yy, xx)],
159
+ "x",
160
+ color="red",
161
+ markersize=3,
162
+ markeredgewidth=0.5,
163
+ label="Ignored",
164
+ )
165
+
166
+ # Autowater history
167
+ if autowater_offered is not None:
168
+ # Autowater offered and collected
169
+ xx = np.nonzero(autowater_collected)[0] + 1
170
+ yy = 0.5 + (choice_history[autowater_collected] - 0.5) * 1.4
171
+ ax_choice_reward.plot(
172
+ *(xx, yy) if not vertical else [*(yy, xx)],
173
+ "|" if not vertical else "_",
174
+ color="royalblue",
175
+ markersize=10,
176
+ markeredgewidth=2,
177
+ label="Autowater collected",
178
+ )
179
+
180
+ # Also highlight the autowater offered but still ignored
181
+ xx = np.nonzero(autowater_ignored)[0] + 1
182
+ yy = [1.1] * sum(autowater_ignored)
183
+ ax_choice_reward.plot(
184
+ *(xx, yy) if not vertical else [*(yy, xx)],
185
+ "x",
186
+ color="royalblue",
187
+ markersize=3,
188
+ markeredgewidth=0.5,
189
+ label="Autowater ignored",
190
+ )
191
+
192
+ # Base probability
193
+ xx = np.arange(0, n_trials) + 1
194
+ yy = p_reward_fraction
195
+ ax_choice_reward.plot(
196
+ *(xx, yy) if not vertical else [*(yy, xx)],
197
+ color=base_color,
198
+ label="Base rew. prob.",
199
+ lw=1.5,
200
+ )
201
+
202
+ # Smoothed choice history
203
+ y = moving_average(choice_history, smooth_factor) / (
204
+ moving_average(~np.isnan(choice_history), smooth_factor) + 1e-6
205
+ )
206
+ y[y > 100] = np.nan
207
+ x = np.arange(0, len(y)) + int(smooth_factor / 2) + 1
208
+ ax_choice_reward.plot(
209
+ *(x, y) if not vertical else [*(y, x)],
210
+ linewidth=1.5,
211
+ color="black",
212
+ label="Choice (smooth = %g)" % smooth_factor,
213
+ )
214
+
215
+ # finished ratio
216
+ if np.sum(np.isnan(choice_history)):
217
+ x = np.arange(0, len(y)) + int(smooth_factor / 2) + 1
218
+ y = moving_average(~np.isnan(choice_history), smooth_factor)
219
+ ax_choice_reward.plot(
220
+ *(x, y) if not vertical else [*(y, x)],
221
+ linewidth=0.8,
222
+ color="m",
223
+ alpha=1,
224
+ label="Finished (smooth = %g)" % smooth_factor,
225
+ )
226
+
227
+ # add valid ranage
228
+ if valid_range is not None:
229
+ add_range = ax_choice_reward.axhline if vertical else ax_choice_reward.axvline
230
+ add_range(valid_range[0], color="m", ls="--", lw=1, label="motivation good")
231
+ add_range(valid_range[1], color="m", ls="--", lw=1)
232
+
233
+ # For each session, if any fitted_data
234
+ if fitted_data is not None:
235
+ x = np.arange(0, n_trials)
236
+ y = fitted_data
237
+ ax_choice_reward.plot(*(x, y) if not vertical else [*(y, x)], linewidth=1.5, label="model")
238
+
239
+ # == photo stim ==
240
+ if photostim is not None:
241
+
242
+ trial = data.photostim.trial
243
+ power = data.photostim.power
244
+ stim_epoch = data.photostim.stim_epoch
245
+
246
+ if stim_epoch is not None:
247
+ edgecolors = [PHOTOSTIM_EPOCH_MAPPING[t] for t in stim_epoch]
248
+ else:
249
+ edgecolors = "darkcyan"
250
+
251
+ x = trial
252
+ y = np.ones_like(trial) + 0.4
253
+ _ = ax_choice_reward.scatter(
254
+ *(x, y) if not vertical else [*(y, x)],
255
+ s=np.array(power) * 2,
256
+ edgecolors=edgecolors,
257
+ marker="v" if not vertical else "<",
258
+ facecolors="none",
259
+ linewidth=0.5,
260
+ label="photostim",
261
+ )
262
+
263
+ # p_reward
264
+ xx = np.arange(0, n_trials) + 1
265
+ ll = p_reward[0, :]
266
+ rr = p_reward[1, :]
267
+ ax_reward_schedule.plot(
268
+ *(xx, rr) if not vertical else [*(rr, xx)], color="b", label="p_right", lw=1
269
+ )
270
+ ax_reward_schedule.plot(
271
+ *(xx, ll) if not vertical else [*(ll, xx)], color="r", label="p_left", lw=1
272
+ )
273
+ ax_reward_schedule.legend(fontsize=5, ncol=1, loc="upper left", bbox_to_anchor=(0, 1))
274
+
275
+ if not vertical:
276
+ ax_choice_reward.set_yticks([0, 1])
277
+ ax_choice_reward.set_yticklabels(["Left", "Right"])
278
+ ax_choice_reward.legend(fontsize=6, loc="upper left", bbox_to_anchor=(0.6, 1.3), ncol=3)
279
+
280
+ # sns.despine(trim=True, bottom=True, ax=ax_1)
281
+ ax_choice_reward.spines["top"].set_visible(False)
282
+ ax_choice_reward.spines["right"].set_visible(False)
283
+ ax_choice_reward.spines["bottom"].set_visible(False)
284
+ ax_choice_reward.tick_params(labelbottom=False)
285
+ ax_choice_reward.xaxis.set_ticks_position("none")
286
+
287
+ # sns.despine(trim=True, ax=ax_2)
288
+ ax_reward_schedule.set_ylim([0, 1])
289
+ ax_reward_schedule.spines["top"].set_visible(False)
290
+ ax_reward_schedule.spines["right"].set_visible(False)
291
+ ax_reward_schedule.spines["bottom"].set_bounds(0, n_trials)
292
+ ax_reward_schedule.set(xlabel="Trial number")
293
+
294
+ else:
295
+ ax_choice_reward.set_xticks([0, 1])
296
+ ax_choice_reward.set_xticklabels(["Left", "Right"])
297
+ ax_choice_reward.invert_yaxis()
298
+ ax_choice_reward.legend(fontsize=6, loc="upper left", bbox_to_anchor=(0, 1.05), ncol=3)
299
+
300
+ # ax_choice_reward.set_yticks([])
301
+ ax_choice_reward.spines["top"].set_visible(False)
302
+ ax_choice_reward.spines["right"].set_visible(False)
303
+ ax_choice_reward.spines["left"].set_visible(False)
304
+ ax_choice_reward.tick_params(labelleft=False)
305
+ ax_choice_reward.yaxis.set_ticks_position("none")
306
+
307
+ ax_reward_schedule.set_xlim([0, 1])
308
+ ax_reward_schedule.spines["top"].set_visible(False)
309
+ ax_reward_schedule.spines["right"].set_visible(False)
310
+ ax_reward_schedule.spines["left"].set_bounds(0, n_trials)
311
+ ax_reward_schedule.set(ylabel="Trial number")
312
+
313
+ ax.remove()
314
+
315
+ return ax_choice_reward.get_figure(), [ax_choice_reward, ax_reward_schedule]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aind-dynamic-foraging-basic-analysis
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Generated from aind-library-template
5
5
  Author: Allen Institute for Neural Dynamics
6
6
  License: MIT
@@ -9,6 +9,8 @@ Requires-Python: >=3.7
9
9
  Description-Content-Type: text/markdown
10
10
  License-File: LICENSE
11
11
  Requires-Dist: numpy
12
+ Requires-Dist: matplotlib
13
+ Requires-Dist: pydantic
12
14
  Provides-Extra: dev
13
15
  Requires-Dist: aind-dynamic-foraging-basic-analysis; extra == "dev"
14
16
  Requires-Dist: black; extra == "dev"
@@ -24,9 +24,12 @@ src/aind_dynamic_foraging_basic_analysis.egg-info/SOURCES.txt
24
24
  src/aind_dynamic_foraging_basic_analysis.egg-info/dependency_links.txt
25
25
  src/aind_dynamic_foraging_basic_analysis.egg-info/requires.txt
26
26
  src/aind_dynamic_foraging_basic_analysis.egg-info/top_level.txt
27
+ src/aind_dynamic_foraging_basic_analysis/data_model/foraging_session.py
28
+ src/aind_dynamic_foraging_basic_analysis/plot/plot_foraging_session.py
27
29
  tests/__init__.py
28
30
  tests/nwb_io.py
29
31
  tests/test_foraging_efficiency.py
32
+ tests/test_plot_foraging_session.py
30
33
  tests/data/697929_2024-02-22_08-38-30.nwb
31
34
  tests/data/703548_2024-03-01_08-51-32.nwb
32
35
  tests/data/727456_2024-06-12_11-10-53.nwb
@@ -11,7 +11,7 @@ def get_history_from_nwb(nwb_file):
11
11
  nwb = io.read()
12
12
  df_trial = nwb.trials.to_dataframe()
13
13
 
14
- autowater_offered = df_trial.auto_waterL | df_trial.auto_waterR
14
+ autowater_offered = (df_trial.auto_waterL == 1) | (df_trial.auto_waterR == 1)
15
15
  choice_history = df_trial.animal_response.map({0: 0, 1: 1, 2: np.nan}).values
16
16
  reward_history = df_trial.rewarded_historyL | df_trial.rewarded_historyR
17
17
  p_reward = [
@@ -117,16 +117,6 @@ class TestForagingEfficiency(unittest.TestCase):
117
117
  random_number=None,
118
118
  )
119
119
 
120
- # Wrong reward_history values
121
- with self.assertRaises(ValueError):
122
- compute_foraging_efficiency(
123
- baited=True,
124
- choice_history=choice_history,
125
- reward_history=[0, 1, 2],
126
- p_reward=p_reward,
127
- random_number=None,
128
- )
129
-
130
120
  # Wrong autowater_offered shape
131
121
  with self.assertRaises(ValueError):
132
122
  compute_foraging_efficiency(
@@ -137,3 +127,7 @@ class TestForagingEfficiency(unittest.TestCase):
137
127
  autowater_offered=np.array([True, False]),
138
128
  random_number=None,
139
129
  )
130
+
131
+
132
+ if __name__ == "__main__":
133
+ unittest.main()
@@ -0,0 +1,136 @@
1
+ """Test plot foraging session
2
+
3
+ To run the test, execute "python -m unittest tests/test_plot_foraging_session.py".
4
+
5
+ """
6
+
7
+ import os
8
+ import unittest
9
+
10
+ import numpy as np
11
+
12
+ from aind_dynamic_foraging_basic_analysis import plot_foraging_session
13
+ from tests.nwb_io import get_history_from_nwb
14
+
15
+
16
+ class TestPlotSession(unittest.TestCase):
17
+ """Test plot session"""
18
+
19
+ @classmethod
20
+ def setUpClass(cls):
21
+ """Load example session"""
22
+ nwb_file = os.path.dirname(__file__) + "/data/697929_2024-02-22_08-38-30.nwb"
23
+ (
24
+ _,
25
+ cls.choice_history,
26
+ cls.reward_history,
27
+ cls.p_reward,
28
+ cls.autowater_offered,
29
+ _,
30
+ ) = get_history_from_nwb(nwb_file)
31
+
32
+ def test_plot_session(self):
33
+ """Test plot real session"""
34
+ # Add some fake data for testing
35
+ fitted_data = np.ones(len(self.choice_history)) * 0.5
36
+ valid_range = [0, 400]
37
+
38
+ # Plot session
39
+ fig, _ = plot_foraging_session(
40
+ choice_history=list(self.choice_history),
41
+ reward_history=list(self.reward_history),
42
+ p_reward=self.p_reward,
43
+ autowater_offered=self.autowater_offered,
44
+ fitted_data=fitted_data,
45
+ photostim={
46
+ "trial": [10, 20, 30],
47
+ "power": np.array([3.0, 3.0, 3.0]),
48
+ "stim_epoch": ["before go cue", "after iti start", "after go cue"],
49
+ },
50
+ valid_range=valid_range,
51
+ smooth_factor=5,
52
+ base_color="y",
53
+ ax=None,
54
+ vertical=False,
55
+ )
56
+
57
+ # Plot session
58
+ fig, _ = plot_foraging_session(
59
+ choice_history=list(self.choice_history),
60
+ reward_history=list(self.reward_history),
61
+ p_reward=self.p_reward,
62
+ autowater_offered=self.autowater_offered,
63
+ fitted_data=fitted_data,
64
+ photostim={
65
+ "trial": [10, 20, 30],
66
+ "power": np.array([3.0, 3.0, 3.0]), # No stim_epoch
67
+ },
68
+ valid_range=valid_range,
69
+ smooth_factor=5,
70
+ base_color="y",
71
+ ax=None,
72
+ vertical=False,
73
+ )
74
+
75
+ # Save fig
76
+ fig.savefig(
77
+ os.path.dirname(__file__) + "/data/test_plot_session.png",
78
+ bbox_inches="tight",
79
+ )
80
+
81
+ def test_plot_session_vertical(self):
82
+ """Test plotting the same session vertically"""
83
+ # Plot session
84
+ fig, _ = plot_foraging_session(
85
+ choice_history=self.choice_history,
86
+ reward_history=self.reward_history,
87
+ p_reward=self.p_reward,
88
+ autowater_offered=None,
89
+ fitted_data=None,
90
+ photostim=None, # trial, power, s_type
91
+ valid_range=None,
92
+ smooth_factor=5,
93
+ base_color="y",
94
+ ax=None,
95
+ vertical=True,
96
+ )
97
+
98
+ # Save fig
99
+ fig.savefig(
100
+ os.path.dirname(__file__) + "/data/test_plot_session_vertical.png",
101
+ bbox_inches="tight",
102
+ )
103
+
104
+ def test_plot_session_wrong_format(self):
105
+ """Some wrong input format"""
106
+ with self.assertRaises(ValueError):
107
+ plot_foraging_session(
108
+ choice_history=[0, 1, np.nan],
109
+ reward_history=[0, 1, 1],
110
+ p_reward=[[0.5, 0.5, 0.4], [0.5, 0.5, 0.4]],
111
+ fitted_data=[0, 1], # Wrong length
112
+ )
113
+
114
+ with self.assertRaises(ValueError):
115
+ plot_foraging_session(
116
+ choice_history=[0, 1, np.nan],
117
+ reward_history=[0, 1, 1],
118
+ p_reward=[[0.5, 0.5, 0.4], [0.5, 0.5, 0.4]],
119
+ photostim={"trial": [1, 2, 3], "power": [3.0, 3.0]}, # Wrong length
120
+ )
121
+
122
+ with self.assertRaises(ValueError):
123
+ plot_foraging_session(
124
+ choice_history=[0, 1, np.nan],
125
+ reward_history=[0, 1, 1],
126
+ p_reward=[[0.5, 0.5, 0.4], [0.5, 0.5, 0.4]],
127
+ photostim={
128
+ "trial": [1, 2, 3],
129
+ "power": [3.0, 3.0, 5.0],
130
+ "stim_epoch": ["after iti start"],
131
+ }, # Wrong length
132
+ )
133
+
134
+
135
+ if __name__ == "__main__":
136
+ unittest.main()
@@ -1,5 +0,0 @@
1
- """Init package"""
2
-
3
- __version__ = "0.1.0"
4
-
5
- from .foraging_efficiency import compute_foraging_efficiency # noqa: F401