-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy path_storage.py
More file actions
147 lines (119 loc) · 4.29 KB
/
_storage.py
File metadata and controls
147 lines (119 loc) · 4.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
from __future__ import annotations
import functools
from typing import Any
import numpy as np
from .. import storage
__all__ = [
"_data_from_dict",
"_storage_from_dict",
"_storage_to_dict",
"_storage_type_to_str",
]
def __dir__() -> list[str]:
return __all__
def _storage_type_to_str(_storage: storage.Storage, /) -> str:
"""Return the canonical storage type string for a storage object."""
match _storage:
case storage.Int64():
return "int"
case storage.Double():
return "double"
case storage.AtomicInt64():
return "int"
case storage.Unlimited():
return "double"
case storage.Weight():
return "weighted"
case storage.Mean():
return "mean"
case storage.WeightedMean():
return "weighted_mean"
case _:
raise TypeError(f"Unsupported storage type: {_storage}")
@functools.singledispatch
def _storage_to_dict(_storage: storage.Storage, /, data: Any) -> dict[str, Any]: # noqa: ARG001
"""Convert a storage to a dictionary."""
msg = f"Unsupported storage type: {_storage}"
raise TypeError(msg)
@_storage_to_dict.register(storage.Int64)
@_storage_to_dict.register(storage.Double)
def _(_storage: storage.Double, /, data: Any) -> dict[str, Any]:
return {"type": _storage_type_to_str(_storage), "values": data}
@_storage_to_dict.register(storage.AtomicInt64)
@_storage_to_dict.register(storage.Unlimited)
def _(
storage_: storage.AtomicInt64 | storage.Unlimited,
/,
data: Any,
) -> dict[str, Any]:
return {
"writer_info": {"boost-histogram": {"orig_type": type(storage_).__name__}},
"type": "int" if np.issubdtype(data.dtype, np.integer) else "double",
"values": data,
}
@_storage_to_dict.register(storage.Weight)
def _(_storage: storage.Weight, /, data: Any) -> dict[str, Any]:
return {
"type": _storage_type_to_str(_storage),
"values": data.value,
"variances": data.variance,
}
@_storage_to_dict.register(storage.Mean)
def _(_storage: storage.Mean, /, data: Any) -> dict[str, Any]:
return {
"type": _storage_type_to_str(_storage),
"counts": data.count,
"values": data.value,
"variances": data.variance,
}
@_storage_to_dict.register(storage.WeightedMean)
def _(_storage: storage.WeightedMean, /, data: Any) -> dict[str, Any]:
return {
"type": _storage_type_to_str(_storage),
"sum_of_weights": data.sum_of_weights,
"sum_of_weights_squared": data.sum_of_weights_squared,
"values": data.value,
"variances": data.variance,
}
def _storage_from_dict(data: dict[str, Any], /) -> storage.Storage:
"""Convert a dictionary to a storage object."""
# If loading a boost-histogram, we can load the exact original type
orig_type = (
data.get("writer_info", {}).get("boost-histogram", {}).get("orig_type", "")
)
if orig_type == "AtomicInt64":
return storage.AtomicInt64()
if orig_type == "Unlimited":
return storage.Unlimited()
storage_type = data["type"]
if storage_type == "int":
return storage.Int64()
if storage_type == "double":
return storage.Double()
if storage_type == "weighted":
return storage.Weight()
if storage_type == "mean":
return storage.Mean()
if storage_type == "weighted_mean":
return storage.WeightedMean()
raise TypeError(f"Unsupported storage type: {storage_type}")
def _data_from_dict(data: dict[str, Any], /) -> np.typing.NDArray[Any]:
"""Convert a dictionary to data."""
storage_type = data["type"]
if storage_type in {"int", "double"}:
return data["values"] # type: ignore[no-any-return]
if storage_type == "weighted":
return np.stack([data["values"], data["variances"]], axis=-1)
if storage_type == "mean":
return np.stack([data["counts"], data["values"], data["variances"]], axis=-1)
if storage_type == "weighted_mean":
return np.stack(
[
data["sum_of_weights"],
data["sum_of_weights_squared"],
data["values"],
data["variances"],
],
axis=-1,
)
raise TypeError(f"Unsupported storage type: {storage_type}")