jdata 0.9.6__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.6/jdata.egg-info → jdata-0.9.7}/PKG-INFO +52 -1
- {jdata-0.9.6 → jdata-0.9.7}/README.md +51 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/__init__.py +19 -4
- {jdata-0.9.6 → jdata-0.9.7}/jdata/__main__.py +1 -1
- {jdata-0.9.6 → jdata-0.9.7}/jdata/csvtsv.py +1 -1
- {jdata-0.9.6 → jdata-0.9.7}/jdata/h5.py +70 -55
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jdata.py +204 -65
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jdictionary.py +5 -3
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jfile.py +12 -7
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jnifti.py +5 -0
- jdata-0.9.7/jdata/jtypes.py +855 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/neurojson.py +3 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njbids.py +1 -1
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njprep.py +16 -13
- {jdata-0.9.6 → jdata-0.9.7/jdata.egg-info}/PKG-INFO +52 -1
- {jdata-0.9.6 → jdata-0.9.7}/jdata.egg-info/SOURCES.txt +7 -0
- {jdata-0.9.6 → jdata-0.9.7}/pyproject.toml +1 -1
- {jdata-0.9.6 → jdata-0.9.7}/setup.py +1 -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.6 → jdata-0.9.7}/test/testjd.py +19 -0
- jdata-0.9.7/test/testjtypes.py +693 -0
- {jdata-0.9.6 → jdata-0.9.7}/LICENSE.txt +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/MANIFEST.in +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jctf.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jeeg.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jfiff.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jgifti.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jmef3.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jpath.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/jschema.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njcas.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njcli.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njcouch.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njdigest.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njdoi.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/njencode.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata/zlibmt.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata.egg-info/dependency_links.txt +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata.egg-info/entry_points.txt +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata.egg-info/requires.txt +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/jdata.egg-info/top_level.txt +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/setup.cfg +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/test_comprehensive.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testgifti.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testjdict.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testjeeg.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testmeg.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testneuroj.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnifti.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjbids.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjcas.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjcli.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjcouch.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjdigest.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjdoi.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjrobust.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testnjviews.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testsnirf.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testspec.py +0 -0
- {jdata-0.9.6 → jdata-0.9.7}/test/testzlibmt.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
|
|
@@ -94,6 +94,7 @@ Dynamic: platform
|
|
|
94
94
|
- [How to build](#how-to-build)
|
|
95
95
|
- [How to use](#how-to-use)
|
|
96
96
|
- [Advanced interfaces](#advanced-interfaces)
|
|
97
|
+
- [Saving other Python objects](#saving-other-python-objects)
|
|
97
98
|
- [Reading JSON via REST-API](#reading-json-via-rest-api)
|
|
98
99
|
- [Using JSONPath to access and query complex datasets](#using-jsonpath-to-access-and-query-complex-datasets)
|
|
99
100
|
- [Downloading and caching `_DataLink_` referenced external data files](#downloading-and-caching-_datalink_-referenced-external-data-files)
|
|
@@ -355,6 +356,56 @@ decompress the data based on the `_ArrayZipType_` annotation present in the data
|
|
|
355
356
|
compression methods support multi-threading. To set the thread number, one should define an `nthread`
|
|
356
357
|
value in the option (`opt`) for both encoding and decoding.
|
|
357
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
|
+
|
|
358
409
|
## Reading JSON via REST-API
|
|
359
410
|
|
|
360
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
|
|
@@ -56,6 +67,7 @@ from . import njdigest
|
|
|
56
67
|
from . import njbids
|
|
57
68
|
from . import njcouch
|
|
58
69
|
from . import njdoi
|
|
70
|
+
from . import jtypes
|
|
59
71
|
|
|
60
72
|
# Re-export all public functions from submodules
|
|
61
73
|
from .jdata import *
|
|
@@ -79,11 +91,12 @@ from .njdigest import *
|
|
|
79
91
|
from .njbids import *
|
|
80
92
|
from .njcouch import *
|
|
81
93
|
from .njdoi import *
|
|
94
|
+
from .jtypes import *
|
|
82
95
|
|
|
83
96
|
# njcli is deliberately not star-imported: its `main` is a console entry point,
|
|
84
97
|
# not part of the library API.
|
|
85
98
|
|
|
86
|
-
__version__ = "0.9.
|
|
99
|
+
__version__ = "0.9.7"
|
|
87
100
|
__all__ = (
|
|
88
101
|
jdata.__all__
|
|
89
102
|
+ jfile.__all__
|
|
@@ -106,6 +119,7 @@ __all__ = (
|
|
|
106
119
|
+ njbids.__all__
|
|
107
120
|
+ njcouch.__all__
|
|
108
121
|
+ njdoi.__all__
|
|
122
|
+
+ jtypes.__all__
|
|
109
123
|
+ [
|
|
110
124
|
"jdata",
|
|
111
125
|
"jfile",
|
|
@@ -128,6 +142,7 @@ __all__ = (
|
|
|
128
142
|
"njbids",
|
|
129
143
|
"njcouch",
|
|
130
144
|
"njdoi",
|
|
145
|
+
"jtypes",
|
|
131
146
|
]
|
|
132
147
|
)
|
|
133
148
|
|
|
@@ -159,7 +159,7 @@ def load_csv_tsv(
|
|
|
159
159
|
# Convert numeric values in each row
|
|
160
160
|
converted_rows = []
|
|
161
161
|
for row in rows:
|
|
162
|
-
converted_row = [
|
|
162
|
+
converted_row = [tonumbers(cell) for cell in row]
|
|
163
163
|
converted_rows.append(converted_row)
|
|
164
164
|
rows = converted_rows
|
|
165
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
|