bagofholding 0.post0.dev1__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,322 @@
1
+ from __future__ import annotations
2
+
3
+ import pathlib
4
+ from typing import Any, ClassVar, Self, TypeAlias, TypeVar, cast
5
+
6
+ import bidict
7
+ import h5py
8
+ import numpy as np
9
+ import pygtrie
10
+
11
+ from bagofholding.bag import PATH_DELIMITER, Bag, BagInfo
12
+ from bagofholding.content import BespokeItem
13
+ from bagofholding.h5.bag import H5Info
14
+ from bagofholding.h5.content import Array, ArrayPacker, ArrayType
15
+ from bagofholding.h5.context import HasH5FileContext
16
+ from bagofholding.h5.dtypes import H5PY_DTYPE_WHITELIST, H5Scalar, IntTypesAlias
17
+ from bagofholding.metadata import Metadata, VersionScrapingMap, VersionValidatorType
18
+ from bagofholding.trie import decompose_stringtrie, reconstruct_stringtrie
19
+
20
+ PackedThingType = TypeVar("PackedThingType", str, bool, int, float, bytes, bytearray)
21
+
22
+ StringArrayType: TypeAlias = np.ndarray[tuple[int, ...], np.dtype[np.str_]]
23
+ IntArrayType: TypeAlias = np.ndarray[tuple[int, ...], IntTypesAlias]
24
+
25
+
26
+ class TrieH5Bag(Bag, HasH5FileContext, ArrayPacker):
27
+ """
28
+ A bag using HDF5 files based on `h5py`.
29
+
30
+ Uses a trie structure to flatten the stored object. Compared to
31
+ :class:`bagofholding.h5.bag.H5Bag`, this is advantageous for file sizes but
32
+ (currently) has worse scaling for save times.
33
+
34
+ The resulting HDF5 file cannot be directly related to the structure of the stored
35
+ object, but must be re-mapped via mapping fields. Metadata is also lumped in with
36
+ other string data to minimize the number of different h5 groups.
37
+ """
38
+
39
+ _content_key: ClassVar[str] = "content_type"
40
+
41
+ _paths_key: ClassVar[str] = "paths"
42
+ _type_index_key: ClassVar[str] = "type_index"
43
+ _position_index_key: ClassVar[str] = "position_index"
44
+ _index_map: ClassVar[bidict.bidict[str, int]] = bidict.bidict(
45
+ {
46
+ "str": 0,
47
+ "bool": 1,
48
+ "long": 2,
49
+ "float": 3,
50
+ "complex_real": 4,
51
+ "complex_imag": 5,
52
+ "bytes": 6,
53
+ "bytearray": 7,
54
+ "array": 8,
55
+ "empty": 9,
56
+ "group": 10,
57
+ }
58
+ )
59
+ _field_delimiter: ClassVar[str] = "::"
60
+ _child_delimiter: ClassVar[str] = ";"
61
+
62
+ @classmethod
63
+ def get_bag_info(cls) -> BagInfo:
64
+ return H5Info(
65
+ qualname=cls.__qualname__,
66
+ module=cls.__module__,
67
+ version=cls.get_version(),
68
+ libver_str=cls.libver_str,
69
+ )
70
+
71
+ @classmethod
72
+ def _bag_info_class(cls) -> type[BagInfo]:
73
+ return H5Info
74
+
75
+ def __init__(
76
+ self, filepath: str | pathlib.Path, *args: object, **kwargs: Any
77
+ ) -> None:
78
+ self._file = None
79
+ self._context_depth = 0
80
+ self._unpacked_paths: StringArrayType | None = None
81
+ self._unpacked_type_index: IntArrayType | None = None
82
+ self._unpacked_position_index: IntArrayType | None = None
83
+ self._unpacked_nonmetadata_paths: list[str] | None = None
84
+ self._path_to_index: dict[str, int] | None = None
85
+ self._unpacked_trie: pygtrie.StringTrie | None = None
86
+ super().__init__(filepath)
87
+ self._packed_trie: pygtrie.StringTrie = pygtrie.StringTrie()
88
+ self._packed: tuple[
89
+ list[str],
90
+ list[bool],
91
+ list[int],
92
+ list[float],
93
+ list[float],
94
+ list[float],
95
+ list[bytes],
96
+ list[bytearray],
97
+ list[ArrayType],
98
+ ] = ([], [], [], [], [], [], [], [], [])
99
+
100
+ @property
101
+ def unpacked_trie(self) -> pygtrie.StringTrie:
102
+ if self._unpacked_trie is None:
103
+ with self:
104
+ self._unpacked_trie = reconstruct_stringtrie(
105
+ self.file["trie_segments"][:].astype("str"),
106
+ self.file["trie_parents"][:],
107
+ [v.tolist() for v in self.file["trie_values"][:]],
108
+ [-1, -1],
109
+ )
110
+ return self._unpacked_trie
111
+
112
+ def _write(self) -> None:
113
+ str_type = h5py.string_dtype(encoding="utf-8")
114
+
115
+ self.open("w")
116
+ segments, parents, values = decompose_stringtrie(
117
+ self._packed_trie, null_value=(-1, -1)
118
+ )
119
+ self.file.create_dataset(
120
+ "trie_segments",
121
+ data=np.array(segments, dtype=h5py.string_dtype(encoding="utf-8")),
122
+ )
123
+ self.file.create_dataset("trie_parents", data=np.array(parents, dtype=np.int32))
124
+ self.file.create_dataset("trie_values", data=np.array(values, dtype=np.int32))
125
+
126
+ self.file.create_dataset("str", data=np.array(self._packed[0], dtype=str_type))
127
+ self.file.create_dataset("bool", data=np.array(self._packed[1], dtype=bool))
128
+ self.file.create_dataset("long", data=np.array(self._packed[2], dtype=int))
129
+ self.file.create_dataset("float", data=np.array(self._packed[3], dtype=float))
130
+ self.file.create_dataset(
131
+ "complex_real", data=np.array(self._packed[4], dtype=float)
132
+ )
133
+ self.file.create_dataset(
134
+ "complex_imag", data=np.array(self._packed[5], dtype=float)
135
+ )
136
+ self.file.create_dataset("bytes", data=np.array(self._packed[6]))
137
+ self.file.create_dataset(
138
+ "bytearray", data=np.array(self._packed[7])
139
+ ) # dtype=bytearray
140
+ array_group = self.file.create_group("ndarrays")
141
+ for i, ra in enumerate(self._packed[8]):
142
+ array_group.create_dataset(f"i{i}", data=ra)
143
+ # Empty doesn't need to be packed -- it's always None so the meta info is enough
144
+ # Groups don't need to be packed -- they are just holders so meta info is enough
145
+
146
+ self.close()
147
+
148
+ def _unpack_bag_info(self) -> BagInfo:
149
+ with self:
150
+ info = super()._unpack_bag_info()
151
+ return info
152
+
153
+ def load(
154
+ self,
155
+ path: str = Bag.storage_root,
156
+ version_validator: VersionValidatorType = "exact",
157
+ version_scraping: VersionScrapingMap | None = None,
158
+ ) -> Any:
159
+ with self:
160
+ unpacked = super().load(
161
+ path=path,
162
+ version_validator=version_validator,
163
+ version_scraping=version_scraping,
164
+ )
165
+ return unpacked
166
+
167
+ def __getitem__(self, path: str) -> Metadata:
168
+ with self:
169
+ return super().__getitem__(self._sanitize_path(path))
170
+
171
+ def list_paths(self) -> list[str]:
172
+ """A list of all available content paths."""
173
+ if self._unpacked_nonmetadata_paths is None:
174
+ paths = self.unpacked_trie.keys()
175
+ self._unpacked_nonmetadata_paths = [
176
+ self._sanitize_path(p)
177
+ for p in np.array(paths)[
178
+ ~np.char.find(paths, self._field_delimiter) >= 0
179
+ ]
180
+ ]
181
+ return self._unpacked_nonmetadata_paths
182
+
183
+ def __enter__(self) -> Self:
184
+ self._context_depth += 1
185
+ if self._file is None:
186
+ self.open("r")
187
+ return self
188
+
189
+ def _pack_trie(self, path: str, type_index: int, position_index: int) -> None:
190
+ self._packed_trie[PATH_DELIMITER + path] = [type_index, position_index]
191
+
192
+ def _read_trie(self, path: str) -> tuple[int, int]:
193
+ return cast(
194
+ tuple[int, int],
195
+ self.unpacked_trie.values(prefix=PATH_DELIMITER + path, shallow=True)[0],
196
+ )
197
+
198
+ def _field_to_path(self, path: str, key: str) -> str:
199
+ return self._sanitize_path(path) + self._field_delimiter + key
200
+
201
+ def _sanitize_path(self, path: str) -> str:
202
+ return path.rstrip(PATH_DELIMITER).lstrip(PATH_DELIMITER)
203
+
204
+ def _pack_field(self, path: str, key: str, value: str) -> None:
205
+ type_index = self._index_map["str"]
206
+ data_list = self._packed[type_index]
207
+ data_list.append(value) # type: ignore[arg-type]
208
+ self._pack_trie(self._field_to_path(path, key), type_index, len(data_list) - 1)
209
+
210
+ def _unpack_field(self, path: str, key: str) -> str | None:
211
+ try:
212
+ return self.maybe_decode(
213
+ cast(str, self._read_pathlike(self._field_to_path(path, key)))
214
+ )
215
+ except KeyError:
216
+ return None
217
+
218
+ def _read_pathlike(self, path: str) -> H5Scalar:
219
+ # A real path or one with the field delimiter to find a metadata field
220
+ type_index, position_index = self._read_trie(path)
221
+ group_name = self._index_map.inverse[type_index]
222
+ with self:
223
+ value = cast(H5Scalar, self.file[group_name][position_index])
224
+ return value
225
+
226
+ def pack_empty(self, path: str) -> None:
227
+ self._pack_trie(path, self._index_map["empty"], -1)
228
+
229
+ def _pack_thing(
230
+ self, obj: PackedThingType | ArrayType, type_name: str, path: str
231
+ ) -> None:
232
+ type_index = self._index_map[type_name]
233
+ group = self._packed[type_index]
234
+ group.append(obj) # type: ignore[arg-type]
235
+ self._pack_trie(path, type_index, len(group) - 1)
236
+
237
+ def pack_string(self, obj: str, path: str) -> None:
238
+ self._pack_thing(obj, "str", path)
239
+
240
+ def unpack_string(self, path: str) -> str:
241
+ return self.maybe_decode(cast(str, self._read_pathlike(path)))
242
+
243
+ def pack_bool(self, obj: bool, path: str) -> None:
244
+ self._pack_thing(obj, "bool", path)
245
+
246
+ def unpack_bool(self, path: str) -> bool:
247
+ return bool(self._read_pathlike(path))
248
+
249
+ def pack_long(self, obj: int, path: str) -> None:
250
+ self._pack_thing(obj, "long", path)
251
+
252
+ def unpack_long(self, path: str) -> int:
253
+ return int(self._read_pathlike(path))
254
+
255
+ def pack_float(self, obj: float, path: str) -> None:
256
+ self._pack_thing(obj, "float", path)
257
+
258
+ def unpack_float(self, path: str) -> float:
259
+ return float(self._read_pathlike(path))
260
+
261
+ def pack_complex(self, obj: complex, path: str) -> None:
262
+ real_index = self._index_map["complex_real"]
263
+ real_group = self._packed[real_index]
264
+ real_group.append(obj.real) # type: ignore[arg-type]
265
+ imag_index = self._index_map["complex_imag"]
266
+ imag_group = self._packed[imag_index]
267
+ imag_group.append(obj.imag) # type: ignore[arg-type]
268
+ self._pack_trie(path, real_index, len(real_group) - 1)
269
+
270
+ def unpack_complex(self, path: str) -> complex:
271
+ _, position_index = self._read_trie(path)
272
+ with self:
273
+ value = complex(
274
+ self.file["complex_real"][position_index],
275
+ self.file["complex_imag"][position_index],
276
+ )
277
+ return value
278
+
279
+ def pack_bytes(self, obj: bytes, path: str) -> None:
280
+ self._pack_thing(obj, "bytes", path)
281
+
282
+ def unpack_bytes(self, path: str) -> bytes:
283
+ return cast(bytes, self._read_pathlike(path).tobytes())
284
+
285
+ def pack_bytearray(self, obj: bytearray, path: str) -> None:
286
+ self._pack_thing(obj, "bytearray", path)
287
+
288
+ def unpack_bytearray(self, path: str) -> bytearray:
289
+ return bytearray(self._read_pathlike(path))
290
+
291
+ def create_group(self, path: str) -> None:
292
+ self._pack_trie(path, self._index_map["group"], -1)
293
+
294
+ def open_group(self, path: str) -> set[str]:
295
+ prefix = PATH_DELIMITER + path
296
+ subpaths = self.unpacked_trie.keys(prefix=prefix, shallow=False)
297
+ next_depth_index = 1
298
+ children = {
299
+ part[next_depth_index]
300
+ for key in subpaths
301
+ if (part := key[len(prefix) :].split(PATH_DELIMITER, next_depth_index + 1))
302
+ and len(part) > next_depth_index
303
+ and self._field_delimiter not in part[next_depth_index]
304
+ }
305
+ return children
306
+
307
+ # def get_bespoke_content_class(self, obj: object) -> type[BespokeItem[Any, Self]] | None:
308
+ def get_bespoke_content_class(
309
+ self, obj: object
310
+ ) -> type[BespokeItem[Any, Self]] | None:
311
+ if type(obj) is np.ndarray and obj.dtype in H5PY_DTYPE_WHITELIST:
312
+ return cast(type[BespokeItem[Any, Self]], Array)
313
+ return None
314
+
315
+ def pack_array(self, obj: ArrayType, path: str) -> None:
316
+ self._pack_thing(obj, "array", path)
317
+
318
+ def unpack_array(self, path: str) -> ArrayType:
319
+ _, position_index = self._read_trie(path)
320
+ with self:
321
+ value = cast(ArrayType, self.file[f"ndarrays/i{position_index}"][:])
322
+ return value
@@ -0,0 +1,197 @@
1
+ """
2
+ Tools for extracting and logging information about python objects.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import dataclasses
8
+ import re
9
+ from collections.abc import Callable, ItemsView
10
+ from importlib import import_module
11
+ from sys import version_info
12
+ from typing import Any, Literal, TypeAlias
13
+
14
+ from bagofholding.exceptions import EnvironmentMismatchError
15
+
16
+
17
+ @dataclasses.dataclass(frozen=True)
18
+ class HasFieldIterator:
19
+ """A simple helper mixin for dataclasses"""
20
+
21
+ def field_items(self) -> ItemsView[str, str | None]:
22
+ return dataclasses.asdict(self).items()
23
+
24
+
25
+ @dataclasses.dataclass(frozen=True)
26
+ class HasContentType:
27
+ content_type: str
28
+
29
+
30
+ @dataclasses.dataclass(frozen=True)
31
+ class HasVersionInfo:
32
+ qualname: str | None = None
33
+ module: str | None = None
34
+ version: str | None = None
35
+
36
+
37
+ @dataclasses.dataclass(frozen=True)
38
+ class Metadata(HasVersionInfo, HasContentType, HasFieldIterator):
39
+ meta: str | None = None
40
+
41
+
42
+ def get_module(obj: Any) -> str:
43
+ return obj.__module__ if isinstance(obj, type) else type(obj).__module__
44
+
45
+
46
+ def get_qualname(obj: Any) -> str:
47
+ return obj.__qualname__ if isinstance(obj, type) else type(obj).__qualname__
48
+
49
+
50
+ VersionScraperType: TypeAlias = Callable[[str], str | None]
51
+ VersionScrapingMap: TypeAlias = dict[str, VersionScraperType]
52
+
53
+
54
+ def get_version(
55
+ module_name: str,
56
+ version_scraping: VersionScrapingMap | None = None,
57
+ ) -> str | None:
58
+ """
59
+ Given a module name, get its associated version (if any). By default, this simply
60
+ looks for the :attr:`__version__` attribute on the imported module.
61
+
62
+ For :mod:`builtins` this is just the python interpreter version.
63
+
64
+ Args:
65
+ module_name (str): The module to examine.
66
+ version_scraping (VersionScrapingMap | None): Since some modules may store
67
+ their version in other ways, this provides an optional map between module
68
+ names and callables to leverage for extracting that module's version.
69
+
70
+ Returns:
71
+ (str | None): The module's version as a string, if any can be found.
72
+ """
73
+ if module_name == "builtins":
74
+ return f"{version_info.major}.{version_info.minor}.{version_info.micro}"
75
+
76
+ module_base = module_name.split(".")[0]
77
+ scraper_map: VersionScrapingMap = (
78
+ {} if version_scraping is None else version_scraping
79
+ )
80
+
81
+ scraper = (
82
+ scraper_map[module_base] # noqa: SIM401
83
+ if module_base in scraper_map
84
+ else _scrape_version_attribute
85
+ )
86
+ # mypy struggles with .get even when the fallback is specified,
87
+ # so break it apart and tell Ruff to not worry that we avoid .get
88
+ return scraper(module_base)
89
+
90
+
91
+ def _scrape_version_attribute(module_name: str) -> str | None:
92
+ module = import_module(module_name)
93
+ try:
94
+ return str(module.__version__)
95
+ except AttributeError:
96
+ return None
97
+
98
+
99
+ VersionValidatorType: TypeAlias = (
100
+ Literal["exact", "semantic-minor", "semantic-major", "none"]
101
+ | Callable[[str, str], bool]
102
+ )
103
+
104
+
105
+ def validate_version(
106
+ metadata: Metadata,
107
+ validator: VersionValidatorType = "exact",
108
+ version_scraping: VersionScrapingMap | None = None,
109
+ ) -> None:
110
+ """
111
+ Check whether versioning information in a piece of metadata matches the current
112
+ environment.
113
+
114
+ Args:
115
+ metadata (Metadata): The metadata to validate.
116
+ validator ("exact" | Callable[[str, str], bool]): A recognized keyword or a
117
+ callable that takes the current and metadata versions as strings and
118
+ returns a boolean to indicate whether the current version matches the
119
+ metadata reference. Keywords are "exact" (versions must be identical),
120
+ "semantic-minor" (semantic versions (X.Y.Z where all are integers) match
121
+ in the first two digits; all non-semantic versions must match exactly),
122
+ "semantic-major" (semantic versions match in the first digit), and "none"
123
+ (don't compare the versions at all).
124
+ version_scraping (dict[str, Callable[[str], str]] | None): An optional
125
+ dictionary mapping module names to a callable that takes this name and
126
+ returns a version (or None). The default callable imports the module
127
+ string and looks for a `__version__` attribute.
128
+
129
+ Raises:
130
+ EnvironmentMismatch: If the module in the metadata cannot be found, or if the
131
+ current and metadata versions do not pass validation.
132
+ """
133
+ if (
134
+ metadata.version is not None
135
+ and metadata.version != ""
136
+ and isinstance(metadata.module, str)
137
+ ):
138
+ try:
139
+ current_version = str(get_version(metadata.module, version_scraping))
140
+ except ModuleNotFoundError as e:
141
+ raise EnvironmentMismatchError(
142
+ f"When unpacking an object, encountered a module {metadata.module} "
143
+ f"in the metadata that could not be found in the current environment."
144
+ ) from e
145
+
146
+ version_validator: VersionValidatorType
147
+ if validator == "exact":
148
+ version_validator = _versions_are_equal
149
+ elif validator == "semantic-minor":
150
+ version_validator = _versions_match_semantic_minor
151
+ elif validator == "semantic-major":
152
+ version_validator = _versions_match_semantic_major
153
+ else:
154
+ version_validator = validator
155
+
156
+ if isinstance(version_validator, str):
157
+ if version_validator == "none":
158
+ return
159
+ else:
160
+ raise ValueError(
161
+ f"Unrecognized validator keyword {version_validator} -- please supply {VersionValidatorType}"
162
+ )
163
+ elif version_validator(current_version, metadata.version):
164
+ return
165
+ raise EnvironmentMismatchError(
166
+ f"{metadata.module} is stored with version {metadata.version}, "
167
+ f"but the current environment has {current_version}. This does not pass "
168
+ f"validation criterion: {version_validator}"
169
+ )
170
+
171
+
172
+ def _versions_are_equal(version: str, reference: str) -> bool:
173
+ return version == reference
174
+
175
+
176
+ def _decompose_semver(version: str) -> tuple[int, int, int] | None:
177
+ match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version)
178
+ if match:
179
+ major, minor, patch = match.groups()
180
+ return int(major), int(minor), int(patch)
181
+ return None
182
+
183
+
184
+ def _versions_match_semantic_minor(version: str, reference: str) -> bool:
185
+ v_parts = _decompose_semver(version)
186
+ r_parts = _decompose_semver(reference)
187
+ if v_parts and r_parts:
188
+ return v_parts[:2] == r_parts[:2]
189
+ return version == reference
190
+
191
+
192
+ def _versions_match_semantic_major(version: str, reference: str) -> bool:
193
+ v_parts = _decompose_semver(version)
194
+ r_parts = _decompose_semver(reference)
195
+ if v_parts and r_parts:
196
+ return v_parts[0] == r_parts[0]
197
+ return version == reference
@@ -0,0 +1,52 @@
1
+ """
2
+ Helper functions for managing the relationship between strings and imports.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from importlib import import_module
8
+ from typing import Any
9
+
10
+ from bagofholding.exceptions import StringReductionNotImportableError
11
+
12
+
13
+ def import_from_string(library_path: str) -> Any:
14
+ split_path = library_path.split(".", 1)
15
+ if len(split_path) == 1:
16
+ module_name, path = split_path[0], ""
17
+ else:
18
+ module_name, path = split_path
19
+ obj = import_module(module_name)
20
+ for k in path.split("."):
21
+ obj = getattr(obj, k)
22
+ return obj
23
+
24
+
25
+ def get_importable_string_from_string_reduction(
26
+ string_reduction: str, reduced_object: object
27
+ ) -> str:
28
+ """
29
+ Per the pickle docs:
30
+
31
+ > If a string is returned, the string should be interpreted as the name of a global
32
+ variable. It should be the object’s local name relative to its module; the pickle
33
+ module searches the module namespace to determine the object’s module. This
34
+ behaviour is typically useful for singletons.
35
+
36
+ To then import such an object from a non-local caller, we try scoping the string
37
+ with the module of the object which returned it.
38
+ """
39
+ try:
40
+ import_from_string(string_reduction)
41
+ importable = string_reduction
42
+ except ModuleNotFoundError:
43
+ importable = reduced_object.__module__ + "." + string_reduction
44
+ try:
45
+ import_from_string(importable)
46
+ except (ModuleNotFoundError, AttributeError) as e:
47
+ raise StringReductionNotImportableError(
48
+ f"Couldn't import {string_reduction} after scoping it as {importable}. "
49
+ f"Please contact the developers so we can figure out how to handle "
50
+ f"this edge case."
51
+ ) from e
52
+ return importable