litkeio 0.1.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.
- litkeio-0.1.0/.gitignore +6 -0
- litkeio-0.1.0/LICENSE +21 -0
- litkeio-0.1.0/PKG-INFO +76 -0
- litkeio-0.1.0/README.md +65 -0
- litkeio-0.1.0/conftest.py +11 -0
- litkeio-0.1.0/pyproject.toml +28 -0
- litkeio-0.1.0/src/litkeio/__init__.py +6 -0
- litkeio-0.1.0/src/litkeio/header.py +217 -0
- litkeio-0.1.0/src/litkeio/layout.py +143 -0
- litkeio-0.1.0/src/litkeio/pack.py +78 -0
- litkeio-0.1.0/src/litkeio/reader.py +233 -0
- litkeio-0.1.0/src/litkeio/unpack.py +191 -0
- litkeio-0.1.0/src/litkeio/writer.py +104 -0
- litkeio-0.1.0/tests/test_difference.py +116 -0
- litkeio-0.1.0/tests/test_header.py +182 -0
- litkeio-0.1.0/tests/test_layout.py +117 -0
- litkeio-0.1.0/tests/test_reader.py +418 -0
- litkeio-0.1.0/tests/test_roundtrip.py +279 -0
- litkeio-0.1.0/tests/test_unpack.py +178 -0
- litkeio-0.1.0/uv.lock +417 -0
litkeio-0.1.0/.gitignore
ADDED
litkeio-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dragos Rezeanu
|
|
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.
|
litkeio-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: litkeio
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A .bin file reader/writer for raw files from Litke multi-electrode arrays.
|
|
5
|
+
Author-email: Dragos Rezeanu <DRezeanu@uw.edu>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: numpy
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# litkeio
|
|
13
|
+
|
|
14
|
+
Read and write raw `.bin` recordings from Litke multi-electrode arrays in pure Python + NumPy. No Cython, no compiled extensions, no build toolchain.
|
|
15
|
+
|
|
16
|
+
## Install
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install litkeio
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Requires Python 3.10+ and NumPy.
|
|
23
|
+
|
|
24
|
+
## Supported arrays
|
|
25
|
+
|
|
26
|
+
The frame layout is chosen from the channel count in the file header:
|
|
27
|
+
|
|
28
|
+
| Board | Channels | Electrodes | Channel 0 (TTL) |
|
|
29
|
+
|-------|----------|------------|-----------------|
|
|
30
|
+
| 512 | 513 | 512 | raw int16 |
|
|
31
|
+
| 519 | 520 | 519 | 12-bit, like the electrodes |
|
|
32
|
+
|
|
33
|
+
Channel 0 is always the TTL channel; electrodes are channels 1 to `num_electrodes`.
|
|
34
|
+
|
|
35
|
+
## Reading
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from litkeio import LitkeReader
|
|
39
|
+
|
|
40
|
+
with LitkeReader('/path/to/data000') as reader:
|
|
41
|
+
print(reader.num_electrodes, reader.length)
|
|
42
|
+
|
|
43
|
+
# All channels: int16 array, shape (num_samples, num_channels)
|
|
44
|
+
block = reader.get_data(start_sample_num=0, num_samples=20_000)
|
|
45
|
+
|
|
46
|
+
# Any subset of channels, decoded without unpacking the rest
|
|
47
|
+
subset = reader.get_data(0, 20_000, channels=[0, 2, 4, 6])
|
|
48
|
+
|
|
49
|
+
# One channel as a 1-D array
|
|
50
|
+
ttl = reader.get_data_for_electrode(0, 0, 20_000)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Pass a dataset folder to read across all its subfiles, or a single subfile to restrict reads to it. Set `is_row_major=True` for `(channels, samples)` arrays.
|
|
54
|
+
|
|
55
|
+
## Writing
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from litkeio import LitkeWriter
|
|
59
|
+
|
|
60
|
+
with LitkeWriter(reader.header, '/path/to/output', 'data000') as writer:
|
|
61
|
+
writer.write_samples(data) # int16, shape (n_samples, num_channels)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Output is split into subfiles (`data000000.bin`, `data000001.bin`, ...) with the header in the first. Existing files are never overwritten.
|
|
65
|
+
|
|
66
|
+
## Development
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
uv sync
|
|
70
|
+
uv run pytest
|
|
71
|
+
uv run pytest --real-bin-dir /path/to/dataset # tests against a real recording
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
MIT
|
litkeio-0.1.0/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# litkeio
|
|
2
|
+
|
|
3
|
+
Read and write raw `.bin` recordings from Litke multi-electrode arrays in pure Python + NumPy. No Cython, no compiled extensions, no build toolchain.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install litkeio
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires Python 3.10+ and NumPy.
|
|
12
|
+
|
|
13
|
+
## Supported arrays
|
|
14
|
+
|
|
15
|
+
The frame layout is chosen from the channel count in the file header:
|
|
16
|
+
|
|
17
|
+
| Board | Channels | Electrodes | Channel 0 (TTL) |
|
|
18
|
+
|-------|----------|------------|-----------------|
|
|
19
|
+
| 512 | 513 | 512 | raw int16 |
|
|
20
|
+
| 519 | 520 | 519 | 12-bit, like the electrodes |
|
|
21
|
+
|
|
22
|
+
Channel 0 is always the TTL channel; electrodes are channels 1 to `num_electrodes`.
|
|
23
|
+
|
|
24
|
+
## Reading
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from litkeio import LitkeReader
|
|
28
|
+
|
|
29
|
+
with LitkeReader('/path/to/data000') as reader:
|
|
30
|
+
print(reader.num_electrodes, reader.length)
|
|
31
|
+
|
|
32
|
+
# All channels: int16 array, shape (num_samples, num_channels)
|
|
33
|
+
block = reader.get_data(start_sample_num=0, num_samples=20_000)
|
|
34
|
+
|
|
35
|
+
# Any subset of channels, decoded without unpacking the rest
|
|
36
|
+
subset = reader.get_data(0, 20_000, channels=[0, 2, 4, 6])
|
|
37
|
+
|
|
38
|
+
# One channel as a 1-D array
|
|
39
|
+
ttl = reader.get_data_for_electrode(0, 0, 20_000)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Pass a dataset folder to read across all its subfiles, or a single subfile to restrict reads to it. Set `is_row_major=True` for `(channels, samples)` arrays.
|
|
43
|
+
|
|
44
|
+
## Writing
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from litkeio import LitkeWriter
|
|
48
|
+
|
|
49
|
+
with LitkeWriter(reader.header, '/path/to/output', 'data000') as writer:
|
|
50
|
+
writer.write_samples(data) # int16, shape (n_samples, num_channels)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Output is split into subfiles (`data000000.bin`, `data000001.bin`, ...) with the header in the first. Existing files are never overwritten.
|
|
54
|
+
|
|
55
|
+
## Development
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
uv sync
|
|
59
|
+
uv run pytest
|
|
60
|
+
uv run pytest --real-bin-dir /path/to/dataset # tests against a real recording
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## License
|
|
64
|
+
|
|
65
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
|
|
3
|
+
def pytest_addoption(parser: pytest.Parser) -> None:
|
|
4
|
+
parser.addoption('--real-bin-dir', action='store', default=None)
|
|
5
|
+
|
|
6
|
+
@pytest.fixture
|
|
7
|
+
def real_bin_dir(request: pytest.FixtureRequest) -> str:
|
|
8
|
+
path = request.config.getoption('--real-bin-dir')
|
|
9
|
+
if path is None:
|
|
10
|
+
pytest.skip('pass --real-bin-dir=<dataset_folder> to test against a real .bin file')
|
|
11
|
+
return path
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "litkeio"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A .bin file reader/writer for raw files from Litke multi-electrode arrays."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{name = "Dragos Rezeanu", email = "DRezeanu@uw.edu"}]
|
|
13
|
+
|
|
14
|
+
dependencies = [
|
|
15
|
+
"numpy",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[dependency-groups]
|
|
19
|
+
dev = [
|
|
20
|
+
"pytest",
|
|
21
|
+
"vision-utils",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[tool.hatch.build.targets.wheel]
|
|
25
|
+
packages = ["src/litkeio"]
|
|
26
|
+
|
|
27
|
+
[tool.uv.sources]
|
|
28
|
+
vision-utils = { path = "../retinanalysis/lib/artificial-retina-software-pipeline/utilities" }
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Parse and serialize the tag-length-value header at the start of subfile 0."""
|
|
2
|
+
|
|
3
|
+
from typing import BinaryIO
|
|
4
|
+
from warnings import warn
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
# Mirrors bin2py, but we can handle any header order
|
|
8
|
+
# as long as tag 0 is first and 499 is last
|
|
9
|
+
tag_order = [0, 1, 2, 3, 4, 5, 8, 7, 499]
|
|
10
|
+
|
|
11
|
+
@dataclass(slots=True, frozen=True)
|
|
12
|
+
class Header:
|
|
13
|
+
"""Parsed .bin header fields.
|
|
14
|
+
|
|
15
|
+
Attributes:
|
|
16
|
+
time_base: Time base from the TIME tag (1).
|
|
17
|
+
seconds: Seconds from the TIME tag (1).
|
|
18
|
+
format: Format code (tag 3).
|
|
19
|
+
comment: UTF-8 comment (tag 2).
|
|
20
|
+
num_electrodes: Channel count as stored in the header, TTL channel included
|
|
21
|
+
(513 or 520).
|
|
22
|
+
array_id: Array ID (tag 4). Informational; layout depends on num_electrodes.
|
|
23
|
+
sample_rate: Sampling frequency in Hz (tag 5).
|
|
24
|
+
dataset_id: Dataset identifier (tag 7).
|
|
25
|
+
n_samples: Sample count (tag 499). Can exceed the true count on
|
|
26
|
+
interrupted recordings.
|
|
27
|
+
header_length: Header length in bytes; frames start here in subfile 0.
|
|
28
|
+
trigger_v2: Raw trigger v2 payload (tag 8), carried through unparsed.
|
|
29
|
+
"""
|
|
30
|
+
time_base: int
|
|
31
|
+
seconds: int
|
|
32
|
+
format: int
|
|
33
|
+
comment: str
|
|
34
|
+
num_electrodes: int
|
|
35
|
+
array_id: int
|
|
36
|
+
sample_rate: int
|
|
37
|
+
dataset_id: str
|
|
38
|
+
n_samples: int
|
|
39
|
+
header_length: int
|
|
40
|
+
trigger_v2: bytes
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def read_bytes(stream: BinaryIO, n_bytes: int) -> bytes:
|
|
44
|
+
"""Read exactly n_bytes or raise EOFError."""
|
|
45
|
+
data = stream.read(n_bytes)
|
|
46
|
+
if len(data) != n_bytes:
|
|
47
|
+
raise EOFError(f'Expected {n_bytes} bytes, but got {len(data)}')
|
|
48
|
+
|
|
49
|
+
return data
|
|
50
|
+
|
|
51
|
+
def read_u32(stream: BinaryIO) -> int:
|
|
52
|
+
"""Read a big-endian uint32."""
|
|
53
|
+
return int.from_bytes(read_bytes(stream, 4), 'big')
|
|
54
|
+
|
|
55
|
+
def read_u64(stream: BinaryIO) -> int:
|
|
56
|
+
"""Read a big-endian uint64."""
|
|
57
|
+
return int.from_bytes(read_bytes(stream, 8), 'big')
|
|
58
|
+
|
|
59
|
+
def encode_entry(tag: int, payload: bytes) -> bytes:
|
|
60
|
+
"""Encode one TLV entry: uint32 tag, uint32 size, payload."""
|
|
61
|
+
return tag.to_bytes(4, 'big') + len(payload).to_bytes(4, 'big') + payload
|
|
62
|
+
|
|
63
|
+
def parse_header(stream: BinaryIO) -> Header:
|
|
64
|
+
"""Parse a header from the start of subfile 0.
|
|
65
|
+
|
|
66
|
+
Tags may appear in any order after tag 0; parsing stops at tag 499.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
stream: Binary stream positioned at byte 0 of subfile 0.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
Header: The parsed fields.
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
ValueError: If the first tag is not 0 or a fixed-size tag has the wrong size.
|
|
76
|
+
EOFError: If the stream ends mid-header.
|
|
77
|
+
"""
|
|
78
|
+
tag = read_u32(stream)
|
|
79
|
+
size = read_u32(stream)
|
|
80
|
+
|
|
81
|
+
if tag != 0:
|
|
82
|
+
raise ValueError(
|
|
83
|
+
'Expected first tag value from Litke bin file to be 0'
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
_check_size('header_length', size, 4)
|
|
87
|
+
header_length = read_u32(stream)
|
|
88
|
+
|
|
89
|
+
time_base = 0
|
|
90
|
+
seconds = 0
|
|
91
|
+
format = 0
|
|
92
|
+
comment = ''
|
|
93
|
+
n = 0
|
|
94
|
+
trigger_v2 = n.to_bytes(16, 'big')
|
|
95
|
+
num_electrodes = 0
|
|
96
|
+
array_id = 0
|
|
97
|
+
sample_rate = 0
|
|
98
|
+
dataset_id = ''
|
|
99
|
+
n_samples = 0
|
|
100
|
+
|
|
101
|
+
while tag != 499:
|
|
102
|
+
tag = read_u32(stream)
|
|
103
|
+
size = read_u32(stream)
|
|
104
|
+
|
|
105
|
+
match tag:
|
|
106
|
+
case 1:
|
|
107
|
+
_check_size('time base and seconds', size, 4+8)
|
|
108
|
+
time_base = read_u32(stream)
|
|
109
|
+
seconds = read_u64(stream)
|
|
110
|
+
case 2:
|
|
111
|
+
b = read_bytes(stream, size)
|
|
112
|
+
comment = b.decode('utf-8')
|
|
113
|
+
case 3:
|
|
114
|
+
_check_size('format', size, 4)
|
|
115
|
+
format = read_u32(stream)
|
|
116
|
+
case 4:
|
|
117
|
+
_check_size('n_electrodes and array_id', size, 4+4)
|
|
118
|
+
num_electrodes = read_u32(stream)
|
|
119
|
+
array_id = read_u32(stream)
|
|
120
|
+
case 5:
|
|
121
|
+
_check_size('sample_rate', size, 4)
|
|
122
|
+
sample_rate = read_u32(stream)
|
|
123
|
+
case 6:
|
|
124
|
+
pos = stream.tell()
|
|
125
|
+
if size != 8:
|
|
126
|
+
warn(
|
|
127
|
+
'Trigger size disagrees (happens on old data), '
|
|
128
|
+
'skipping 8 bytes no matter what'
|
|
129
|
+
)
|
|
130
|
+
stream.seek(pos+8)
|
|
131
|
+
case 8:
|
|
132
|
+
_check_size('trigger_v2', size, 16)
|
|
133
|
+
trigger_v2 = read_bytes(stream, size)
|
|
134
|
+
case 7:
|
|
135
|
+
b = read_bytes(stream, size)
|
|
136
|
+
dataset_id = b.decode('utf-8')
|
|
137
|
+
case 499:
|
|
138
|
+
_check_size('n_samples', size, 4)
|
|
139
|
+
n_samples = read_u32(stream)
|
|
140
|
+
case _:
|
|
141
|
+
warn(
|
|
142
|
+
f'Unknown tag, skipping {size} bytes per size field.'
|
|
143
|
+
)
|
|
144
|
+
pos = stream.tell()
|
|
145
|
+
stream.seek(pos+size)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
return Header(
|
|
150
|
+
time_base=time_base,
|
|
151
|
+
seconds=seconds,
|
|
152
|
+
format=format,
|
|
153
|
+
comment=comment,
|
|
154
|
+
num_electrodes=num_electrodes,
|
|
155
|
+
array_id=array_id,
|
|
156
|
+
sample_rate=sample_rate,
|
|
157
|
+
dataset_id=dataset_id,
|
|
158
|
+
n_samples=n_samples,
|
|
159
|
+
header_length=header_length,
|
|
160
|
+
trigger_v2=trigger_v2,
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def header_to_bytes(header: Header) -> bytes:
|
|
164
|
+
"""Serialize a Header to bytes, recomputing header_length.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
header: Header to encode. The stored header_length is ignored.
|
|
168
|
+
|
|
169
|
+
Returns:
|
|
170
|
+
bytes: The full header, tag 0 through tag 499.
|
|
171
|
+
"""
|
|
172
|
+
t1_payload = header.time_base.to_bytes(4, 'big') + header.seconds.to_bytes(8, 'big')
|
|
173
|
+
if len(header.comment) % 2 == 0:
|
|
174
|
+
t2_payload = header.comment.encode('utf-8')
|
|
175
|
+
else:
|
|
176
|
+
t2_payload = f'{header.comment} '.encode('utf-8')
|
|
177
|
+
|
|
178
|
+
t3_payload = header.format.to_bytes(4, 'big')
|
|
179
|
+
t4_payload = header.num_electrodes.to_bytes(4, 'big') + header.array_id.to_bytes(4, 'big')
|
|
180
|
+
t5_payload = header.sample_rate.to_bytes(4, 'big')
|
|
181
|
+
t7_payload = header.dataset_id.encode('utf-8')
|
|
182
|
+
t499_payload = header.n_samples.to_bytes(4, 'big')
|
|
183
|
+
|
|
184
|
+
entries = [
|
|
185
|
+
encode_entry(1, t1_payload),
|
|
186
|
+
encode_entry(2, t2_payload),
|
|
187
|
+
encode_entry(3, t3_payload),
|
|
188
|
+
encode_entry(4, t4_payload),
|
|
189
|
+
encode_entry(5, t5_payload),
|
|
190
|
+
]
|
|
191
|
+
|
|
192
|
+
if header.trigger_v2:
|
|
193
|
+
entries.append(encode_entry(8, header.trigger_v2))
|
|
194
|
+
|
|
195
|
+
entries += [
|
|
196
|
+
encode_entry(7, t7_payload),
|
|
197
|
+
encode_entry(499, t499_payload),
|
|
198
|
+
]
|
|
199
|
+
|
|
200
|
+
body = b''.join(entries)
|
|
201
|
+
header_length = 12 + len(body)
|
|
202
|
+
t0_payload = header_length.to_bytes(4, 'big')
|
|
203
|
+
t0 = encode_entry(0, t0_payload)
|
|
204
|
+
|
|
205
|
+
return t0 + body
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _check_size(
|
|
209
|
+
name: str,
|
|
210
|
+
size: int,
|
|
211
|
+
expected_size: int,
|
|
212
|
+
) -> None:
|
|
213
|
+
"""Raise ValueError if a tag's size field differs from expected_size."""
|
|
214
|
+
if size != expected_size:
|
|
215
|
+
raise ValueError(
|
|
216
|
+
f'Wrong size for {name} data. Expected {expected_size} but got {size}'
|
|
217
|
+
)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Frame layout for each supported board, chosen by channel count."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from litkeio.header import Header
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
@dataclass(slots=True, frozen=True)
|
|
8
|
+
class ArrayGeometry:
|
|
9
|
+
"""Frame layout for one recording.
|
|
10
|
+
|
|
11
|
+
Channel 0 is always the TTL channel.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
array_id: Array ID from the header. Informational only.
|
|
15
|
+
num_channels: Channels per frame, TTL included (513 or 520).
|
|
16
|
+
num_electrodes: Electrode channels, TTL excluded (512 or 519).
|
|
17
|
+
frame_bytes: Bytes per frame (770 or 780).
|
|
18
|
+
n_groups: 3-byte groups per frame, two 12-bit channels each.
|
|
19
|
+
raw_ttl_channel: True if channel 0 is a raw int16 (512 board); False if
|
|
20
|
+
it is 12-bit packed like the other channels (519 board).
|
|
21
|
+
"""
|
|
22
|
+
array_id: int
|
|
23
|
+
num_channels: int
|
|
24
|
+
num_electrodes: int
|
|
25
|
+
frame_bytes: int
|
|
26
|
+
n_groups: int
|
|
27
|
+
raw_ttl_channel: bool
|
|
28
|
+
|
|
29
|
+
def get_array_geometry(header: Header) -> ArrayGeometry:
|
|
30
|
+
"""Build the frame layout from a header's channel count.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
header: Parsed header.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
ArrayGeometry: Layout for 513 channels (512 board) or 520 channels (519 board).
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
ValueError: If the channel count is neither 513 nor 520.
|
|
40
|
+
"""
|
|
41
|
+
array_id = header.array_id
|
|
42
|
+
num_channels = header.num_electrodes
|
|
43
|
+
num_electrodes = num_channels-1
|
|
44
|
+
|
|
45
|
+
if num_channels == 513:
|
|
46
|
+
frame_bytes = 770
|
|
47
|
+
n_groups = 256
|
|
48
|
+
raw_ttl_channel = True
|
|
49
|
+
elif num_channels == 520:
|
|
50
|
+
frame_bytes = 780
|
|
51
|
+
n_groups = 260
|
|
52
|
+
raw_ttl_channel = False
|
|
53
|
+
else:
|
|
54
|
+
raise ValueError(
|
|
55
|
+
'Unrecognized channel count. '
|
|
56
|
+
f'Must be either 513 or 520. Got {num_channels}'
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
return ArrayGeometry(
|
|
60
|
+
array_id = array_id,
|
|
61
|
+
num_channels=num_channels,
|
|
62
|
+
num_electrodes=num_electrodes,
|
|
63
|
+
frame_bytes=frame_bytes,
|
|
64
|
+
n_groups=n_groups,
|
|
65
|
+
raw_ttl_channel=raw_ttl_channel,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_channel_span(
|
|
70
|
+
geometry: ArrayGeometry,
|
|
71
|
+
channel: int,
|
|
72
|
+
) -> tuple[int, int, Literal['RAW16', 'FIRST12', 'SECOND12']]:
|
|
73
|
+
"""Locate one channel's bytes within a frame.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
geometry: Frame layout.
|
|
77
|
+
channel: Channel index, 0 to num_channels - 1.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
tuple: (start, end, kind). Frame bytes [start, end) hold the value; kind
|
|
81
|
+
is 'RAW16' (raw int16), 'FIRST12' or 'SECOND12' (slot within a 3-byte group).
|
|
82
|
+
|
|
83
|
+
Raises:
|
|
84
|
+
ValueError: If channel is out of range.
|
|
85
|
+
"""
|
|
86
|
+
if not 0 <= channel < geometry.num_channels:
|
|
87
|
+
raise ValueError(
|
|
88
|
+
f'Channel must be between 0 and {geometry.num_channels}. '
|
|
89
|
+
f'Got {channel}.'
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
if geometry.raw_ttl_channel:
|
|
93
|
+
group = (channel-1)//2
|
|
94
|
+
k = 2 + 3*group
|
|
95
|
+
if channel == 0:
|
|
96
|
+
start = 0
|
|
97
|
+
end = 2
|
|
98
|
+
kind = 'RAW16'
|
|
99
|
+
elif channel % 2 == 0:
|
|
100
|
+
start = k+1
|
|
101
|
+
end = k+3
|
|
102
|
+
kind = 'SECOND12'
|
|
103
|
+
else:
|
|
104
|
+
start = k
|
|
105
|
+
end = k+2
|
|
106
|
+
kind = 'FIRST12'
|
|
107
|
+
|
|
108
|
+
else:
|
|
109
|
+
group = channel // 2
|
|
110
|
+
k = 3*group
|
|
111
|
+
|
|
112
|
+
if channel % 2 == 0:
|
|
113
|
+
start = k
|
|
114
|
+
end = k+2
|
|
115
|
+
kind = 'FIRST12'
|
|
116
|
+
else:
|
|
117
|
+
start = k+1
|
|
118
|
+
end = k+3
|
|
119
|
+
kind = 'SECOND12'
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
return start, end, kind
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def frame_count(
|
|
126
|
+
file_size: int,
|
|
127
|
+
geometry: ArrayGeometry,
|
|
128
|
+
header_size: int = 0,
|
|
129
|
+
) -> int:
|
|
130
|
+
"""Count whole frames in a subfile.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
file_size: Subfile size in bytes.
|
|
134
|
+
geometry: Frame layout.
|
|
135
|
+
header_size: Header bytes to skip (nonzero only for subfile 0).
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
int: Number of complete frames; a trailing partial frame is dropped.
|
|
139
|
+
"""
|
|
140
|
+
return (file_size - header_size) // geometry.frame_bytes
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Encode int16 samples into packed frame bytes."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from litkeio.layout import ArrayGeometry
|
|
5
|
+
|
|
6
|
+
def pack_frames(
|
|
7
|
+
data: np.ndarray,
|
|
8
|
+
geometry: ArrayGeometry
|
|
9
|
+
) -> bytes:
|
|
10
|
+
"""Pack samples into frames, the inverse of unpack_frames.
|
|
11
|
+
|
|
12
|
+
Args:
|
|
13
|
+
data: int16 array of shape (n_samples, num_channels).
|
|
14
|
+
geometry: Frame layout.
|
|
15
|
+
|
|
16
|
+
Returns:
|
|
17
|
+
bytes: n_samples * geometry.frame_bytes bytes of frame data (no header).
|
|
18
|
+
|
|
19
|
+
Raises:
|
|
20
|
+
ValueError: If data is not 2-D or has the wrong channel count.
|
|
21
|
+
TypeError: If data is not int16.
|
|
22
|
+
"""
|
|
23
|
+
if data.ndim != 2:
|
|
24
|
+
raise ValueError(
|
|
25
|
+
'Data must be in the shape (n_samples, n_channels). '
|
|
26
|
+
f'Got {data.shape}.'
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if data.shape[1] != geometry.num_channels:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
'Input data must be shaped (n_samples, n_channels). '
|
|
32
|
+
f'Expected {geometry.num_channels} channels but got {data.shape[1]}'
|
|
33
|
+
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
if data.dtype != np.int16:
|
|
37
|
+
raise TypeError(
|
|
38
|
+
f'Data must be type int16. Got {data.dtype}'
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
n_frames = data.shape[0]
|
|
42
|
+
byte_matrix = np.empty((n_frames, geometry.frame_bytes), dtype=np.uint8)
|
|
43
|
+
packed = data.copy() + 2048
|
|
44
|
+
if geometry.raw_ttl_channel:
|
|
45
|
+
# TTL is a raw 16 bit value packed into two bytes
|
|
46
|
+
# Start with the 16-bir value and shift it over 8 for the first byte
|
|
47
|
+
# Then mask out the first 8 for the second byte.
|
|
48
|
+
# Cast both to uint8 to match the byte_matrix
|
|
49
|
+
byte_matrix[:,0] = (data[:,0] >> 8).astype(np.uint8)
|
|
50
|
+
byte_matrix[:,1] = (data[:,0] & 0xFF).astype(np.uint8)
|
|
51
|
+
|
|
52
|
+
# Add 2048 back to each value to get it back into unsigned 12-bit territory
|
|
53
|
+
|
|
54
|
+
# Shift bytes into place. Start with a 12-bit value held in 16-bits per channel
|
|
55
|
+
# and put it into the appropriate 1.5 bytes...
|
|
56
|
+
# Odd channels take up byte 1 and the first half of 2
|
|
57
|
+
# Even channels take up the second half of 2 and byte 3
|
|
58
|
+
byte_matrix[:, 2:None:3] = (packed[:, 1:None:2] >> 4).astype(np.uint8)
|
|
59
|
+
byte_matrix[:, 3:None:3] = ((packed[:, 1:None:2] & 0xF) << 4).astype(np.uint8) | (packed[:, 2:None:2]>> 8).astype(np.uint8)
|
|
60
|
+
byte_matrix[:, 4:None:3] = (packed[:, 2:None:2] & 0xFF).astype(np.uint8)
|
|
61
|
+
else:
|
|
62
|
+
# TTL (channel 0) is 12-bit packed like every other channel.
|
|
63
|
+
# Even channels take up byte 1 and the first half of 2
|
|
64
|
+
# Odd channels take up the second half of 2 and byte 3
|
|
65
|
+
byte_matrix[:, 0:None:3] = (packed[:, 0:None:2] >> 4).astype(np.uint8)
|
|
66
|
+
byte_matrix[:, 1:None:3] = ((packed[:, 0:None:2] & 0xF) << 4).astype(np.uint8) | (packed[:, 1:None:2] >> 8).astype(np.uint8)
|
|
67
|
+
byte_matrix[:, 2:None:3] = (packed[:, 1:None:2] & 0xFF).astype(np.uint8)
|
|
68
|
+
|
|
69
|
+
return byte_matrix.tobytes()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|