ndarrayarray 0.1.0__py3-none-any.whl → 0.2.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.
ndarrayarray/__init__.py CHANGED
@@ -1,18 +1,12 @@
1
- from darr import Array, RaggedArray
2
- from darr.datadir import DataDir
3
- from .ndarrayarray import *
4
- from . import _version
5
- __version__ = _version.get_versions()['version']
6
-
7
- def open(path, accessmode='r'):
8
- dd = DataDir(path)
9
- arraytype = dd.read_jsondict('arraydescription.json')['darrobject']
10
- if arraytype == 'Array':
11
- return Array(path=path, accessmode=accessmode)
12
- elif arraytype == 'RaggedArray':
13
- return RaggedArray(path=path, accessmode=accessmode)
14
- elif arraytype == 'NDArrayArray':
15
- return NDArrayArray(path=path, accessmode=accessmode)
16
- else:
17
- raise ValueError(f"'{arraytype}' not supported in this version of "
18
- f"Darr ({__version__}) ")
1
+ """A disk-backed sequence of arbitrarily shaped numeric arrays."""
2
+ from .ndarrayarray import (NDArrayArray, asndarrayarray, create_ndarrayarray,
3
+ delete_ndarrayarray)
4
+
5
+ __version__ = '0.2.0'
6
+ __all__ = ['NDArrayArray', 'asndarrayarray', 'create_ndarrayarray',
7
+ 'delete_ndarrayarray', 'open']
8
+
9
+
10
+ def open(path, accessmode='r'):
11
+ """Open an NDArrayArray directory (read-only by default)."""
12
+ return NDArrayArray(path, accessmode)
@@ -1,551 +1,339 @@
1
- from pathlib import Path
2
- from contextlib import contextmanager
3
-
4
- import numpy as np
5
- from ._version import get_versions
6
-
7
- from darr import Array, asarray, create_array, delete_array,\
8
- RaggedArray, asraggedarray, delete_raggedarray, create_raggedarray
9
- from darr.datadir import DataDir, create_datadir
10
- from darr.metadata import MetaData
11
- from .readcode import readcode, readcodefunc
12
- from darr.utils import wrap, check_accessmode
13
-
14
- __all__ = ['NDArrayArray', 'asndarrayarray', 'create_ndarrayarray',
15
- 'delete_ndarrayarray']
16
-
17
-
18
- class NDArrayArray:
19
- _valuesdirname = 'values'
20
- _indicesandshapesdirname = 'indicesandshapes'
21
- _arraydescrfilename = 'arraydescription.json'
22
- _metadatafilename = 'metadata.json'
23
- _readmefilename = 'README.txt'
24
- _protectedfiles = {_valuesdirname, _indicesandshapesdirname,
25
- _readmefilename, _metadatafilename,
26
- _arraydescrfilename}
27
- _formatversion = get_versions()['version']
28
-
29
- def __init__(self, path, accessmode='r'):
30
- self._datadir = DataDir(path=path,
31
- protectedpaths=self._protectedfiles)
32
- self._path = self._datadir._path
33
- self._accessmode = check_accessmode(accessmode)
34
- self._valuespath = self._path / self._valuesdirname
35
- self._indicesandshapespath = self._path / self._indicesandshapesdirname
36
- self._arraydescrpath = self._path / self._arraydescrfilename
37
- self._values = Array(self._valuespath, accessmode=self._accessmode)
38
- self._indicesandshapes = RaggedArray(self._indicesandshapespath,
39
- accessmode=self._accessmode)
40
- self._metadata = MetaData(self._path / self._metadatafilename,
41
- accessmode=accessmode)
42
- arrayinfo = {}
43
- arrayinfo['len'] = len(self._indicesandshapes)
44
- arrayinfo['size'] = self._values.size
45
- arrayinfo['numtype'] = self._values._arrayinfo['numtype']
46
- arrayinfo['darrversion'] = NDArrayArray._formatversion
47
- arrayinfo['darrobject'] = 'VarDimArray'
48
- self._arrayinfo = arrayinfo
49
-
50
- @property
51
- def accessmode(self):
52
- """Data access mode of metadata, {'r', 'r+'}."""
53
- return self._accessmode
54
-
55
- @accessmode.setter
56
- def accessmode(self, value):
57
- self._accessmode = check_accessmode(value)
58
- self._metadata.accessmode = value
59
- self._values.accessmode = value
60
- self._indicesandshapes.accessmode = value
61
-
62
- @property
63
- def dtype(self):
64
- """Numpy data type of the array values.
65
-
66
- """
67
- return self._values._dtype
68
-
69
- @property
70
- def datadir(self):
71
- """Data directory object with many useful methods, such as
72
- writing information to text or json files, archiving all data,
73
- calculating checksums etc."""
74
- return self._datadir
75
-
76
- @property
77
- def narrays(self):
78
- """number of subarrays in the RaggedArray.
79
-
80
- """
81
- return len(self._indicesandshapes)
82
-
83
- @property
84
- def metadata(self):
85
- """
86
- Dictionary of meta data.
87
-
88
- """
89
- return self._metadata
90
-
91
- @property
92
- def mb(self):
93
- """Storage size in megabytes of the ragged array.
94
-
95
- """
96
- return self._values.mb + self._indicesandshapes.mb
97
-
98
- @property
99
- def path(self):
100
- """File system path to array data"""
101
- return self._path
102
-
103
- @property
104
- def size(self):
105
- """Total number of values in the ragged array."""
106
- return int(self._values._size)
107
-
108
- @property
109
- def readcodelanguages(self):
110
- """Tuple of the languages that the `readcode` method can produce
111
- reading code for. Code in these languages is also included in the
112
- README.txt file that is stored as part of the array ."""
113
- languages = []
114
- for lang in readcodefunc.keys():
115
- if readcode(self, lang) is not None:
116
- languages.append(lang)
117
- return tuple(sorted(languages))
118
-
119
- def __getitem__(self, item):
120
- if not np.issubdtype(type(item), np.integer):
121
- raise TypeError("Only integers can be used for indexing " \
122
- "VarDimArrays, which '{}' is not".format(item))
123
- indicesandshape = self._indicesandshapes[item]
124
- index = slice(*indicesandshape[:2])
125
- shape = indicesandshape[2:]
126
- return self._values[index].reshape(shape)
127
-
128
- def __len__(self):
129
- return len(self._indicesandshapes)
130
-
131
- def __repr__(self):
132
- return f'NDArrayArray ({self.narrays} variable dimension subarrays ' \
133
- f'({self.accessmode})'
134
-
135
- __str__ = __repr__
136
-
137
- def _update_readmetxt(self):
138
- txt = readmetxt(self)
139
- self._datadir._write_txt(self._readmefilename, txt, overwrite=True)
140
-
141
- def _update_arraydescr(self, **kwargs):
142
- self._arrayinfo.update(kwargs)
143
- self._datadir._write_jsondict(filename=self._arraydescrfilename,
144
- d=self._arrayinfo, overwrite=True)
145
-
146
- def _append(self, array, valfd, isaindfdv, isavalfd, vallen,
147
- isavallen):
148
- """Private method that appends data but does not update attributes
149
- and info/readme files.
150
-
151
- Parameters
152
- ----------
153
- array
154
- valfd: file descriptor
155
- File with array values.
156
- isaindfdv: file descriptor
157
- File with indicesandshapes array indices.
158
- isavalfd: file descriptor
159
- File with indicesandshapes array values.
160
- vallen: int
161
- The current length of the values array.
162
- isavallen: int
163
- The current length of the indicesandshapes values arrays
164
-
165
- Returns
166
- -------
167
-
168
- """
169
- array = np.asarray(array, dtype=self.dtype)
170
- shape = array.shape
171
- # append values to values array
172
- vlenincr = self._values._append(array.flatten(),
173
- valfd)
174
- # append index and shape info to indicesandshapes raggedarray
175
- indshape = [vallen, vallen+array.size] + list(shape)
176
- isavallenincr, isaindlenincr = \
177
- self._indicesandshapes._append(array=indshape, fdv=isavalfd,
178
- fdi=isaindfdv,
179
- vlen=isavallen)
180
- return (vlenincr, isavallenincr, isaindlenincr)
181
-
182
- def append(self, array):
183
- """Append array-like objects to the ragged array.
184
-
185
- The shape of the data and the darr must be compliant. The length of
186
- its first axis may vary, but if the are more axes, these should
187
- have the same lengths as all other subarrays (which is the `atom` of
188
- the raged array). When appending data repeatedly it is more efficient
189
- to use `iterappend`.
190
-
191
-
192
- Parameters
193
- ----------
194
- array: array-like object
195
- This can be a numpy array, a sequence that can be converted into a
196
- numpy array.
197
-
198
- Returns
199
- -------
200
- None
201
-
202
- """
203
- with self.open_arrays() as ((isaindmm, isavalmm),
204
- (isaindfdv, isavalfd),
205
- (valmm, valfd)):
206
- vallen = self._values.shape[0]
207
- isavallen = self._indicesandshapes._values.shape[0]
208
- (vlenincr, isavallenincr, isaindlenincr) = \
209
- self._append(array=array, valfd=valfd, isaindfdv=isaindfdv,
210
- isavalfd=isavalfd, vallen=vallen,
211
- isavallen=isavallen)
212
- self._values._update_len(lenincrease=vlenincr)
213
- self._values._update_arrayinfo()
214
- self._values._update_readmetxt()
215
- self._indicesandshapes._values._update_len(lenincrease=isavallenincr)
216
- self._indicesandshapes._values._update_arrayinfo()
217
- self._indicesandshapes._values._update_readmetxt()
218
- self._indicesandshapes._indices._update_len(lenincrease=isaindlenincr)
219
- self._indicesandshapes._indices._update_arrayinfo()
220
- self._indicesandshapes._indices._update_readmetxt()
221
- self._update_arraydescr(len=len(self._indicesandshapes),
222
- size=self._values.size)
223
- self._update_readmetxt()
224
-
225
-
226
- def copy(self, path, dtype=None, accessmode='r', overwrite=False):
227
- """Copy vardimarray to a different path, potentially changing its
228
- dtype.
229
-
230
- The copying is performed in chunks to avoid RAM memory overflow for
231
- very large darr arrays.
232
-
233
- Parameters
234
- ----------
235
- path: str or pathlib.Path
236
- dtype: <dtype, None>
237
- Numpy data type of the copy. Default is None, which corresponds to
238
- the dtype of the darr to be copied.
239
- accessmode: {'r', 'r+'}, default 'r'
240
- File access mode of the darr data of the returned Darr
241
- object. `r` means read-only, `r+` means read-write.
242
- overwrite: (True, False), optional
243
- Overwrites existing darr data if it exists. Note that a
244
- darr path is a directory. If that directory contains
245
- additional files, these will not be removed and an OSError is
246
- raised. Default is `False`.
247
-
248
- Returns
249
- -------
250
- Array
251
- copy of the darr array
252
-
253
- """
254
- arrayiterable = (self[i] for i in range(len(self)))
255
- metadata = dict(self.metadata)
256
- if dtype is None:
257
- dtype = self.dtype
258
- return asndarrayarray(path=path, arrayiterable=arrayiterable,
259
- dtype=dtype, metadata=metadata,
260
- accessmode=accessmode, overwrite=overwrite)
261
- # FIXME
262
- @contextmanager
263
- def _view(self, accessmode=None):
264
- with self._indicesandshapes._view(accessmode=accessmode) as (iv, _), \
265
- self._values._open_array(accessmode=accessmode) as (vv, _):
266
- yield iv, vv
267
-
268
- @contextmanager
269
- def open_arrays(self, accessmode=None):
270
- with self._indicesandshapes.open_arrays(accessmode=accessmode) as \
271
- ((isaindmm, isavalmm), (isavalfd, isaindfdv)), \
272
- self._values._open_array(accessmode=accessmode) as (valmm, valfd):
273
- yield (isaindmm, isavalmm), (isaindfdv, isavalfd), (valmm, valfd)
274
-
275
- def iter_arrays(self, startindex=0, endindex=None, stepsize=1,
276
- accessmode=None):
277
- """Iterate over vardim array yielding subarrays.
278
-
279
- startindex: <int, None>
280
- Start index value.
281
- Default is None, which means to start at the beginning.
282
- endindex: <int, None>
283
- End index value.
284
- Default is None, which means to end at the end.
285
- stepsize: <int, None>
286
- Size of the shift per iteration across the first axis.
287
- Default is None, which means that `stepsize` equals `chunklen`.
288
-
289
- """
290
-
291
- if endindex is None:
292
- endindex = self.narrays
293
- with self._view(accessmode=accessmode):
294
- for i in range(startindex, endindex, stepsize):
295
- yield np.array(self[i], copy=True)
296
-
297
- def iterappend(self, arrayiterable):
298
- """Iteratively append data from a data iterable.
299
-
300
- The iterable has to yield array-like objects compliant with darr.
301
- The length of first dimension of these objects may be different,
302
- but the length of other dimensions, if any, has to be the same.
303
-
304
- Parameters
305
- ----------
306
- arrayiterable: an iterable that yield array-like objects
307
-
308
- Returns
309
- -------
310
- None
311
-
312
- """
313
-
314
- with self.open_arrays() as ((isaindmm, isavalmm),
315
- (isaindfdv, isavalfd),
316
- (valmm, valfd)):
317
-
318
- vallen = self._values.shape[0]
319
- isavallen = self._indicesandshapes._values.shape[0]
320
- isaindlen = self._indicesandshapes._indices.shape[0]
321
- for a in arrayiterable:
322
- (vlenincr, isavallenincr, isaindlenincr) = \
323
- self._append(array=a, valfd=valfd,
324
- isaindfdv=isaindfdv,
325
- isavalfd=isavalfd, vallen=vallen,
326
- isavallen=isavallen)
327
- vallen += vlenincr
328
- isavallen += isavallenincr
329
- isaindlen += isaindlenincr
330
- self._values._update_len(lenincrease=vallen)
331
- self._values._update_arrayinfo()
332
- self._values._update_readmetxt()
333
- self._indicesandshapes._values._update_len(lenincrease=isavallen)
334
- self._indicesandshapes._values._update_arrayinfo()
335
- self._indicesandshapes._values._update_readmetxt()
336
- self._indicesandshapes._indices._update_len(lenincrease=isaindlen)
337
- self._indicesandshapes._indices._update_arrayinfo()
338
- self._indicesandshapes._indices._update_readmetxt()
339
- self._update_arraydescr(len=len(self._indicesandshapes),
340
- size=self._values.size)
341
- self._update_readmetxt()
342
-
343
-
344
- def archive(self, filepath=None, compressiontype='xz', overwrite=False):
345
- """Archive ragged array data into a single compressed file.
346
-
347
- Parameters
348
- ----------
349
- filepath: str
350
- Name of the archive. In None, it will be derived from the data's
351
- path name.
352
- compressiontype: str
353
- One of 'xz', 'gz', or 'bz2', corresponding to the gzip, bz2 and
354
- lzma compression algorithms supported by the Python standard
355
- library.
356
- overwrite: (True, False), optional
357
- Overwrites existing archive if it exists. Default is False.
358
-
359
- Returns
360
- -------
361
- pathlib.Path
362
- The path of the created archive
363
-
364
- Notes
365
- -----
366
- See the `tarfile library`_ for more info on archiving formats
367
-
368
- .. _tarfile library:
369
- https://docs.python.org/3/library/tarfile.html
370
-
371
- """
372
- return self._datadir.archive(filepath=filepath,
373
- compressiontype=compressiontype,
374
- overwrite=overwrite)
375
-
376
- def asndarrayarray(path, arrayiterable, dtype=None, metadata=None,
377
- accessmode='r+', indextype='int64', overwrite=False):
378
- """Creates an empty NDArrayArray.
379
-
380
- Parameters
381
- ----------
382
- path : str or pathlib.Path
383
- Path to disk-based array directory.
384
- arrayiterable: iterator yielding array-like objects
385
- This can be a numpy array, a sequence that can be converted into a
386
- numpy array, or an iterator that yields such objects. The latter
387
- will be concatenated along the first dimension.
388
- dtype : dtype, optional
389
- The type of the `darr`. Default is 'float64'
390
- metadata: {None, dict}
391
- Dictionary with metadata to be saved in a separate JSON file. Default
392
- None
393
- accessmode : {'r', 'r+'}, default 'r'
394
- File access mode of the darr data. `r` means read-only, `r+` means
395
- read-write. `w` does not exist. To create new darr arrays, potentially
396
- overwriting an other one, use the `asarray` or `create_array`
397
- functions.
398
- indextype : dtype, optional
399
- The dtype of the index array underlying the disk-based ragged array
400
- format. Defaults to 'int64'. But other possibilities are int8','uint8',
401
- 'int16', 'uint16', 'int32', 'uint32', 'int64'. This determines the
402
- maximum length of the ragged array, but also how compatible the
403
- array is with other languages.
404
- overwrite: <True, False>, optional
405
- Overwrites existing darr data if it exists. Note that a darr
406
- paths is a directory. If that directory contains additional files,
407
- these will not be removed and an OSError is raised.
408
- Default is `False`.
409
-
410
- Returns
411
- -------
412
- NDArrayArray
413
- A NDArrayArray instance.
414
-
415
- """
416
- path = Path(path)
417
- supportedindextypes = ('int8','uint8', 'int16', 'uint16', 'int32',
418
- 'uint32', 'int64')
419
- if not indextype in supportedindextypes:
420
- raise ValueError(f'`indextype` {indextype} not one of '
421
- f'{supportedindextypes}')
422
- if not hasattr(arrayiterable, 'next'):
423
- arrayiterable = (a for a in arrayiterable)
424
- bd = create_datadir(path=path, overwrite=overwrite)
425
- firstarray = np.asarray(next(arrayiterable), dtype=dtype)
426
- dtype = firstarray.dtype
427
- valuespath = bd.path.joinpath(NDArrayArray._valuesdirname)
428
- indicesandshapespath = bd.path.joinpath(NDArrayArray._indicesandshapesdirname)
429
- valuesda = asarray(path=valuespath, array=firstarray.flatten(), dtype=dtype,
430
- accessmode='r+', overwrite=overwrite)
431
- firstindicesandshape = [[0, firstarray.size] + list(firstarray.shape)]
432
- indshapera = asraggedarray(path=indicesandshapespath,
433
- arrayiterable=firstindicesandshape,
434
- dtype=indextype, accessmode='r+',
435
- overwrite=overwrite)
436
- datainfo = {}
437
- datainfo['len'] = len(indshapera)
438
- datainfo['size'] = valuesda.size
439
- datainfo['numtype'] = valuesda._arrayinfo['numtype']
440
- datainfo['darrversion'] = Array._formatversion
441
- datainfo['darrobject'] = 'VarDimArray'
442
- bd._write_jsondict(filename=NDArrayArray._arraydescrfilename,
443
- d=datainfo, overwrite=overwrite)
444
- metadatapath = path.joinpath(Array._metadatafilename)
445
- if metadata is not None:
446
- bd._write_jsondict(filename=Array._metadatafilename,
447
- d=metadata, overwrite=overwrite)
448
- elif metadatapath.exists(): # no metadata but file exists, remove it
449
- metadatapath.unlink()
450
- vda = NDArrayArray(path=path, accessmode=accessmode)
451
- vda.iterappend(arrayiterable)
452
- return vda
453
-
454
-
455
- def create_ndarrayarray(path, dtype='float64', metadata=None,
456
- accessmode='r+', indextype='int64', overwrite=False):
457
- """Creates an empty NDArrayArray.
458
-
459
- Parameters
460
- ----------
461
- path : str or pathlib.Path
462
- Path to disk-based array directory.
463
- dtype : dtype, optional
464
- The type of the `darr`. Default is 'float64'
465
- metadata: {None, dict}
466
- Dictionary with metadata to be saved in a separate JSON file. Default
467
- None
468
- accessmode : {'r', 'r+'}, default 'r'
469
- File access mode of the darr data. `r` means read-only, `r+` means
470
- read-write. `w` does not exist. To create new darr arrays, potentially
471
- overwriting an other one, use the `asarray` or `create_array`
472
- functions.
473
- indextype : dtype, optional
474
- The dtype of the index array underlying the disk-based ragged array
475
- format. Defaults to 'int64'. But other possibilities are int8','uint8',
476
- 'int16', 'uint16', 'int32', 'uint32', 'int64'. This determines the
477
- maximum length of the ragged array, but also how compatible the
478
- array is with other languages.
479
- overwrite: <True, False>, optional
480
- Overwrites existing darr data if it exists. Note that a darr
481
- paths is a directory. If that directory contains additional files,
482
- these will not be removed and an OSError is raised.
483
- Default is `False`.
484
-
485
- Returns
486
- -------
487
- NDArrayArray
488
- A NDArrayArray instance.
489
-
490
- """
491
- ar = np.zeros([0], dtype=dtype) # 1D array with len0
492
- vda = asndarrayarray(path=path, arrayiterable=[ar], metadata=metadata,
493
- accessmode=accessmode, indextype=indextype,
494
- overwrite=overwrite)
495
- # the current ragged array has one element, which is an empty array
496
- # but we want an empty ragged array => we should get rid of the indices
497
- create_raggedarray(path=vda._indicesandshapespath,
498
- atom=(), dtype=np.int64, overwrite=True)
499
- vda._update_arraydescr(len=0, size=0)
500
- return NDArrayArray(vda.path, accessmode=accessmode)
501
-
502
- def readmetxt(ndaa):
503
- txt = wrap("This directory hold data for a VarDimArray, which is an "
504
- "experimental type of Darr array.") + ' \n\n'
505
- txt += wrap("A VarDimArray can be seen as a sequence of subarrays, "
506
- "each of which may have a variable number of dimensions that "
507
- "can be variable in length. In essence it is a sequence of "
508
- "ND-arrays that can have arbitrary shapes.") + ' \n\n'
509
- txt += wrap("VarDimArrays are still experimental, so an elaborate "
510
- "description is not yet provided. On disk, the array is saved "
511
- "as a combination of a Darr Array that holds the values and "
512
- "a Darr RaggedArray that holds information on the location "
513
- "and shape of each subarray in the values array.")
514
- return txt
515
-
516
- def readcodetxt(ndaa):
517
- txt = wrap("NOT IMPLEMENTED YET\n")
518
- return txt
519
-
520
- def delete_ndarrayarray(ndaa):
521
- """
522
- Delete Darr vardim array data from disk.
523
-
524
- Parameters
525
- ----------
526
- ndaa: RaggedArray or path to VarDimArray to be deleted.
527
-
528
- """
529
- try:
530
- if not isinstance(ndaa, NDArrayArray):
531
- ndaa = NDArrayArray(ndaa, accessmode='r+')
532
- except:
533
- raise TypeError(f"'{ndaa}' not recognized as a Darr vardim array")
534
- if not ndaa.accessmode == 'r+':
535
- raise OSError('Darr ragged array is read-only; set accessmode to '
536
- '"r+" to change')
537
- for fn in ndaa._protectedfiles:
538
- path = ndaa.path.joinpath(fn)
539
- if path.exists() and not path.is_dir():
540
- path.unlink()
541
- delete_array(ndaa._values)
542
- delete_raggedarray(ndaa._indicesandshapes)
543
- try:
544
- ndaa._path.rmdir()
545
- except OSError as error:
546
- message = f"Error: could not fully delete Darr vardim array " \
547
- f"directory " \
548
- f"'{ndaa.path}'. It may contain additional files that are " \
549
- f"not part of the darr. If so, these should be removed " \
550
- f"manually."
551
- raise OSError(message) from error
1
+ """A disk-backed sequence of arbitrarily shaped numeric NumPy arrays.
2
+
3
+ Only public darr APIs are used. Writers must have exclusive access.
4
+ """
5
+
6
+ from contextlib import contextmanager
7
+ import json
8
+ import math
9
+ import operator
10
+ from pathlib import Path
11
+ import tempfile
12
+
13
+ import darr
14
+ import numpy as np
15
+
16
+ __all__ = ['NDArrayArray', 'asndarrayarray', 'create_ndarrayarray',
17
+ 'delete_ndarrayarray']
18
+
19
+ _FORMAT = {'ndarrayarray': 1, 'order': 'C'}
20
+ _FILES = {'arraydescription.json', 'README.txt', 'values', 'shapes'}
21
+ _README = """NDArrayArray format version 1
22
+
23
+ This directory contains two ordinary Darr RaggedArrays:
24
+ values/: flattened numeric subarrays, in C (row-major) order.
25
+ shapes/: corresponding dimension lengths, stored as int64 arrays.
26
+ User metadata is stored on the values RaggedArray.
27
+
28
+ The number of committed subarrays is len(shapes). Any trailing entries in
29
+ values are uncommitted and must be ignored. A scalar has shape [] and one
30
+ value. Empty arrays retain all their dimensions, including zero-length axes.
31
+
32
+ Python reconstruction using only darr and NumPy:
33
+ import darr
34
+ values = darr.open('values')
35
+ shapes = darr.open('shapes')
36
+ array = values[i].reshape(tuple(shapes[i]), order='C')
37
+
38
+ Each component's README.txt describes its format and provides reading code.
39
+ In column-major languages, reshape to the reversed shape and then reverse
40
+ the axis order to reconstruct the original array.
41
+
42
+ Only one writer is supported. There are no cross-file transactions or
43
+ power-loss durability guarantees. Never modify the components separately.
44
+ """
45
+
46
+
47
+ def _mode(mode):
48
+ if mode not in ('r', 'r+'):
49
+ raise ValueError("accessmode must be 'r' or 'r+'")
50
+ return mode
51
+
52
+
53
+ def _dtype(dtype):
54
+ dtype = np.dtype(dtype)
55
+ if dtype.name not in {'int8', 'uint8', 'int16', 'uint16', 'int32',
56
+ 'uint32', 'int64', 'uint64', 'float16', 'float32',
57
+ 'float64', 'complex64', 'complex128'}:
58
+ raise ValueError(f'Unsupported numeric dtype: {dtype}')
59
+ return dtype
60
+
61
+
62
+ def _separate(source, destination):
63
+ source, destination = Path(source).resolve(), Path(destination).resolve()
64
+ if source == destination or source in destination.parents or destination in source.parents:
65
+ raise ValueError('Source and destination paths must not overlap')
66
+
67
+
68
+ class NDArrayArray:
69
+ """Open an NDArrayArray directory, read-only by default.
70
+
71
+ Indexing returns an independent NumPy array. A collection may exceed RAM,
72
+ but each retrieved subarray must fit in memory. All subarrays share one
73
+ numeric dtype. Legacy experimental directories require explicit migration.
74
+ """
75
+
76
+ def __init__(self, path, accessmode='r'):
77
+ self._path = Path(path).absolute()
78
+ self._accessmode = _mode(accessmode)
79
+ with (self.path / 'arraydescription.json').open(encoding='utf-8') as f:
80
+ description = json.load(f)
81
+ if description != _FORMAT:
82
+ raise ValueError('Unsupported NDArrayArray format; legacy experimental '
83
+ 'data must be migrated explicitly')
84
+ self._values = darr.open(self.path / 'values', accessmode=self.accessmode)
85
+ self._shapes = darr.open(self.path / 'shapes', accessmode=self.accessmode)
86
+ for component in (self._values, self._shapes):
87
+ if not isinstance(component, darr.RaggedArray) or component.atom != ():
88
+ raise ValueError('Components must be one-dimensional RaggedArrays')
89
+ if self._shapes.dtype != np.dtype('int64'):
90
+ raise ValueError('Shapes must have dtype int64')
91
+ if len(self._values) < len(self._shapes):
92
+ raise ValueError('Missing values for committed shapes')
93
+
94
+ @property
95
+ def path(self):
96
+ """Directory containing the collection."""
97
+ return self._path
98
+
99
+ @property
100
+ def accessmode(self):
101
+ """Access mode: 'r' or 'r+'."""
102
+ return self._accessmode
103
+
104
+ @accessmode.setter
105
+ def accessmode(self, value):
106
+ value = _mode(value)
107
+ self._values.accessmode = value
108
+ self._shapes.accessmode = value
109
+ self._accessmode = value
110
+
111
+ @property
112
+ def dtype(self):
113
+ return self._values.dtype
114
+
115
+ @property
116
+ def metadata(self):
117
+ """Persistent dictionary-like user metadata (on the values component)."""
118
+ return self._values.metadata
119
+
120
+ @property
121
+ def datadir(self):
122
+ return darr.DataDir(self.path, protectedpaths=_FILES)
123
+
124
+ @property
125
+ def narrays(self):
126
+ return len(self)
127
+
128
+ @property
129
+ def size(self):
130
+ """Number of numeric values in committed subarrays."""
131
+ if len(self._values) == len(self):
132
+ return self._values.size
133
+ # Recovery is exceptional; avoid loading any numeric subarray.
134
+ return sum(math.prod(int(d) for d in self._shapes[i]) for i in range(len(self)))
135
+
136
+ @property
137
+ def mb(self):
138
+ """Component storage in decimal megabytes, excluding text files."""
139
+ return self._values.mb + self._shapes.mb
140
+
141
+ def __len__(self):
142
+ return len(self._shapes)
143
+
144
+ def __repr__(self):
145
+ return f'NDArrayArray ({len(self)} subarrays, dtype={self.dtype}, {self.accessmode})'
146
+
147
+ def __getitem__(self, index):
148
+ if isinstance(index, (bool, np.bool_)):
149
+ raise TypeError('Only integer indices are supported')
150
+ index = operator.index(index)
151
+ if index < 0:
152
+ index += len(self)
153
+ if not 0 <= index < len(self):
154
+ raise IndexError('NDArrayArray index out of range')
155
+ shape = tuple(int(d) for d in self._shapes[index])
156
+ values = self._values[index]
157
+ if any(d < 0 for d in shape) or math.prod(shape) != values.size:
158
+ raise ValueError(f'Invalid shape or value count at subarray {index}')
159
+ return values.reshape(shape, order='C')
160
+
161
+ def __iter__(self):
162
+ return self.iter_arrays()
163
+
164
+ def iter_arrays(self, startindex=0, endindex=None, stepsize=1,
165
+ accessmode=None):
166
+ """Yield copies of subarrays using range-style bounds."""
167
+ with self.open_arrays(accessmode):
168
+ for i in range(startindex, len(self) if endindex is None else endindex, stepsize):
169
+ yield self[i]
170
+
171
+ @contextmanager
172
+ def open_arrays(self, accessmode=None):
173
+ """Keep both components open for efficient repeated reads."""
174
+ if accessmode is not None and _mode(accessmode) != self.accessmode:
175
+ raise ValueError('Set accessmode on the collection before opening arrays')
176
+ with self._values.open_arrays(), self._shapes.open_arrays():
177
+ yield self
178
+
179
+ def close(self):
180
+ self._values.close()
181
+ self._shapes.close()
182
+
183
+ def __enter__(self):
184
+ return self
185
+
186
+ def __exit__(self, *exc):
187
+ self.close()
188
+
189
+ def _recover(self):
190
+ # Reopen because a failed darr append may have updated descriptions
191
+ # before raising (for example, when README generation fails).
192
+ self.close()
193
+ self._values = darr.open(self.path / 'values', accessmode=self.accessmode)
194
+ self._shapes = darr.open(self.path / 'shapes', accessmode=self.accessmode)
195
+ if len(self._values) < len(self._shapes):
196
+ raise ValueError('Missing values for committed shapes')
197
+ if len(self._values) > len(self._shapes):
198
+ darr.truncate_raggedarray(self._values, len(self._shapes))
199
+
200
+ def append(self, array):
201
+ """Append one array, converting to the collection dtype.
202
+
203
+ A completed shape entry commits the corresponding values. If an
204
+ exception occurs after that commit, the entry may already be present.
205
+ """
206
+ if self.accessmode != 'r+':
207
+ raise OSError("Collection is read-only; set accessmode='r+' to append")
208
+ if np.ma.isMaskedArray(array):
209
+ raise TypeError('Masked arrays are not supported')
210
+ array = np.asarray(array, dtype=self.dtype)
211
+ shape = np.asarray(array.shape, dtype='int64')
212
+ values = array.ravel(order='C')
213
+ self._recover()
214
+ try:
215
+ self._values.append(values)
216
+ self._shapes.append(shape)
217
+ except BaseException:
218
+ self._recover()
219
+ raise
220
+
221
+ def iterappend(self, arrayiterable):
222
+ """Stream arrays; completed entries remain if iteration fails."""
223
+ if self.accessmode != 'r+':
224
+ raise OSError('Collection is read-only')
225
+ for array in arrayiterable:
226
+ self.append(array)
227
+
228
+ def copy(self, path, dtype=None, accessmode='r', overwrite=False):
229
+ """Copy one subarray at a time, optionally converting dtype."""
230
+ _separate(self.path, path)
231
+ return asndarrayarray(path, self, dtype=self.dtype if dtype is None else dtype,
232
+ metadata=dict(self.metadata), accessmode=accessmode,
233
+ overwrite=overwrite)
234
+
235
+ def archive(self, filepath=None, compressiontype='xz', overwrite=False):
236
+ return self.datadir.archive(filepath, compressiontype, overwrite)
237
+
238
+
239
+ def _check_owned(path):
240
+ """Refuse destructive operations on symlinks or additional user files."""
241
+ path = Path(path)
242
+ if path.is_symlink():
243
+ raise OSError(f'Refusing to delete symlink: {path}')
244
+ a = NDArrayArray(path)
245
+ a.close()
246
+ for child in path.iterdir():
247
+ if child.name not in _FILES or child.is_symlink():
248
+ raise OSError(f'Refusing to delete additional file: {child}')
249
+ for component in (a._values, a._shapes):
250
+ _check_darr_owned(component)
251
+ return a
252
+
253
+
254
+ def _check_darr_owned(component):
255
+ for child in component.path.iterdir():
256
+ if child.is_symlink() or child.name not in component.datadir.protectedfiles:
257
+ raise OSError(f'Refusing to delete additional file: {child}')
258
+ if child.is_dir():
259
+ _check_darr_owned(darr.open(child))
260
+
261
+
262
+ def delete_ndarrayarray(ndaa):
263
+ """Delete recognized collection files; refuse additional files beforehand."""
264
+ if isinstance(ndaa, NDArrayArray):
265
+ if ndaa.accessmode != 'r+':
266
+ raise OSError('Collection is read-only')
267
+ ndaa.close()
268
+ path = ndaa.path
269
+ else:
270
+ path = Path(ndaa)
271
+ a = _check_owned(path)
272
+ darr.delete_raggedarray(a.path / 'values')
273
+ darr.delete_raggedarray(a.path / 'shapes')
274
+ for filename in ('arraydescription.json', 'README.txt'):
275
+ (a.path / filename).unlink(missing_ok=True)
276
+ a.path.rmdir()
277
+
278
+
279
+ def create_ndarrayarray(path, dtype='float64', metadata=None, accessmode='r+',
280
+ indextype='int64', overwrite=False):
281
+ """Create an empty collection. Only recognized collections can be overwritten.
282
+
283
+ Shapes always use int64; indextype controls both RaggedArrays' offsets.
284
+ The destination's parent directory must exist.
285
+ """
286
+ path = Path(path).absolute()
287
+ dtype, accessmode = _dtype(dtype), _mode(accessmode)
288
+ if indextype not in ('int8', 'uint8', 'int16', 'uint16', 'int32', 'uint32', 'int64'):
289
+ raise ValueError('Unsupported indextype')
290
+ if path.exists() or path.is_symlink():
291
+ if not overwrite:
292
+ raise FileExistsError(path)
293
+ _check_owned(path)
294
+ # Build the replacement before deleting an existing collection.
295
+ with tempfile.TemporaryDirectory(prefix='.ndarrayarray-', dir=path.parent) as tmp:
296
+ staged = Path(tmp) / 'array'
297
+ staged.mkdir()
298
+ for name, dt, md in (('values', dtype, metadata), ('shapes', 'int64', None)):
299
+ component = darr.create_raggedarray(staged / name, dtype=dt,
300
+ metadata=md, indextype=indextype)
301
+ component.close()
302
+ (staged / 'arraydescription.json').write_text(json.dumps(_FORMAT) + '\n', encoding='utf-8')
303
+ (staged / 'README.txt').write_text(_README, encoding='utf-8')
304
+ if path.exists():
305
+ delete_ndarrayarray(path)
306
+ staged.rename(path)
307
+ return NDArrayArray(path, accessmode)
308
+
309
+
310
+ def asndarrayarray(path, arrayiterable, dtype=None, metadata=None,
311
+ accessmode='r+', indextype='int64', overwrite=False):
312
+ """Create from an iterable, inferring dtype from its first item.
313
+
314
+ An empty iterable requires an explicit dtype. Later failure leaves the
315
+ completed prefix readable. Construction writes before applying accessmode.
316
+ """
317
+ _mode(accessmode)
318
+ if isinstance(arrayiterable, NDArrayArray):
319
+ _separate(arrayiterable.path, path)
320
+ arrays = iter(arrayiterable)
321
+ sentinel = object()
322
+ first = next(arrays, sentinel)
323
+ if first is sentinel and dtype is None:
324
+ raise ValueError('An empty iterable requires an explicit dtype')
325
+ if first is not sentinel:
326
+ if np.ma.isMaskedArray(first):
327
+ raise TypeError('Masked arrays are not supported')
328
+ first = np.asarray(first, dtype=dtype)
329
+ dtype = first.dtype
330
+ a = create_ndarrayarray(path, dtype=dtype, metadata=metadata,
331
+ indextype=indextype, overwrite=overwrite)
332
+ try:
333
+ if first is not sentinel:
334
+ a.append(first)
335
+ a.iterappend(arrays)
336
+ finally:
337
+ a.close()
338
+ a.accessmode = accessmode
339
+ return a
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: ndarrayarray
3
+ Version: 0.2.0
4
+ Summary: A disk-backed sequence of arbitrarily shaped numeric NumPy arrays.
5
+ Author-email: Gabriël Beckers <gabriel@gbeckers.nl>
6
+ License-Expression: BSD-3-Clause
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering
10
+ Requires-Python: >=3.12
11
+ Description-Content-Type: text/x-rst
12
+ License-File: LICENSE
13
+ Requires-Dist: darr>=0.6.4
14
+ Requires-Dist: numpy
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=8; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ Ndarrayarray
20
+ ============
21
+
22
+ Ndarrayarray stores a disk-backed sequence of numeric NumPy arrays whose
23
+ shapes and numbers of dimensions may differ. It is a small companion to
24
+ `Darr <https://github.com/gbeckers/Darr/>`_, using Darr's public API for
25
+ storage, memory mapping and metadata.
26
+
27
+ This package is experimental. Version 0.2 introduces a new storage format
28
+ and deliberately rejects directories created by the old work-in-progress
29
+ implementation. Keep old data unchanged until it has been explicitly migrated.
30
+
31
+ Installation
32
+ ------------
33
+
34
+ Requires Python 3.12 or newer, NumPy, and Darr 0.6.4 or newer::
35
+
36
+ pip install ndarrayarray
37
+
38
+ For development against the sibling Darr checkout::
39
+
40
+ python -m pip install -e ../darr
41
+ python -m pip install -e '.[test]'
42
+ python -m pytest
43
+
44
+ Darr 0.6.4 must be released before publishing this package: the implementation
45
+ relies on its public truncation and append recovery behavior, including
46
+ truncation to an empty collection.
47
+
48
+ Example
49
+ -------
50
+
51
+ .. code:: python
52
+
53
+ import numpy as np
54
+ import ndarrayarray as ndaa
55
+
56
+ with ndaa.create_ndarrayarray('example.ndaa', dtype='float64',
57
+ metadata={'unit': 'mV'}) as a:
58
+ a.append(np.ones((3, 1, 3)))
59
+ a.append(2 * np.ones((2, 4)))
60
+ a.append(np.array(7)) # zero-dimensional array
61
+ a.append(np.empty((0, 3))) # empty axes retain their shape
62
+ print(len(a)) # 4
63
+ print(a[1].shape) # (2, 4)
64
+
65
+ with ndaa.open('example.ndaa') as a: # read-only by default
66
+ print(a[-1].shape) # (0, 3)
67
+ print(a.metadata['unit']) # mV
68
+ for subarray in a:
69
+ print(subarray.shape)
70
+
71
+ A collection can exceed RAM because its backing data is memory-mapped by
72
+ Darr. Indexing returns an independent NumPy copy, so each retrieved subarray
73
+ must fit in RAM. Mutating that copy does not modify the stored data.
74
+
75
+ API
76
+ ---
77
+
78
+ * ``create_ndarrayarray(path, dtype='float64', metadata=None,
79
+ accessmode='r+', indextype='int64', overwrite=False)`` creates an empty
80
+ collection. The parent directory must exist.
81
+ * ``asndarrayarray(path, arrayiterable, dtype=None, metadata=None,
82
+ accessmode='r+', indextype='int64', overwrite=False)`` streams an iterable
83
+ into a collection. If omitted, dtype comes from the first item; an empty
84
+ iterable requires an explicit dtype. Later items are converted to that
85
+ dtype using NumPy conversion rules. Construction can return a read-only
86
+ collection after writing its contents.
87
+ * ``open(path, accessmode='r')`` or ``NDArrayArray(path, accessmode='r')``
88
+ opens an existing collection. This opens ndarrayarray directories only;
89
+ use ``darr.open`` for ordinary Darr arrays.
90
+ * ``a[i]`` accepts positive or negative integer indices. Slices and advanced
91
+ indexing are not supported. ``iter(a)`` and
92
+ ``a.iter_arrays(startindex=0, endindex=None, stepsize=1)`` yield subarrays;
93
+ iteration bounds follow Python's ``range`` convention.
94
+ * ``a.append(array)`` and ``a.iterappend(iterable)`` append data. If a batch
95
+ fails, its completed entries remain readable.
96
+ * ``a.metadata`` is Darr's persistent dictionary-like metadata interface.
97
+ ``a.accessmode = 'r+'`` enables appending and metadata changes.
98
+ * ``a.copy(path, dtype=None, accessmode='r', overwrite=False)`` copies one
99
+ subarray at a time. Source and destination directories must not overlap.
100
+ * ``a.archive(filepath=None, compressiontype='xz', overwrite=False)``
101
+ creates a Darr directory archive. Supported compression types are
102
+ ``xz``, ``gz`` and ``bz2``.
103
+ * ``delete_ndarrayarray(a_or_path)`` deletes a recognized collection.
104
+ Passing a read-only object is rejected; passing a path explicitly requests
105
+ deletion. Deletion and overwrite refuse symlinks and extra user files
106
+ before removing any collection files. Overwrite accepts only the new
107
+ recognized format, including an empty collection.
108
+
109
+ ``len(a)`` and ``a.narrays`` count committed subarrays. ``a.size`` counts
110
+ their numeric values; ``a.dtype`` describes their shared numeric type.
111
+ ``a.mb`` reports component storage in decimal megabytes, excluding text
112
+ files (including uncommitted trailing storage if present).
113
+ ``a.path`` and ``a.datadir`` provide the directory path and Darr's directory
114
+ utilities. ``with a.open_arrays():`` keeps both components open for repeated
115
+ reads; the context yields the collection. ``a.close()`` explicitly closes
116
+ resources, and collections also support ``with`` statements.
117
+
118
+ Signed and unsigned integers, float16/32/64 and complex64/128 are supported.
119
+ Object, string, boolean, structured and masked arrays are not supported.
120
+ Subarrays share a numeric dtype, but can otherwise have arbitrary shapes.
121
+ Scalars and empty arrays are supported. Shape-changing replacement and
122
+ in-place modification of stored subarrays are outside this API.
123
+
124
+ Format and recovery
125
+ -------------------
126
+
127
+ Each collection contains::
128
+
129
+ arraydescription.json # {"ndarrayarray": 1, "order": "C"}
130
+ README.txt # self-contained reconstruction instructions
131
+ values/ # Darr RaggedArray: flattened subarrays
132
+ shapes/ # Darr RaggedArray: int64 dimension lengths
133
+
134
+ User metadata belongs to the values component. ``indextype`` controls the
135
+ offset types in both components; shapes themselves always use int64.
136
+ The format version is independent of the package version.
137
+
138
+ Each component is an ordinary Darr RaggedArray, independently readable
139
+ with ``darr.open``. Reconstruction uses C order::
140
+
141
+ values[i].reshape(tuple(shapes[i]), order='C')
142
+
143
+ The component READMEs include Darr's reading code for other languages.
144
+ For column-major languages, reshape to the reversed shape and then reverse
145
+ the axes. A scalar has an empty shape record and one value; an empty array
146
+ has zero values and a shape containing at least one zero.
147
+
148
+ Appending writes values first and then shape. A shape entry commits its
149
+ corresponding values. Read-only opening ignores extra trailing values
150
+ entries without modifying disk. Before the next append, trailing values
151
+ are removed through Darr's public truncation API. Missing values for
152
+ committed shapes are rejected on opening; malformed shape/value pairs
153
+ are rejected when accessed. Opening does not scan every stored subarray.
154
+ If an append raises after its shape was committed, that entry may already
155
+ be present; inspect the collection before retrying.
156
+
157
+ Only one writer is supported. Close and reopen other collection objects
158
+ after writes to refresh their state. The components must not be modified
159
+ separately. Recovery handles incomplete pairs when the underlying Darr
160
+ components remain readable; it is not a cross-file transaction or a
161
+ power-loss durability guarantee. Overwrite stages an empty replacement
162
+ before removing the old collection, but replacement is not atomic.
163
+
164
+ Development and release
165
+ -----------------------
166
+
167
+ The test suite covers mixed shapes, scalar and empty arrays, dtype
168
+ conversion, read-only access, metadata, copying, recovery, failed iterators,
169
+ index overflow, safe deletion and overwrite, and legacy-format rejection.
170
+ Run it with ``python -m pytest``. Build distributions with
171
+ ``python -m build`` after installing the ``build`` package.
172
+
173
+ GitHub Actions runs on pushes, pull requests and manual dispatch. It builds
174
+ both distributions and runs the tests against an installed wheel outside
175
+ the checkout on Linux, macOS and Windows, using Python 3.12 and 3.14.
176
+ An additional Linux job pins Darr to the minimum supported version, 0.6.4;
177
+ the other jobs use the latest compatible release. CI installs dependencies
178
+ from PyPI, so Darr 0.6.4 must be published before these jobs can pass.
179
+ The workflow tests packages without publishing them.
180
+
181
+ Ndarrayarray is distributed under the BSD 3-Clause License.
182
+ Copyright (c) 2022-2026, Gabriël Beckers.
@@ -0,0 +1,7 @@
1
+ ndarrayarray/__init__.py,sha256=e14Za1R62Ox_VXlZ5fbG63bI5jA76nARCmTLPkvP4ZA,467
2
+ ndarrayarray/ndarrayarray.py,sha256=OSaJ4phORM77LZ3sG04LbSfR3ObD8CS9-b57OXYRK78,13175
3
+ ndarrayarray-0.2.0.dist-info/licenses/LICENSE,sha256=DfYBIXs2eDGZXdDxGjepLXUaerbbqAqyvmo609eeZjg,1529
4
+ ndarrayarray-0.2.0.dist-info/METADATA,sha256=0fZMYIBAfOquqNJSabmASriLlR4R6lkuAHXVm4lWyyU,8360
5
+ ndarrayarray-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ ndarrayarray-0.2.0.dist-info/top_level.txt,sha256=j5s8UUwggFD52a4rxI86UQsoG_0NnpJCjIoMd9Pd-XA,13
7
+ ndarrayarray-0.2.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.37.1)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -0,0 +1,30 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2022-2026, Gabriël Beckers
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice,
10
+ this list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
+ POSSIBILITY OF SUCH DAMAGE.
ndarrayarray/_version.py DELETED
@@ -1,21 +0,0 @@
1
-
2
- # This file was generated by 'versioneer.py' (0.22) from
3
- # revision-control system data, or from the parent directory name of an
4
- # unpacked source archive. Distribution tarballs contain a pre-generated copy
5
- # of this file.
6
-
7
- import json
8
-
9
- version_json = '''
10
- {
11
- "date": "2022-07-11T17:10:13+0200",
12
- "dirty": false,
13
- "error": null,
14
- "full-revisionid": "34ed02c301762be3b08f3b20d248421c5b3c8b83",
15
- "version": "0.1.0"
16
- }
17
- ''' # END VERSION_JSON
18
-
19
-
20
- def get_versions():
21
- return json.loads(version_json)
ndarrayarray/readcode.py DELETED
@@ -1,63 +0,0 @@
1
- from pathlib import Path
2
- from darr.readcodearray import shapeexplanationtextarray
3
- from darr.utils import wrap
4
-
5
- # Row-major: Mathematica, Numpy
6
- # Column-major: Julia, Matlab/Octave, R, Maple, IDL/GDL
7
-
8
- # start counting at 0: Python, IDL
9
- # start counting at 1: Julia, Mathematica, Matlab/Octave, R, Maple,
10
-
11
- # inclusive end index: Julia, Mathematica, Matlab/Octave, R, Maple, IDL/GDL
12
- # non-inclusive end index: Python
13
-
14
- # TO BE IMPLEMENTED
15
-
16
- readcodefunc = {}
17
-
18
- def readcode(vda, language, basepath='', abspath=False):
19
- """Produces the code to read the Darr raggedarray `dra` in a given
20
- programming language.
21
-
22
- Parameters
23
- ----------
24
- dra: Darr raggedarray
25
- language: str
26
- A supported language, such as 'julia', 'R', or 'matlab'
27
- abspath: bool
28
- Should the paths to the data files be absolute or not? Default:
29
- True.
30
- basepath: str or pathlib.Path or None
31
- Path relative to which the binary array data file should be
32
- provided. Default: None.
33
-
34
- Returns
35
- -------
36
- A string with code
37
-
38
- """
39
- if language not in readcodefunc:
40
- raise ValueError(f"'{language}' not supported ({readcodefunc.keys()})")
41
- if abspath:
42
- isp = vda._indicesandshapes.path.absolute().resolve()
43
- vp = vda._values.path.absolute().resolve()
44
- elif basepath is not None:
45
- isp = Path(basepath) / vda._indicesandshapesdirname
46
- vp = Path(basepath) / vda._valuesdirname
47
- else:
48
- isp = Path(vda._indicesandshapesdirname)
49
- vp = Path(vda._valuesdirname)
50
- return readcodefunc[language](vda=vda, indicespath=isp, valuespath=vp)
51
-
52
-
53
- shapeindexexplanationtextraggedarray = shapeexplanationtextarray + '\n\n' + \
54
- wrap(f'Further, Python starts counting at 0. So the first subarray in a '
55
- f'ragged array has index number 0. This is also true for IDL/GDL. '
56
- f'However, Julia, Mathematica, Matlab/Octave, R, and Maple start '
57
- f'counting at 1, so the first subarray has index number 1 in these '
58
- f'languages. Finally, in Python indexing the end index is '
59
- f'non-inclusive. E.g., a[0:2] returns a[0] and a[1], but not a[2]. '
60
- f'However, all other languages for which reading code is provided, Julia, '
61
- f'Mathematica, Matlab/Octave, R, Maple, and IDL/GDL have an inclusive '
62
- f'end index. The reading code provided takes these differences into '
63
- f'account.\n')
@@ -1,13 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: ndarrayarray
3
- Version: 0.1.0
4
- Summary: A memory-mapped array of arbitrarily shaped numpy ndarrays.
5
- Home-page:
6
- Author: Gabriel Beckers
7
- Author-email: gabriel@gbeckers.nl
8
- License: UNKNOWN
9
- Platform: UNKNOWN
10
- Requires-Dist: darr
11
-
12
- UNKNOWN
13
-
@@ -1,8 +0,0 @@
1
- ndarrayarray/__init__.py,sha256=PeMO09Q1Zg3h__eGM_D0tvbIfUrHoWK-O7XCYUrxwug,734
2
- ndarrayarray/_version.py,sha256=B2AMtoAg1akn5IMSeiYjfRrSmxXsvxLw0zbP952GAhg,518
3
- ndarrayarray/ndarrayarray.py,sha256=84GHevE_KZXyQWCDi6EI_rNixRMIr37YQOL6iIdfW_Q,22706
4
- ndarrayarray/readcode.py,sha256=1JtET8bRW9aRFNdH7W2O0CZwI0bVUUyXeM75d3sp6CQ,2437
5
- ndarrayarray-0.1.0.dist-info/METADATA,sha256=pmUwmllMQtbYKcHt5hXrmaMtnw8maTrdMn5Tk61UBlA,260
6
- ndarrayarray-0.1.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92
7
- ndarrayarray-0.1.0.dist-info/top_level.txt,sha256=j5s8UUwggFD52a4rxI86UQsoG_0NnpJCjIoMd9Pd-XA,13
8
- ndarrayarray-0.1.0.dist-info/RECORD,,