SciFile-Core 0.0.1__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.
@@ -0,0 +1,111 @@
1
+ """Shared foundation of the SciFile file-format packages.
2
+
3
+ Each SciFile package reads and writes one file format, and follows one
4
+ contract: the functions ``read``, ``create`` and ``write``, an immutable model
5
+ of the file that carries its diagnostics, and the exceptions `Error`,
6
+ `InputError` and `ReadError`. This package holds what they have in common:
7
+
8
+ - the diagnostics that reading a file and checking its rules report:
9
+ `Diagnostic`, `Diagnostics`, `DiagnosticSeverity`, `DiagnosticType` and
10
+ `SharedDiagnosticType`, with `create_diagnostic`, which builds a diagnostic,
11
+ and the wording of the shared types in `scifile_core.wording`;
12
+ - the exceptions that each package subclasses: `Error`, `InputError` and
13
+ `ReadError`;
14
+ - the reading of inputs and the writing to targets: `read_text`,
15
+ `read_bytes`, `deliver_text` and `deliver_bytes`, with `positional`,
16
+ which writes a number in full in a text format, and `map_file`, which
17
+ maps a file into memory as a `FileMap`, for a package of large arrays;
18
+ - the base classes of the models, of the types of their fields and of
19
+ their write options: `FileModel`, `TextFileModel`, `BinaryFileModel`,
20
+ `FieldModel` and `WriteConfig`, with `immutable_array`, `with_parsed`
21
+ and `configure`;
22
+ - and, in `scifile_core.testing`, a kit that tests a package against the
23
+ contract.
24
+
25
+ The package needs no NumPy: it never imports NumPy to check a value, and
26
+ only `immutable_array` imports it, for a package that stores arrays and
27
+ depends on NumPy itself.
28
+ """
29
+
30
+ from importlib.metadata import PackageNotFoundError as _PackageNotFoundError
31
+ from importlib.metadata import version as _version
32
+
33
+ from scifile_core._content import immutable_array
34
+ from scifile_core._diagnostic import (
35
+ PARSER,
36
+ VERIFIER,
37
+ Diagnostic,
38
+ Diagnostics,
39
+ DiagnosticSeverity,
40
+ DiagnosticType,
41
+ SharedDiagnosticType,
42
+ create_diagnostic,
43
+ )
44
+ from scifile_core._exception import Error, InputError, ReadError
45
+ from scifile_core._io import (
46
+ BinarySource,
47
+ BinaryTarget,
48
+ TextSource,
49
+ TextTarget,
50
+ check_encoding,
51
+ deliver_bytes,
52
+ deliver_text,
53
+ read_bytes,
54
+ read_text,
55
+ )
56
+ from scifile_core._mapping import FileMap, map_file
57
+ from scifile_core._model import (
58
+ BinaryFileModel,
59
+ FieldModel,
60
+ FileModel,
61
+ TextFileModel,
62
+ WriteConfig,
63
+ configure,
64
+ with_parsed,
65
+ )
66
+ from scifile_core._number import positional
67
+
68
+ __version__: str
69
+ """The version of the installed distribution.
70
+
71
+ A source tree that is not installed has 0.0.0+unknown.
72
+ """
73
+ try:
74
+ __version__ = _version("scifile_core")
75
+ except _PackageNotFoundError: # pragma: no cover - a source tree, not installed
76
+ __version__ = "0.0.0+unknown"
77
+
78
+ __all__ = [
79
+ "PARSER",
80
+ "VERIFIER",
81
+ "BinaryFileModel",
82
+ "BinarySource",
83
+ "BinaryTarget",
84
+ "Diagnostic",
85
+ "DiagnosticSeverity",
86
+ "DiagnosticType",
87
+ "Diagnostics",
88
+ "Error",
89
+ "FieldModel",
90
+ "FileMap",
91
+ "FileModel",
92
+ "InputError",
93
+ "ReadError",
94
+ "SharedDiagnosticType",
95
+ "TextFileModel",
96
+ "TextSource",
97
+ "TextTarget",
98
+ "WriteConfig",
99
+ "__version__",
100
+ "check_encoding",
101
+ "configure",
102
+ "create_diagnostic",
103
+ "deliver_bytes",
104
+ "deliver_text",
105
+ "immutable_array",
106
+ "map_file",
107
+ "positional",
108
+ "read_bytes",
109
+ "read_text",
110
+ "with_parsed",
111
+ ]
@@ -0,0 +1,490 @@
1
+ """The content of the fields of a model: freezing, comparing and hashing it.
2
+
3
+ NumPy is optional: a package that stores arrays depends on it, and this
4
+ module never imports it to check a value, since no value is a NumPy value
5
+ unless NumPy is imported. The checks take it from
6
+ `scifile_core._optional.imported_numpy` instead, after the checks of the
7
+ builtin types, which no NumPy value passes. The helpers of arrays and of
8
+ dates run only once a check found one, and take NumPy from there too.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import cmath
14
+ import functools
15
+ import itertools
16
+ import math
17
+ import operator
18
+ from typing import TYPE_CHECKING, Any, Literal, cast
19
+
20
+ from scifile_core._optional import imported_numpy
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Callable, Iterable, Iterator
24
+ from types import ModuleType
25
+
26
+ import numpy as np
27
+ from numpy.typing import ArrayLike, DTypeLike, NDArray
28
+
29
+ _BLOCK_ELEMENTS = 1 << 18
30
+ """Most elements that comparing or hashing an array handles at a time."""
31
+
32
+ _EXACT_KINDS = "biuSUmM"
33
+ """Kinds of dtypes whose equal elements have equal bytes: booleans,
34
+ integers, strings, dates and times."""
35
+
36
+ _SELF_SAME = frozenset({bool, int, str, bytes, type(None)})
37
+ """Exact types whose values are their own content: two of the same type are
38
+ the same if they are equal, and each is its own digest."""
39
+
40
+ _SEQUENCES = (list, tuple)
41
+ """The sequences whose items a field value compares and hashes one by one."""
42
+
43
+ _PLAIN = frozenset({*_SELF_SAME, float})
44
+ """Exact types of values that hold no array, and that `==` compares as
45
+ `same` does, apart from NaN."""
46
+
47
+
48
+ def immutable_array(
49
+ values: ArrayLike, dtype: DTypeLike | None = None
50
+ ) -> NDArray[Any]:
51
+ """Return values as an array that a model keeps without a copy.
52
+
53
+ The values are copied at most once: when they must be converted to the
54
+ dtype, or when the caller could still change them. An array that is
55
+ read-only already, such as one that ``read`` made, is kept: whoever gave
56
+ it must not make it writable again. The caller's array is never changed.
57
+ A package's ``create`` converts its arrays with this function, so that the
58
+ constructor of the model does not copy them again.
59
+
60
+ Parameters
61
+ ----------
62
+ values
63
+ An array, or anything that `numpy.array` takes.
64
+ dtype
65
+ The dtype of the array, or `None` to keep that of the values.
66
+
67
+ Returns
68
+ -------
69
+ A read-only array, whose flag cannot be set writable again if its
70
+ memory was copied.
71
+
72
+ Raises
73
+ ------
74
+ ImportError
75
+ If NumPy is not installed. SciFile-Core does not install it: a
76
+ package that stores arrays depends on it.
77
+ """
78
+ import numpy as np # noqa: PLC0415 - only a package of arrays needs it
79
+
80
+ if isinstance(values, np.ndarray):
81
+ array = values if dtype is None else values.astype(dtype, copy=False)
82
+ return frozen(array, fresh=array is not values)
83
+ return frozen(np.array(values, dtype=dtype), fresh=True)
84
+
85
+
86
+ def frozen_value(value: object, *, fresh: bool = False) -> object:
87
+ """Return a field value with its arrays frozen, also those of a tuple.
88
+
89
+ The arrays of a tuple or a named tuple are frozen, and the tuple is
90
+ rebuilt if one of them is copied. A tuple of another class is kept as it
91
+ is, since its constructor is unknown, so that its arrays must be
92
+ read-only already. `fresh` says that nobody else holds the arrays, as
93
+ after unpickling.
94
+ """
95
+ kind = type(value)
96
+ if kind in _SELF_SAME or kind is float:
97
+ return value
98
+ if not isinstance(value, tuple):
99
+ np = imported_numpy()
100
+ if np is not None and isinstance(value, np.ndarray):
101
+ return frozen(value, fresh=fresh)
102
+ return value
103
+ make = tuple_maker(value)
104
+ if make is None:
105
+ return value
106
+ items = [frozen_value(item, fresh=fresh) for item in value]
107
+ if all(new is old for new, old in zip(items, value, strict=True)):
108
+ return value
109
+ return make(items)
110
+
111
+
112
+ def frozen_values(values: tuple[object, ...]) -> tuple[object, ...]:
113
+ """Return the values of the fields of a model, as `frozen_value` does.
114
+
115
+ The values are returned as they are if none is or can hold an array.
116
+ """
117
+ if is_plain(values):
118
+ return values
119
+ return tuple(map(frozen_value, values))
120
+
121
+
122
+ def is_plain(values: Iterable[object]) -> bool:
123
+ """Return whether no value of some fields is or can hold an array."""
124
+ return _PLAIN.issuperset(map(type, values))
125
+
126
+
127
+ def tuple_maker(
128
+ value: tuple[object, ...],
129
+ ) -> Callable[[list[object]], object] | None:
130
+ """Return what makes a tuple of the class of a value from items.
131
+
132
+ That is `tuple` for a tuple, the class's ``_make`` for a named tuple,
133
+ and `None` for a tuple of another class, whose constructor is unknown.
134
+ """
135
+ return tuple if type(value) is tuple else _maker(value)
136
+
137
+
138
+ def frozen(array: NDArray[Any], *, fresh: bool = False) -> NDArray[Any]:
139
+ """Return an array as a read-only array that a model can keep.
140
+
141
+ The array is copied if it is writable or its memory belongs to something
142
+ writable, unless `fresh` says that nobody else holds it. An array that
143
+ owns its memory is returned as a read-only view of it, whose flag cannot
144
+ be set writable again.
145
+ """
146
+ if not (fresh and array.base is None) and (
147
+ array.flags.writeable or _changeable(array)
148
+ ):
149
+ array = array.copy(order="K")
150
+ array.flags.writeable = False
151
+ if array.base is None:
152
+ array = array.view()
153
+ array.flags.writeable = False
154
+ return array
155
+
156
+
157
+ def arrays(value: object) -> Iterator[NDArray[Any]]:
158
+ """Yield the arrays of a field value, also those of a tuple."""
159
+ if isinstance(value, tuple):
160
+ for item in value:
161
+ yield from arrays(item)
162
+ return
163
+ np = imported_numpy()
164
+ if np is not None and isinstance(value, np.ndarray):
165
+ yield value
166
+
167
+
168
+ def _maker(
169
+ value: tuple[object, ...],
170
+ ) -> Callable[[list[object]], object] | None:
171
+ """Return what makes a named tuple from items, or `None` for others."""
172
+ make = getattr(type(value), "_make", None)
173
+ return make if callable(make) and hasattr(type(value), "_fields") else None
174
+
175
+
176
+ def _changeable(array: NDArray[Any]) -> bool:
177
+ """Return whether the memory of a read-only array can change.
178
+
179
+ The memory can change through a writable array or buffer that it
180
+ belongs to. The owner at the end of the chain is unchangeable if it is
181
+ the array's own memory, bytes, or another read-only buffer, such as a
182
+ file that is mapped read-only.
183
+ """
184
+ np = _numpy_in_use()
185
+ owner: object = array.base
186
+ while isinstance(owner, np.ndarray | memoryview):
187
+ if isinstance(owner, np.ndarray):
188
+ if owner.flags.writeable:
189
+ return True
190
+ owner = owner.base
191
+ else:
192
+ if not owner.readonly:
193
+ return True
194
+ owner = owner.obj
195
+ if owner is None or isinstance(owner, bytes):
196
+ return False
197
+ try:
198
+ with memoryview(cast("Any", owner)) as view:
199
+ return not view.readonly
200
+ except TypeError:
201
+ return True
202
+
203
+
204
+ def same(left: object, right: object) -> bool:
205
+ """Return whether two field values have the same content.
206
+
207
+ A NumPy scalar other than a date or a time is compared as the Python
208
+ value that it holds. A float or complex NaN equals NaN, and NaT equals
209
+ NaT. Two values of the same exact builtin type, such as two strings or
210
+ two floats, take a shorter path to the same answer.
211
+ """
212
+ kind = type(left)
213
+ if kind is type(right) and (kind in _SELF_SAME or kind is float):
214
+ return bool(left == right) or (
215
+ kind is float
216
+ and math.isnan(cast("float", left))
217
+ and math.isnan(cast("float", right))
218
+ )
219
+ np: ModuleType | None = None
220
+ if not (isinstance(left, _SEQUENCES) and isinstance(right, _SEQUENCES)):
221
+ np = imported_numpy()
222
+ if np is not None:
223
+ # A structured scalar becomes a tuple, which compares as one.
224
+ left, right = _plain(np, left), _plain(np, right)
225
+ if isinstance(left, np.ndarray) or isinstance(right, np.ndarray):
226
+ return (
227
+ isinstance(left, np.ndarray)
228
+ and isinstance(right, np.ndarray)
229
+ and _same_arrays(left, right)
230
+ )
231
+ if isinstance(left, _SEQUENCES) and isinstance(right, _SEQUENCES):
232
+ return (
233
+ type(left) is type(right)
234
+ and len(left) == len(right)
235
+ and all(same(a, b) for a, b in zip(left, right, strict=True))
236
+ )
237
+ try:
238
+ # NumPy compares a number with a date or a time as a count of its
239
+ # unit, which their digests do not agree with: they are not the same.
240
+ if _is_time(np, left) is _is_time(np, right) and bool(left == right):
241
+ return True
242
+ except (TypeError, OverflowError):
243
+ # Values that NumPy cannot compare, as dates and times of units
244
+ # that do not convert, are not the same.
245
+ return False
246
+ missing = _missing(np, left)
247
+ return missing is not None and missing == _missing(np, right)
248
+
249
+
250
+ def same_values(left: tuple[object, ...], right: tuple[object, ...]) -> bool:
251
+ """Return whether the values of the fields of two models are the same.
252
+
253
+ Values of the builtin types that `==` compares as `same` does are
254
+ compared at once, and the others, or a NaN, one by one with `same`.
255
+ """
256
+ if (
257
+ _PLAIN.issuperset(map(type, left))
258
+ and _PLAIN.issuperset(map(type, right))
259
+ and left == right
260
+ ):
261
+ return True
262
+ return len(left) == len(right) and all(map(same, left, right))
263
+
264
+
265
+ def _same_arrays(left: NDArray[Any], right: NDArray[Any]) -> bool:
266
+ """Return whether two arrays have the same shape, dtype and elements.
267
+
268
+ NaN equals NaN and NaT equals NaT, while elements of objects and
269
+ structures compare as Python and NumPy compare them. The byte order of
270
+ the dtype does not matter, and the arrays are compared block by block,
271
+ which stops at the first difference.
272
+ """
273
+ if left is right:
274
+ return True
275
+ if left.shape != right.shape or _native(left) != _native(right):
276
+ return False
277
+ missing = _missing_test(left.dtype.kind)
278
+ pairs = (
279
+ _block_pairs(left, right)
280
+ if left.size > _BLOCK_ELEMENTS
281
+ else ((left, right),)
282
+ )
283
+ for a, b in pairs:
284
+ equal = a == b
285
+ if not equal.all() and not (
286
+ missing is not None and (equal | (missing(a) & missing(b))).all()
287
+ ):
288
+ return False
289
+ return True
290
+
291
+
292
+ def _block_pairs(
293
+ left: NDArray[Any], right: NDArray[Any]
294
+ ) -> Iterator[tuple[NDArray[Any], NDArray[Any]]]:
295
+ """Yield the corresponding blocks of two arrays of the same shape.
296
+
297
+ Arrays of the same memory order are read in that order, as flat views;
298
+ others in tiles, so that a block of each stays in the cache.
299
+ """
300
+ if left.flags.c_contiguous and right.flags.c_contiguous:
301
+ order: Literal["C", "F"] | None = "C"
302
+ elif left.flags.f_contiguous and right.flags.f_contiguous:
303
+ order = "F"
304
+ else:
305
+ order = None
306
+ if order is None:
307
+ for tile in _tiles(left.shape):
308
+ yield left[tile], right[tile]
309
+ return
310
+ flat_left = left.ravel(order=order)
311
+ flat_right = right.ravel(order=order)
312
+ for start in range(0, flat_left.size, _BLOCK_ELEMENTS):
313
+ block = slice(start, start + _BLOCK_ELEMENTS)
314
+ yield flat_left[block], flat_right[block]
315
+
316
+
317
+ def digest(value: object) -> object:
318
+ """Return a hashable digest of a field value, which agrees with `same`."""
319
+ kind = type(value)
320
+ if kind in _SELF_SAME or (
321
+ kind is float and not math.isnan(cast("float", value))
322
+ ):
323
+ return value
324
+ np: ModuleType | None = None
325
+ if not isinstance(value, _SEQUENCES):
326
+ np = imported_numpy()
327
+ if np is not None:
328
+ # A structured scalar becomes a tuple, which hashes as one.
329
+ value = _plain(np, value)
330
+ if isinstance(value, np.ndarray):
331
+ return _array_digest(value)
332
+ if isinstance(value, _SEQUENCES):
333
+ return (type(value).__name__, tuple(digest(item) for item in value))
334
+ missing = _missing(np, value)
335
+ if missing is not None:
336
+ return (missing,)
337
+ if np is not None and isinstance(value, np.datetime64 | np.timedelta64):
338
+ return _time_digest(value)
339
+ return value
340
+
341
+
342
+ def digests(values: tuple[object, ...]) -> tuple[object, ...]:
343
+ """Return the digests of the values of the fields of a model.
344
+
345
+ Values of the builtin types that are their own digest, without a NaN,
346
+ are returned as they are, and the others are digested one by one.
347
+ """
348
+ if _PLAIN.issuperset(map(type, values)) and not any(
349
+ map(operator.ne, values, values)
350
+ ):
351
+ return values
352
+ return tuple(map(digest, values))
353
+
354
+
355
+ def _array_digest(array: NDArray[Any]) -> tuple[object, ...]:
356
+ """Return a digest of the shape, dtype and elements of an array.
357
+
358
+ The elements are hashed in C order, tile by tile, in the native byte
359
+ order, with one NaN for every NaN, 0 for -0, and one byte for each
360
+ boolean, so that the digest does not depend on the memory layout.
361
+ Elements whose bytes do not follow from their value, such as those of
362
+ objects, structures and extended precision, are not hashed.
363
+ """
364
+ np = _numpy_in_use()
365
+ native = _native(array)
366
+ key = ("ndarray", array.shape, native.str)
367
+ floating = native in _floating()
368
+ if array.size == 0 or not (floating or native.kind in _EXACT_KINDS):
369
+ return key
370
+ blocks = (
371
+ (array[tile] for tile in _tiles(array.shape))
372
+ if array.size > _BLOCK_ELEMENTS
373
+ else (array,)
374
+ )
375
+ hashes = []
376
+ for block in blocks:
377
+ if floating:
378
+ canonical = np.array(block, dtype=native)
379
+ np.add(canonical, 0, out=canonical)
380
+ np.copyto(canonical, np.nan, where=np.isnan(canonical))
381
+ elif native.kind == "b":
382
+ canonical = block.view(np.uint8) != 0
383
+ else:
384
+ canonical = block.astype(native, copy=False)
385
+ hashes.append(hash(canonical.tobytes()))
386
+ return (*key, hash(tuple(hashes)))
387
+
388
+
389
+ def _tiles(shape: tuple[int, ...]) -> Iterator[tuple[slice, ...]]:
390
+ """Yield the tiles of an array of a shape, in C order.
391
+
392
+ A tile spans at most `_BLOCK_ELEMENTS` elements, and its bounds follow
393
+ from the shape alone. The longest side of a tile is halved until it is
394
+ small enough, so that a tile is close to a cube in any memory order.
395
+ """
396
+ lengths = list(shape)
397
+ while math.prod(lengths) > _BLOCK_ELEMENTS:
398
+ axis = lengths.index(max(lengths))
399
+ lengths[axis] = -(-lengths[axis] // 2)
400
+ starts = (
401
+ range(0, size, length)
402
+ for size, length in zip(shape, lengths, strict=True)
403
+ )
404
+ for start in itertools.product(*starts):
405
+ yield tuple(
406
+ slice(first, first + length)
407
+ for first, length in zip(start, lengths, strict=True)
408
+ )
409
+
410
+
411
+ def _native(array: NDArray[Any]) -> np.dtype[Any]:
412
+ """Return the dtype of an array in native byte order."""
413
+ return array.dtype.newbyteorder("=")
414
+
415
+
416
+ def _plain(np: ModuleType, value: object) -> object:
417
+ """Return a NumPy scalar as the Python value that it holds.
418
+
419
+ A date or a time stays as it is, since its Python value loses NaT and
420
+ the precision of nanoseconds.
421
+ """
422
+ if isinstance(value, np.generic) and not isinstance(
423
+ value, np.datetime64 | np.timedelta64
424
+ ):
425
+ return value.item()
426
+ return value
427
+
428
+
429
+ def _numpy_in_use() -> ModuleType:
430
+ """Return NumPy, which an array or a date that a helper got has imported."""
431
+ return cast("ModuleType", imported_numpy())
432
+
433
+
434
+ def _is_time(np: ModuleType | None, value: object) -> bool:
435
+ """Return whether a value is a NumPy date or time.
436
+
437
+ A date or a time equals only another date or time.
438
+ """
439
+ return np is not None and isinstance(value, np.datetime64 | np.timedelta64)
440
+
441
+
442
+ def _missing(np: ModuleType | None, value: object) -> str | None:
443
+ """Return the kind of a missing value, NaN or NaT, or `None` for others."""
444
+ if isinstance(value, float) and math.isnan(value):
445
+ return "nan"
446
+ if isinstance(value, complex) and cmath.isnan(value):
447
+ return "nan"
448
+ if (
449
+ np is not None
450
+ and isinstance(value, np.datetime64 | np.timedelta64)
451
+ and np.isnat(value)
452
+ ):
453
+ return f"NaT of {type(value).__name__}"
454
+ return None
455
+
456
+
457
+ @functools.cache
458
+ def _floating() -> frozenset[np.dtype[Any]]:
459
+ """Return the dtypes of floating-point numbers that hash by their bytes.
460
+
461
+ The bytes of these follow from their value, once every NaN is one NaN
462
+ and -0 is 0.
463
+ """
464
+ np = _numpy_in_use()
465
+ names = ("float16", "float32", "float64", "complex64", "complex128")
466
+ return frozenset(np.dtype(name) for name in names)
467
+
468
+
469
+ def _missing_test(kind: str) -> Callable[[NDArray[Any]], NDArray[Any]] | None:
470
+ """Return the test of missing values of a kind of dtype, or `None`.
471
+
472
+ Missing values, NaN and NaT, equal each other.
473
+ """
474
+ np = _numpy_in_use()
475
+ test = np.isnan if kind in "fc" else np.isnat if kind in "mM" else None
476
+ return cast("Callable[[NDArray[Any]], NDArray[Any]] | None", test)
477
+
478
+
479
+ def _time_digest(value: np.datetime64 | np.timedelta64) -> tuple[str, ...]:
480
+ """Return a digest of a date or a time that its unit does not change.
481
+
482
+ The value is truncated to days, so that equal values of other units
483
+ agree; a time in months or years, which has no days, gives its kind.
484
+ """
485
+ np = _numpy_in_use()
486
+ kind = "datetime64" if isinstance(value, np.datetime64) else "timedelta64"
487
+ try:
488
+ return (kind, str(value.astype(f"{kind}[D]")))
489
+ except TypeError:
490
+ return (kind,)