jdata 0.9.5__tar.gz → 0.9.7__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.7}/PKG-INFO +56 -1
- {jdata-0.9.5 → jdata-0.9.7}/README.md +51 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/__init__.py +62 -4
- {jdata-0.9.5 → jdata-0.9.7}/jdata/__main__.py +1 -1
- {jdata-0.9.5 → jdata-0.9.7}/jdata/csvtsv.py +35 -8
- {jdata-0.9.5 → jdata-0.9.7}/jdata/h5.py +70 -55
- jdata-0.9.7/jdata/jctf.py +348 -0
- jdata-0.9.7/jdata/jdata.py +1458 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/jdictionary.py +5 -3
- jdata-0.9.7/jdata/jeeg.py +993 -0
- jdata-0.9.7/jdata/jfiff.py +194 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/jfile.py +141 -14
- jdata-0.9.7/jdata/jmef3.py +290 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/jnifti.py +149 -22
- jdata-0.9.7/jdata/jtypes.py +855 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/neurojson.py +3 -0
- jdata-0.9.7/jdata/njbids.py +1541 -0
- jdata-0.9.7/jdata/njcas.py +673 -0
- jdata-0.9.7/jdata/njcli.py +1064 -0
- jdata-0.9.7/jdata/njcouch.py +422 -0
- jdata-0.9.7/jdata/njdigest.py +494 -0
- jdata-0.9.7/jdata/njdoi.py +312 -0
- jdata-0.9.7/jdata/njencode.py +395 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/njprep.py +16 -13
- jdata-0.9.7/jdata/zlibmt.py +282 -0
- {jdata-0.9.5 → jdata-0.9.7/jdata.egg-info}/PKG-INFO +56 -1
- jdata-0.9.7/jdata.egg-info/SOURCES.txt +63 -0
- jdata-0.9.7/jdata.egg-info/entry_points.txt +2 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata.egg-info/requires.txt +5 -0
- {jdata-0.9.5 → jdata-0.9.7}/pyproject.toml +7 -3
- {jdata-0.9.5 → jdata-0.9.7}/setup.py +1 -1
- {jdata-0.9.5 → jdata-0.9.7}/test/test_comprehensive.py +61 -1
- jdata-0.9.7/test/test_cov_core.py +1585 -0
- jdata-0.9.7/test/test_cov_formats.py +1286 -0
- jdata-0.9.7/test/test_cov_jdict.py +778 -0
- jdata-0.9.7/test/test_cov_neurojson.py +782 -0
- jdata-0.9.7/test/test_cov_njcli.py +931 -0
- {jdata-0.9.5 → jdata-0.9.7}/test/testjd.py +19 -0
- jdata-0.9.7/test/testjeeg.py +579 -0
- jdata-0.9.7/test/testjtypes.py +693 -0
- jdata-0.9.7/test/testmeg.py +543 -0
- {jdata-0.9.5 → jdata-0.9.7}/test/testneuroj.py +10 -4
- jdata-0.9.7/test/testnifti.py +347 -0
- jdata-0.9.7/test/testnjbids.py +1309 -0
- jdata-0.9.7/test/testnjcas.py +625 -0
- jdata-0.9.7/test/testnjcli.py +244 -0
- jdata-0.9.7/test/testnjcouch.py +490 -0
- jdata-0.9.7/test/testnjdigest.py +358 -0
- jdata-0.9.7/test/testnjdoi.py +224 -0
- jdata-0.9.7/test/testnjrobust.py +199 -0
- jdata-0.9.7/test/testnjviews.py +354 -0
- jdata-0.9.7/test/testspec.py +195 -0
- jdata-0.9.7/test/testzlibmt.py +503 -0
- jdata-0.9.5/jdata/jdata.py +0 -963
- jdata-0.9.5/jdata.egg-info/SOURCES.txt +0 -31
- jdata-0.9.5/test/testnifti.py +0 -171
- {jdata-0.9.5 → jdata-0.9.7}/LICENSE.txt +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/MANIFEST.in +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/jgifti.py +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/jpath.py +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata/jschema.py +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata.egg-info/dependency_links.txt +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/jdata.egg-info/top_level.txt +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/setup.cfg +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/test/testgifti.py +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/test/testjdict.py +0 -0
- {jdata-0.9.5 → jdata-0.9.7}/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.7
|
|
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"
|
|
@@ -90,6 +94,7 @@ Dynamic: platform
|
|
|
90
94
|
- [How to build](#how-to-build)
|
|
91
95
|
- [How to use](#how-to-use)
|
|
92
96
|
- [Advanced interfaces](#advanced-interfaces)
|
|
97
|
+
- [Saving other Python objects](#saving-other-python-objects)
|
|
93
98
|
- [Reading JSON via REST-API](#reading-json-via-rest-api)
|
|
94
99
|
- [Using JSONPath to access and query complex datasets](#using-jsonpath-to-access-and-query-complex-datasets)
|
|
95
100
|
- [Downloading and caching `_DataLink_` referenced external data files](#downloading-and-caching-_datalink_-referenced-external-data-files)
|
|
@@ -351,6 +356,56 @@ decompress the data based on the `_ArrayZipType_` annotation present in the data
|
|
|
351
356
|
compression methods support multi-threading. To set the thread number, one should define an `nthread`
|
|
352
357
|
value in the option (`opt`) for both encoding and decoding.
|
|
353
358
|
|
|
359
|
+
## Saving other Python objects
|
|
360
|
+
|
|
361
|
+
Besides numpy arrays, `encode()` (and therefore `save()`/`savejd()`) converts the data types of
|
|
362
|
+
other Python libraries to the JData construct that fits them. It recognises an object by the
|
|
363
|
+
protocol it provides, or its class by name, so none of those libraries is imported unless one of
|
|
364
|
+
their objects is passed in:
|
|
365
|
+
|
|
366
|
+
| Object | Stored as |
|
|
367
|
+
|---|---|
|
|
368
|
+
| arrays of other libraries: `torch.Tensor`, cupy, jax, PIL images, `memoryview`, `array.array`, anything with `__array__`, `__dlpack__` or the buffer protocol | N-D array (`_ArrayType_`); a GPU tensor is copied to the host, `bfloat16` stored as `single` |
|
|
369
|
+
| tables: `pandas.DataFrame`, `polars.DataFrame`, `pyarrow.Table`, numpy structured arrays, anything with `__arrow_c_stream__` or `__dataframe__` | table: a structure of arrays in `_TableData_` (typed, compressible columns), row labels in `_TableRows_`, index columns in `_TableIndex_` |
|
|
370
|
+
| labeled arrays: `xarray.DataArray`, `pandas.Series` | N-D array with `_ArrayLabel_`, `_ArrayCoords_` and `_ArrayUnits_` |
|
|
371
|
+
| categoricals: `pandas.Categorical`, category/dictionary columns, numpy string arrays with few distinct values | enumeration (`_EnumKey_`/`_EnumValue_`, `_EnumOrdered_`) |
|
|
372
|
+
| `xarray.Dataset`, dataclasses, attrs classes, pydantic models, namedtuples | object of their fields |
|
|
373
|
+
| numpy object arrays | a number array if they hold numbers, one stacked array if they hold equal-shaped arrays, otherwise nested lists of their elements (as jsonlab stores MATLAB cell arrays) |
|
|
374
|
+
| `datetime`/`date`/`time`, `datetime64` | ISO 8601 strings |
|
|
375
|
+
| `timedelta`, `timedelta64` | seconds |
|
|
376
|
+
| `Decimal`, `UUID`, `Path`, `Enum` | strings (an `int`/`str` enum by its value) |
|
|
377
|
+
|
|
378
|
+
The class of a converted object is recorded in `"_DataInfo_": {"PythonClass": ...}` (set
|
|
379
|
+
`typeinfo=False` to omit it). Loading gives numpy arrays, dicts and lists by default (a table as a
|
|
380
|
+
dict of its columns), which is also what MATLAB/jsonlab reads; `restore=True` rebuilds the
|
|
381
|
+
original objects:
|
|
382
|
+
|
|
383
|
+
```
|
|
384
|
+
import jdata as jd, pandas as pd, torch
|
|
385
|
+
|
|
386
|
+
df = pd.DataFrame({'name': ['a', 'b'], 'age': [21, 22], 'sex': pd.Categorical(['M', 'F'])})
|
|
387
|
+
jd.save({'table': df, 'weights': torch.randn(3, 4)}, 'data.jdb')
|
|
388
|
+
|
|
389
|
+
jd.load('data.jdb') # {'table': {'name': [...], 'age': array(...), ...}, 'weights': array(...)}
|
|
390
|
+
jd.load('data.jdb', restore=True) # {'table': DataFrame, 'weights': tensor}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
To save a table in the row form jsonlab reads as a MATLAB `table`, use `table='records'`
|
|
394
|
+
(`_TableCols_`/`_TableRecords_`).
|
|
395
|
+
|
|
396
|
+
A class can control how it is saved by defining `__jdata__()` (returning anything `encode()`
|
|
397
|
+
handles) and, to be restored, a `__from_jdata__(d)` classmethod. Classes you do not own can be
|
|
398
|
+
registered, by the class or by its name without importing it:
|
|
399
|
+
|
|
400
|
+
```
|
|
401
|
+
jd.register(MyDataclass) # saved by its fields, rebuilt by restore=True
|
|
402
|
+
jd.register('torch.nn.Parameter', encode=lambda p: p.detach().numpy(),
|
|
403
|
+
decode=lambda a: torch.nn.Parameter(torch.from_numpy(a)))
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
Only the classes known to `jdata` and those registered are rebuilt: a class named in a file is
|
|
407
|
+
never imported or constructed from that name, so loading an untrusted file does not run its code.
|
|
408
|
+
|
|
354
409
|
## Reading JSON via REST-API
|
|
355
410
|
|
|
356
411
|
If a REST-API (URL) is given as the first input of `load`, it reads the JSON data directly
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
- [How to build](#how-to-build)
|
|
21
21
|
- [How to use](#how-to-use)
|
|
22
22
|
- [Advanced interfaces](#advanced-interfaces)
|
|
23
|
+
- [Saving other Python objects](#saving-other-python-objects)
|
|
23
24
|
- [Reading JSON via REST-API](#reading-json-via-rest-api)
|
|
24
25
|
- [Using JSONPath to access and query complex datasets](#using-jsonpath-to-access-and-query-complex-datasets)
|
|
25
26
|
- [Downloading and caching `_DataLink_` referenced external data files](#downloading-and-caching-_datalink_-referenced-external-data-files)
|
|
@@ -281,6 +282,56 @@ decompress the data based on the `_ArrayZipType_` annotation present in the data
|
|
|
281
282
|
compression methods support multi-threading. To set the thread number, one should define an `nthread`
|
|
282
283
|
value in the option (`opt`) for both encoding and decoding.
|
|
283
284
|
|
|
285
|
+
## Saving other Python objects
|
|
286
|
+
|
|
287
|
+
Besides numpy arrays, `encode()` (and therefore `save()`/`savejd()`) converts the data types of
|
|
288
|
+
other Python libraries to the JData construct that fits them. It recognises an object by the
|
|
289
|
+
protocol it provides, or its class by name, so none of those libraries is imported unless one of
|
|
290
|
+
their objects is passed in:
|
|
291
|
+
|
|
292
|
+
| Object | Stored as |
|
|
293
|
+
|---|---|
|
|
294
|
+
| arrays of other libraries: `torch.Tensor`, cupy, jax, PIL images, `memoryview`, `array.array`, anything with `__array__`, `__dlpack__` or the buffer protocol | N-D array (`_ArrayType_`); a GPU tensor is copied to the host, `bfloat16` stored as `single` |
|
|
295
|
+
| tables: `pandas.DataFrame`, `polars.DataFrame`, `pyarrow.Table`, numpy structured arrays, anything with `__arrow_c_stream__` or `__dataframe__` | table: a structure of arrays in `_TableData_` (typed, compressible columns), row labels in `_TableRows_`, index columns in `_TableIndex_` |
|
|
296
|
+
| labeled arrays: `xarray.DataArray`, `pandas.Series` | N-D array with `_ArrayLabel_`, `_ArrayCoords_` and `_ArrayUnits_` |
|
|
297
|
+
| categoricals: `pandas.Categorical`, category/dictionary columns, numpy string arrays with few distinct values | enumeration (`_EnumKey_`/`_EnumValue_`, `_EnumOrdered_`) |
|
|
298
|
+
| `xarray.Dataset`, dataclasses, attrs classes, pydantic models, namedtuples | object of their fields |
|
|
299
|
+
| numpy object arrays | a number array if they hold numbers, one stacked array if they hold equal-shaped arrays, otherwise nested lists of their elements (as jsonlab stores MATLAB cell arrays) |
|
|
300
|
+
| `datetime`/`date`/`time`, `datetime64` | ISO 8601 strings |
|
|
301
|
+
| `timedelta`, `timedelta64` | seconds |
|
|
302
|
+
| `Decimal`, `UUID`, `Path`, `Enum` | strings (an `int`/`str` enum by its value) |
|
|
303
|
+
|
|
304
|
+
The class of a converted object is recorded in `"_DataInfo_": {"PythonClass": ...}` (set
|
|
305
|
+
`typeinfo=False` to omit it). Loading gives numpy arrays, dicts and lists by default (a table as a
|
|
306
|
+
dict of its columns), which is also what MATLAB/jsonlab reads; `restore=True` rebuilds the
|
|
307
|
+
original objects:
|
|
308
|
+
|
|
309
|
+
```
|
|
310
|
+
import jdata as jd, pandas as pd, torch
|
|
311
|
+
|
|
312
|
+
df = pd.DataFrame({'name': ['a', 'b'], 'age': [21, 22], 'sex': pd.Categorical(['M', 'F'])})
|
|
313
|
+
jd.save({'table': df, 'weights': torch.randn(3, 4)}, 'data.jdb')
|
|
314
|
+
|
|
315
|
+
jd.load('data.jdb') # {'table': {'name': [...], 'age': array(...), ...}, 'weights': array(...)}
|
|
316
|
+
jd.load('data.jdb', restore=True) # {'table': DataFrame, 'weights': tensor}
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
To save a table in the row form jsonlab reads as a MATLAB `table`, use `table='records'`
|
|
320
|
+
(`_TableCols_`/`_TableRecords_`).
|
|
321
|
+
|
|
322
|
+
A class can control how it is saved by defining `__jdata__()` (returning anything `encode()`
|
|
323
|
+
handles) and, to be restored, a `__from_jdata__(d)` classmethod. Classes you do not own can be
|
|
324
|
+
registered, by the class or by its name without importing it:
|
|
325
|
+
|
|
326
|
+
```
|
|
327
|
+
jd.register(MyDataclass) # saved by its fields, rebuilt by restore=True
|
|
328
|
+
jd.register('torch.nn.Parameter', encode=lambda p: p.detach().numpy(),
|
|
329
|
+
decode=lambda a: torch.nn.Parameter(torch.from_numpy(a)))
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Only the classes known to `jdata` and those registered are rebuilt: a class named in a file is
|
|
333
|
+
never imported or constructed from that name, so loading an untrusted file does not run its code.
|
|
334
|
+
|
|
284
335
|
## Reading JSON via REST-API
|
|
285
336
|
|
|
286
337
|
If a REST-API (URL) is given as the first input of `load`, it reads the JSON data directly
|
|
@@ -25,9 +25,20 @@ into JData compatible dict-based objects
|
|
|
25
25
|
* python bytes/bytearray objects ==> unchanged (JData/JSON bytestream)
|
|
26
26
|
* python set objects ==> unchanged (JData/JSON arrays)
|
|
27
27
|
* python complex numbers and complex arrays ==> JData complex array objects
|
|
28
|
-
* numpy.ndarray objects ==> JData array objects
|
|
29
|
-
|
|
30
|
-
*
|
|
28
|
+
* numpy.ndarray objects ==> JData array objects (object, string, structured and
|
|
29
|
+
datetime arrays included)
|
|
30
|
+
* arrays of other libraries (torch, cupy, jax, PIL, ... anything with __array__,
|
|
31
|
+
__dlpack__ or the buffer protocol) ==> JData array objects
|
|
32
|
+
* tables (pandas, polars, pyarrow, or anything with __dataframe__ or
|
|
33
|
+
__arrow_c_stream__) ==> JData table objects (_TableData_)
|
|
34
|
+
* labeled arrays (xarray.DataArray, pandas.Series) ==> JData arrays with _ArrayLabel_,
|
|
35
|
+
_ArrayCoords_ and _ArrayUnits_
|
|
36
|
+
* categoricals ==> JData enumerations (_EnumKey_/_EnumValue_)
|
|
37
|
+
* dataclasses, attrs classes, pydantic models, namedtuples ==> JData objects
|
|
38
|
+
* objects with a __jdata__() method, and classes added with register()
|
|
39
|
+
|
|
40
|
+
The class of a converted object is kept in "_DataInfo_"; decode(..., restore=True)
|
|
41
|
+
rebuilds it, for the classes jdata knows and those added with register().
|
|
31
42
|
|
|
32
43
|
The JData-encoded data object can then be decoded using ``decode``
|
|
33
44
|
to restore the original data types
|
|
@@ -42,10 +53,21 @@ from . import csvtsv
|
|
|
42
53
|
from . import h5
|
|
43
54
|
from . import jnifti
|
|
44
55
|
from . import jgifti
|
|
56
|
+
from . import jeeg
|
|
57
|
+
from . import jctf
|
|
58
|
+
from . import jfiff
|
|
59
|
+
from . import jmef3
|
|
45
60
|
from . import jpath
|
|
46
61
|
from . import jschema
|
|
47
62
|
from . import njprep
|
|
48
63
|
from . import neurojson
|
|
64
|
+
from . import zlibmt
|
|
65
|
+
from . import njcas
|
|
66
|
+
from . import njdigest
|
|
67
|
+
from . import njbids
|
|
68
|
+
from . import njcouch
|
|
69
|
+
from . import njdoi
|
|
70
|
+
from . import jtypes
|
|
49
71
|
|
|
50
72
|
# Re-export all public functions from submodules
|
|
51
73
|
from .jdata import *
|
|
@@ -55,12 +77,26 @@ from .csvtsv import *
|
|
|
55
77
|
from .h5 import *
|
|
56
78
|
from .jnifti import *
|
|
57
79
|
from .jgifti import *
|
|
80
|
+
from .jeeg import *
|
|
81
|
+
from .jctf import *
|
|
82
|
+
from .jfiff import *
|
|
83
|
+
from .jmef3 import *
|
|
58
84
|
from .jpath import *
|
|
59
85
|
from .jschema import *
|
|
60
86
|
from .njprep import *
|
|
61
87
|
from .neurojson import *
|
|
88
|
+
from .zlibmt import *
|
|
89
|
+
from .njcas import *
|
|
90
|
+
from .njdigest import *
|
|
91
|
+
from .njbids import *
|
|
92
|
+
from .njcouch import *
|
|
93
|
+
from .njdoi import *
|
|
94
|
+
from .jtypes import *
|
|
95
|
+
|
|
96
|
+
# njcli is deliberately not star-imported: its `main` is a console entry point,
|
|
97
|
+
# not part of the library API.
|
|
62
98
|
|
|
63
|
-
__version__ = "0.9.
|
|
99
|
+
__version__ = "0.9.7"
|
|
64
100
|
__all__ = (
|
|
65
101
|
jdata.__all__
|
|
66
102
|
+ jfile.__all__
|
|
@@ -69,10 +105,21 @@ __all__ = (
|
|
|
69
105
|
+ h5.__all__
|
|
70
106
|
+ jnifti.__all__
|
|
71
107
|
+ jgifti.__all__
|
|
108
|
+
+ jeeg.__all__
|
|
109
|
+
+ jctf.__all__
|
|
110
|
+
+ jfiff.__all__
|
|
111
|
+
+ jmef3.__all__
|
|
72
112
|
+ jpath.__all__
|
|
73
113
|
+ jschema.__all__
|
|
74
114
|
+ njprep.__all__
|
|
75
115
|
+ neurojson.__all__
|
|
116
|
+
+ zlibmt.__all__
|
|
117
|
+
+ njcas.__all__
|
|
118
|
+
+ njdigest.__all__
|
|
119
|
+
+ njbids.__all__
|
|
120
|
+
+ njcouch.__all__
|
|
121
|
+
+ njdoi.__all__
|
|
122
|
+
+ jtypes.__all__
|
|
76
123
|
+ [
|
|
77
124
|
"jdata",
|
|
78
125
|
"jfile",
|
|
@@ -81,10 +128,21 @@ __all__ = (
|
|
|
81
128
|
"h5",
|
|
82
129
|
"jnifti",
|
|
83
130
|
"jgifti",
|
|
131
|
+
"jeeg",
|
|
132
|
+
"jctf",
|
|
133
|
+
"jfiff",
|
|
134
|
+
"jmef3",
|
|
84
135
|
"jpath",
|
|
85
136
|
"jschema",
|
|
86
137
|
"neurojson",
|
|
87
138
|
"njprep",
|
|
139
|
+
"zlibmt",
|
|
140
|
+
"njcas",
|
|
141
|
+
"njdigest",
|
|
142
|
+
"njbids",
|
|
143
|
+
"njcouch",
|
|
144
|
+
"njdoi",
|
|
145
|
+
"jtypes",
|
|
88
146
|
]
|
|
89
147
|
)
|
|
90
148
|
|
|
@@ -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)
|
|
@@ -132,7 +159,7 @@ def load_csv_tsv(
|
|
|
132
159
|
# Convert numeric values in each row
|
|
133
160
|
converted_rows = []
|
|
134
161
|
for row in rows:
|
|
135
|
-
converted_row = [
|
|
162
|
+
converted_row = [tonumbers(cell) for cell in row]
|
|
136
163
|
converted_rows.append(converted_row)
|
|
137
164
|
rows = converted_rows
|
|
138
165
|
|
|
@@ -185,7 +185,25 @@ def loadh5(filename, *args, **kwargs) -> Union[Dict, Tuple[Dict, Dict]]:
|
|
|
185
185
|
sub_data, axes=tuple(range(sub_data.ndim - 1, -1, -1))
|
|
186
186
|
)
|
|
187
187
|
|
|
188
|
-
|
|
188
|
+
if isinstance(sub_data, (np.ndarray, np.void)) and sub_data.dtype.names:
|
|
189
|
+
# a compound dataset (a complex array as saveh5 writes it: a Real/Imag
|
|
190
|
+
# pair of members, or a sparse one) as a dict of its members, which
|
|
191
|
+
# fix_data combines; any other compound dataset is kept as read
|
|
192
|
+
members = {}
|
|
193
|
+
for fname in sub_data.dtype.names:
|
|
194
|
+
val = np.asarray(sub_data[fname])
|
|
195
|
+
members[fname] = val.item() if val.ndim == 0 else val
|
|
196
|
+
fixed = fix_data(members, attr, inputdata["opt"])
|
|
197
|
+
if not isinstance(fixed, dict):
|
|
198
|
+
if (
|
|
199
|
+
isinstance(fixed, np.ndarray)
|
|
200
|
+
and fixed.ndim > 1
|
|
201
|
+
and inputdata["opt"]["dotranspose"]
|
|
202
|
+
):
|
|
203
|
+
fixed = np.transpose(fixed, axes=tuple(range(fixed.ndim - 1, -1, -1)))
|
|
204
|
+
sub_data = fixed
|
|
205
|
+
else:
|
|
206
|
+
sub_data = fix_data(sub_data, attr, inputdata["opt"])
|
|
189
207
|
|
|
190
208
|
data[name] = sub_data
|
|
191
209
|
meta[name] = attr
|
|
@@ -284,14 +302,14 @@ def loadh5(filename, *args, **kwargs) -> Union[Dict, Tuple[Dict, Dict]]:
|
|
|
284
302
|
elif len(args) == 1:
|
|
285
303
|
path = args[0]
|
|
286
304
|
|
|
305
|
+
# Merge kwargs into opt (before the defaults below, which read them)
|
|
306
|
+
opt.update(kwargs)
|
|
307
|
+
|
|
287
308
|
# Set default options
|
|
288
309
|
opt["dotranspose"] = opt.get("Transpose", opt.get("transpose", 0))
|
|
289
310
|
opt["stringarray"] = opt.get("StringArray", opt.get("stringarray", 0))
|
|
290
311
|
opt["rootpath"] = path
|
|
291
312
|
|
|
292
|
-
# Merge kwargs into opt
|
|
293
|
-
opt.update(kwargs)
|
|
294
|
-
|
|
295
313
|
# Handle file opening
|
|
296
314
|
if isinstance(filename, h5py.File):
|
|
297
315
|
loc = filename
|
|
@@ -321,7 +339,7 @@ def loadh5(filename, *args, **kwargs) -> Union[Dict, Tuple[Dict, Dict]]:
|
|
|
321
339
|
if path:
|
|
322
340
|
try:
|
|
323
341
|
# Try to open as group first
|
|
324
|
-
if path in loc:
|
|
342
|
+
if path in loc and isinstance(loc[path], h5py.Group):
|
|
325
343
|
rootgid = loc[path]
|
|
326
344
|
data, meta = load_one(rootgid, opt)
|
|
327
345
|
else:
|
|
@@ -440,7 +458,9 @@ def saveh5(data: Any, fname, *args, **kwargs):
|
|
|
440
458
|
return struct2h5(name, item, handle, level, opt)
|
|
441
459
|
elif isinstance(item, (str, bytes)):
|
|
442
460
|
return mat2h5(name, item, handle, level, opt)
|
|
443
|
-
elif isinstance(item, (bool, int, float, complex, np.ndarray)):
|
|
461
|
+
elif isinstance(item, (bool, int, float, complex, np.ndarray, np.generic)):
|
|
462
|
+
return mat2h5(name, item, handle, level, opt)
|
|
463
|
+
elif hasattr(item, "tocoo"): # a scipy sparse matrix
|
|
444
464
|
return mat2h5(name, item, handle, level, opt)
|
|
445
465
|
else:
|
|
446
466
|
return OrderedDict()
|
|
@@ -543,6 +563,21 @@ def saveh5(data: Any, fname, *args, **kwargs):
|
|
|
543
563
|
|
|
544
564
|
is1dvector = False
|
|
545
565
|
|
|
566
|
+
if issparse(item):
|
|
567
|
+
# a sparse matrix: its nonzeros by their 1-based column-major linear index
|
|
568
|
+
# (the SparseIndex/Real/Imag compound loadh5 reads back)
|
|
569
|
+
coo = item.tocoo()
|
|
570
|
+
sparse_data = {
|
|
571
|
+
"Size": list(coo.shape),
|
|
572
|
+
"SparseIndex": coo.col.astype(np.uint64) * np.uint64(coo.shape[0])
|
|
573
|
+
+ coo.row.astype(np.uint64)
|
|
574
|
+
+ np.uint64(1),
|
|
575
|
+
"Real": coo.data.real,
|
|
576
|
+
}
|
|
577
|
+
if np.iscomplexobj(coo.data):
|
|
578
|
+
sparse_data["Imag"] = coo.data.imag
|
|
579
|
+
return sparse2h5(name, sparse_data, handle, level, opt)
|
|
580
|
+
|
|
546
581
|
# Convert to numpy array if needed
|
|
547
582
|
if not isinstance(item, np.ndarray):
|
|
548
583
|
if isinstance(item, (list, tuple)):
|
|
@@ -581,51 +616,25 @@ def saveh5(data: Any, fname, *args, **kwargs):
|
|
|
581
616
|
|
|
582
617
|
# Handle complex numbers
|
|
583
618
|
if isinstance(item, np.ndarray) and np.iscomplexobj(item):
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
opt["complexformat"] = ["Real", "Imag"]
|
|
604
|
-
|
|
605
|
-
# Create compound datatype for complex numbers
|
|
606
|
-
complex_data = np.empty(
|
|
607
|
-
item.shape,
|
|
608
|
-
dtype=[
|
|
609
|
-
(opt["complexformat"][0], item.real.dtype),
|
|
610
|
-
(opt["complexformat"][1], item.imag.dtype),
|
|
611
|
-
],
|
|
612
|
-
)
|
|
613
|
-
complex_data[opt["complexformat"][0]] = item.real
|
|
614
|
-
complex_data[opt["complexformat"][1]] = item.imag
|
|
615
|
-
item = complex_data
|
|
616
|
-
|
|
617
|
-
# Handle real arrays including sparse
|
|
618
|
-
elif isinstance(item, np.ndarray) and issparse(item):
|
|
619
|
-
# Handle real sparse arrays
|
|
620
|
-
idx = find(item)
|
|
621
|
-
sparse_data = {
|
|
622
|
-
"Size": item.shape,
|
|
623
|
-
"SparseIndex": idx[0] * item.shape[1]
|
|
624
|
-
+ idx[1]
|
|
625
|
-
+ 1, # Convert to 1-based linear index
|
|
626
|
-
"Real": item.data,
|
|
627
|
-
}
|
|
628
|
-
return sparse2h5(name, sparse_data, handle, level, opt)
|
|
619
|
+
# Handle complex dense arrays
|
|
620
|
+
if not (
|
|
621
|
+
"complexformat" in opt
|
|
622
|
+
and isinstance(opt["complexformat"], list)
|
|
623
|
+
and len(opt["complexformat"]) == 2
|
|
624
|
+
):
|
|
625
|
+
opt["complexformat"] = ["Real", "Imag"]
|
|
626
|
+
|
|
627
|
+
# Create compound datatype for complex numbers
|
|
628
|
+
complex_data = np.empty(
|
|
629
|
+
item.shape,
|
|
630
|
+
dtype=[
|
|
631
|
+
(opt["complexformat"][0], item.real.dtype),
|
|
632
|
+
(opt["complexformat"][1], item.imag.dtype),
|
|
633
|
+
],
|
|
634
|
+
)
|
|
635
|
+
complex_data[opt["complexformat"][0]] = item.real
|
|
636
|
+
complex_data[opt["complexformat"][1]] = item.imag
|
|
637
|
+
item = complex_data
|
|
629
638
|
|
|
630
639
|
# Determine dataset shape
|
|
631
640
|
if isinstance(item, np.ndarray):
|
|
@@ -651,6 +660,7 @@ def saveh5(data: Any, fname, *args, **kwargs):
|
|
|
651
660
|
ds = handle.create_dataset(
|
|
652
661
|
name,
|
|
653
662
|
shape,
|
|
663
|
+
data=item.decode("utf-8") if isinstance(item, bytes) else item,
|
|
654
664
|
dtype=dt,
|
|
655
665
|
compression=compression,
|
|
656
666
|
compression_opts=compression_opts,
|
|
@@ -787,13 +797,10 @@ def saveh5(data: Any, fname, *args, **kwargs):
|
|
|
787
797
|
opt["scalar"] = opt.get("Scalar", opt.get("scalar", 1))
|
|
788
798
|
opt["skipempty"] = False # h5py handles empty datasets
|
|
789
799
|
|
|
790
|
-
# Handle root name
|
|
800
|
+
# Handle root name; as in easyh5, rootname='' saves to the file's root group
|
|
791
801
|
if "rootname" in opt:
|
|
792
802
|
rootname = "/" + opt["rootname"]
|
|
793
803
|
|
|
794
|
-
if rootname.endswith("/"):
|
|
795
|
-
rootname = rootname + "data"
|
|
796
|
-
|
|
797
804
|
# Apply JData encoding if requested
|
|
798
805
|
if opt.get("JData", opt.get("jdata", 0)):
|
|
799
806
|
data = jdataencode(data, base64=False, **opt)
|
|
@@ -913,6 +920,14 @@ def regrouph5(root: Union[Dict, Any], *args) -> Dict:
|
|
|
913
920
|
# Filter names if dictionary filter is provided
|
|
914
921
|
group_names = list(newnames.keys())
|
|
915
922
|
if dict_filter:
|
|
923
|
+
# indexed fields outside the filter are kept as they are
|
|
924
|
+
for name in group_names:
|
|
925
|
+
if name not in dict_filter:
|
|
926
|
+
for num in newnames[name]:
|
|
927
|
+
dataname = f"{name}{num}"
|
|
928
|
+
for k in range(len(root_list)):
|
|
929
|
+
obj = root_list[k][dataname]
|
|
930
|
+
data[k][dataname] = regrouph5(obj) if isinstance(obj, dict) else obj
|
|
916
931
|
group_names = [name for name in group_names if name in dict_filter]
|
|
917
932
|
|
|
918
933
|
# Process grouped fields in reverse order to maintain field positions
|