jdata 0.9.5__tar.gz → 0.9.6__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.
- {jdata-0.9.5/jdata.egg-info → jdata-0.9.6}/PKG-INFO +5 -1
- {jdata-0.9.5 → jdata-0.9.6}/jdata/__init__.py +44 -1
- {jdata-0.9.5 → jdata-0.9.6}/jdata/csvtsv.py +34 -7
- jdata-0.9.6/jdata/jctf.py +348 -0
- jdata-0.9.6/jdata/jdata.py +1319 -0
- jdata-0.9.6/jdata/jeeg.py +993 -0
- jdata-0.9.6/jdata/jfiff.py +194 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/jfile.py +129 -7
- jdata-0.9.6/jdata/jmef3.py +290 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/jnifti.py +144 -22
- jdata-0.9.6/jdata/njbids.py +1541 -0
- jdata-0.9.6/jdata/njcas.py +673 -0
- jdata-0.9.6/jdata/njcli.py +1064 -0
- jdata-0.9.6/jdata/njcouch.py +422 -0
- jdata-0.9.6/jdata/njdigest.py +494 -0
- jdata-0.9.6/jdata/njdoi.py +312 -0
- jdata-0.9.6/jdata/njencode.py +395 -0
- jdata-0.9.6/jdata/zlibmt.py +282 -0
- {jdata-0.9.5 → jdata-0.9.6/jdata.egg-info}/PKG-INFO +5 -1
- {jdata-0.9.5 → jdata-0.9.6}/jdata.egg-info/SOURCES.txt +26 -1
- jdata-0.9.6/jdata.egg-info/entry_points.txt +2 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata.egg-info/requires.txt +5 -0
- {jdata-0.9.5 → jdata-0.9.6}/pyproject.toml +7 -3
- {jdata-0.9.5 → jdata-0.9.6}/setup.py +1 -1
- {jdata-0.9.5 → jdata-0.9.6}/test/test_comprehensive.py +61 -1
- jdata-0.9.6/test/testjeeg.py +579 -0
- jdata-0.9.6/test/testmeg.py +543 -0
- {jdata-0.9.5 → jdata-0.9.6}/test/testneuroj.py +10 -4
- jdata-0.9.6/test/testnifti.py +347 -0
- jdata-0.9.6/test/testnjbids.py +1309 -0
- jdata-0.9.6/test/testnjcas.py +625 -0
- jdata-0.9.6/test/testnjcli.py +244 -0
- jdata-0.9.6/test/testnjcouch.py +490 -0
- jdata-0.9.6/test/testnjdigest.py +358 -0
- jdata-0.9.6/test/testnjdoi.py +224 -0
- jdata-0.9.6/test/testnjrobust.py +199 -0
- jdata-0.9.6/test/testnjviews.py +354 -0
- jdata-0.9.6/test/testspec.py +195 -0
- jdata-0.9.6/test/testzlibmt.py +503 -0
- jdata-0.9.5/jdata/jdata.py +0 -963
- jdata-0.9.5/test/testnifti.py +0 -171
- {jdata-0.9.5 → jdata-0.9.6}/LICENSE.txt +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/MANIFEST.in +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/README.md +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/__main__.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/h5.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/jdictionary.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/jgifti.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/jpath.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/jschema.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/neurojson.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata/njprep.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata.egg-info/dependency_links.txt +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/jdata.egg-info/top_level.txt +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/setup.cfg +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/test/testgifti.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/test/testjd.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/test/testjdict.py +0 -0
- {jdata-0.9.5 → jdata-0.9.6}/test/testsnirf.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: jdata
|
|
3
|
-
Version: 0.9.
|
|
3
|
+
Version: 0.9.6
|
|
4
4
|
Summary: JSON/binary JSON formats for exchanging Python and Numpy data
|
|
5
5
|
Home-page: https://github.com/NeuroJSON/pyjdata
|
|
6
6
|
Author: Qianqian Fang
|
|
@@ -38,6 +38,8 @@ Provides-Extra: bjdata
|
|
|
38
38
|
Requires-Dist: bjdata; extra == "bjdata"
|
|
39
39
|
Provides-Extra: lz4
|
|
40
40
|
Requires-Dist: lz4; extra == "lz4"
|
|
41
|
+
Provides-Extra: zstd
|
|
42
|
+
Requires-Dist: zstandard; extra == "zstd"
|
|
41
43
|
Provides-Extra: hdf5
|
|
42
44
|
Requires-Dist: h5py; extra == "hdf5"
|
|
43
45
|
Provides-Extra: matlab
|
|
@@ -49,6 +51,7 @@ Requires-Dist: blosc2; extra == "blosc2"
|
|
|
49
51
|
Provides-Extra: all
|
|
50
52
|
Requires-Dist: bjdata; extra == "all"
|
|
51
53
|
Requires-Dist: lz4; extra == "all"
|
|
54
|
+
Requires-Dist: zstandard; extra == "all"
|
|
52
55
|
Requires-Dist: h5py; extra == "all"
|
|
53
56
|
Requires-Dist: scipy; extra == "all"
|
|
54
57
|
Requires-Dist: msgpack; extra == "all"
|
|
@@ -56,6 +59,7 @@ Requires-Dist: blosc2; extra == "all"
|
|
|
56
59
|
Provides-Extra: dev
|
|
57
60
|
Requires-Dist: bjdata; extra == "dev"
|
|
58
61
|
Requires-Dist: lz4; extra == "dev"
|
|
62
|
+
Requires-Dist: zstandard; extra == "dev"
|
|
59
63
|
Requires-Dist: h5py; extra == "dev"
|
|
60
64
|
Requires-Dist: scipy; extra == "dev"
|
|
61
65
|
Requires-Dist: msgpack; extra == "dev"
|
|
@@ -42,10 +42,20 @@ from . import csvtsv
|
|
|
42
42
|
from . import h5
|
|
43
43
|
from . import jnifti
|
|
44
44
|
from . import jgifti
|
|
45
|
+
from . import jeeg
|
|
46
|
+
from . import jctf
|
|
47
|
+
from . import jfiff
|
|
48
|
+
from . import jmef3
|
|
45
49
|
from . import jpath
|
|
46
50
|
from . import jschema
|
|
47
51
|
from . import njprep
|
|
48
52
|
from . import neurojson
|
|
53
|
+
from . import zlibmt
|
|
54
|
+
from . import njcas
|
|
55
|
+
from . import njdigest
|
|
56
|
+
from . import njbids
|
|
57
|
+
from . import njcouch
|
|
58
|
+
from . import njdoi
|
|
49
59
|
|
|
50
60
|
# Re-export all public functions from submodules
|
|
51
61
|
from .jdata import *
|
|
@@ -55,12 +65,25 @@ from .csvtsv import *
|
|
|
55
65
|
from .h5 import *
|
|
56
66
|
from .jnifti import *
|
|
57
67
|
from .jgifti import *
|
|
68
|
+
from .jeeg import *
|
|
69
|
+
from .jctf import *
|
|
70
|
+
from .jfiff import *
|
|
71
|
+
from .jmef3 import *
|
|
58
72
|
from .jpath import *
|
|
59
73
|
from .jschema import *
|
|
60
74
|
from .njprep import *
|
|
61
75
|
from .neurojson import *
|
|
76
|
+
from .zlibmt import *
|
|
77
|
+
from .njcas import *
|
|
78
|
+
from .njdigest import *
|
|
79
|
+
from .njbids import *
|
|
80
|
+
from .njcouch import *
|
|
81
|
+
from .njdoi import *
|
|
62
82
|
|
|
63
|
-
|
|
83
|
+
# njcli is deliberately not star-imported: its `main` is a console entry point,
|
|
84
|
+
# not part of the library API.
|
|
85
|
+
|
|
86
|
+
__version__ = "0.9.6"
|
|
64
87
|
__all__ = (
|
|
65
88
|
jdata.__all__
|
|
66
89
|
+ jfile.__all__
|
|
@@ -69,10 +92,20 @@ __all__ = (
|
|
|
69
92
|
+ h5.__all__
|
|
70
93
|
+ jnifti.__all__
|
|
71
94
|
+ jgifti.__all__
|
|
95
|
+
+ jeeg.__all__
|
|
96
|
+
+ jctf.__all__
|
|
97
|
+
+ jfiff.__all__
|
|
98
|
+
+ jmef3.__all__
|
|
72
99
|
+ jpath.__all__
|
|
73
100
|
+ jschema.__all__
|
|
74
101
|
+ njprep.__all__
|
|
75
102
|
+ neurojson.__all__
|
|
103
|
+
+ zlibmt.__all__
|
|
104
|
+
+ njcas.__all__
|
|
105
|
+
+ njdigest.__all__
|
|
106
|
+
+ njbids.__all__
|
|
107
|
+
+ njcouch.__all__
|
|
108
|
+
+ njdoi.__all__
|
|
76
109
|
+ [
|
|
77
110
|
"jdata",
|
|
78
111
|
"jfile",
|
|
@@ -81,10 +114,20 @@ __all__ = (
|
|
|
81
114
|
"h5",
|
|
82
115
|
"jnifti",
|
|
83
116
|
"jgifti",
|
|
117
|
+
"jeeg",
|
|
118
|
+
"jctf",
|
|
119
|
+
"jfiff",
|
|
120
|
+
"jmef3",
|
|
84
121
|
"jpath",
|
|
85
122
|
"jschema",
|
|
86
123
|
"neurojson",
|
|
87
124
|
"njprep",
|
|
125
|
+
"zlibmt",
|
|
126
|
+
"njcas",
|
|
127
|
+
"njdigest",
|
|
128
|
+
"njbids",
|
|
129
|
+
"njcouch",
|
|
130
|
+
"njdoi",
|
|
88
131
|
]
|
|
89
132
|
)
|
|
90
133
|
|
|
@@ -38,6 +38,7 @@ def load_csv_tsv(
|
|
|
38
38
|
convert_numeric: bool = True,
|
|
39
39
|
header: bool = True,
|
|
40
40
|
encoding: str = "utf-8",
|
|
41
|
+
errors: str = "replace",
|
|
41
42
|
**kwargs,
|
|
42
43
|
) -> Union[Dict[str, List], List[List[str]]]:
|
|
43
44
|
"""
|
|
@@ -50,6 +51,10 @@ def load_csv_tsv(
|
|
|
50
51
|
convert_numeric: If True, attempt to convert numeric strings to numbers
|
|
51
52
|
header: If True, treat first row as header
|
|
52
53
|
encoding: File encoding (default: 'utf-8')
|
|
54
|
+
errors: Decoding error policy (default: 'replace'). Real-world BIDS
|
|
55
|
+
tables are not reliably UTF-8 -- unit columns commonly carry a
|
|
56
|
+
latin-1 micro sign in "\xb5V" -- and refusing to read such a file
|
|
57
|
+
loses the whole table over one byte.
|
|
53
58
|
**kwargs: Additional arguments passed to csv.reader/DictReader
|
|
54
59
|
|
|
55
60
|
Returns:
|
|
@@ -79,11 +84,33 @@ def load_csv_tsv(
|
|
|
79
84
|
# Determine if file is compressed
|
|
80
85
|
is_compressed = filename.lower().endswith(".gz")
|
|
81
86
|
|
|
82
|
-
# Open file (compressed or regular)
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
+
# Open file (compressed or regular). Try the requested encoding strictly
|
|
88
|
+
# first and fall back to latin-1, which cannot fail and round-trips the
|
|
89
|
+
# single-byte characters that show up in practice (a bare 0xb5 for the
|
|
90
|
+
# micro sign in unit columns is the common case). Decoding with
|
|
91
|
+
# errors="replace" straight away would silently turn those into U+FFFD.
|
|
92
|
+
def _open(enc, err):
|
|
93
|
+
if is_compressed:
|
|
94
|
+
return gzip.open(filename, "rt", encoding=enc, errors=err)
|
|
95
|
+
return open(filename, "r", encoding=enc, errors=err)
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
file_handle = _open(encoding, "strict")
|
|
99
|
+
file_handle.read()
|
|
100
|
+
file_handle.seek(0)
|
|
101
|
+
except UnicodeDecodeError:
|
|
102
|
+
try:
|
|
103
|
+
file_handle.close()
|
|
104
|
+
except Exception:
|
|
105
|
+
pass
|
|
106
|
+
file_handle = _open("latin-1", errors)
|
|
107
|
+
|
|
108
|
+
# Python's csv module raises _csv.Error("line contains NUL") on a stray
|
|
109
|
+
# null byte, and Postgres jsonb rejects \u0000 as well, so strip them here
|
|
110
|
+
# rather than lose the table. Seen in OpenNeuro events.tsv files.
|
|
111
|
+
def _denul(handle):
|
|
112
|
+
for line in handle:
|
|
113
|
+
yield line.replace("\x00", "")
|
|
87
114
|
|
|
88
115
|
try:
|
|
89
116
|
# Set up CSV reader parameters
|
|
@@ -96,7 +123,7 @@ def load_csv_tsv(
|
|
|
96
123
|
|
|
97
124
|
if return_dict and header:
|
|
98
125
|
# Use DictReader for dictionary output with headers
|
|
99
|
-
reader = csv.DictReader(file_handle, **csv_params)
|
|
126
|
+
reader = csv.DictReader(_denul(file_handle), **csv_params)
|
|
100
127
|
|
|
101
128
|
# Read all rows
|
|
102
129
|
rows = list(reader)
|
|
@@ -120,7 +147,7 @@ def load_csv_tsv(
|
|
|
120
147
|
|
|
121
148
|
else:
|
|
122
149
|
# Use regular reader for list output
|
|
123
|
-
reader = csv.reader(file_handle, **csv_params)
|
|
150
|
+
reader = csv.reader(_denul(file_handle), **csv_params)
|
|
124
151
|
|
|
125
152
|
# Read all rows
|
|
126
153
|
rows = list(reader)
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""JCTF: a JData wrapper for CTF MEG ``.ds`` recordings.
|
|
2
|
+
|
|
3
|
+
A CTF recording is a *directory*, not a file, so the wrapper mirrors the
|
|
4
|
+
directory: every file in the ``.ds`` becomes a key, exactly as an HDF5 group
|
|
5
|
+
name becomes a key in JSNIRF. Nothing below the container key is renamed.
|
|
6
|
+
|
|
7
|
+
{
|
|
8
|
+
"CTFData": {
|
|
9
|
+
"res4": {...}, # parsed acquisition header
|
|
10
|
+
"meg4": ndarray, # the samples, [trial, channel, sample]
|
|
11
|
+
"hc": {...}, "acq": {...}, "MarkerFile.mrk": {...}, ...
|
|
12
|
+
},
|
|
13
|
+
"CTFSource": {...} # what a byte-exact rebuild needs
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
Field names come from three different places, and which one applies depends on
|
|
17
|
+
the file:
|
|
18
|
+
|
|
19
|
+
* ``.infods``, ``.acq``, ``MarkerFile.mrk``, ``params.dsc`` are tagged or
|
|
20
|
+
key/value ASCII -- the names are *in* the file, so they are read, never
|
|
21
|
+
invented.
|
|
22
|
+
* ``res4`` is a fixed-layout binary struct with no names in it at all (grep it:
|
|
23
|
+
there are zero occurrences of "no_samples" or "sample_rate"). Its names come
|
|
24
|
+
from CTF's published struct declaration, the same way JNIfTI takes ``dim``
|
|
25
|
+
and ``pixdim`` from ``nifti1.h``.
|
|
26
|
+
* ``.hc`` names its contents in English prose ("standard nasion coil position
|
|
27
|
+
relative to dewar (cm):"), which is not a key set. It is kept as bytes.
|
|
28
|
+
|
|
29
|
+
Everything is big-endian, unlike MEF3.
|
|
30
|
+
|
|
31
|
+
**Losslessness.** Encoding does not keep the original bytes in the content
|
|
32
|
+
store, so this wrapper is the only remaining description of the recording.
|
|
33
|
+
Every non-bulk file is therefore kept verbatim as a ``_ByteStream_`` beside its
|
|
34
|
+
parsed view, which costs 0.13% of a container (a 3.19 MB ``res4`` against a
|
|
35
|
+
2.42 GB ``meg4``) and makes a byte-exact rebuild a property of the container
|
|
36
|
+
rather than of this parser being complete.
|
|
37
|
+
|
|
38
|
+
author: Qianqian Fang <q.fang at neu.edu>
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
import hashlib
|
|
42
|
+
import os
|
|
43
|
+
import re
|
|
44
|
+
import struct
|
|
45
|
+
|
|
46
|
+
import numpy as np
|
|
47
|
+
|
|
48
|
+
__all__ = ["ctf2jctf", "jctf2ctf", "ctfinfo"]
|
|
49
|
+
|
|
50
|
+
# res4 offsets, verified against 7 datasets. Two invariants pin them:
|
|
51
|
+
# epoch_time == no_trials * no_samples / sample_rate
|
|
52
|
+
# meg4 data bytes == no_trials * no_channels * no_samples * 4
|
|
53
|
+
_RES4_MAGIC = b"MEG42RS\x00"
|
|
54
|
+
_MEG4_MAGIC = b"MEG41CP\x00"
|
|
55
|
+
_OFF_APPNAME = 8
|
|
56
|
+
_OFF_ORIGIN = 264
|
|
57
|
+
_OFF_DESC = 520
|
|
58
|
+
_OFF_TRIALS_AVGD = 776
|
|
59
|
+
_OFF_TIME = 778
|
|
60
|
+
_OFF_DATE = 1033
|
|
61
|
+
_OFF_NSAMP = 1288
|
|
62
|
+
_OFF_NCHAN = 1292
|
|
63
|
+
_OFF_SRATE = 1296
|
|
64
|
+
_OFF_EPOCH = 1304
|
|
65
|
+
_OFF_NTRIALS = 1312
|
|
66
|
+
# Channel names sit at a fixed offset in every file examined, 32 bytes each,
|
|
67
|
+
# NUL padded, immediately followed by the per-sensor records.
|
|
68
|
+
_OFF_CHANNAMES = 1847
|
|
69
|
+
_NAMELEN = 32
|
|
70
|
+
|
|
71
|
+
_NAME_RE = re.compile(rb"^[A-Za-z][A-Za-z0-9_\-\+\.]{0,31}$")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _text(blob):
|
|
75
|
+
"""A NUL-padded fixed-width field as text."""
|
|
76
|
+
return blob.split(b"\0")[0].decode("latin1", "replace").strip()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _sha256(path):
|
|
80
|
+
h = hashlib.sha256()
|
|
81
|
+
with open(path, "rb") as fid:
|
|
82
|
+
for chunk in iter(lambda: fid.read(1 << 20), b""):
|
|
83
|
+
h.update(chunk)
|
|
84
|
+
return h.hexdigest()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _meg4_parts(dspath):
|
|
88
|
+
"""``.meg4`` plus its 2 GB continuation files, in acquisition order.
|
|
89
|
+
|
|
90
|
+
CTF splits the sample stream at 2 GB into ``.1_meg4``, ``.2_meg4`` and so
|
|
91
|
+
on; the parts are one logical array and must be concatenated in order.
|
|
92
|
+
"""
|
|
93
|
+
parts = []
|
|
94
|
+
for name in os.listdir(dspath):
|
|
95
|
+
if name.endswith(".meg4"):
|
|
96
|
+
parts.append((0, name))
|
|
97
|
+
else:
|
|
98
|
+
hit = re.match(r"^.*\.(\d+)_meg4$", name)
|
|
99
|
+
if hit:
|
|
100
|
+
parts.append((int(hit.group(1)), name))
|
|
101
|
+
return [name for _, name in sorted(parts)]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _parse_res4(raw):
|
|
105
|
+
"""The fields whose offsets are verified; the rest stays in _ByteStream_."""
|
|
106
|
+
if raw[:8] != _RES4_MAGIC:
|
|
107
|
+
raise ValueError("not a CTF res4 file (bad magic %r)" % raw[:8])
|
|
108
|
+
|
|
109
|
+
head = {
|
|
110
|
+
"appName": _text(raw[_OFF_APPNAME : _OFF_APPNAME + 256]),
|
|
111
|
+
"dataOrigin": _text(raw[_OFF_ORIGIN : _OFF_ORIGIN + 256]),
|
|
112
|
+
"dataDescription": _text(raw[_OFF_DESC : _OFF_DESC + 256]),
|
|
113
|
+
"no_trials_avgd": struct.unpack(">h", raw[_OFF_TRIALS_AVGD : _OFF_TRIALS_AVGD + 2])[0],
|
|
114
|
+
"data_time": _text(raw[_OFF_TIME : _OFF_TIME + 255]),
|
|
115
|
+
"data_date": _text(raw[_OFF_DATE : _OFF_DATE + 255]),
|
|
116
|
+
"no_samples": struct.unpack(">i", raw[_OFF_NSAMP : _OFF_NSAMP + 4])[0],
|
|
117
|
+
"no_channels": struct.unpack(">h", raw[_OFF_NCHAN : _OFF_NCHAN + 2])[0],
|
|
118
|
+
"sample_rate": struct.unpack(">d", raw[_OFF_SRATE : _OFF_SRATE + 8])[0],
|
|
119
|
+
"epoch_time": struct.unpack(">d", raw[_OFF_EPOCH : _OFF_EPOCH + 8])[0],
|
|
120
|
+
"no_trials": struct.unpack(">h", raw[_OFF_NTRIALS : _OFF_NTRIALS + 2])[0],
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
nchan = head["no_channels"]
|
|
124
|
+
names = []
|
|
125
|
+
for k in range(max(0, nchan)):
|
|
126
|
+
start = _OFF_CHANNAMES + _NAMELEN * k
|
|
127
|
+
field = raw[start : start + _NAMELEN]
|
|
128
|
+
if len(field) < _NAMELEN:
|
|
129
|
+
break
|
|
130
|
+
names.append(_text(field))
|
|
131
|
+
if names:
|
|
132
|
+
head["chanName"] = names
|
|
133
|
+
|
|
134
|
+
return head
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _parse_markerfile(text):
|
|
138
|
+
"""MarkerFile.mrk names its own fields, so they are read rather than coined."""
|
|
139
|
+
out = {"markers": []}
|
|
140
|
+
lines = [ln.rstrip("\r") for ln in text.split("\n")]
|
|
141
|
+
cur = None
|
|
142
|
+
idx = 0
|
|
143
|
+
while idx < len(lines):
|
|
144
|
+
key = lines[idx].strip()
|
|
145
|
+
if key.endswith(":") and idx + 1 < len(lines):
|
|
146
|
+
name = key[:-1].strip()
|
|
147
|
+
value = lines[idx + 1].strip()
|
|
148
|
+
if name == "CLASSGROUPID":
|
|
149
|
+
cur = {}
|
|
150
|
+
out["markers"].append(cur)
|
|
151
|
+
if name == "LIST OF SAMPLES":
|
|
152
|
+
samples = []
|
|
153
|
+
idx += 2 # step past "LIST OF SAMPLES:" and the column titles
|
|
154
|
+
while idx < len(lines):
|
|
155
|
+
row = lines[idx].split()
|
|
156
|
+
if len(row) != 2:
|
|
157
|
+
break
|
|
158
|
+
try:
|
|
159
|
+
samples.append([int(row[0]), float(row[1])])
|
|
160
|
+
except ValueError:
|
|
161
|
+
break
|
|
162
|
+
idx += 1
|
|
163
|
+
if cur is not None:
|
|
164
|
+
cur["samples"] = samples
|
|
165
|
+
continue
|
|
166
|
+
target = cur if cur is not None else out
|
|
167
|
+
try:
|
|
168
|
+
target[name] = int(value)
|
|
169
|
+
except ValueError:
|
|
170
|
+
target[name] = value
|
|
171
|
+
idx += 2
|
|
172
|
+
continue
|
|
173
|
+
idx += 1
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _read_samples(dspath, parts, nchan, nsamp, ntrials, maxsamples=None):
|
|
178
|
+
"""Concatenate the ``.meg4`` parts into [trial, channel, sample] int32.
|
|
179
|
+
|
|
180
|
+
Verified layout: channel-major within a trial. Autocorrelation alone gets
|
|
181
|
+
this wrong on empty-room noise, where there is no signal to correlate; the
|
|
182
|
+
reliable evidence is that under this layout unused channels have exactly
|
|
183
|
+
zero variance while the others do not.
|
|
184
|
+
"""
|
|
185
|
+
blobs = []
|
|
186
|
+
for name in parts:
|
|
187
|
+
with open(os.path.join(dspath, name), "rb") as fid:
|
|
188
|
+
magic = fid.read(8)
|
|
189
|
+
if magic != _MEG4_MAGIC:
|
|
190
|
+
raise ValueError("bad meg4 magic %r in %s" % (magic, name))
|
|
191
|
+
blobs.append(fid.read())
|
|
192
|
+
|
|
193
|
+
data = b"".join(blobs)
|
|
194
|
+
per = nchan * nsamp
|
|
195
|
+
if per <= 0:
|
|
196
|
+
raise ValueError("res4 declares %d channels and %d samples" % (nchan, nsamp))
|
|
197
|
+
|
|
198
|
+
available = len(data) // (per * 4)
|
|
199
|
+
if ntrials <= 0 or ntrials > available:
|
|
200
|
+
ntrials = available
|
|
201
|
+
if maxsamples:
|
|
202
|
+
ntrials = min(ntrials, max(1, int(maxsamples) // per))
|
|
203
|
+
|
|
204
|
+
want = ntrials * per * 4
|
|
205
|
+
arr = np.frombuffer(data[:want], dtype=">i4").astype(np.int32)
|
|
206
|
+
return arr.reshape(ntrials, nchan, nsamp), [len(b) for b in blobs]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def ctfinfo(dspath):
|
|
210
|
+
"""The small summary that sits beside ``_DataLink_`` in a document.
|
|
211
|
+
|
|
212
|
+
Only fields that are absent from the BIDS sidecars, non-identifying, and
|
|
213
|
+
that change what a client does *before* fetching the attachment.
|
|
214
|
+
"""
|
|
215
|
+
res4 = [f for f in os.listdir(dspath) if f.endswith(".res4")]
|
|
216
|
+
if not res4:
|
|
217
|
+
raise ValueError("no .res4 in %s" % dspath)
|
|
218
|
+
with open(os.path.join(dspath, res4[0]), "rb") as fid:
|
|
219
|
+
head = _parse_res4(fid.read(1 << 16))
|
|
220
|
+
return {
|
|
221
|
+
"Format": "CTF",
|
|
222
|
+
"NumberOfSamples": head["no_samples"],
|
|
223
|
+
"NumberOfTrials": head["no_trials"],
|
|
224
|
+
"SplitParts": len(_meg4_parts(dspath)),
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def ctf2jctf(dspath, maxsamples=None, **kwargs):
|
|
229
|
+
"""Read a CTF ``.ds`` directory into a JCTF structure."""
|
|
230
|
+
dspath = dspath.rstrip(os.sep)
|
|
231
|
+
if not os.path.isdir(dspath):
|
|
232
|
+
raise ValueError("%s is not a CTF .ds directory" % dspath)
|
|
233
|
+
|
|
234
|
+
entries = sorted(os.listdir(dspath))
|
|
235
|
+
res4name = next((f for f in entries if f.endswith(".res4")), None)
|
|
236
|
+
if res4name is None:
|
|
237
|
+
raise ValueError("no .res4 in %s" % dspath)
|
|
238
|
+
|
|
239
|
+
with open(os.path.join(dspath, res4name), "rb") as fid:
|
|
240
|
+
res4raw = fid.read()
|
|
241
|
+
head = _parse_res4(res4raw)
|
|
242
|
+
|
|
243
|
+
parts = _meg4_parts(dspath)
|
|
244
|
+
if not parts:
|
|
245
|
+
raise ValueError("no .meg4 payload in %s" % dspath)
|
|
246
|
+
|
|
247
|
+
samples, partsizes = _read_samples(
|
|
248
|
+
dspath,
|
|
249
|
+
parts,
|
|
250
|
+
head["no_channels"],
|
|
251
|
+
head["no_samples"],
|
|
252
|
+
head["no_trials"],
|
|
253
|
+
maxsamples,
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
# res4 is kept whole: only a fraction of its 3.19 MB has verified offsets
|
|
257
|
+
# (the per-sensor records and a ~2.78 MB trailing block are not yet
|
|
258
|
+
# mapped), so the bytes are what guarantees a rebuild, not the parse.
|
|
259
|
+
head["_ByteStream_"] = res4raw
|
|
260
|
+
data = {"res4": head, "meg4": samples}
|
|
261
|
+
|
|
262
|
+
files = [{"Name": res4name, "Bytes": len(res4raw), "SHA256": hashlib.sha256(res4raw).hexdigest()}]
|
|
263
|
+
for name in parts:
|
|
264
|
+
full = os.path.join(dspath, name)
|
|
265
|
+
files.append({"Name": name, "Bytes": os.path.getsize(full), "SHA256": _sha256(full), "Role": "data"})
|
|
266
|
+
|
|
267
|
+
for name in entries:
|
|
268
|
+
if name == res4name or name in parts:
|
|
269
|
+
continue
|
|
270
|
+
full = os.path.join(dspath, name)
|
|
271
|
+
if not os.path.isfile(full):
|
|
272
|
+
continue
|
|
273
|
+
with open(full, "rb") as fid:
|
|
274
|
+
blob = fid.read()
|
|
275
|
+
files.append({"Name": name, "Bytes": len(blob), "SHA256": hashlib.sha256(blob).hexdigest()})
|
|
276
|
+
|
|
277
|
+
key = name.split(".")[-1] if name.startswith(os.path.basename(dspath)[:8]) else name
|
|
278
|
+
if name.endswith((".hc", ".acq", ".infods")):
|
|
279
|
+
key = name.rsplit(".", 1)[-1]
|
|
280
|
+
node = {"_ByteStream_": blob}
|
|
281
|
+
if name == "MarkerFile.mrk":
|
|
282
|
+
try:
|
|
283
|
+
node.update(_parse_markerfile(blob.decode("latin1")))
|
|
284
|
+
except Exception:
|
|
285
|
+
pass
|
|
286
|
+
elif name == "BadChannels":
|
|
287
|
+
try:
|
|
288
|
+
node["channels"] = [ln.strip() for ln in blob.decode("latin1").split("\n") if ln.strip()]
|
|
289
|
+
except Exception:
|
|
290
|
+
pass
|
|
291
|
+
data[key] = node
|
|
292
|
+
|
|
293
|
+
return {
|
|
294
|
+
"CTFData": data,
|
|
295
|
+
"CTFSource": {
|
|
296
|
+
"Format": "CTF",
|
|
297
|
+
"Container": os.path.basename(dspath),
|
|
298
|
+
"ContainerType": "directory",
|
|
299
|
+
"SampleLayout": "trial-channel-sample",
|
|
300
|
+
"Endian": "big",
|
|
301
|
+
"MEG4Parts": parts,
|
|
302
|
+
"MEG4PartBytes": partsizes,
|
|
303
|
+
"Files": files,
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def jctf2ctf(jctf, dspath):
|
|
309
|
+
"""Rebuild the ``.ds`` directory. Returns {filename: sha256} of the result."""
|
|
310
|
+
data = jctf["CTFData"]
|
|
311
|
+
src = jctf.get("CTFSource", {})
|
|
312
|
+
os.makedirs(dspath, exist_ok=True)
|
|
313
|
+
|
|
314
|
+
byname = {f["Name"]: f for f in src.get("Files", [])}
|
|
315
|
+
written = {}
|
|
316
|
+
|
|
317
|
+
res4name = next((n for n in byname if n.endswith(".res4")), None)
|
|
318
|
+
if res4name is None:
|
|
319
|
+
raise ValueError("CTFSource lists no .res4")
|
|
320
|
+
blob = bytes(data["res4"]["_ByteStream_"])
|
|
321
|
+
with open(os.path.join(dspath, res4name), "wb") as fid:
|
|
322
|
+
fid.write(blob)
|
|
323
|
+
written[res4name] = hashlib.sha256(blob).hexdigest()
|
|
324
|
+
|
|
325
|
+
parts = src.get("MEG4Parts", [])
|
|
326
|
+
partbytes = src.get("MEG4PartBytes", [])
|
|
327
|
+
payload = np.ascontiguousarray(np.asarray(data["meg4"], dtype=np.int32)).astype(">i4").tobytes()
|
|
328
|
+
pos = 0
|
|
329
|
+
for idx, name in enumerate(parts):
|
|
330
|
+
take = partbytes[idx] if idx < len(partbytes) else len(payload) - pos
|
|
331
|
+
chunk = _MEG4_MAGIC + payload[pos : pos + take]
|
|
332
|
+
pos += take
|
|
333
|
+
with open(os.path.join(dspath, name), "wb") as fid:
|
|
334
|
+
fid.write(chunk)
|
|
335
|
+
written[name] = hashlib.sha256(chunk).hexdigest()
|
|
336
|
+
|
|
337
|
+
for key, node in data.items():
|
|
338
|
+
if key in ("res4", "meg4"):
|
|
339
|
+
continue
|
|
340
|
+
if not isinstance(node, dict) or "_ByteStream_" not in node:
|
|
341
|
+
continue
|
|
342
|
+
name = next((n for n in byname if n == key or n.endswith("." + key)), key)
|
|
343
|
+
blob = bytes(node["_ByteStream_"])
|
|
344
|
+
with open(os.path.join(dspath, name), "wb") as fid:
|
|
345
|
+
fid.write(blob)
|
|
346
|
+
written[name] = hashlib.sha256(blob).hexdigest()
|
|
347
|
+
|
|
348
|
+
return written
|