litkeio 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.
- litkeio/__init__.py +6 -0
- litkeio/header.py +217 -0
- litkeio/layout.py +143 -0
- litkeio/pack.py +78 -0
- litkeio/reader.py +233 -0
- litkeio/unpack.py +191 -0
- litkeio/writer.py +104 -0
- litkeio-0.1.0.dist-info/METADATA +76 -0
- litkeio-0.1.0.dist-info/RECORD +11 -0
- litkeio-0.1.0.dist-info/WHEEL +4 -0
- litkeio-0.1.0.dist-info/licenses/LICENSE +21 -0
litkeio/__init__.py
ADDED
litkeio/header.py
ADDED
|
@@ -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
|
+
)
|
litkeio/layout.py
ADDED
|
@@ -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
|
+
|
litkeio/pack.py
ADDED
|
@@ -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
|
+
|
litkeio/reader.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Read samples from a Litke .bin recording split across subfiles."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from litkeio.header import parse_header
|
|
5
|
+
from litkeio.layout import get_array_geometry, frame_count
|
|
6
|
+
from litkeio.unpack import unpack_frames, unpack_channels, validate_and_sort_channels
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
class LitkeReader:
|
|
10
|
+
"""Reader for a Litke .bin recording (one dataset folder of subfiles).
|
|
11
|
+
|
|
12
|
+
Channel 0 is always the TTL channel: raw int16 on the 512 board, 12-bit
|
|
13
|
+
minus 2048 on the 519 board. Electrodes are channels 1 to num_electrodes.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
bin_file_path: Dataset folder, or one subfile within it. A single file
|
|
17
|
+
restricts reads to that subfile.
|
|
18
|
+
bin_file_ext: Subfile extension.
|
|
19
|
+
chunk_samples: Samples decoded per read call.
|
|
20
|
+
is_row_major: If True, returned arrays are (channels, samples).
|
|
21
|
+
|
|
22
|
+
Attributes:
|
|
23
|
+
header: Parsed header from the first subfile.
|
|
24
|
+
geometry: Frame layout.
|
|
25
|
+
handles: Subfile paths in read order.
|
|
26
|
+
sample_number_list: Cumulative sample count at the end of each subfile.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
bin_file_path: str | Path,
|
|
32
|
+
bin_file_ext: str = '.bin',
|
|
33
|
+
chunk_samples: int = 10_000,
|
|
34
|
+
is_row_major: bool = False,
|
|
35
|
+
):
|
|
36
|
+
|
|
37
|
+
self.chunk_samples = chunk_samples
|
|
38
|
+
self.is_row_major = is_row_major
|
|
39
|
+
|
|
40
|
+
if isinstance(bin_file_path, str):
|
|
41
|
+
bin_file_path = Path(bin_file_path)
|
|
42
|
+
|
|
43
|
+
bin_dir = bin_file_path.parent if bin_file_path.is_file() else bin_file_path
|
|
44
|
+
bin_files = sorted([f for f in bin_dir.iterdir() if f.is_file() and f.name.endswith(bin_file_ext)])
|
|
45
|
+
|
|
46
|
+
if not bin_files:
|
|
47
|
+
raise IOError(
|
|
48
|
+
'No files in bin file directory.'
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
self.header_file = bin_files[0]
|
|
52
|
+
with open(self.header_file, 'rb') as h_file:
|
|
53
|
+
self.header = parse_header(h_file)
|
|
54
|
+
self.geometry = get_array_geometry(self.header)
|
|
55
|
+
|
|
56
|
+
if bin_file_path.is_file():
|
|
57
|
+
self.handles = [bin_file_path]
|
|
58
|
+
if not bin_file_path.name.endswith(bin_file_ext):
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f'{bin_file_path.name} does not end in {bin_file_ext}.'
|
|
61
|
+
)
|
|
62
|
+
header_length = self.header.header_length if bin_file_path == self.header_file else 0
|
|
63
|
+
self.sample_number_list = [frame_count(bin_file_path.stat().st_size, self.geometry, header_length)]
|
|
64
|
+
|
|
65
|
+
else:
|
|
66
|
+
self.handles = bin_files
|
|
67
|
+
self.sample_number_list = []
|
|
68
|
+
for i in range(len(self.handles)):
|
|
69
|
+
if i == 0:
|
|
70
|
+
self.sample_number_list.append(frame_count(self.handles[i].stat().st_size, self.geometry, self.header.header_length))
|
|
71
|
+
else:
|
|
72
|
+
self.sample_number_list.append(self.sample_number_list[i-1] + frame_count(self.handles[i].stat().st_size, self.geometry))
|
|
73
|
+
|
|
74
|
+
self._closed = False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def num_electrodes(self) -> int:
|
|
79
|
+
"""Electrode count, TTL excluded."""
|
|
80
|
+
return self.geometry.num_electrodes
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def num_channels(self) -> int:
|
|
84
|
+
"""Channel count, TTL included."""
|
|
85
|
+
return self.geometry.num_channels
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def raw_ttl_channel(self) -> bool:
|
|
89
|
+
"""True if the TTL channel is raw int16 (512 board)."""
|
|
90
|
+
return self.geometry.raw_ttl_channel
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def array_id(self) -> int:
|
|
94
|
+
"""Array ID from the header."""
|
|
95
|
+
return self.geometry.array_id
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def length(self) -> int:
|
|
99
|
+
"""Total samples, from file sizes rather than header n_samples."""
|
|
100
|
+
return self.sample_number_list[-1]
|
|
101
|
+
|
|
102
|
+
def get_data(
|
|
103
|
+
self,
|
|
104
|
+
start_sample_num: int,
|
|
105
|
+
num_samples: int,
|
|
106
|
+
channels=None,
|
|
107
|
+
) -> np.ndarray:
|
|
108
|
+
"""Read a block of samples, spanning subfiles as needed.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
start_sample_num: First sample to read.
|
|
112
|
+
num_samples: Number of samples.
|
|
113
|
+
channels: Channel index or list of indices; None reads all channels.
|
|
114
|
+
A list is deduplicated and sorted.
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
np.ndarray: int16 array of shape (num_samples, n_channels), transposed
|
|
118
|
+
if is_row_major.
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
ValueError: If the reader is closed or channels are invalid.
|
|
122
|
+
IndexError: If the range falls outside the recording.
|
|
123
|
+
EOFError: If a subfile is shorter than expected.
|
|
124
|
+
"""
|
|
125
|
+
|
|
126
|
+
if self._closed:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
'This instance of LitkeReader has been closed. Cannot read data.'
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
# Check bounds
|
|
132
|
+
end_sample_num = start_sample_num + num_samples
|
|
133
|
+
if end_sample_num-1 >= self.length:
|
|
134
|
+
raise IndexError(
|
|
135
|
+
'Samples out of range. start_sample_num + num_samples extends beyond the end of the recording.'
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
if start_sample_num < 0:
|
|
139
|
+
raise IndexError(
|
|
140
|
+
'Cannot start at a negative sample number.'
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
if channels is not None:
|
|
144
|
+
channels = validate_and_sort_channels(channels)
|
|
145
|
+
|
|
146
|
+
n_cols = self.num_channels if channels is None else len(channels)
|
|
147
|
+
output = np.empty((num_samples, n_cols), dtype=np.int16)
|
|
148
|
+
start_file_idx = np.searchsorted(self.sample_number_list, start_sample_num, side='right')
|
|
149
|
+
end_file_idx = np.searchsorted(self.sample_number_list, end_sample_num-1, side='right')
|
|
150
|
+
|
|
151
|
+
for i in range(start_file_idx, end_file_idx+1):
|
|
152
|
+
header_length = self.header.header_length if self.handles[i] == self.header_file else 0
|
|
153
|
+
|
|
154
|
+
file_start = self.sample_number_list[i-1] if i > 0 else 0
|
|
155
|
+
file_end = self.sample_number_list[i]
|
|
156
|
+
|
|
157
|
+
read_start_sample = max(start_sample_num, file_start)
|
|
158
|
+
read_end_sample = min(start_sample_num + num_samples, file_end)
|
|
159
|
+
read_total_samples = read_end_sample - read_start_sample
|
|
160
|
+
|
|
161
|
+
offset = read_start_sample - file_start
|
|
162
|
+
start_byte = header_length + offset * self.geometry.frame_bytes
|
|
163
|
+
|
|
164
|
+
with open(self.handles[i], 'rb') as stream:
|
|
165
|
+
# Find the proper offset, should be 0 for everything but the first file
|
|
166
|
+
stream.seek(start_byte)
|
|
167
|
+
|
|
168
|
+
for j in range(0, read_total_samples, self.chunk_samples):
|
|
169
|
+
# Calculate how many samples to read
|
|
170
|
+
samples_remaining = read_total_samples - j
|
|
171
|
+
to_read = min(self.chunk_samples, samples_remaining)
|
|
172
|
+
|
|
173
|
+
# Read bytes
|
|
174
|
+
raw_bytes = stream.read(to_read * self.geometry.frame_bytes)
|
|
175
|
+
|
|
176
|
+
if len(raw_bytes) != to_read * self.geometry.frame_bytes:
|
|
177
|
+
raise EOFError(
|
|
178
|
+
'File read produced fewer bytes than expected. '
|
|
179
|
+
f'{self.handles[i].name} may be truncated unexpectedly.'
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
row = read_start_sample - start_sample_num + j
|
|
183
|
+
if channels is None:
|
|
184
|
+
output[row : row+to_read] = unpack_frames(raw_bytes, self.geometry)
|
|
185
|
+
else:
|
|
186
|
+
output[row: row+to_read] = unpack_channels(raw_bytes, self.geometry, channels)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
if self.is_row_major:
|
|
190
|
+
return output.T
|
|
191
|
+
else:
|
|
192
|
+
return output
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def get_data_for_electrode(
|
|
196
|
+
self,
|
|
197
|
+
electrode_num: int,
|
|
198
|
+
start_sample_num: int,
|
|
199
|
+
num_samples: int,
|
|
200
|
+
) -> np.ndarray:
|
|
201
|
+
"""Read one channel as a 1-D array.
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
electrode_num: Channel index (0 is TTL).
|
|
205
|
+
start_sample_num: First sample to read.
|
|
206
|
+
num_samples: Number of samples.
|
|
207
|
+
|
|
208
|
+
Returns:
|
|
209
|
+
np.ndarray: int16 array of shape (num_samples,).
|
|
210
|
+
"""
|
|
211
|
+
if self._closed:
|
|
212
|
+
raise ValueError(
|
|
213
|
+
'This instance of LitkeReader has been closed. Cannot read data.'
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
if self.is_row_major:
|
|
217
|
+
output = self.get_data(start_sample_num, num_samples, channels = [electrode_num])[0,:]
|
|
218
|
+
else:
|
|
219
|
+
output = self.get_data(start_sample_num, num_samples, channels = [electrode_num])[:,0]
|
|
220
|
+
|
|
221
|
+
return output
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def close(self):
|
|
225
|
+
"""Mark the reader closed; later reads raise ValueError."""
|
|
226
|
+
self._closed = True
|
|
227
|
+
|
|
228
|
+
def __enter__(self):
|
|
229
|
+
return self
|
|
230
|
+
|
|
231
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
232
|
+
self.close()
|
|
233
|
+
|
litkeio/unpack.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Decode packed frame bytes into int16 samples."""
|
|
2
|
+
|
|
3
|
+
import numbers
|
|
4
|
+
from warnings import warn
|
|
5
|
+
import numpy as np
|
|
6
|
+
from litkeio.layout import ArrayGeometry, get_channel_span
|
|
7
|
+
|
|
8
|
+
def unpack_frames(
|
|
9
|
+
raw_bytes: bytes | bytearray | memoryview,
|
|
10
|
+
geometry: ArrayGeometry,
|
|
11
|
+
) -> np.ndarray:
|
|
12
|
+
"""Decode whole frames into int16 samples for every channel.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
raw_bytes: Frame bytes only (no header); length must be a multiple of
|
|
16
|
+
geometry.frame_bytes.
|
|
17
|
+
geometry: Frame layout.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
np.ndarray: int16 array of shape (n_frames, num_channels). Column 0 is the
|
|
21
|
+
TTL channel: raw int16 if geometry.raw_ttl_channel, else 12-bit minus 2048.
|
|
22
|
+
|
|
23
|
+
Raises:
|
|
24
|
+
ValueError: If len(raw_bytes) is not a multiple of geometry.frame_bytes.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
buffer = np.frombuffer(raw_bytes, dtype=np.uint8) # the buffer is made up of 8-bit integers
|
|
28
|
+
|
|
29
|
+
_check_buffer(buffer, geometry.frame_bytes)
|
|
30
|
+
|
|
31
|
+
n_frames = buffer.size // geometry.frame_bytes
|
|
32
|
+
byte_matrix = buffer.reshape(n_frames, geometry.frame_bytes)
|
|
33
|
+
|
|
34
|
+
out = np.empty((n_frames, geometry.num_channels), dtype=np.int16)
|
|
35
|
+
if geometry.raw_ttl_channel:
|
|
36
|
+
ttl = ((byte_matrix[:,0].astype(np.int32) << 8) | byte_matrix[:,1]).astype(np.int16)
|
|
37
|
+
out[:,0] = ttl
|
|
38
|
+
groups = byte_matrix[:, 2:].reshape(n_frames, geometry.n_groups, 3)
|
|
39
|
+
else:
|
|
40
|
+
groups = byte_matrix.reshape(n_frames, geometry.n_groups, 3)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
byte_1 = groups[:, :, 0]
|
|
44
|
+
byte_2 = groups[:, :, 1]
|
|
45
|
+
byte_3 = groups[:, :, 2]
|
|
46
|
+
|
|
47
|
+
# Cast to int16 FIRST before bit shifting. If you shift a uint8 << 4, it stays uint8 and wraps
|
|
48
|
+
# Using bitshift and bitwise or operations, we create create the two 12-bit components out of the three
|
|
49
|
+
# bytes.
|
|
50
|
+
|
|
51
|
+
# byte_1 : 10101011 -> cast to 16-bit = 00000000 10101011 -> shifted left by 4 = 00001010 10110000
|
|
52
|
+
# byte_2 : 11110011 -> shifted right by 4 = 00001111
|
|
53
|
+
# bitwise OR: byte_2 is 0-padded automatically to 00000000 00001111
|
|
54
|
+
# b1 = 00001010 10110000, b2 = 00000000 00001111, b1 | b2 = 0000101010111111
|
|
55
|
+
first12 = (byte_1.astype(np.int16) << 4) | (byte_2 >> 4)
|
|
56
|
+
|
|
57
|
+
# byte_2 = 10101011
|
|
58
|
+
# bitwise AND with 0xF mask (00001111) = 00001011 -> cast to int16 = 00000000 00001011
|
|
59
|
+
# shifted 8 bits left = 00001011 00000000
|
|
60
|
+
# byte_3 = 10110011
|
|
61
|
+
# bitwise OR: byte_2 is zero_padded automatically to 00000000 10110011
|
|
62
|
+
# b2 = 00001011 00000000, b3 = 00000000 10110011, b2 | b3 = 00001011 10110011
|
|
63
|
+
second12 = ((byte_2 & 0xF).astype(np.int16) << 8) | byte_3
|
|
64
|
+
|
|
65
|
+
# 2048 offset allows us to map -2047 - 2048 in the 12-bit slot, since electrode signals are bipolar around 0
|
|
66
|
+
if geometry.raw_ttl_channel:
|
|
67
|
+
out[:, 1:None:2] = first12 - 2048
|
|
68
|
+
out[:, 2:None:2] = second12 - 2048
|
|
69
|
+
else:
|
|
70
|
+
out[:, 0:None:2] = first12 - 2048
|
|
71
|
+
out[:, 1:None:2] = second12 - 2048
|
|
72
|
+
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
def unpack_channels(
|
|
76
|
+
raw_bytes: bytes | bytearray | memoryview,
|
|
77
|
+
geometry: ArrayGeometry,
|
|
78
|
+
channels: int | float | list[int] | list[float],
|
|
79
|
+
):
|
|
80
|
+
"""Decode a subset of channels from whole frames.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
raw_bytes: Frame bytes only (no header); length must be a multiple of
|
|
84
|
+
geometry.frame_bytes.
|
|
85
|
+
geometry: Frame layout.
|
|
86
|
+
channels: Channel index or list of indices. Integer-valued floats are
|
|
87
|
+
accepted; the list is deduplicated and sorted.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
np.ndarray: int16 array of shape (n_frames, n_unique_channels), columns in
|
|
91
|
+
sorted channel order.
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
ValueError: If raw_bytes is not a whole number of frames, or a channel is
|
|
95
|
+
non-integer or out of range.
|
|
96
|
+
TypeError: If a channel is not a number.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
channels = validate_and_sort_channels(channels)
|
|
100
|
+
|
|
101
|
+
spans = [get_channel_span(geometry, channel) for channel in channels]
|
|
102
|
+
|
|
103
|
+
buffer = np.frombuffer(raw_bytes, dtype=np.uint8)
|
|
104
|
+
|
|
105
|
+
_check_buffer(buffer, geometry.frame_bytes)
|
|
106
|
+
|
|
107
|
+
n_frames = buffer.size // geometry.frame_bytes
|
|
108
|
+
byte_matrix = np.reshape(buffer, (n_frames, geometry.frame_bytes))
|
|
109
|
+
|
|
110
|
+
out = np.empty((n_frames, len(channels)), dtype=np.int16)
|
|
111
|
+
for idx, (s, _, kind) in enumerate(spans):
|
|
112
|
+
column_0 = byte_matrix[:, s]
|
|
113
|
+
column_1 = byte_matrix[:, s+1]
|
|
114
|
+
|
|
115
|
+
if kind == 'RAW16':
|
|
116
|
+
vals = (column_0.astype(np.int32) << 8 | column_1).astype(np.int16)
|
|
117
|
+
out[:, idx] = vals
|
|
118
|
+
elif kind == 'FIRST12':
|
|
119
|
+
vals = (column_0.astype(np.int16) << 4) | (column_1 >> 4)
|
|
120
|
+
out[:, idx] = vals - 2048
|
|
121
|
+
elif kind == 'SECOND12':
|
|
122
|
+
vals = ((column_0 & 0xF).astype(np.int16) << 8) | column_1
|
|
123
|
+
out[:, idx] = vals - 2048
|
|
124
|
+
else:
|
|
125
|
+
raise ValueError(
|
|
126
|
+
'Decoded kind must be either RAW16, FIRST12, or SECOND12. '
|
|
127
|
+
f'Got {kind} for channel {channels[idx]}.'
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _check_buffer(
|
|
134
|
+
buffer: np.ndarray,
|
|
135
|
+
frame_bytes: int,
|
|
136
|
+
) -> None:
|
|
137
|
+
"""Raise ValueError if the buffer is not a whole number of frames."""
|
|
138
|
+
if buffer.size % frame_bytes != 0:
|
|
139
|
+
raise ValueError(
|
|
140
|
+
f"Geometry and raw_bytes don't match. Expected {frame_bytes} per frame, "
|
|
141
|
+
f"but buffer.size / frame_bytes = {buffer.size / frame_bytes:.2f}"
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def validate_and_sort_channels(
|
|
146
|
+
channels
|
|
147
|
+
) -> list[int]:
|
|
148
|
+
"""Normalize channel input to a sorted list of unique ints.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
channels: A number or iterable of numbers; each must be integer-valued.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
list[int]: Sorted, deduplicated channel indices. Warns if duplicates were dropped.
|
|
155
|
+
|
|
156
|
+
Raises:
|
|
157
|
+
TypeError: If any channel is not a number.
|
|
158
|
+
ValueError: If any channel is not integer-valued.
|
|
159
|
+
"""
|
|
160
|
+
if isinstance(channels, numbers.Real):
|
|
161
|
+
channels = [channels]
|
|
162
|
+
|
|
163
|
+
output = []
|
|
164
|
+
for c in channels:
|
|
165
|
+
if not isinstance(c, numbers.Real):
|
|
166
|
+
raise TypeError(
|
|
167
|
+
f'All channels must be a number, got {c!r}'
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
c = float(c)
|
|
171
|
+
|
|
172
|
+
if not c.is_integer():
|
|
173
|
+
raise ValueError(
|
|
174
|
+
f'All channels must be integers. Got {c} in {channels}.'
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
output.append(int(c))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
if len(set(output)) < len(output):
|
|
181
|
+
warn(
|
|
182
|
+
f'Found duplicate channels in channel list: {output}. '
|
|
183
|
+
'Only pulling each channel once.'
|
|
184
|
+
)
|
|
185
|
+
output = sorted(list(set(output)))
|
|
186
|
+
else:
|
|
187
|
+
output = sorted(output)
|
|
188
|
+
|
|
189
|
+
return output
|
|
190
|
+
|
|
191
|
+
|
litkeio/writer.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Write samples as a Litke .bin recording."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import numpy as np
|
|
5
|
+
from litkeio.layout import get_array_geometry
|
|
6
|
+
from litkeio.header import Header, header_to_bytes
|
|
7
|
+
from litkeio.pack import pack_frames
|
|
8
|
+
from dataclasses import replace
|
|
9
|
+
|
|
10
|
+
class LitkeWriter:
|
|
11
|
+
"""Writer for a Litke .bin recording.
|
|
12
|
+
|
|
13
|
+
Writes path_to_write/dataset_name/dataset_name000.bin, 001.bin, ...; the
|
|
14
|
+
header goes in the first subfile only. Existing files are never overwritten.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
header: Header to write; n_samples is replaced from the data.
|
|
18
|
+
path_to_write: Parent directory for the dataset folder.
|
|
19
|
+
dataset_name: Dataset folder name and subfile prefix.
|
|
20
|
+
bin_ext: Subfile extension.
|
|
21
|
+
bin_file_n_samples: Samples per subfile.
|
|
22
|
+
|
|
23
|
+
Raises:
|
|
24
|
+
NotADirectoryError: If path_to_write is a file.
|
|
25
|
+
ValueError: If the header's channel count is not 513 or 520.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
header: Header,
|
|
31
|
+
path_to_write: str | Path,
|
|
32
|
+
dataset_name: str,
|
|
33
|
+
bin_ext: str = '.bin',
|
|
34
|
+
bin_file_n_samples: int = 2_400_000,
|
|
35
|
+
):
|
|
36
|
+
self.header = header
|
|
37
|
+
self.geometry = get_array_geometry(self.header)
|
|
38
|
+
self.dataset_name = dataset_name
|
|
39
|
+
self.path_to_write = Path(path_to_write)
|
|
40
|
+
self.output_path = self.path_to_write / dataset_name
|
|
41
|
+
self.bin_ext = bin_ext
|
|
42
|
+
self.bin_file_n_samples = bin_file_n_samples
|
|
43
|
+
|
|
44
|
+
if self.path_to_write.is_file():
|
|
45
|
+
raise NotADirectoryError(
|
|
46
|
+
'path_to_write is a file, expected a directory.'
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
if not self.output_path.is_dir():
|
|
50
|
+
self.output_path.mkdir(parents=True, exist_ok = True)
|
|
51
|
+
|
|
52
|
+
self._closed = False
|
|
53
|
+
|
|
54
|
+
def write_samples(self, data_array: np.ndarray) -> None:
|
|
55
|
+
"""Write a full recording, split into subfiles.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
data_array: int16 array of shape (n_samples, num_channels).
|
|
59
|
+
|
|
60
|
+
Raises:
|
|
61
|
+
ValueError: If the writer is closed or data has the wrong shape.
|
|
62
|
+
TypeError: If data is not int16.
|
|
63
|
+
FileExistsError: If a target subfile already exists.
|
|
64
|
+
"""
|
|
65
|
+
if self._closed:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
'This instance of LitkeWriter is closed, cannot write samples.'
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
n_samples = data_array.shape[0]
|
|
72
|
+
out_header = replace(self.header, n_samples=n_samples)
|
|
73
|
+
|
|
74
|
+
n_files = np.ceil(n_samples / self.bin_file_n_samples).astype(int)
|
|
75
|
+
|
|
76
|
+
starts = np.arange(0, n_samples, self.bin_file_n_samples)
|
|
77
|
+
ends = np.minimum(starts + self.bin_file_n_samples, n_samples)
|
|
78
|
+
|
|
79
|
+
for f_num in range(n_files):
|
|
80
|
+
subfile_name = f'{self.dataset_name}{f_num:03d}{self.bin_ext}'
|
|
81
|
+
file_path = self.output_path / subfile_name
|
|
82
|
+
|
|
83
|
+
if file_path.is_file():
|
|
84
|
+
raise FileExistsError(
|
|
85
|
+
f'{file_path} already exists. Overwrite not permitted.'
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
header_bytes = header_to_bytes(out_header) if f_num == 0 else b''
|
|
89
|
+
frame_bytes = pack_frames(data_array[starts[f_num]:ends[f_num]], self.geometry)
|
|
90
|
+
|
|
91
|
+
file_bytes = header_bytes+frame_bytes
|
|
92
|
+
with open(self.output_path / subfile_name, 'wb') as f:
|
|
93
|
+
f.write(file_bytes)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def close(self) -> None:
|
|
97
|
+
"""Mark the writer closed; later writes raise ValueError."""
|
|
98
|
+
self._closed = True
|
|
99
|
+
|
|
100
|
+
def __enter__(self):
|
|
101
|
+
return self
|
|
102
|
+
|
|
103
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
104
|
+
self.close()
|
|
@@ -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
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
litkeio/__init__.py,sha256=6o9FXF4sUZ0G2ZLN7fmx3FbhpuMyVJV2ixwnoro7h5k,191
|
|
2
|
+
litkeio/header.py,sha256=wCHzcS55QwNXjqCtAahtcQZJAo7XI0W9Jgbe5YvidkE,6759
|
|
3
|
+
litkeio/layout.py,sha256=8kjU1KoR9-whfdVkb9al4lKLEZWgmI1tZWS0o8pjaE8,3839
|
|
4
|
+
litkeio/pack.py,sha256=SdJOZMEnV_TvQYIpw7kNAxnmPhuCRD0pr-WDjlIUdgY,2834
|
|
5
|
+
litkeio/reader.py,sha256=-N3pIdpcMEDYTAi-YyjlclfnSX5aY3kmysyx-K45eEc,8522
|
|
6
|
+
litkeio/unpack.py,sha256=sUhFKQ8n4xUoSAnaTZoZkkARNbIGK61G2ptbhibreBs,6453
|
|
7
|
+
litkeio/writer.py,sha256=AQALHNeuXaZMNXpPTecBFHlFVL_PY6-s6uzram4UIxI,3543
|
|
8
|
+
litkeio-0.1.0.dist-info/METADATA,sha256=LyLejpM36PEZjZ1VaE7DxD_ms_NhFEXZ_0pEMLYzdVc,2116
|
|
9
|
+
litkeio-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
litkeio-0.1.0.dist-info/licenses/LICENSE,sha256=MTE6Xdk0mEjdkqsOyFWJMbj6txw1MH351B5SRgk5lQA,1071
|
|
11
|
+
litkeio-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|