dr-datacube 0.1.1__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.
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: dr-datacube
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Access to the Dynamic Routing datacube: consolidated NWB tables as polars LazyFrames, with standard session filters.
|
|
5
|
+
Author: Ben Hardcastle
|
|
6
|
+
Author-email: Ben Hardcastle <ben.hardcastle@alleninstitute.org>
|
|
7
|
+
Requires-Dist: lazynwb>=1.0.0
|
|
8
|
+
Requires-Dist: npc-session>=0.1.41
|
|
9
|
+
Requires-Dist: polars>=1.43.2
|
|
10
|
+
Requires-Dist: pydantic-settings
|
|
11
|
+
Requires-Dist: universal-pathlib
|
|
12
|
+
Requires-Dist: aind-session>=0.3.26 ; extra == 'co'
|
|
13
|
+
Requires-Dist: marimo ; extra == 'nb'
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Project-URL: Repository, https://github.com/AllenNeuralDynamics/dr-datacube
|
|
16
|
+
Project-URL: Issues, https://github.com/AllenNeuralDynamics/dr-datacube/issues
|
|
17
|
+
Provides-Extra: co
|
|
18
|
+
Provides-Extra: nb
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
### Loading data
|
|
24
|
+
|
|
25
|
+
Use `get_lf` to read a consolidated table as a `polars.LazyFrame`; apply `.select(...)` to choose specific columns and
|
|
26
|
+
`.collect()` to materialize as a `DataFrame`.
|
|
27
|
+
|
|
28
|
+
Pass `session_id` to restrict the result to one session. By default, parquet
|
|
29
|
+
results are restricted to behavior-passing brainwide sessions in the published
|
|
30
|
+
datacube session list. Use `session_type` to select `"brainwide"`, `"naive"`, or
|
|
31
|
+
`"templeton"` sessions, pass a collection to select multiple types, or pass
|
|
32
|
+
`session_type=None` and `with_behavior_filter=False` to include all sessions.
|
|
33
|
+
|
|
34
|
+
Pass `nwb=True` to read directly from NWB files. With `session_id`, this reads
|
|
35
|
+
that session's NWB file; without it, it reads all NWB sources available from the
|
|
36
|
+
configured data source.
|
|
37
|
+
|
|
38
|
+
`get_lf("units")` always loads the full units table,
|
|
39
|
+
including spike times, and can be slow. Use `get_lf("unit_metrics")` for the table without spike times and other large array-like columns. The spike-inclusive
|
|
40
|
+
parquet files are only available in the cache; when using the datacube asset,
|
|
41
|
+
`units` is automatically read from NWB.
|
|
42
|
+
|
|
43
|
+
Pass `only_in_data_asset=False` to bypass the published session list, for
|
|
44
|
+
example to load another session available in the cache.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import polars as pl
|
|
48
|
+
from dr_datacube import get_lf
|
|
49
|
+
|
|
50
|
+
performance = get_lf("performance").collect()
|
|
51
|
+
session_units = (
|
|
52
|
+
get_lf("units", session_id="123456_2024-01-01")
|
|
53
|
+
# filter to reduce the number of rows fetched:
|
|
54
|
+
.filter(
|
|
55
|
+
'is_qc_pass',
|
|
56
|
+
pl.col('structure') == 'MOs',
|
|
57
|
+
)
|
|
58
|
+
# drop large columns that aren't needed to save time/memory:
|
|
59
|
+
.drop('spike_amplitudes', 'waveform_mean', 'waveform_std')
|
|
60
|
+
# alternatively, select the columns you need directly:
|
|
61
|
+
.select('spike_times', 'unit_id')
|
|
62
|
+
.collect()
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Load all behavior-passing sessions from multiple standard session sets:
|
|
66
|
+
ephys = get_lf(
|
|
67
|
+
"unit_metrics",
|
|
68
|
+
session_type=["brainwide", "templeton"],
|
|
69
|
+
).collect()
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Use `get_session_table` for the standard session sets. By default it applies
|
|
73
|
+
the behavior filter and keeps only sessions in the configured data asset:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from dr_datacube import get_session_table
|
|
77
|
+
|
|
78
|
+
brainwide = get_session_table(["brainwide", "templeton"])
|
|
79
|
+
all_sessions = get_session_table(None, with_behavior_filter=False)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Datacube session IDs
|
|
83
|
+
A list of standard ephys sets is published in
|
|
84
|
+
[`assets/datacube_sessions.csv`](assets/datacube_sessions.csv). The table contains the session and
|
|
85
|
+
subject IDs, the standard session type (`brainwide`, `naive`, and
|
|
86
|
+
`templeton`), and whether the session passed the relevant behavior filter for its type. The table is generated by
|
|
87
|
+
[`scripts/dump_datacube_sessions.py`](scripts/dump_datacube_sessions.py) and updated automatically in GitHub Actions when changes are made to the filtering logic or the datacube default version (as it requires CO and AWS credentials).
|
|
88
|
+
|
|
89
|
+
Read it directly from GitHub with pandas:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import pandas as pd
|
|
93
|
+
|
|
94
|
+
url = "https://raw.githubusercontent.com/allenneuraldynamics/dr-datacube/main/assets/datacube_sessions.csv"
|
|
95
|
+
session_ids = pd.read_csv(url).query("is_behavior_pass and session_type == 'brainwide'")["session_id"].tolist()
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Or with Polars:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
import polars as pl
|
|
102
|
+
|
|
103
|
+
url = "https://raw.githubusercontent.com/allenneuraldynamics/dr-datacube/main/assets/datacube_sessions.csv"
|
|
104
|
+
session_ids = (
|
|
105
|
+
pl.read_csv(url)
|
|
106
|
+
.filter(pl.col("is_behavior_pass") & (pl.col("session_type") == "brainwide"))["session_id"]
|
|
107
|
+
.to_list()
|
|
108
|
+
)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
This package also provides a convenience function to get the list of session IDs directly:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from dr_datacube import get_session_ids_from_github
|
|
115
|
+
|
|
116
|
+
good_session_ids = get_session_ids_from_github("brainwide")
|
|
117
|
+
all_session_ids = get_session_ids_from_github(["brainwide", "templeton"], with_behavior_filter=False)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
### Data source and configuration
|
|
122
|
+
|
|
123
|
+
The datacube version and data source are controlled by `dr_datacube.config`.
|
|
124
|
+
Set configuration near the top of your script or notebook before loading data:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
import dr_datacube
|
|
128
|
+
|
|
129
|
+
dr_datacube.config.version = "v0.0.301"
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
By default, the package uses a matching local `dynamicrouting_datacube` asset
|
|
133
|
+
when running on Code Ocean. If no matching local asset is available, it streams
|
|
134
|
+
from the datacube asset directory on S3 through fsspec/boto. The S3 asset
|
|
135
|
+
directory is currently private, so credentials are required for this fallback.
|
|
136
|
+
|
|
137
|
+
The main configuration options are:
|
|
138
|
+
|
|
139
|
+
| Option | Effect |
|
|
140
|
+
|---|---|
|
|
141
|
+
| `version` | Select the datacube version. |
|
|
142
|
+
| `use_cache` | Use the public scratch bucket (`aind-scratch-data`) for both NWB files and parquet tables. |
|
|
143
|
+
| `disable_asset_streaming` | Disable streaming the datacube asset through fsspec/boto; a matching asset must be attached locally in Code Ocean. |
|
|
144
|
+
| `anon` | Use anonymous access: AWS credentials are not required and are not used, even if available. |
|
|
145
|
+
| `nwb_only` | Disable access to parquet tables, so reads use NWB data only. |
|
|
146
|
+
|
|
147
|
+
To use the public scratch-bucket cache instead, enable the cache:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
dr_datacube.config.use_cache = True
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
If credentials are not available, enable anonymous access as well:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
dr_datacube.config.anon = True
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Temporary configuration
|
|
160
|
+
|
|
161
|
+
Use `config.override(...)` when an operation needs different settings without
|
|
162
|
+
changing the module-level `config`. The temporary configuration is restored
|
|
163
|
+
when the context exits, even if an exception is raised:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
from dr_datacube import config, get_lf
|
|
167
|
+
|
|
168
|
+
with config.override(use_cache=True):
|
|
169
|
+
units = get_lf("units")
|
|
170
|
+
```
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
### Loading data
|
|
4
|
+
|
|
5
|
+
Use `get_lf` to read a consolidated table as a `polars.LazyFrame`; apply `.select(...)` to choose specific columns and
|
|
6
|
+
`.collect()` to materialize as a `DataFrame`.
|
|
7
|
+
|
|
8
|
+
Pass `session_id` to restrict the result to one session. By default, parquet
|
|
9
|
+
results are restricted to behavior-passing brainwide sessions in the published
|
|
10
|
+
datacube session list. Use `session_type` to select `"brainwide"`, `"naive"`, or
|
|
11
|
+
`"templeton"` sessions, pass a collection to select multiple types, or pass
|
|
12
|
+
`session_type=None` and `with_behavior_filter=False` to include all sessions.
|
|
13
|
+
|
|
14
|
+
Pass `nwb=True` to read directly from NWB files. With `session_id`, this reads
|
|
15
|
+
that session's NWB file; without it, it reads all NWB sources available from the
|
|
16
|
+
configured data source.
|
|
17
|
+
|
|
18
|
+
`get_lf("units")` always loads the full units table,
|
|
19
|
+
including spike times, and can be slow. Use `get_lf("unit_metrics")` for the table without spike times and other large array-like columns. The spike-inclusive
|
|
20
|
+
parquet files are only available in the cache; when using the datacube asset,
|
|
21
|
+
`units` is automatically read from NWB.
|
|
22
|
+
|
|
23
|
+
Pass `only_in_data_asset=False` to bypass the published session list, for
|
|
24
|
+
example to load another session available in the cache.
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
import polars as pl
|
|
28
|
+
from dr_datacube import get_lf
|
|
29
|
+
|
|
30
|
+
performance = get_lf("performance").collect()
|
|
31
|
+
session_units = (
|
|
32
|
+
get_lf("units", session_id="123456_2024-01-01")
|
|
33
|
+
# filter to reduce the number of rows fetched:
|
|
34
|
+
.filter(
|
|
35
|
+
'is_qc_pass',
|
|
36
|
+
pl.col('structure') == 'MOs',
|
|
37
|
+
)
|
|
38
|
+
# drop large columns that aren't needed to save time/memory:
|
|
39
|
+
.drop('spike_amplitudes', 'waveform_mean', 'waveform_std')
|
|
40
|
+
# alternatively, select the columns you need directly:
|
|
41
|
+
.select('spike_times', 'unit_id')
|
|
42
|
+
.collect()
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# Load all behavior-passing sessions from multiple standard session sets:
|
|
46
|
+
ephys = get_lf(
|
|
47
|
+
"unit_metrics",
|
|
48
|
+
session_type=["brainwide", "templeton"],
|
|
49
|
+
).collect()
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Use `get_session_table` for the standard session sets. By default it applies
|
|
53
|
+
the behavior filter and keeps only sessions in the configured data asset:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from dr_datacube import get_session_table
|
|
57
|
+
|
|
58
|
+
brainwide = get_session_table(["brainwide", "templeton"])
|
|
59
|
+
all_sessions = get_session_table(None, with_behavior_filter=False)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Datacube session IDs
|
|
63
|
+
A list of standard ephys sets is published in
|
|
64
|
+
[`assets/datacube_sessions.csv`](assets/datacube_sessions.csv). The table contains the session and
|
|
65
|
+
subject IDs, the standard session type (`brainwide`, `naive`, and
|
|
66
|
+
`templeton`), and whether the session passed the relevant behavior filter for its type. The table is generated by
|
|
67
|
+
[`scripts/dump_datacube_sessions.py`](scripts/dump_datacube_sessions.py) and updated automatically in GitHub Actions when changes are made to the filtering logic or the datacube default version (as it requires CO and AWS credentials).
|
|
68
|
+
|
|
69
|
+
Read it directly from GitHub with pandas:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import pandas as pd
|
|
73
|
+
|
|
74
|
+
url = "https://raw.githubusercontent.com/allenneuraldynamics/dr-datacube/main/assets/datacube_sessions.csv"
|
|
75
|
+
session_ids = pd.read_csv(url).query("is_behavior_pass and session_type == 'brainwide'")["session_id"].tolist()
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Or with Polars:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
import polars as pl
|
|
82
|
+
|
|
83
|
+
url = "https://raw.githubusercontent.com/allenneuraldynamics/dr-datacube/main/assets/datacube_sessions.csv"
|
|
84
|
+
session_ids = (
|
|
85
|
+
pl.read_csv(url)
|
|
86
|
+
.filter(pl.col("is_behavior_pass") & (pl.col("session_type") == "brainwide"))["session_id"]
|
|
87
|
+
.to_list()
|
|
88
|
+
)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
This package also provides a convenience function to get the list of session IDs directly:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from dr_datacube import get_session_ids_from_github
|
|
95
|
+
|
|
96
|
+
good_session_ids = get_session_ids_from_github("brainwide")
|
|
97
|
+
all_session_ids = get_session_ids_from_github(["brainwide", "templeton"], with_behavior_filter=False)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
### Data source and configuration
|
|
102
|
+
|
|
103
|
+
The datacube version and data source are controlled by `dr_datacube.config`.
|
|
104
|
+
Set configuration near the top of your script or notebook before loading data:
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
import dr_datacube
|
|
108
|
+
|
|
109
|
+
dr_datacube.config.version = "v0.0.301"
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
By default, the package uses a matching local `dynamicrouting_datacube` asset
|
|
113
|
+
when running on Code Ocean. If no matching local asset is available, it streams
|
|
114
|
+
from the datacube asset directory on S3 through fsspec/boto. The S3 asset
|
|
115
|
+
directory is currently private, so credentials are required for this fallback.
|
|
116
|
+
|
|
117
|
+
The main configuration options are:
|
|
118
|
+
|
|
119
|
+
| Option | Effect |
|
|
120
|
+
|---|---|
|
|
121
|
+
| `version` | Select the datacube version. |
|
|
122
|
+
| `use_cache` | Use the public scratch bucket (`aind-scratch-data`) for both NWB files and parquet tables. |
|
|
123
|
+
| `disable_asset_streaming` | Disable streaming the datacube asset through fsspec/boto; a matching asset must be attached locally in Code Ocean. |
|
|
124
|
+
| `anon` | Use anonymous access: AWS credentials are not required and are not used, even if available. |
|
|
125
|
+
| `nwb_only` | Disable access to parquet tables, so reads use NWB data only. |
|
|
126
|
+
|
|
127
|
+
To use the public scratch-bucket cache instead, enable the cache:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
dr_datacube.config.use_cache = True
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
If credentials are not available, enable anonymous access as well:
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
dr_datacube.config.anon = True
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Temporary configuration
|
|
140
|
+
|
|
141
|
+
Use `config.override(...)` when an operation needs different settings without
|
|
142
|
+
changing the module-level `config`. The temporary configuration is restored
|
|
143
|
+
when the context exits, even if an exception is raised:
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from dr_datacube import config, get_lf
|
|
147
|
+
|
|
148
|
+
with config.override(use_cache=True):
|
|
149
|
+
units = get_lf("units")
|
|
150
|
+
```
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "dr-datacube"
|
|
3
|
+
version = "0.1.1"
|
|
4
|
+
description = "Access to the Dynamic Routing datacube: consolidated NWB tables as polars LazyFrames, with standard session filters."
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "Ben Hardcastle", email = "ben.hardcastle@alleninstitute.org" },
|
|
7
|
+
]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.10"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"lazynwb>=1.0.0",
|
|
12
|
+
"npc-session>=0.1.41",
|
|
13
|
+
"polars>=1.43.2",
|
|
14
|
+
"pydantic-settings",
|
|
15
|
+
"universal-pathlib",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
co = ["aind-session>=0.3.26"]
|
|
20
|
+
nb = ["marimo"]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Repository = "https://github.com/AllenNeuralDynamics/dr-datacube"
|
|
24
|
+
Issues = "https://github.com/AllenNeuralDynamics/dr-datacube/issues"
|
|
25
|
+
|
|
26
|
+
[dependency-groups]
|
|
27
|
+
task_runner = ["poethepoet>=0.33.1"]
|
|
28
|
+
bump = ["bump-my-version>=1.1.1"]
|
|
29
|
+
|
|
30
|
+
[tool.uv]
|
|
31
|
+
package = true
|
|
32
|
+
default-groups = ["task_runner", "bump"]
|
|
33
|
+
|
|
34
|
+
[tool.bumpversion]
|
|
35
|
+
tag = true
|
|
36
|
+
allow_dirty = true
|
|
37
|
+
commit = true
|
|
38
|
+
commit_args = "-a"
|
|
39
|
+
message = "Bump version: {current_version} → {new_version} [skip actions]"
|
|
40
|
+
pre_commit_hooks = [
|
|
41
|
+
"uv lock --upgrade-package dr-datacube",
|
|
42
|
+
"uv build",
|
|
43
|
+
"uv publish",
|
|
44
|
+
]
|
|
45
|
+
post_commit_hooks = [
|
|
46
|
+
"git push origin main",
|
|
47
|
+
"git push --tags",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
[[tool.bumpversion.files]]
|
|
51
|
+
filename = "pyproject.toml"
|
|
52
|
+
search = 'version = "{current_version}"'
|
|
53
|
+
replace = 'version = "{new_version}"'
|
|
54
|
+
|
|
55
|
+
[tool.poe.tasks]
|
|
56
|
+
test = "python -m unittest discover -s tests -v"
|
|
57
|
+
bump_pub_tag = "bump-my-version bump patch"
|
|
58
|
+
release = ["bump_pub_tag"]
|
|
59
|
+
|
|
60
|
+
[build-system]
|
|
61
|
+
requires = ["uv_build>=0.10.7,<0.11.0"]
|
|
62
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from collections.abc import Callable, Collection, Iterable
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
import lazynwb
|
|
6
|
+
import npc_session
|
|
7
|
+
import polars as pl
|
|
8
|
+
from polars._typing import FrameType
|
|
9
|
+
|
|
10
|
+
from .settings import _get_config
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
SessionType = Literal["brainwide", "naive", "templeton"]
|
|
15
|
+
_GITHUB_SESSION_TABLE_URL = (
|
|
16
|
+
"https://raw.githubusercontent.com/AllenNeuralDynamics/dr-datacube/main/assets/datacube_sessions.csv"
|
|
17
|
+
)
|
|
18
|
+
_GITHUB_SESSION_TABLE: pl.DataFrame | None = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _behavior_summary(block_dprime_threshold: float = 1.0) -> pl.DataFrame:
|
|
22
|
+
logger.info("Building behavior summary from get_lf('performance')")
|
|
23
|
+
return (
|
|
24
|
+
get_lf("performance", session_type=None, with_behavior_filter=False, only_in_data_asset=False)
|
|
25
|
+
.with_columns(
|
|
26
|
+
pl.col("n_contingent_rewards").ge(10).alias("is_engaged_block"),
|
|
27
|
+
pl.col("cross_modality_dprime").ge(block_dprime_threshold).alias("is_good_block"),
|
|
28
|
+
)
|
|
29
|
+
.with_columns(
|
|
30
|
+
(pl.col("is_good_block") & pl.col("is_engaged_block")).alias("is_good_engaged_block"),
|
|
31
|
+
)
|
|
32
|
+
.group_by("session_id", "rewarded_modality")
|
|
33
|
+
.agg(
|
|
34
|
+
"is_engaged_block",
|
|
35
|
+
"is_good_block",
|
|
36
|
+
"is_good_engaged_block",
|
|
37
|
+
pl.col("is_engaged_block", "is_good_block", "is_good_engaged_block")
|
|
38
|
+
.sum()
|
|
39
|
+
.name.replace("is_", "n_")
|
|
40
|
+
.name.suffix("s"),
|
|
41
|
+
)
|
|
42
|
+
.group_by("session_id")
|
|
43
|
+
.agg(
|
|
44
|
+
pl.col("n_engaged_blocks").sum(),
|
|
45
|
+
pl.col("n_good_blocks").sum(),
|
|
46
|
+
pl.col("n_good_engaged_blocks").sum(),
|
|
47
|
+
pl.col("n_good_blocks").filter(pl.col("rewarded_modality") == "vis").first().alias("n_good_vis_blocks"),
|
|
48
|
+
pl.col("n_good_blocks").filter(pl.col("rewarded_modality") == "aud").first().alias("n_good_aud_blocks"),
|
|
49
|
+
pl.col("n_good_engaged_blocks")
|
|
50
|
+
.filter(pl.col("rewarded_modality") == "vis")
|
|
51
|
+
.first()
|
|
52
|
+
.alias("n_good_engaged_vis_blocks"),
|
|
53
|
+
pl.col("n_good_engaged_blocks")
|
|
54
|
+
.filter(pl.col("rewarded_modality") == "aud")
|
|
55
|
+
.first()
|
|
56
|
+
.alias("n_good_engaged_aud_blocks"),
|
|
57
|
+
)
|
|
58
|
+
).collect()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _session_ids_with_trials() -> list[str]:
|
|
62
|
+
"""Return the IDs of sessions that have rows in the task ``trials`` table.
|
|
63
|
+
|
|
64
|
+
A session can be written as a valid NWB without task trials (for example when its
|
|
65
|
+
task block fails a timing-validity check), whatever its ``keywords`` say: the ``task``
|
|
66
|
+
keyword can also come from an epoch tag. Presence in the trials table is the ground
|
|
67
|
+
truth for "has task trials".
|
|
68
|
+
"""
|
|
69
|
+
logger.info("Finding sessions with task trials from get_lf('trials')")
|
|
70
|
+
return (
|
|
71
|
+
get_lf("trials", session_type=None, with_behavior_filter=False, only_in_data_asset=False)
|
|
72
|
+
.select("session_id")
|
|
73
|
+
.unique()
|
|
74
|
+
.collect()["session_id"]
|
|
75
|
+
.sort()
|
|
76
|
+
.to_list()
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _brainwide_ephys_filter(with_behavior_filter: bool = True) -> pl.Expr:
|
|
81
|
+
logger.info("Building brainwide session filter (with_behavior_filter=%s)", with_behavior_filter)
|
|
82
|
+
required = (
|
|
83
|
+
"prod",
|
|
84
|
+
"brainwide_survey",
|
|
85
|
+
"task",
|
|
86
|
+
"ephys",
|
|
87
|
+
"ccf",
|
|
88
|
+
) # behavior is filtered via performance table below, not the `good_behavior` keyword
|
|
89
|
+
excluded = (
|
|
90
|
+
"issues",
|
|
91
|
+
"context_naive",
|
|
92
|
+
) # mutually exclusive with brainwide_survey from >=v0.0.290 (keyword was "context naive" before)
|
|
93
|
+
if with_behavior_filter:
|
|
94
|
+
good_behavior_session_ids = (
|
|
95
|
+
_behavior_summary(block_dprime_threshold=1.0).filter(
|
|
96
|
+
pl.col("n_good_engaged_aud_blocks").ge(2),
|
|
97
|
+
pl.col("n_good_engaged_vis_blocks").ge(2),
|
|
98
|
+
)
|
|
99
|
+
)["session_id"].to_list()
|
|
100
|
+
else:
|
|
101
|
+
good_behavior_session_ids = []
|
|
102
|
+
return pl.all_horizontal(
|
|
103
|
+
*[pl.col("keywords").list.contains(keyword) for keyword in required],
|
|
104
|
+
*[~pl.col("keywords").list.contains(keyword) for keyword in excluded],
|
|
105
|
+
pl.col("session_id").is_in(good_behavior_session_ids) if with_behavior_filter else pl.lit(True),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _naive_ephys_filter(with_behavior_filter: bool = True) -> pl.Expr:
|
|
110
|
+
logger.info("Building naive session filter (with_behavior_filter=%s)", with_behavior_filter)
|
|
111
|
+
# "prod" is deliberately not required: 676909 context-naive sessions are production-quality
|
|
112
|
+
# but tracked as is_production=False (one-off), see npc_lims tracked_sessions.yaml
|
|
113
|
+
required = ("dynamic_routing", "task", "ephys", "ccf", "context_naive")
|
|
114
|
+
# "context naive" (with space) keyword was replaced by "context_naive" in >=v0.0.290
|
|
115
|
+
excluded = ("issues", "templeton", "brainwide_survey")
|
|
116
|
+
if with_behavior_filter:
|
|
117
|
+
engaged_session_ids = (
|
|
118
|
+
_behavior_summary().filter(
|
|
119
|
+
pl.col("n_engaged_blocks").ge(4),
|
|
120
|
+
)
|
|
121
|
+
)["session_id"].to_list()
|
|
122
|
+
else:
|
|
123
|
+
engaged_session_ids = []
|
|
124
|
+
return pl.all_horizontal(
|
|
125
|
+
*[pl.col("keywords").list.contains(keyword) for keyword in required],
|
|
126
|
+
*[~pl.col("keywords").list.contains(keyword) for keyword in excluded],
|
|
127
|
+
pl.col("session_id").is_in(engaged_session_ids) if with_behavior_filter else pl.lit(True),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _templeton_ephys_filter(with_behavior_filter: bool = True) -> pl.Expr:
|
|
132
|
+
logger.info("Building Templeton session filter (with_behavior_filter=%s)", with_behavior_filter)
|
|
133
|
+
required = ("prod", "templeton", "task", "ephys", "ccf")
|
|
134
|
+
excluded = ("issues",)
|
|
135
|
+
if with_behavior_filter:
|
|
136
|
+
good_behavior_session_ids = (
|
|
137
|
+
(
|
|
138
|
+
get_lf("performance", session_type=None, with_behavior_filter=False, only_in_data_asset=False).filter(
|
|
139
|
+
pl.col("cross_modality_dprime").is_null(),
|
|
140
|
+
pl.col("aud_dprime").ge(1.0) | pl.col("vis_dprime").ge(1.0),
|
|
141
|
+
)
|
|
142
|
+
)
|
|
143
|
+
.collect()["session_id"]
|
|
144
|
+
.to_list()
|
|
145
|
+
)
|
|
146
|
+
else:
|
|
147
|
+
good_behavior_session_ids = []
|
|
148
|
+
return pl.all_horizontal(
|
|
149
|
+
*[pl.col("keywords").list.contains(keyword) for keyword in required],
|
|
150
|
+
*[~pl.col("keywords").list.contains(keyword) for keyword in excluded],
|
|
151
|
+
pl.col("session_id").is_in(good_behavior_session_ids) if with_behavior_filter else pl.lit(True),
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def filter_functions() -> dict[str, Callable[[bool], pl.Expr]]:
|
|
156
|
+
"""Return filter functions keyed by session type."""
|
|
157
|
+
return {
|
|
158
|
+
"brainwide": _brainwide_ephys_filter,
|
|
159
|
+
"naive": _naive_ephys_filter,
|
|
160
|
+
"templeton": _templeton_ephys_filter,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def get_session_table(
|
|
165
|
+
session_type: SessionType | Collection[SessionType] | None = None,
|
|
166
|
+
with_behavior_filter: bool = True,
|
|
167
|
+
only_in_data_asset: bool = True,
|
|
168
|
+
) -> pl.DataFrame:
|
|
169
|
+
"""Return sessions and their standard session-set classifications.
|
|
170
|
+
|
|
171
|
+
``session_type`` selects brainwide, naive, or Templeton sessions. Passing
|
|
172
|
+
``None`` returns every session in the datacube. Sessions without task trials
|
|
173
|
+
are never returned, whatever their keywords. When
|
|
174
|
+
``with_behavior_filter`` is true, each session type's standard behavioral
|
|
175
|
+
filter is applied. When ``only_in_data_asset`` is true, only sessions in the
|
|
176
|
+
configured Code Ocean data asset are returned.
|
|
177
|
+
"""
|
|
178
|
+
config = _get_config()
|
|
179
|
+
logger.info(
|
|
180
|
+
"Loading session table (session_type=%s, with_behavior_filter=%s, only_in_data_asset=%s) via get_lf('session')",
|
|
181
|
+
session_type,
|
|
182
|
+
with_behavior_filter,
|
|
183
|
+
only_in_data_asset,
|
|
184
|
+
)
|
|
185
|
+
session_expr = (
|
|
186
|
+
pl.lit(True)
|
|
187
|
+
if session_type is None
|
|
188
|
+
else (
|
|
189
|
+
pl.col("session_type").is_in(session_type)
|
|
190
|
+
if not isinstance(session_type, str)
|
|
191
|
+
else pl.col("session_type").eq(session_type)
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
filtered = (
|
|
195
|
+
# Bypass the published GitHub catalog: it is generated from this function, so
|
|
196
|
+
# using it here would drop sessions that are new in the configured data asset.
|
|
197
|
+
get_lf("session", session_type=None, with_behavior_filter=False, only_in_data_asset=False)
|
|
198
|
+
.select("session_id", "subject_id", "keywords")
|
|
199
|
+
# Sessions without task trials don't belong in the datacube. Don't rely on the
|
|
200
|
+
# `task` keyword alone for this: require rows in the trials table.
|
|
201
|
+
.filter(pl.col("session_id").is_in(_session_ids_with_trials()))
|
|
202
|
+
.with_columns(
|
|
203
|
+
session_type=pl.coalesce(
|
|
204
|
+
*(
|
|
205
|
+
pl.when(func(with_behavior_filter=with_behavior_filter)).then(pl.lit(name))
|
|
206
|
+
for name, func in filter_functions().items()
|
|
207
|
+
)
|
|
208
|
+
)
|
|
209
|
+
)
|
|
210
|
+
.with_columns(
|
|
211
|
+
is_behavior_pass=(
|
|
212
|
+
pl.when(pl.col("session_type").eq("brainwide"))
|
|
213
|
+
.then(filter_functions()["brainwide"](with_behavior_filter=True))
|
|
214
|
+
.when(pl.col("session_type").eq("naive"))
|
|
215
|
+
.then(filter_functions()["naive"](with_behavior_filter=True))
|
|
216
|
+
.when(pl.col("session_type").eq("templeton"))
|
|
217
|
+
.then(filter_functions()["templeton"](with_behavior_filter=True))
|
|
218
|
+
.when(pl.col("session_type").is_not_null())
|
|
219
|
+
.then(pl.lit(False))
|
|
220
|
+
)
|
|
221
|
+
)
|
|
222
|
+
.filter(session_expr)
|
|
223
|
+
.join(_behavior_summary().lazy(), on="session_id", how="left")
|
|
224
|
+
.collect()
|
|
225
|
+
)
|
|
226
|
+
if only_in_data_asset:
|
|
227
|
+
logger.info("Filtering session table against session_table.parquet in configured data asset")
|
|
228
|
+
session_ids_in_data_asset = (
|
|
229
|
+
pl.read_parquet((config.asset_dir / "session_table.parquet").as_posix(), columns=["session_id"])[
|
|
230
|
+
"session_id"
|
|
231
|
+
]
|
|
232
|
+
.sort()
|
|
233
|
+
.to_list()
|
|
234
|
+
)
|
|
235
|
+
filtered = filtered.filter(pl.col("session_id").is_in(session_ids_in_data_asset))
|
|
236
|
+
return filtered
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def get_session_ids_from_github(
|
|
240
|
+
session_type: SessionType | Collection[SessionType] | None = "brainwide",
|
|
241
|
+
with_behavior_filter: bool = True,
|
|
242
|
+
) -> list[str]:
|
|
243
|
+
"""Return session IDs from the published table without requiring Code Ocean credentials.
|
|
244
|
+
|
|
245
|
+
The published table is cached in memory for the lifetime of the Python process.
|
|
246
|
+
"""
|
|
247
|
+
global _GITHUB_SESSION_TABLE
|
|
248
|
+
if _GITHUB_SESSION_TABLE is None:
|
|
249
|
+
logger.info("Loading session catalog from GitHub: %s", _GITHUB_SESSION_TABLE_URL)
|
|
250
|
+
_GITHUB_SESSION_TABLE = pl.read_csv(_GITHUB_SESSION_TABLE_URL)
|
|
251
|
+
else:
|
|
252
|
+
logger.debug("Using cached session catalog loaded from GitHub")
|
|
253
|
+
|
|
254
|
+
if session_type is None:
|
|
255
|
+
filter_expr = pl.lit(True)
|
|
256
|
+
else:
|
|
257
|
+
filter_expr = (
|
|
258
|
+
pl.col("session_type").is_in(session_type)
|
|
259
|
+
if not isinstance(session_type, str)
|
|
260
|
+
else pl.col("session_type").eq(session_type)
|
|
261
|
+
)
|
|
262
|
+
if with_behavior_filter:
|
|
263
|
+
filter_expr = filter_expr & pl.col("is_behavior_pass")
|
|
264
|
+
return _GITHUB_SESSION_TABLE.filter(filter_expr)["session_id"].sort().to_list()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def get_lf(
|
|
268
|
+
name: str,
|
|
269
|
+
session_id: str | None = None,
|
|
270
|
+
nwb: bool | None = None,
|
|
271
|
+
session_type: SessionType | Collection[SessionType] | None = "brainwide",
|
|
272
|
+
with_behavior_filter: bool = True,
|
|
273
|
+
only_in_data_asset: bool = True,
|
|
274
|
+
**scan_args,
|
|
275
|
+
) -> pl.LazyFrame:
|
|
276
|
+
"""Return a lazily scanned table, from parquet or NWB.
|
|
277
|
+
|
|
278
|
+
``units`` always refers to the full table, including spike times and other
|
|
279
|
+
large array-like columns. Use ``unit_metrics`` for the smaller consolidated
|
|
280
|
+
parquet table without spike times. Set ``only_in_data_asset=False`` to
|
|
281
|
+
bypass the published session list, for example when loading another session
|
|
282
|
+
that is present in the cache.
|
|
283
|
+
"""
|
|
284
|
+
|
|
285
|
+
config = _get_config()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
if only_in_data_asset:
|
|
289
|
+
logger.info("get_lf(%s): restricting sessions to the published GitHub session catalog", name)
|
|
290
|
+
session_ids = get_session_ids_from_github(session_type, with_behavior_filter)
|
|
291
|
+
else:
|
|
292
|
+
logger.info("get_lf(%s): bypassing the published session catalog", name)
|
|
293
|
+
session_ids = []
|
|
294
|
+
if session_id:
|
|
295
|
+
session_id = npc_session.extract_session_id(session_id)
|
|
296
|
+
if session_id not in session_ids and only_in_data_asset:
|
|
297
|
+
raise ValueError(f"{session_id} is not in the session list ({session_type=}, {with_behavior_filter=}).")
|
|
298
|
+
session_ids = [session_id]
|
|
299
|
+
|
|
300
|
+
session_filter = pl.col("session_id").is_in(session_ids) if session_ids else pl.lit(True)
|
|
301
|
+
if name == "units" and not nwb and not config.use_cache:
|
|
302
|
+
logger.warning("Full units parquet files are not available in the datacube asset; fetching from NWB.")
|
|
303
|
+
nwb = True
|
|
304
|
+
|
|
305
|
+
if name == "units" and nwb:
|
|
306
|
+
logger.warning(
|
|
307
|
+
"Fetching `units` includes spike times and can be slow. "
|
|
308
|
+
"Setting `infer_schema_length=1` for faster inference: set it to `None` to disable this optimization.\n"
|
|
309
|
+
"Use `get_lf('unit_metrics')` for the consolidated units table without spike times."
|
|
310
|
+
)
|
|
311
|
+
scan_args.setdefault("infer_schema_length", 1)
|
|
312
|
+
|
|
313
|
+
if nwb is not True and not config.nwb_only:
|
|
314
|
+
storage_options = config.storage_options | scan_args.pop("storage_options", {})
|
|
315
|
+
if name == "units":
|
|
316
|
+
path = (
|
|
317
|
+
config.parquet_dir.parent
|
|
318
|
+
/ "units"
|
|
319
|
+
/ (f"{session_id}.parquet" if session_id is not None else "*.parquet")
|
|
320
|
+
)
|
|
321
|
+
logger.info(f"Fetching full units table from parquet at {path.as_posix()}")
|
|
322
|
+
elif name == "unit_metrics":
|
|
323
|
+
path = config.parquet_dir / "units.parquet"
|
|
324
|
+
logger.info("Fetching unit_metrics from consolidated parquet at %s", path)
|
|
325
|
+
else:
|
|
326
|
+
path = config.parquet_dir / f"{name}.parquet"
|
|
327
|
+
logger.info("Fetching %s from consolidated parquet at %s", name, path)
|
|
328
|
+
if path.exists():
|
|
329
|
+
logger.info("Using parquet data source for %s: %s", name, path)
|
|
330
|
+
return (
|
|
331
|
+
pl.scan_parquet(
|
|
332
|
+
path.as_posix(),
|
|
333
|
+
storage_options=storage_options,
|
|
334
|
+
**scan_args,
|
|
335
|
+
)
|
|
336
|
+
.pipe(_ensure_id_cols)
|
|
337
|
+
.filter(session_filter)
|
|
338
|
+
)
|
|
339
|
+
logger.info("Parquet data source for %s does not exist at %s; attempting NWB", name, path)
|
|
340
|
+
elif config.nwb_only:
|
|
341
|
+
logger.info("Parquet access disabled by config.nwb_only=True; using NWB for %s", name)
|
|
342
|
+
else:
|
|
343
|
+
logger.info("NWB explicitly requested for %s; skipping parquet", name)
|
|
344
|
+
requested_name = name
|
|
345
|
+
name = _name_to_nwb_internal_path(name)
|
|
346
|
+
sources = list_nwb_sources(session_ids)
|
|
347
|
+
if not sources:
|
|
348
|
+
raise ValueError(
|
|
349
|
+
f"No NWB sources found for session_ids: {session_ids} ({session_type=}, {with_behavior_filter=})."
|
|
350
|
+
)
|
|
351
|
+
logger.info("Using NWB data source for %s (%s): %d files from %s", requested_name, name, len(sources), config.nwb_dir)
|
|
352
|
+
lf = lazynwb.scan_nwb(sources, name, **scan_args).pipe(_ensure_id_cols)
|
|
353
|
+
if requested_name == "unit_metrics":
|
|
354
|
+
lf = lf.drop("spike_times", "spike_amplitudes", "waveform_mean", "waveform_std", strict=False)
|
|
355
|
+
return lf
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _name_to_nwb_internal_path(name: str) -> str:
|
|
359
|
+
if any(
|
|
360
|
+
name.startswith(prefix)
|
|
361
|
+
for prefix in ("performance", "optotagging", "rf_mapping", "aud_rf_mapping", "vis_rf_mapping", "epochs")
|
|
362
|
+
):
|
|
363
|
+
name = f"intervals/{name}"
|
|
364
|
+
if any(name.endswith(suffix) for suffix in ("optotagging", "rf_mapping")):
|
|
365
|
+
name += "_trials"
|
|
366
|
+
if name.startswith("frametimes"):
|
|
367
|
+
name = f"acquisition/{name}"
|
|
368
|
+
if name in (
|
|
369
|
+
"dlc_eye_camera",
|
|
370
|
+
"eye_tracking",
|
|
371
|
+
"facemap_front_camera",
|
|
372
|
+
"facemap_side_camera",
|
|
373
|
+
"lp_front_camera",
|
|
374
|
+
"lp_side_camera",
|
|
375
|
+
"licks",
|
|
376
|
+
"running_speed",
|
|
377
|
+
"rewards",
|
|
378
|
+
"quiescent_interval_violations",
|
|
379
|
+
):
|
|
380
|
+
name = f"processing/behavior/{name}"
|
|
381
|
+
if name == "electrodes":
|
|
382
|
+
name = "general/extracellular_ephys/electrodes"
|
|
383
|
+
if name == "unit_metrics":
|
|
384
|
+
name = "units"
|
|
385
|
+
return name
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def list_nwb_sources(session_id: str | Iterable[str] | None = None) -> tuple[str, ...]:
|
|
389
|
+
"""Get all file URIs from data asset(s) or from scratch bucket cache, depending on current config."""
|
|
390
|
+
config = _get_config()
|
|
391
|
+
logger.info(
|
|
392
|
+
"Searching for NWB data in %s (%s)",
|
|
393
|
+
config.nwb_dir,
|
|
394
|
+
"scratch cache" if config.use_cache else "configured data asset",
|
|
395
|
+
)
|
|
396
|
+
available_sources = config.nwb_dir.glob("*.nwb*")
|
|
397
|
+
if session_id:
|
|
398
|
+
session_ids = [session_id] if isinstance(session_id, str) else list(session_id)
|
|
399
|
+
else:
|
|
400
|
+
session_ids = []
|
|
401
|
+
if session_ids:
|
|
402
|
+
sources = sorted(path.as_posix() for path in available_sources if path.stem in session_ids)
|
|
403
|
+
else:
|
|
404
|
+
sources = sorted(path.as_posix() for path in available_sources)
|
|
405
|
+
logger.info(f"Found {len(sources)} NWB sources in {config.nwb_dir}")
|
|
406
|
+
return tuple(sources)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _ensure_id_cols(df: FrameType) -> FrameType:
|
|
410
|
+
schema = df.lazy().collect_schema() # works if we pass a dataframe or lazyframe
|
|
411
|
+
if "session_id" in schema and "subject_id" in schema:
|
|
412
|
+
logger.debug("DataFrame already has a `session_id` and `subject_id` columns, skipping parsing from `_nwb_path`")
|
|
413
|
+
return df
|
|
414
|
+
if "_nwb_path" not in schema and "session_id" not in schema:
|
|
415
|
+
raise ValueError("Attempted to parse `session_id` from `_nwb_path` column, which doesn't exist in dataframe")
|
|
416
|
+
if "session_id" not in schema:
|
|
417
|
+
df = df.with_columns(
|
|
418
|
+
pl.col("_nwb_path").str.split("/").list.get(-1).str.split(".").list.get(0).alias("session_id")
|
|
419
|
+
)
|
|
420
|
+
if "subject_id" not in schema:
|
|
421
|
+
df = df.with_columns(pl.col("session_id").str.split("_").list.get(0).alias("subject_id"))
|
|
422
|
+
return df
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import functools
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from contextvars import ContextVar
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import lazynwb
|
|
11
|
+
import pydantic
|
|
12
|
+
import pydantic_settings
|
|
13
|
+
import upath
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
def _pipeline_data_dir() -> upath.UPath:
|
|
19
|
+
return upath.UPath("/tmp/data")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _capsule_data_dir() -> upath.UPath:
|
|
23
|
+
return upath.UPath("/root/capsule/data")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@functools.cache
|
|
27
|
+
def on_codeocean() -> bool:
|
|
28
|
+
with contextlib.suppress(Exception):
|
|
29
|
+
return _capsule_data_dir().exists() or is_pipeline()
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@functools.cache
|
|
34
|
+
def is_pipeline() -> bool:
|
|
35
|
+
with contextlib.suppress(Exception):
|
|
36
|
+
return _pipeline_data_dir().exists() and bool(os.environ.get("AWS_BATCH_JOB_ID"))
|
|
37
|
+
return False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class DatacubeConfig(pydantic_settings.BaseSettings):
|
|
41
|
+
model_config = pydantic_settings.SettingsConfigDict(
|
|
42
|
+
env_prefix="DR_DATACUBE_",
|
|
43
|
+
validate_assignment=True,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
version: str = "v0.0.301"
|
|
47
|
+
disable_asset_streaming: bool = False
|
|
48
|
+
use_cache: bool = False
|
|
49
|
+
nwb_only: bool = False
|
|
50
|
+
anon: bool = False
|
|
51
|
+
storage_options: dict = pydantic.Field(default_factory=lambda: {"region": "us-west-2"})
|
|
52
|
+
|
|
53
|
+
@pydantic.field_validator("version")
|
|
54
|
+
@classmethod
|
|
55
|
+
def ensure_version_prefix(cls, value: str) -> str:
|
|
56
|
+
return value if value.startswith("v") else f"v{value}"
|
|
57
|
+
|
|
58
|
+
@pydantic.model_validator(mode="after")
|
|
59
|
+
def set_anonymous_storage_options(self) -> "DatacubeConfig":
|
|
60
|
+
if self.anon:
|
|
61
|
+
self.storage_options["skip_signature"] = "true"
|
|
62
|
+
else:
|
|
63
|
+
self.storage_options.pop("skip_signature", None)
|
|
64
|
+
return self
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def s3_cache_dir(self) -> upath.UPath:
|
|
68
|
+
return upath.UPath("s3://aind-scratch-data/dynamic-routing/cache", anon=self.anon)
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def asset_dir(self) -> upath.UPath:
|
|
72
|
+
if on_codeocean():
|
|
73
|
+
logger.info(
|
|
74
|
+
"Resolving datacube asset for config version=%s from local Code Ocean data directories",
|
|
75
|
+
self.version,
|
|
76
|
+
)
|
|
77
|
+
data_dir = _pipeline_data_dir() if is_pipeline() else _capsule_data_dir()
|
|
78
|
+
datacube_dir = tuple(data_dir.glob("dynamicrouting_datacube*"))
|
|
79
|
+
if not datacube_dir:
|
|
80
|
+
logger.warning(f"Could not find dynamicrouting_datacube data asset in {data_dir}")
|
|
81
|
+
elif len(datacube_dir) > 1:
|
|
82
|
+
choice = next(
|
|
83
|
+
(d for d in datacube_dir if _asset_name_has_version(d.name, self.version)),
|
|
84
|
+
None,
|
|
85
|
+
)
|
|
86
|
+
if choice is not None:
|
|
87
|
+
logger.warning(
|
|
88
|
+
f"Found multiple dynamicrouting_datacube data assets in {data_dir}, using: {choice} (set `dr_datacube.config.version` to change)"
|
|
89
|
+
)
|
|
90
|
+
return choice
|
|
91
|
+
logger.warning(
|
|
92
|
+
f"Found multiple dynamicrouting_datacube data assets in {data_dir}, but none match the requested version {self.version}. Set `dr_datacube.config.version` to match an available local asset to use it."
|
|
93
|
+
)
|
|
94
|
+
logger.warning("Falling back to streaming assets from S3.")
|
|
95
|
+
elif _asset_name_has_version(datacube_dir[0].name, self.version):
|
|
96
|
+
logger.info("Using local datacube data asset: %s", datacube_dir[0])
|
|
97
|
+
return datacube_dir[0]
|
|
98
|
+
else:
|
|
99
|
+
logger.warning(
|
|
100
|
+
f"Found dynamicrouting_datacube data asset in {data_dir}, but it does not match the requested version {self.version}. Set `dr_datacube.config.version` to match an available local asset to use it."
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
if self.disable_asset_streaming:
|
|
104
|
+
raise FileNotFoundError(
|
|
105
|
+
f"No local data asset matching {self.version} is attached and streaming has been disabled. Set `dr_datacube.config.version` to match an available local asset or set `dr_datacube.config.disable_asset_streaming` to False."
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
# To avoid dependencies, hardcode S3 paths for well-known assets.
|
|
109
|
+
asset_paths = {
|
|
110
|
+
"v0.0.272": "s3://codeocean-s3datasetsbucket-1u41qdg42ur9/bfaffa07-a179-4f02-9724-4e51451d8ba6",
|
|
111
|
+
"v0.0.288.naive": "s3://codeocean-s3datasetsbucket-1u41qdg42ur9/e8468ee4-9825-4254-b374-fb0b9dab160a",
|
|
112
|
+
"v0.0.289": "s3://codeocean-s3datasetsbucket-1u41qdg42ur9/4491d1c4-400c-4e76-b81a-c437478f188b",
|
|
113
|
+
"v0.0.301": "s3://codeocean-s3datasetsbucket-1u41qdg42ur9/642c3e39-e5a7-433f-a269-9f6773c24c25",
|
|
114
|
+
}
|
|
115
|
+
if self.version in asset_paths:
|
|
116
|
+
asset_dir = upath.UPath(asset_paths[self.version], anon=self.anon)
|
|
117
|
+
logger.info(
|
|
118
|
+
"Using streamed S3 datacube data asset for config version=%s: %s",
|
|
119
|
+
self.version,
|
|
120
|
+
asset_dir,
|
|
121
|
+
)
|
|
122
|
+
return asset_dir
|
|
123
|
+
|
|
124
|
+
# Get the S3 directory of the datacube asset from the Code Ocean API.
|
|
125
|
+
# TODO replace with docdb query when possible
|
|
126
|
+
try:
|
|
127
|
+
import aind_session
|
|
128
|
+
except ImportError:
|
|
129
|
+
raise ImportError(
|
|
130
|
+
"aind_session and a CO_API_TOKEN are required to find the datacube data asset on S3. Install as an optional-dependency with `dr-datacube[co]`."
|
|
131
|
+
)
|
|
132
|
+
asset_dir = upath.UPath(
|
|
133
|
+
aind_session.get_data_asset_source_dir(
|
|
134
|
+
next(
|
|
135
|
+
d
|
|
136
|
+
for d in reversed(aind_session.get_data_assets("dynamicrouting_datacube"))
|
|
137
|
+
if _asset_name_has_version(d.name, self.version)
|
|
138
|
+
).id
|
|
139
|
+
),
|
|
140
|
+
anon=self.anon,
|
|
141
|
+
)
|
|
142
|
+
logger.info(
|
|
143
|
+
"Using streamed Code Ocean S3 datacube data asset for config version=%s: %s",
|
|
144
|
+
self.version,
|
|
145
|
+
asset_dir,
|
|
146
|
+
)
|
|
147
|
+
return asset_dir
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def nwb_dir(self) -> upath.UPath:
|
|
151
|
+
if self.use_cache:
|
|
152
|
+
nwb_dir = self.s3_cache_dir / "nwb" / self.version
|
|
153
|
+
logger.info("Config selects NWB data from scratch cache: %s", nwb_dir)
|
|
154
|
+
return nwb_dir
|
|
155
|
+
nwb_dir = self.asset_dir / "nwb"
|
|
156
|
+
logger.info("Config selects NWB data from datacube asset: %s", nwb_dir)
|
|
157
|
+
return nwb_dir
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def parquet_dir(self) -> upath.UPath:
|
|
161
|
+
if self.use_cache:
|
|
162
|
+
parquet_dir = self.s3_cache_dir / "nwb_components" / self.version / "consolidated"
|
|
163
|
+
logger.info("Config selects consolidated parquet from scratch cache: %s", parquet_dir)
|
|
164
|
+
return parquet_dir
|
|
165
|
+
parquet_dir = self.nwb_dir.parent / "consolidated"
|
|
166
|
+
logger.info("Config selects consolidated parquet from datacube asset: %s", parquet_dir)
|
|
167
|
+
return parquet_dir
|
|
168
|
+
|
|
169
|
+
def override(self, **overrides: Any) -> contextlib.AbstractContextManager["DatacubeConfig"]:
|
|
170
|
+
"""Temporarily use a copy of this config without changing this object."""
|
|
171
|
+
base = _get_config() if self is config else self
|
|
172
|
+
return _temporary_config(base, overrides)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
config = DatacubeConfig()
|
|
176
|
+
_active_config: ContextVar[DatacubeConfig | None] = ContextVar("dr_datacube_config", default=None)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _get_config() -> DatacubeConfig:
|
|
180
|
+
"""Return the config active in the current context, or the global config."""
|
|
181
|
+
active_config = _active_config.get()
|
|
182
|
+
return config if active_config is None else active_config
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class _ContextualAnon:
|
|
186
|
+
"""Resolve Lazynwb anonymous access from the active datacube config."""
|
|
187
|
+
|
|
188
|
+
def __bool__(self) -> bool:
|
|
189
|
+
return _get_config().anon
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# Lazynwb resolves this option when it opens a file, including when a LazyFrame is
|
|
193
|
+
# collected after ``get_lf`` returns. Keeping the value context-aware avoids sharing
|
|
194
|
+
# temporary anonymous-access settings between concurrent tasks.
|
|
195
|
+
lazynwb.config.anon = None # fallback to fsspec storage options
|
|
196
|
+
lazynwb.config.fsspec_storage_options["anon"] = _ContextualAnon()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _asset_name_has_version(asset_name: str, version: str) -> bool:
|
|
200
|
+
"""Return whether an asset name contains the complete requested version token."""
|
|
201
|
+
version_token = re.escape(version)
|
|
202
|
+
return re.search(rf"(?<![A-Za-z0-9.]){version_token}(?![A-Za-z0-9.])", asset_name) is not None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@contextlib.contextmanager
|
|
206
|
+
def _temporary_config(base: DatacubeConfig, overrides: dict[str, Any]) -> Iterator[DatacubeConfig]:
|
|
207
|
+
temporary_config = DatacubeConfig(**{**base.model_dump(), **overrides})
|
|
208
|
+
token = _active_config.set(temporary_config)
|
|
209
|
+
try:
|
|
210
|
+
yield temporary_config
|
|
211
|
+
finally:
|
|
212
|
+
_active_config.reset(token)
|