-
Notifications
You must be signed in to change notification settings - Fork 15
/
_bin_utils.py
210 lines (170 loc) · 6.33 KB
/
_bin_utils.py
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""Methods for investigation and manipulation of bin arrays."""
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from typing import Optional, Tuple, Union
from typing_extensions import Literal
from physt.typing_aliases import ArrayLike
def make_bin_array(bins: ArrayLike) -> np.ndarray:
"""Turn bin data into array understood by HistogramXX classes.
Parameters
----------
bins: Array of edges or array of edge tuples
Examples
--------
>>> make_bin_array([0, 1, 2])
array([[0, 1],
[1, 2]])
>>> make_bin_array([[0, 1], [2, 3]])
array([[0, 1],
[2, 3]])
"""
bins = np.asarray(bins)
if bins.ndim == 1:
# if bins.shape[0] == 0:
# raise RuntimeError("Needs at least one bin")
return np.hstack((bins[:-1, np.newaxis], bins[1:, np.newaxis]))
elif bins.ndim == 2:
if bins.shape[1] != 2:
raise ValueError(
f"Binning schema with ndim==2 requires shape (n, 2), {bins.shape} found."
)
# if bins.shape[0] == 0:
# raise RuntimeError("Needs at least one bin")
return bins # Already correct, just pass
else:
raise ValueError(
f"Binning schema must have ndim==1 or ndim==2, {bins.ndim} found."
)
def to_numpy_bins(bins: ArrayLike) -> np.ndarray:
"""Convert physt bin format to numpy edges.
Parameters
----------
bins: 1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: all edges
"""
bins = np.asarray(bins)
if bins.ndim == 1: # Already in the proper format
return bins
if not is_consecutive(bins):
raise ValueError("Cannot create numpy bins from inconsecutive edges.")
return np.concatenate([bins[:1, 0], bins[:, 1]])
def to_numpy_bins_with_mask(bins: ArrayLike) -> Tuple[np.ndarray, np.ndarray]:
"""Numpy binning edges including gaps.
Parameters
----------
bins: 1-D (n) or 2-D (n, 2) array of edges
Returns
-------
edges: All edges
mask: List of indices that correspond to bins that have to be included
Examples
--------
>>> to_numpy_bins_with_mask([0, 1, 2])
(array([0, 1, 2]), array([0, 1]))
>>> to_numpy_bins_with_mask([[0, 1], [2, 3]])
(array([0, 1, 2, 3]), array([0, 2]))
"""
bins = np.asarray(bins)
if bins.ndim == 1:
edges_: Union[np.ndarray, list] = bins
if bins.shape[0] > 1:
mask_: Union[np.ndarray, list] = np.arange(bins.shape[0] - 1)
else:
mask_ = []
elif bins.ndim == 2:
edges_ = []
mask_ = []
j = 0
if bins.shape[0] > 0:
edges_.append(bins[0, 0])
for i in range(bins.shape[0] - 1):
mask_.append(j)
edges_.append(bins[i, 1])
if bins[i, 1] != bins[i + 1, 0]:
edges_.append(bins[i + 1, 0])
j += 1
j += 1
mask_.append(j)
edges_.append(bins[-1, 1])
else:
raise ValueError("to_numpy_bins_with_mask: array with dim=1 or 2 expected")
if not np.all(np.diff(edges_) > 0):
raise ValueError("to_numpy_bins_with_mask: edges array not monotone.")
return np.asarray(edges_), np.asarray(mask_)
def is_rising(bins: ArrayLike) -> bool:
"""Check whether the bins are in raising order.
Does not check if the bins are consecutive.
Parameters
----------
bins: array_like
"""
# TODO: Optimize for numpy bins
bins = make_bin_array(bins)
if np.any(bins[:, 0] >= bins[:, 1]):
return False
if np.any(bins[1:, 0] < bins[:-1, 1]):
return False
return True
def is_consecutive(bins: ArrayLike, rtol: float = 1.0e-5, atol: float = 1.0e-8) -> bool:
"""Check whether the bins are consecutive (edges match).
Does not check if the bins are in rising order.
"""
bins = np.asarray(bins)
if bins.ndim == 1:
return True
else:
bins = make_bin_array(bins)
return np.allclose(bins[1:, 0], bins[:-1, 1], rtol, atol)
def is_bin_subset(sub: ArrayLike, sup: ArrayLike) -> bool:
"""Check whether all bins in one binning are present also in another:
Parameters
----------
sub: Candidate for the bin subset
sup: Candidate for the bin superset
"""
sub = make_bin_array(sub)
sup = make_bin_array(sup)
for row in sub:
if not (row == sup).all(axis=1).any():
# TODO: Enable also approximate equality
return False
return True
def is_bin_superset(sup: ArrayLike, sub: ArrayLike) -> bool:
"""Inverse of is_bin_subset."""
return is_bin_subset(sub=sub, sup=sup)
def find_human_width_decimal(raw_width: float) -> float:
"""Find the human bin width un decimal scale close to raw_width."""
subscales = np.array([0.5, 1, 2, 2.5, 5, 10])
power = np.floor(np.log10(raw_width)).astype(int)
best_index = np.argmin(np.abs(np.log(subscales * (10.0**power) / raw_width)))
return (10.0**power) * subscales[best_index]
def find_human_width_60(raw_width: float) -> int:
"""Find the best human bin width for seconds and minutes close to raw_width."""
subscales = np.array([1, 2, 5, 10, 15, 20, 30])
best_index = np.argmin(np.abs(np.log(subscales / raw_width)))
return subscales[best_index]
def find_human_width_24(raw_width: float) -> int:
"""Find the best human bin width for hours close to raw_width."""
subscales = np.array([1, 2, 3, 4, 6, 12])
best_index = np.argmin(np.abs(np.log(subscales / raw_width)))
return subscales[best_index]
def find_human_width(raw_width: float, kind: Optional[Literal["time"]] = None) -> float:
"""Find the best human width close to a given raw_width."""
# TODO: Deal with infinity
if not kind:
return find_human_width_decimal(raw_width)
if kind == "time":
if raw_width < 0.8:
return find_human_width_decimal(raw_width)
if raw_width < 50:
return find_human_width_60(raw_width)
if raw_width < 3000:
return find_human_width_60(raw_width / 60) * 60
if raw_width < 70000:
return find_human_width_24(raw_width / 3600) * 3600
return find_human_width_decimal(raw_width / 86400) * 86400
raise ValueError(f"Value of 'kind' not understood: '{kind}'.")