aind-dynamic-foraging-basic-analysis 0.1.0__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.
@@ -0,0 +1,5 @@
1
+ """Init package"""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .foraging_efficiency import compute_foraging_efficiency # noqa: F401
@@ -0,0 +1,209 @@
1
+ """Compute foraging efficiency for baited or non-baited 2-arm bandit task."""
2
+
3
+ from typing import List, Tuple, Union
4
+
5
+ import numpy as np
6
+
7
+
8
+ def compute_foraging_efficiency(
9
+ baited: bool,
10
+ choice_history: Union[List, np.ndarray],
11
+ reward_history: Union[List, np.ndarray],
12
+ p_reward: Union[List, np.ndarray],
13
+ autowater_offered: Union[List, np.ndarray] = None,
14
+ random_number: Union[List, np.ndarray] = None,
15
+ ) -> Tuple[float, float]:
16
+ """Compute foraging efficiency for baited or non-baited 2-arm bandit task.
17
+
18
+ Definition of foraging efficiency (i.e., a single value measurement to quantify "performance")
19
+ is a complex and unsolved topic especially in the context of reward baiting. I have a
20
+ presentation for this (https://alleninstitute.sharepoint.com/:p:/s/NeuralDynamics/EejfBIEvFA
21
+ 5DjmfOZV8atWgBx7q68GsKnavkVrfghL9y8g?e=OnR5r4).
22
+
23
+ Simply speaking, foraging eff = actual reward of the mouse / reward of an optimal_forager in
24
+ the same session. The question is how to define the optimal_forager.
25
+
26
+ 1. For the coupled-block-with-baiting task (Jeremiah's 2019 Neuron paper),
27
+ I assume the optimal_forager knows the underlying reward probability and the baiting dynamics,
28
+ and do the optimal choice pattern ("fix-and-sample" in this case, see references on p.24 of my
29
+ slides).
30
+
31
+ 2. For the non-baiting task (Cooper Grossman), I assume the optimal_forager knows the underlying
32
+ probability and makes the greedy choice, i.e., always choose the better side.
33
+
34
+ This might not be the best way because the optimal_foragers I assumed is kind of cheating
35
+ in the sense that they already know the underlying probability, but it sets an upper bound for
36
+ all realistic agents, at least in an average sense.
37
+
38
+ For a single session, however, there are chances where the efficiency
39
+ can be larger than 1 because of the randomness of the task (sometimes the mice are really
40
+ lucky that they get more reward than performing "optimally"). To **partially** alleviate this
41
+ fluctuation, when the user provides the actual random_number that were generated in that
42
+ session, I calculate the efficiency based on simulating the optimal_forager's performance with
43
+ the same set of random numbers, yielding the foraging_efficiency_actual_random_seed
44
+
45
+ Parameters
46
+ ----------
47
+ baited : bool
48
+ Whether the task is baited or not.
49
+ choice_history : Union[List, np.ndarray]
50
+ Choice history (0 = left choice, 1 = right choice, np.nan = ignored).
51
+ Notes: choice_history allows ignored trials or autowater trials,
52
+ but we'll remove them in the foraging efficiency calculation.
53
+ reward_history : Union[List, np.ndarray]
54
+ Reward history (0 = unrewarded, 1 = rewarded).
55
+ p_reward : Union[List, np.ndarray]
56
+ Reward probability for both sides. The size should be (2, len(choice_history)).
57
+ autowater_offered: Union[List, np.ndarray], optional
58
+ If not None, indicates trials where autowater was offered, which will be excluded from
59
+ the foraging efficiency calculation.
60
+ random_number : Union[List, np.ndarray], optional
61
+ The actual random numbers generated in the session (see above). Must be the same shape as
62
+ reward_probability, by default None.
63
+
64
+ Returns
65
+ -------
66
+ Tuple[float, float]
67
+ foraging_efficiency, foraging_efficiency_actual_random_seed
68
+ """
69
+
70
+ # Choose the optimal_forager function based on baiting
71
+ if baited:
72
+ reward_optimal_func = _reward_optimal_forager_baiting
73
+ else:
74
+ reward_optimal_func = _reward_optimal_forager_no_baiting
75
+
76
+ # 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.")
100
+
101
+ # Foraging_efficiency is calculated only on finished AND non-autowater trials
102
+ ignored = np.isnan(choice_history)
103
+ valid_trials = (~ignored & ~autowater_offered) if autowater_offered is not None else ~ignored
104
+
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
109
+
110
+ # Compute reward of the optimal forager
111
+ reward_optimal, reward_optimal_random_seed = reward_optimal_func(
112
+ p_Ls=p_reward[0],
113
+ p_Rs=p_reward[1],
114
+ random_number_L=(random_number[0] if random_number is not None else None),
115
+ random_number_R=(random_number[1] if random_number is not None else None),
116
+ )
117
+ reward_actual = reward_history.sum()
118
+
119
+ return (
120
+ reward_actual / reward_optimal,
121
+ reward_actual / reward_optimal_random_seed,
122
+ )
123
+
124
+
125
+ def _reward_optimal_forager_no_baiting(p_Ls, p_Rs, random_number_L, random_number_R):
126
+ """Compute the expected reward of the optimal forager for the non-baiting task."""
127
+
128
+ # --- Optimal-aver (use optimal expectation as 100% efficiency) ---
129
+ reward_optimal = np.nanmean(np.max([p_Ls, p_Rs], axis=0)) * len(p_Ls)
130
+
131
+ if random_number_L is None:
132
+ return reward_optimal, np.nan
133
+
134
+ # --- Optimal-actual (uses the actual random numbers by simulation)
135
+ reward_refills = np.vstack([p_Ls >= random_number_L, p_Rs >= random_number_R])
136
+ # Greedy choice, assuming the agent knows the groundtruth
137
+ optimal_choices = np.argmax([p_Ls, p_Rs], axis=0)
138
+ reward_optimal_random_seed = (
139
+ reward_refills[0][optimal_choices == 0].sum()
140
+ + reward_refills[1][optimal_choices == 1].sum()
141
+ )
142
+
143
+ return reward_optimal, reward_optimal_random_seed
144
+
145
+
146
+ def _reward_optimal_forager_baiting(p_Ls, p_Rs, random_number_L, random_number_R):
147
+ """Compute the expected reward of the optimal forager for the baiting task."""
148
+
149
+ # --- Optimal-aver (use optimal expectation as 100% efficiency) ---
150
+ p_stars = np.zeros_like(p_Ls)
151
+ for i, (p_L, p_R) in enumerate(zip(p_Ls, p_Rs)): # Sum over all ps
152
+ p_max = np.max([p_L, p_R])
153
+ p_min = np.min([p_L, p_R])
154
+ if p_min == 0 or p_max >= 1:
155
+ p_stars[i] = p_max
156
+ else:
157
+ m_star = np.floor(np.log(1 - p_max) / np.log(1 - p_min))
158
+ p_stars[i] = p_max + (1 - (1 - p_min) ** (m_star + 1) - p_max**2) / (m_star + 1)
159
+
160
+ reward_optimal = np.nanmean(p_stars) * len(p_Ls)
161
+
162
+ if random_number_L is None:
163
+ return reward_optimal, np.nan
164
+
165
+ # --- Optimal-actual (uses the actual random numbers by simulation)
166
+ block_start_ind_left = np.where(np.diff(np.hstack([np.inf, p_Ls, np.inf])))[0].tolist()
167
+ block_start_ind_right = np.where(np.diff(np.hstack([np.inf, p_Rs, np.inf])))[0].tolist()
168
+ block_start_ind_effective = np.sort(
169
+ np.unique(np.hstack([block_start_ind_left, block_start_ind_right]))
170
+ )
171
+
172
+ reward_refills = [p_Ls >= random_number_L, p_Rs >= random_number_R]
173
+ reward_optimal_random_seed = 0
174
+
175
+ # Generate optimal choice pattern
176
+ for b_start, b_end in zip(block_start_ind_effective[:-1], block_start_ind_effective[1:]):
177
+ p_max = np.max([p_Ls[b_start], p_Rs[b_start]])
178
+ p_min = np.min([p_Ls[b_start], p_Rs[b_start]])
179
+ side_max = np.argmax([p_Ls[b_start], p_Rs[b_start]])
180
+
181
+ # Get optimal choice pattern and expected optimal rate
182
+ if p_min == 0 or p_max >= 1:
183
+ # Greedy is obviously optimal
184
+ this_choice = np.array([1] * (b_end - b_start))
185
+ else:
186
+ m_star = np.floor(np.log(1 - p_max) / np.log(1 - p_min))
187
+ this_choice = np.array(
188
+ (([1] * int(m_star) + [0]) * (1 + int((b_end - b_start) / (m_star + 1))))[
189
+ : b_end - b_start
190
+ ]
191
+ )
192
+
193
+ # Do simulation, using optimal choice pattern and actual random numbers
194
+ reward_refill = np.vstack(
195
+ [
196
+ reward_refills[1 - side_max][b_start:b_end],
197
+ reward_refills[side_max][b_start:b_end],
198
+ ]
199
+ ).astype(
200
+ int
201
+ ) # Max = 1, Min = 0
202
+ reward_remain = [0, 0]
203
+ for t in range(b_end - b_start):
204
+ reward_available = reward_remain | reward_refill[:, t]
205
+ reward_optimal_random_seed += reward_available[this_choice[t]]
206
+ reward_remain = reward_available.copy()
207
+ reward_remain[this_choice[t]] = 0
208
+
209
+ return reward_optimal, (reward_optimal_random_seed if reward_optimal_random_seed else np.nan)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Allen Institute for Neural Dynamics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.1
2
+ Name: aind-dynamic-foraging-basic-analysis
3
+ Version: 0.1.0
4
+ Summary: Generated from aind-library-template
5
+ Author: Allen Institute for Neural Dynamics
6
+ License: MIT
7
+ Classifier: Programming Language :: Python :: 3
8
+ Requires-Python: >=3.7
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: numpy
12
+ Provides-Extra: dev
13
+ Requires-Dist: aind-dynamic-foraging-basic-analysis ; extra == 'dev'
14
+ Requires-Dist: black ; extra == 'dev'
15
+ Requires-Dist: coverage ; extra == 'dev'
16
+ Requires-Dist: flake8 ; extra == 'dev'
17
+ Requires-Dist: interrogate ; extra == 'dev'
18
+ Requires-Dist: isort ; extra == 'dev'
19
+ Requires-Dist: Sphinx ; extra == 'dev'
20
+ Requires-Dist: furo ; extra == 'dev'
21
+ Requires-Dist: pynwb ; extra == 'dev'
22
+
23
+ # aind-dynamic-foraging-basic-analysis
24
+
25
+ [![License](https://img.shields.io/badge/license-MIT-brightgreen)](LICENSE)
26
+ ![Code Style](https://img.shields.io/badge/code%20style-black-black)
27
+ [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
28
+ ![Interrogate](https://img.shields.io/badge/interrogate-100.0%25-brightgreen)
29
+ ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen?logo=codecov)
30
+ ![Python](https://img.shields.io/badge/python->=3.7-blue?logo=python)
31
+
32
+
33
+
34
+ ## Usage
35
+ - To use this template, click the green `Use this template` button and `Create new repository`.
36
+ - After github initially creates the new repository, please wait an extra minute for the initialization scripts to finish organizing the repo.
37
+ - To enable the automatic semantic version increments: in the repository go to `Settings` and `Collaborators and teams`. Click the green `Add people` button. Add `svc-aindscicomp` as an admin. Modify the file in `.github/workflows/tag_and_publish.yml` and remove the if statement in line 10. The semantic version will now be incremented every time a code is committed into the main branch.
38
+ - To publish to PyPI, enable semantic versioning and uncomment the publish block in `.github/workflows/tag_and_publish.yml`. The code will now be published to PyPI every time the code is committed into the main branch.
39
+ - The `.github/workflows/test_and_lint.yml` file will run automated tests and style checks every time a Pull Request is opened. If the checks are undesired, the `test_and_lint.yml` can be deleted. The strictness of the code coverage level, etc., can be modified by altering the configurations in the `pyproject.toml` file and the `.flake8` file.
40
+
41
+ ## Installation
42
+ To use the software, in the root directory, run
43
+ ```bash
44
+ pip install -e .
45
+ ```
46
+
47
+ To develop the code, run
48
+ ```bash
49
+ pip install -e .[dev]
50
+ ```
51
+
52
+ ## Contributing
53
+
54
+ ### Linters and testing
55
+
56
+ There are several libraries used to run linters, check documentation, and run tests.
57
+
58
+ - Please test your changes using the **coverage** library, which will run the tests and log a coverage report:
59
+
60
+ ```bash
61
+ coverage run -m unittest discover && coverage report
62
+ ```
63
+
64
+ - Use **interrogate** to check that modules, methods, etc. have been documented thoroughly:
65
+
66
+ ```bash
67
+ interrogate .
68
+ ```
69
+
70
+ - Use **flake8** to check that code is up to standards (no unused imports, etc.):
71
+ ```bash
72
+ flake8 .
73
+ ```
74
+
75
+ - Use **black** to automatically format the code into PEP standards:
76
+ ```bash
77
+ black .
78
+ ```
79
+
80
+ - Use **isort** to automatically sort import statements:
81
+ ```bash
82
+ isort .
83
+ ```
84
+
85
+ ### Pull requests
86
+
87
+ For internal members, please create a branch. For external members, please fork the repository and open a pull request from the fork. We'll primarily use [Angular](https://github.com/angular/angular/blob/main/CONTRIBUTING.md#commit) style for commit messages. Roughly, they should follow the pattern:
88
+ ```text
89
+ <type>(<scope>): <short summary>
90
+ ```
91
+
92
+ where scope (optional) describes the packages affected by the code changes and type (mandatory) is one of:
93
+
94
+ - **build**: Changes that affect build tools or external dependencies (example scopes: pyproject.toml, setup.py)
95
+ - **ci**: Changes to our CI configuration files and scripts (examples: .github/workflows/ci.yml)
96
+ - **docs**: Documentation only changes
97
+ - **feat**: A new feature
98
+ - **fix**: A bugfix
99
+ - **perf**: A code change that improves performance
100
+ - **refactor**: A code change that neither fixes a bug nor adds a feature
101
+ - **test**: Adding missing tests or correcting existing tests
102
+
103
+ ### Semantic Release
104
+
105
+ The table below, from [semantic release](https://github.com/semantic-release/semantic-release), shows which commit message gets you which release type when `semantic-release` runs (using the default configuration):
106
+
107
+ | Commit message | Release type |
108
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
109
+ | `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release, Default release |
110
+ | `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
111
+ | `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release <br /> (Note that the `BREAKING CHANGE: ` token must be in the footer of the commit) |
112
+
113
+ ### Documentation
114
+ To generate the rst files source files for documentation, run
115
+ ```bash
116
+ sphinx-apidoc -o doc_template/source/ src
117
+ ```
118
+ Then to create the documentation HTML files, run
119
+ ```bash
120
+ sphinx-build -b html doc_template/source/ doc_template/build/html
121
+ ```
122
+ More info on sphinx installation can be found [here](https://www.sphinx-doc.org/en/master/usage/installation.html).
@@ -0,0 +1,7 @@
1
+ aind_dynamic_foraging_basic_analysis/__init__.py,sha256=JBiMfoiXCGlwVCZjH2CXNjDk7jDXB0nKzMXR2ULrn4Y,118
2
+ aind_dynamic_foraging_basic_analysis/foraging_efficiency.py,sha256=GBL8PKhjisb6ALeYTLlLDd5DyfPP_qDrGMg__s3FGxk,9530
3
+ aind_dynamic_foraging_basic_analysis-0.1.0.dist-info/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
4
+ aind_dynamic_foraging_basic_analysis-0.1.0.dist-info/METADATA,sha256=tNAaumni2dAMIkqkb-IadJVdIBQnz-0k4y7H1udUZW8,6521
5
+ aind_dynamic_foraging_basic_analysis-0.1.0.dist-info/WHEEL,sha256=cpQTJ5IWu9CdaPViMhC9YzF8gZuS5-vlfoFihTBC86A,91
6
+ aind_dynamic_foraging_basic_analysis-0.1.0.dist-info/top_level.txt,sha256=gc5fvvd3cR7uvCHkTaSx-TcC4JmKMt9dBYMPncEO8VY,37
7
+ aind_dynamic_foraging_basic_analysis-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (70.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ aind_dynamic_foraging_basic_analysis