ezmsg-neo 0.1__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.
- ezmsg/neo/__init__.py +1 -0
- ezmsg/neo/__version__.py +16 -0
- ezmsg/neo/py.typed +0 -0
- ezmsg/neo/source.py +241 -0
- ezmsg/neo/util.py +21 -0
- ezmsg_neo-0.1.dist-info/METADATA +35 -0
- ezmsg_neo-0.1.dist-info/RECORD +9 -0
- ezmsg_neo-0.1.dist-info/WHEEL +4 -0
- ezmsg_neo-0.1.dist-info/licenses/LICENSE +21 -0
ezmsg/neo/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .__version__ import __version__ as __version__
|
ezmsg/neo/__version__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# file generated by setuptools_scm
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
TYPE_CHECKING = False
|
|
4
|
+
if TYPE_CHECKING:
|
|
5
|
+
from typing import Tuple, Union
|
|
6
|
+
VERSION_TUPLE = Tuple[Union[int, str], ...]
|
|
7
|
+
else:
|
|
8
|
+
VERSION_TUPLE = object
|
|
9
|
+
|
|
10
|
+
version: str
|
|
11
|
+
__version__: str
|
|
12
|
+
__version_tuple__: VERSION_TUPLE
|
|
13
|
+
version_tuple: VERSION_TUPLE
|
|
14
|
+
|
|
15
|
+
__version__ = version = '0.1'
|
|
16
|
+
__version_tuple__ = version_tuple = (0, 1)
|
ezmsg/neo/py.typed
ADDED
|
File without changes
|
ezmsg/neo/source.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from collections import deque
|
|
3
|
+
from dataclasses import replace
|
|
4
|
+
import os
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import time
|
|
7
|
+
import typing
|
|
8
|
+
|
|
9
|
+
import ezmsg.core as ez
|
|
10
|
+
|
|
11
|
+
from .util import AxisArray # This one has labels field.
|
|
12
|
+
from ezmsg.util.generator import GenState
|
|
13
|
+
import neo.rawio.baserawio
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class NeoIteratorSettings(ez.Settings):
|
|
18
|
+
"""Settings for :obj:`NeoIterator`."""
|
|
19
|
+
|
|
20
|
+
filepath: os.PathLike
|
|
21
|
+
chunk_dur: float = 0.1
|
|
22
|
+
self_terminating: bool = True
|
|
23
|
+
t_offset: typing.Optional[float] = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class NeoIterator:
|
|
27
|
+
def __init__(self, settings: NeoIteratorSettings):
|
|
28
|
+
self._settings = settings
|
|
29
|
+
self._reader: typing.Optional[neo.rawio.baserawio.BaseRawIO] = None
|
|
30
|
+
self._playback_state: typing.Optional[dict] = None
|
|
31
|
+
self._reset()
|
|
32
|
+
|
|
33
|
+
def _reset(self):
|
|
34
|
+
self._playback_state = {
|
|
35
|
+
"t_offset": self._settings.t_offset
|
|
36
|
+
if self._settings.t_offset is not None
|
|
37
|
+
else time.time(),
|
|
38
|
+
"t_start": np.inf,
|
|
39
|
+
"chunk_ix": 0,
|
|
40
|
+
"msg_queue": deque(),
|
|
41
|
+
"streams": {},
|
|
42
|
+
}
|
|
43
|
+
self._preload()
|
|
44
|
+
|
|
45
|
+
def _preload(self):
|
|
46
|
+
fpath = Path(self._settings.filepath)
|
|
47
|
+
|
|
48
|
+
if not fpath.exists():
|
|
49
|
+
raise FileNotFoundError(f"File not found: {fpath}")
|
|
50
|
+
|
|
51
|
+
if fpath.suffix == ".vhdr":
|
|
52
|
+
from neo.rawio import BrainVisionRawIO as RawIO
|
|
53
|
+
else:
|
|
54
|
+
raise ValueError(f"Unsupported file type: {fpath.suffix}")
|
|
55
|
+
|
|
56
|
+
self._reader = RawIO(filename=str(fpath))
|
|
57
|
+
self._reader.parse_header()
|
|
58
|
+
|
|
59
|
+
nb_block = self._reader.block_count()
|
|
60
|
+
if nb_block > 1:
|
|
61
|
+
raise NotImplementedError("Only single-block files are supported.")
|
|
62
|
+
nb_seg = [self._reader.segment_count(_) for _ in range(nb_block)][0]
|
|
63
|
+
if nb_seg > 1:
|
|
64
|
+
raise NotImplementedError("Only single-segment files are supported.")
|
|
65
|
+
nb_sig_streams = self._reader.signal_streams_count()
|
|
66
|
+
|
|
67
|
+
t_stop = -np.inf
|
|
68
|
+
|
|
69
|
+
# Fill out metadata for analogsignal streams
|
|
70
|
+
for strm_ix in range(nb_sig_streams):
|
|
71
|
+
t_start = self._reader.get_signal_t_start(0, 0, strm_ix)
|
|
72
|
+
self._playback_state["t_start"] = min(
|
|
73
|
+
self._playback_state["t_start"], t_start
|
|
74
|
+
)
|
|
75
|
+
nb_chans = self._reader.signal_channels_count(strm_ix)
|
|
76
|
+
fs = self._reader.get_signal_sampling_rate(strm_ix)
|
|
77
|
+
nb_samps = self._reader.get_signal_size(0, 0, strm_ix)
|
|
78
|
+
t_stop = max(t_stop, t_start + nb_samps / fs)
|
|
79
|
+
chan_struct_arr = self._reader.header["signal_channels"]
|
|
80
|
+
key = self._reader.header["signal_streams"][strm_ix]["name"]
|
|
81
|
+
template = AxisArray(
|
|
82
|
+
data=np.zeros((0, nb_chans), dtype=float),
|
|
83
|
+
dims=["time", "ch"],
|
|
84
|
+
axes={
|
|
85
|
+
"time": AxisArray.Axis.TimeAxis(fs=fs, offset=0.0),
|
|
86
|
+
"ch": AxisArray.Axis(labels=chan_struct_arr["name"].tolist()),
|
|
87
|
+
},
|
|
88
|
+
key=key,
|
|
89
|
+
)
|
|
90
|
+
self._playback_state["streams"][key] = {
|
|
91
|
+
"idx": strm_ix,
|
|
92
|
+
"type": "analogsignal",
|
|
93
|
+
"t_start": t_start,
|
|
94
|
+
"template": template,
|
|
95
|
+
"prev_samp": 0,
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
# Fill out metadata for event streams
|
|
99
|
+
nb_event_channel = self._reader.event_channels_count()
|
|
100
|
+
if nb_event_channel > 0:
|
|
101
|
+
# TODO: Event should probably use SampleTriggerMessage
|
|
102
|
+
self._playback_state["streams"]["events"] = {
|
|
103
|
+
"type": "event",
|
|
104
|
+
"nchan": nb_event_channel,
|
|
105
|
+
"template": AxisArray(
|
|
106
|
+
data=np.array([""]),
|
|
107
|
+
dims=["time"],
|
|
108
|
+
axes={"time": AxisArray.Axis.TimeAxis(fs=1, offset=0.0)},
|
|
109
|
+
key="events",
|
|
110
|
+
),
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
# TODO: Add support for spiketrain streams
|
|
114
|
+
# nb_unit = self._reader.spike_channels_count()
|
|
115
|
+
|
|
116
|
+
t_elapsed = t_stop - self._playback_state["t_start"]
|
|
117
|
+
self._playback_state["n_chunks"] = int(
|
|
118
|
+
np.ceil(t_elapsed / self._settings.chunk_dur)
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
def __iter__(self):
|
|
122
|
+
self._reset()
|
|
123
|
+
return self
|
|
124
|
+
|
|
125
|
+
def _chunk_step(self):
|
|
126
|
+
state = self._playback_state
|
|
127
|
+
t_range = (
|
|
128
|
+
state["chunk_ix"] * self._settings.chunk_dur,
|
|
129
|
+
(state["chunk_ix"] + 1) * self._settings.chunk_dur,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
for key, strm in state["streams"].items():
|
|
133
|
+
if strm["type"] == "analogsignal":
|
|
134
|
+
# Fetch data from last_idx to next_idx = next_time * fs
|
|
135
|
+
fs = 1 / strm["template"].axes["time"].gain
|
|
136
|
+
prev_samp = strm["prev_samp"]
|
|
137
|
+
next_samp = max(0, int((t_range[1] - strm["t_start"]) * fs))
|
|
138
|
+
dat = self._reader.get_analogsignal_chunk(
|
|
139
|
+
seg_index=0,
|
|
140
|
+
stream_index=strm["idx"],
|
|
141
|
+
i_start=prev_samp,
|
|
142
|
+
i_stop=next_samp,
|
|
143
|
+
)
|
|
144
|
+
if dat.size:
|
|
145
|
+
dat = self._reader.rescale_signal_raw_to_float(dat, dtype=float)
|
|
146
|
+
msg = replace(
|
|
147
|
+
strm["template"],
|
|
148
|
+
data=dat,
|
|
149
|
+
axes={
|
|
150
|
+
"ch": strm["template"].axes["ch"],
|
|
151
|
+
"time": replace(
|
|
152
|
+
strm["template"].axes["time"],
|
|
153
|
+
offset=t_range[0] + state["t_offset"],
|
|
154
|
+
),
|
|
155
|
+
},
|
|
156
|
+
)
|
|
157
|
+
state["msg_queue"].append(msg)
|
|
158
|
+
strm["prev_samp"] = next_samp
|
|
159
|
+
elif strm["type"] == "event":
|
|
160
|
+
# TODO: Event should probably use SampleTriggerMessage
|
|
161
|
+
for ev_ch_ix in range(strm["nchan"]):
|
|
162
|
+
ev_timestamps, ev_durations, ev_labels = (
|
|
163
|
+
self._reader.get_event_timestamps(
|
|
164
|
+
block_index=0,
|
|
165
|
+
seg_index=0,
|
|
166
|
+
event_channel_index=ev_ch_ix,
|
|
167
|
+
t_start=t_range[0],
|
|
168
|
+
t_stop=t_range[1],
|
|
169
|
+
)
|
|
170
|
+
)
|
|
171
|
+
ev_times = self._reader.rescale_event_timestamp(
|
|
172
|
+
ev_timestamps, dtype=float
|
|
173
|
+
)
|
|
174
|
+
for ev_t, ev_l in zip(ev_times, ev_labels):
|
|
175
|
+
msg = replace(
|
|
176
|
+
strm["template"],
|
|
177
|
+
data=np.array(
|
|
178
|
+
[ev_l],
|
|
179
|
+
),
|
|
180
|
+
axes={
|
|
181
|
+
"time": replace(
|
|
182
|
+
strm["template"].axes["time"],
|
|
183
|
+
offset=ev_t + state["t_offset"],
|
|
184
|
+
),
|
|
185
|
+
},
|
|
186
|
+
)
|
|
187
|
+
state["msg_queue"].append(msg)
|
|
188
|
+
|
|
189
|
+
else:
|
|
190
|
+
# TODO: spiketrain
|
|
191
|
+
# spike_timestamps = self._reader.get_spike_timestamps(block_index=0, seg_index=0, spike_channel_index=0,
|
|
192
|
+
# t_start=0, t_stop=10)
|
|
193
|
+
# spike_timestamps
|
|
194
|
+
# spike_times = self._reader.rescale_spike_timestamp(spike_timestamps, dtype='float64')
|
|
195
|
+
# raw_waveforms = reader.get_spike_raw_waveforms(block_index=0, seg_index=0, spike_channel_index=0,
|
|
196
|
+
# t_start=0, t_stop=10)
|
|
197
|
+
# float_waveforms = reader.rescale_waveforms_to_float(raw_waveforms, dtype='float32', spike_channel_index=0)
|
|
198
|
+
raise NotImplementedError(f"Unsupported stream type: {strm['type']}")
|
|
199
|
+
|
|
200
|
+
state["chunk_ix"] += 1
|
|
201
|
+
|
|
202
|
+
def __next__(self) -> AxisArray:
|
|
203
|
+
state = self._playback_state
|
|
204
|
+
if not state["msg_queue"]:
|
|
205
|
+
if state["chunk_ix"] >= state["n_chunks"]:
|
|
206
|
+
# TODO Close file
|
|
207
|
+
raise StopIteration
|
|
208
|
+
self._chunk_step()
|
|
209
|
+
|
|
210
|
+
if not state["msg_queue"]:
|
|
211
|
+
raise StopIteration
|
|
212
|
+
|
|
213
|
+
return state["msg_queue"].popleft()
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class NeoIteratorUnit(ez.Unit):
|
|
217
|
+
STATE = GenState
|
|
218
|
+
SETTINGS = NeoIteratorSettings
|
|
219
|
+
|
|
220
|
+
OUTPUT_SIGNAL = ez.OutputStream(AxisArray)
|
|
221
|
+
OUTPUT_TERM = ez.OutputStream(typing.Any)
|
|
222
|
+
|
|
223
|
+
def initialize(self) -> None:
|
|
224
|
+
self.construct_generator()
|
|
225
|
+
|
|
226
|
+
def construct_generator(self):
|
|
227
|
+
self.STATE.gen = NeoIterator(
|
|
228
|
+
settings=self.SETTINGS,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
@ez.publisher(OUTPUT_SIGNAL)
|
|
232
|
+
async def pub_chunk(self) -> typing.AsyncGenerator:
|
|
233
|
+
for msg in self.STATE.gen:
|
|
234
|
+
# TODO: Direct msg to OUTPUT_TRIGGER if type is SampleTriggerMessage
|
|
235
|
+
yield self.OUTPUT_SIGNAL, msg
|
|
236
|
+
await asyncio.sleep(0)
|
|
237
|
+
|
|
238
|
+
ez.logger.debug(f"File ({self.SETTINGS.filepath}) exhausted.")
|
|
239
|
+
if self.SETTINGS.self_terminating:
|
|
240
|
+
raise ez.NormalTermination
|
|
241
|
+
yield self.OUTPUT_TERM, ez.Flag
|
ezmsg/neo/util.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
import typing
|
|
3
|
+
|
|
4
|
+
from ezmsg.util.messages.axisarray import AxisArray
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class CustomAxis(AxisArray.Axis):
|
|
9
|
+
labels: typing.List[str] = field(default_factory=lambda: [])
|
|
10
|
+
|
|
11
|
+
@classmethod
|
|
12
|
+
def SpaceAxis(
|
|
13
|
+
cls,
|
|
14
|
+
labels: typing.List[str],
|
|
15
|
+
# locs: typing.Optional[npt.NDArray] = None
|
|
16
|
+
):
|
|
17
|
+
return cls(unit="mm", labels=labels)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
# Monkey-patch AxisArray with our customized Axis
|
|
21
|
+
AxisArray.Axis = CustomAxis
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: ezmsg-neo
|
|
3
|
+
Version: 0.1
|
|
4
|
+
Summary: Load and stream data from neo files into ezmsg.
|
|
5
|
+
Author-email: Chadwick Boulay <chadwick.boulay@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Requires-Dist: ezmsg>=3.5.0
|
|
10
|
+
Requires-Dist: neo>=0.13.3
|
|
11
|
+
Provides-Extra: tests
|
|
12
|
+
Requires-Dist: pytest>=8.3.3; extra == 'tests'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# ezmsg-neo
|
|
16
|
+
|
|
17
|
+
Load and stream data from [neo](https://github.com/NeuralEnsemble/python-neo) files into [ezmsg](https://github.com/iscoe/ezmsg).
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
TODO: `pip install ezmsg-neo`
|
|
22
|
+
|
|
23
|
+
For now `pip install ezmsg-neo@git+https://github.com/ezmsg-org/ezmsg-neo`
|
|
24
|
+
|
|
25
|
+
## Dependencies
|
|
26
|
+
* `ezmsg`
|
|
27
|
+
* `neo`
|
|
28
|
+
|
|
29
|
+
## Setup (Development)
|
|
30
|
+
|
|
31
|
+
1. Clone this repo
|
|
32
|
+
2. `uv init`
|
|
33
|
+
3. ezmsg-neo modules are available under `import ezmsg.neo`
|
|
34
|
+
|
|
35
|
+
TODO: See the `examples` folder for more details.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
ezmsg/neo/__init__.py,sha256=8K4IcOA3-pfzadoM6s2Sfg5460KlJUocGgyTJTJl96U,52
|
|
2
|
+
ezmsg/neo/__version__.py,sha256=7V2ukxSfzXlOjRj21NN9XMWrUwTZJIQZggSzFRx5qs8,406
|
|
3
|
+
ezmsg/neo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
ezmsg/neo/source.py,sha256=AGyvZOV_TkfU94RzJ1btSrhHD0hqY01Mu3Q6oZp3WNQ,9149
|
|
5
|
+
ezmsg/neo/util.py,sha256=lUJcem-nZq-rlv8DfOTPC6f-014TINNkpzHxDeZYXyc,488
|
|
6
|
+
ezmsg_neo-0.1.dist-info/METADATA,sha256=KKCkQpskhVjDlL3ZyINUdmOk8Dhvw-U0OaxTq-O4ozA,870
|
|
7
|
+
ezmsg_neo-0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
8
|
+
ezmsg_neo-0.1.dist-info/licenses/LICENSE,sha256=KImy0vSiKLkW28zWqI8rIaLwvjGKxOjE5kZmVxZDdy4,1066
|
|
9
|
+
ezmsg_neo-0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 ezmsg-org
|
|
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.
|