-
Notifications
You must be signed in to change notification settings - Fork 15
/
binnings.py
1112 lines (938 loc) · 34.9 KB
/
binnings.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Different binning algorithms/schemas for the histograms."""
from __future__ import annotations
import warnings
from contextlib import suppress
from typing import TYPE_CHECKING, cast
import numpy as np
from physt._bin_utils import (
find_human_width,
is_bin_subset,
is_consecutive,
is_rising,
make_bin_array,
to_numpy_bins,
to_numpy_bins_with_mask,
)
from physt._util import find_subclass
if TYPE_CHECKING:
from typing import (
Any,
Callable,
ClassVar,
Dict,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
)
from typing_extensions import Literal
from physt.typing_aliases import ArrayLike, RangeTuple
BinningType = TypeVar("BinningType", bound="BinningBase")
binning_methods = {}
"""Dictionary of available binnnings."""
def register_binning(name: Optional[str] = None):
"""Decorator to register among available binning methods."""
def decorator(f: Callable) -> Callable:
key = name or f.__name__[:-8]
binning_methods[key] = f
return f
return decorator
# TODO: Locking and edit operations (like numpy read-only)
class BinningBase:
"""Abstract base class for binning schemas.
Inheriting
----------
- define at least one of the following properties: bins, numpy_bins (cached conversion exists)
- if you modify bins, put _bins and _numpy_bins into proper state (None may be sufficient)
- checking of proper bins should be done in __init__
- if you want to support adaptive histogram, override _force_bin_existence
- implement _update_dict to contain the binning representation
- the constructor (and facade methods) must accept any kwargs (and ignores those that are not used).
"""
adaptive_allowed: ClassVar[bool] = False
"""Whether it is possible to update the bins dynamically."""
inconsecutive_allowed: ClassVar[bool] = False
"""Whether it is possible to have bins with gaps."""
def __init__(
self,
bins: Optional[ArrayLike] = None,
numpy_bins: Optional[ArrayLike] = None,
includes_right_edge: bool = False,
adaptive: bool = False,
):
# TODO: Incorporate integrity_check?
self._consecutive = None
if bins is not None:
if numpy_bins is not None:
raise ValueError("Cannot specify numpy_bins and bins at the same time.")
bins = make_bin_array(bins)
if not is_rising(bins):
raise ValueError("Bins must be in rising order.")
# TODO: Test for consecutiveness?
elif numpy_bins is not None:
numpy_bins = to_numpy_bins(numpy_bins)
if not np.all(numpy_bins[1:] > numpy_bins[:-1]):
raise ValueError("Bins must be in rising order.")
self._consecutive = True
self._bins = bins
self._numpy_bins = numpy_bins
self._includes_right_edge = includes_right_edge
if adaptive and not self.adaptive_allowed:
raise ValueError(f"Adaptivity not allowed for {self.__class__.__name__}.")
if adaptive and includes_right_edge:
raise ValueError(
"Adaptivity does not work together with right-edge inclusion."
)
self._adaptive = adaptive
def __getitem__(self, index: Union[slice, int]):
if isinstance(index, slice):
new_binning = self.as_static()
new_binning._bins = new_binning.bins[index]
return new_binning
return self.bins[index]
@staticmethod
def from_dict(a_dict: Dict[str, Any]) -> BinningBase:
binning_type = a_dict.pop("binning_type", "StaticBinning")
klass = find_subclass(BinningBase, binning_type)
return klass(**a_dict)
def to_dict(self) -> Dict[str, Any]:
"""Dictionary representation of the binning schema.
This serves as template method, please implement _update_dict
"""
result: Dict[str, Any] = {
"adaptive": self._adaptive,
"binning_type": type(self).__name__,
}
self._update_dict(result)
return result
def _update_dict(self, a_dict):
raise NotImplementedError(
f"Dictionary representation of {type(self).__name__} is not implemented."
)
@property
def includes_right_edge(self) -> bool:
# TODO: Document and explain
return self._includes_right_edge
def is_regular(self, *, rtol: float = 1.0e-5, atol: float = 1.0e-8) -> bool:
"""Whether all bins have the same width.
Parameters
----------
rtol, atol : numpy tolerance parameters
"""
return np.allclose(
np.diff(self.bins[1] - self.bins[0]), 0.0, rtol=rtol, atol=atol
)
def is_consecutive(self, rtol: float = 1.0e-5, atol: float = 1.0e-8) -> bool:
"""Whether all bins are in a growing order.
Parameters
----------
rtol, atol : numpy tolerance parameters
"""
if self.inconsecutive_allowed:
if self._consecutive is None:
if self._numpy_bins is not None:
self._consecutive = True
self._consecutive = is_consecutive(self.bins, rtol, atol)
return self._consecutive
return True
def is_adaptive(self) -> bool:
"""Whether the binning can be adapted to include values not currently spanned."""
return self._adaptive
def force_bin_existence(self, values):
"""Change schema so that there is a bin for value.
It is necessary to implement the _force_bin_existence template method.
Parameters
----------
values: np.ndarray
All values we want bins for.
Returns
-------
bin_map: Iterable[tuple] or None or int
None => There was no change in bins
int => The bins are only shifted (allows mass assignment)
Otherwise => the iterable contains tuples (old bin index, new bin index)
new bin index can occur multiple times, which corresponds to bin merging
"""
# TODO: Rename to something less evil
if not self.is_adaptive():
raise RuntimeError("Histogram is not adaptive")
else:
return self._force_bin_existence(values)
def _force_bin_existence(self, values):
# TODO: in-place
raise NotImplementedError()
def adapt(self, other: "BinningBase"):
"""Adapt this binning so that it contains all bins of another binning.
Parameters
----------
other: BinningBase
"""
# TODO: in-place arg
if np.array_equal(self.bins, other.bins):
return None, None
elif not self.is_adaptive():
raise RuntimeError("Cannot adapt non-adaptive binning.")
else:
return self._adapt(other)
def set_adaptive(self, value: bool = True) -> None:
"""Set/unset the adaptive property of the binning.
This is available only for some of the binning types.
"""
if value and not self.adaptive_allowed:
raise RuntimeError("Cannot change binning to adaptive.")
self._adaptive = value
def _adapt(self, other):
raise RuntimeError("Cannot adapt binning.")
@property
def bins(self) -> np.ndarray:
"""Bins in the wider format (as edge pairs)
Returns
-------
bins: np.ndarray
shape=(bin_count, 2)
"""
if self._bins is None:
self._bins = make_bin_array(self.numpy_bins)
return self._bins
def __eq__(self, other):
if self is other:
return True
if other.__class__ != self.__class__:
return False
if self._bins is not None:
return np.array_equal(self.bins, other.bins)
if self._numpy_bins is not None:
return np.array_equal(self.numpy_bins, other.numpy_bins)
bins = self.bins
if bins is not None:
return np.array_equal(self.bins, other.bins)
return False
@property
def bin_count(self) -> int:
"""The total number of bins."""
return self.bins.shape[0]
@property
def numpy_bins(self) -> np.ndarray:
"""Bins in the numpy format
This might not be available for inconsecutive binnings.
Returns
-------
edges: np.ndarray
shape=(bin_count+1,)
"""
if self._numpy_bins is None:
self._numpy_bins = to_numpy_bins(self.bins)
return self._numpy_bins
@property
def numpy_bins_with_mask(self) -> Tuple[np.ndarray, np.ndarray]:
"""Bins in the numpy format, including the gaps in inconsecutive binnings.
Returns
-------
edges, mask: np.ndarray
See Also
--------
bin_utils.to_numpy_bins_with_mask
"""
edges, mask = to_numpy_bins_with_mask(self.bins)
if not self.includes_right_edge:
edges = np.concatenate([edges, np.asarray([np.inf])])
return edges, mask
@property
def first_edge(self) -> float:
"""The left edge of the first bin."""
if self._numpy_bins is not None:
return self._numpy_bins[0]
return self.bins[0][0]
@property
def last_edge(self) -> float:
"""The right edge of the last bin."""
if self._numpy_bins is not None:
return self._numpy_bins[-1]
return self.bins[-1][1]
def as_static(self, copy: bool = True) -> "StaticBinning": # pylint: disable=unused-argument
"""Convert binning to a static form.
Parameters
----------
copy: bool
Ensure that we receive another object
Returns
-------
StaticBinning
A new static binning with a copy of bins.
"""
return StaticBinning(
bins=self.bins.copy(), includes_right_edge=self.includes_right_edge
)
def as_fixed_width(self, copy: bool = True) -> "FixedWidthBinning": # pylint: disable=unused-argument
"""Convert binning to recipe with fixed width (if possible.)
Parameters
----------
copy: If True, ensure that we receive another object.
"""
if self.bin_count == 0:
raise ValueError("Cannot guess binning width with zero bins")
elif self.bin_count == 1 or self.is_consecutive() and self.is_regular():
return FixedWidthBinning(
min=self.bins[0][0],
bin_count=self.bin_count,
bin_width=self.bins[1] - self.bins[0],
)
else:
raise ValueError(
"Cannot create fixed-width binning from differing bin widths."
)
def copy(self: "BinningType") -> "BinningType":
"""An identical, independent copy."""
raise NotImplementedError()
def apply_bin_map(self, bin_map) -> "BinningBase":
"""
Parameters
----------
bin_map: Iterator(tuple)
The bins must be in ascending order
"""
length = max(item[1] for item in bin_map) + 1
bins = np.empty((length, 2), dtype=float)
bins[:] = np.nan
for old, new in bin_map:
if np.isnan(bins[new, 0]):
bins[new, :] = self.bins[old, :]
else:
if bins[new, 1] != self.bins[old, 0]:
raise ValueError("Merging non-consecutive bins.")
bins[new, 1] = self.bins[old, 1]
if np.any(np.isnan(bins)):
raise ValueError("New binning is not complete.")
includes_right_edge = (
self.includes_right_edge and bins[-1, 1] == self.bins[-1, 1]
)
binning = StaticBinning(bins, includes_right_edge=includes_right_edge)
return binning
def __repr__(self):
return f"{self.__class__.__name__}({self.numpy_bins!r})"
if TYPE_CHECKING:
BinningLike = Union[BinningBase, ArrayLike]
"""Anything that can be converted to a binning."""
class StaticBinning(BinningBase):
"""Binning defined by an array of bin edge pairs."""
inconsecutive_allowed = True
def __init__(self, bins, includes_right_edge=True, **kwargs):
super().__init__(bins=bins, includes_right_edge=includes_right_edge)
def as_static(self, copy: bool = True) -> "StaticBinning":
"""Convert binning to a static form.
Returns
-------
StaticBinning
A new static binning with a copy of bins.
Parameters
----------
copy : if True, returns itself (already satisfying conditions).
"""
if copy:
return self.copy()
return self
def copy(self):
return StaticBinning(
bins=self.bins.copy(), includes_right_edge=self.includes_right_edge
)
def __getitem__(self, item):
copy = self.copy()
copy._bins = self._bins[item]
# TODO: check for the right_edge??
return copy
def _update_dict(self, a_dict):
a_dict["bins"] = self.bins.tolist()
def _adapt(self, other):
if is_bin_subset(other.bins, self.bins):
indices = np.searchsorted(other.bins[:, 0], self.bins[:, 0])
return None, list(enumerate(indices))
def __repr__(self):
return f"{self.__class__.__name__}({self.bins!r})"
class NumpyBinning(BinningBase):
"""Binning schema working as numpy.histogram."""
def __init__(self, numpy_bins: ArrayLike, includes_right_edge=True, **kwargs):
if not is_rising(numpy_bins):
raise ValueError("Bins not in rising order.")
super().__init__(
numpy_bins=numpy_bins, includes_right_edge=includes_right_edge, **kwargs
)
@property
def numpy_bins(self):
return self._numpy_bins
def copy(self) -> "NumpyBinning":
return NumpyBinning(
numpy_bins=self.numpy_bins, includes_right_edge=self.includes_right_edge
)
def _update_dict(self, a_dict: dict) -> None:
a_dict["numpy_bins"] = self.numpy_bins.tolist()
class FixedWidthBinning(BinningBase):
"""Binning schema with predefined bin width."""
adaptive_allowed = True
def __init__(
self,
*,
bin_width,
bin_count=0,
bin_times_min=None,
min=None,
includes_right_edge=False,
adaptive=False,
bin_shift=None,
align=True,
**kwargs,
):
super().__init__(adaptive=adaptive, includes_right_edge=includes_right_edge)
# TODO: Check edge cases for min/shift/align
if bin_width <= 0:
raise ValueError("Bin width must be > 0.")
if bin_count < 0:
raise ValueError("Bin count must be >= 0.")
if (bin_times_min is not None or bin_shift is not None) and (min is not None):
raise ValueError("Cannot specify both min and (times_min or shift)")
if (bin_count == 0) and ((bin_times_min is not None) or (min is not None)):
raise ValueError("Cannot set min for an empty binning.")
self._bin_width = float(bin_width)
self._align = align
self._bin_count = int(bin_count)
if min is not None:
self._times_min = int(np.floor(min / self.bin_width))
self._shift = min - self._times_min * self.bin_width
else:
self._times_min = bin_times_min
self._shift = bin_shift or 0.0
self._bins = None
self._numpy_bins = None
def __repr__(self):
result = (
f"{self.__class__.__name__}(bin_width={self.bin_width}, "
f"bin_count={self.bin_count}, min={self.first_edge}"
)
if self.is_adaptive():
result += ", adaptive=True"
return result + ")"
def is_regular(self, **kwargs) -> bool:
return True
def _force_bin_existence_single(self, value, includes_right_edge=None):
if includes_right_edge is None:
includes_right_edge = self.includes_right_edge
if self._bin_count == 0:
self._times_min = int(np.floor((value - self._shift) / self.bin_width))
if not self._align:
self._shift = value - self._times_min * self.bin_width
self._bin_count = 1
self._bins = None
self._numpy_bins = None
return ()
else:
add_left = add_right = 0
if value < self.numpy_bins[0]:
add_left = int(np.ceil((self.numpy_bins[0] - value) / self.bin_width))
self._times_min -= add_left
self._bin_count += add_left
elif value >= self.numpy_bins[-1]:
add_right = (value - self.numpy_bins[-1]) / self.bin_width
add_right = int(np.ceil(add_right))
self._bin_count += add_right
if self.last_edge == value and not includes_right_edge:
add_right += 1
self._bin_count += 1
if add_left or add_right:
self._bins = None
self._numpy_bins = None
return add_left
else:
return None
def _force_bin_existence(self, values, *, includes_right_edge=None):
if np.isscalar(values):
return self._force_bin_existence_single(
values, includes_right_edge=includes_right_edge
)
else:
min_, max_ = np.min(values), np.max(values)
result = self._force_bin_existence_single(min_)
result2 = self._force_bin_existence_single(
max_, includes_right_edge=includes_right_edge
)
if result is None:
return result2
else:
return result
@property
def first_edge(self) -> float:
return self._times_min * self._bin_width + self._shift
@property
def last_edge(self) -> float:
return (self._times_min + self._bin_count) * self._bin_width + self._shift
@property
def numpy_bins(self):
if self._numpy_bins is None:
self._bins = None
if self._bin_count == 0:
return np.zeros((0, 2), dtype=float)
self._numpy_bins = (
self._times_min + np.arange(self._bin_count + 1, dtype=int)
) * self._bin_width + self._shift
return self._numpy_bins
@property
def bin_count(self):
return self._bin_count
def copy(self):
return FixedWidthBinning(
bin_width=self._bin_width,
bin_count=self._bin_count,
align=self._align, # Not necessary
bin_times_min=self._times_min,
bin_shift=self._shift,
includes_right_edge=self.includes_right_edge,
adaptive=self._adaptive,
)
@property
def bin_width(self):
return self._bin_width
def _force_new_min_max(self, new_min, new_max):
bin_map = None
add_right = add_left = 0
if new_min < self._times_min:
add_left = self._times_min - new_min
if new_max - self._times_min > self._bin_count:
add_right = new_max - self._times_min - self._bin_count
if add_left or add_right:
bin_map = ((i, i + add_left) for i in range(self._bin_count))
self._set_min_and_count(
self._times_min - add_left, self._bin_count + add_left + add_right
)
return bin_map
def _set_min_and_count(self, times_min, bin_count):
self._bin_count = bin_count
self._times_min = times_min
self._bins = None
self._numpy_bins = None
def _adapt(self, other: BinningBase):
"""
Returns
-------
bin_map1: Iterable[tuple] or None
bin_map2: Iterable[tuple] or None
"""
other = other.as_fixed_width()
if self.bin_width != other.bin_width:
raise ValueError(
"Cannot adapt fixed-width histograms with different widths"
)
if self._shift != other._shift:
raise ValueError(
f"Cannot adapt shifted fixed-width histograms: {self._shift} vs {other._shift}"
)
# Following operations modify schemas
other = cast(FixedWidthBinning, other.copy())
if other.bin_count == 0:
return None, ()
if self.bin_count == 0:
self._set_min_and_count(other._times_min, other.bin_count)
return (), None
new_min = min(self._times_min, other._times_min)
new_max = max(
self._times_min + self._bin_count, other._times_min + other._bin_count
)
bin_map1 = self._force_new_min_max(new_min, new_max)
bin_map2 = other._force_new_min_max(new_min, new_max)
return bin_map1, bin_map2
def as_fixed_width(self, copy: bool = True) -> "FixedWidthBinning":
if copy:
return self.copy()
return self
def _update_dict(self, a_dict: Dict[str, Any]) -> None:
# TODO: Fix to be instantiable from JSON
a_dict["bin_count"] = self.bin_count
a_dict["bin_width"] = self.bin_width
a_dict["bin_shift"] = self._shift
a_dict["bin_times_min"] = self._times_min
class ExponentialBinning(BinningBase):
"""Binning schema with exponentially distributed bins."""
adaptive_allowed = False
# TODO: Implement adaptivity
def __init__(
self,
log_min: float,
log_width: float,
bin_count: int,
includes_right_edge: bool = True,
adaptive: bool = False,
**kwargs,
):
super(ExponentialBinning, self).__init__(
includes_right_edge=includes_right_edge, adaptive=adaptive
)
self._log_min = log_min
self._log_width = log_width
self._bin_count = bin_count
def is_regular(self, **kwargs) -> bool:
return False
@property
def numpy_bins(self):
if self._bin_count == 0:
return np.ndarray((0,), dtype=float)
if self._numpy_bins is None:
log_bins = self._log_min + np.arange(self._bin_count + 1) * self._log_width
self._numpy_bins = 10.0**log_bins
return self._numpy_bins
def copy(self) -> "ExponentialBinning":
return ExponentialBinning(
self._log_min, self._log_width, self._bin_count, self.includes_right_edge
)
def _update_dict(self, a_dict):
a_dict["log_min"] = self._log_min
a_dict["log_width"] = self._log_width
a_dict["bin_count"] = self._bin_count
@register_binning()
def numpy_binning(
data: Optional[np.ndarray] = None,
bin_count: int = 10,
range: Optional[RangeTuple] = None,
**kwargs,
) -> NumpyBinning:
"""Construct binning schema compatible with numpy.histogram together with int argument
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bin_count: int
range: Optional[tuple]
(min, max)
includes_right_edge: Optional[bool]
default: True
See Also
--------
numpy.histogram
static_binning
"""
if not isinstance(bin_count, int):
raise TypeError("bin_count must be a number.")
if range:
bins = np.linspace(range[0], range[1], bin_count + 1)
else:
if data is None:
raise ValueError("Either `range` or `data` must be set.")
if data.size < 2:
raise ValueError(
f"At least 2 values required to infer bins, {data.size} given."
)
start = data.min()
stop = data.max()
if start == stop:
raise ValueError(
f"At least 2 different values required to infer bins, all are equal to {start}."
)
if not np.isfinite(stop - start):
raise ValueError(f"Range too large to find bins: {start} to {stop}.")
bins = np.linspace(start, stop, bin_count + 1)
if (np.diff(bins) == 0).any():
raise ValueError(
f"Range too narrow to split into {bin_count} bins: {start} to {stop}."
)
return NumpyBinning(bins)
@register_binning()
def human_binning(
data: Optional[np.ndarray],
bin_count: Optional[int] = None,
*,
kind: Optional[Literal["time"]] = None,
range: Optional[RangeTuple] = None,
min_bin_width: Optional[float] = None,
max_bin_width: Optional[float] = None,
**kwargs,
) -> FixedWidthBinning:
"""Construct fixed-width ninning schema with bins automatically optimized to human-friendly widths.
Typical widths are: 1.0, 25,0, 0.02, 500, 2.5e-7, ...
Parameters
----------
bin_count: Starting number of bins (the result will be close)
kind: Optional value "time" works in h,m,s scale instead of seconds
range: Tuple of (min, max)
min_bin_width: If present, the bin cannot be narrower than this.
max_bin_width: If present, the bin cannot be wider than this.
"""
# TODO: remove colliding kwargs
if range is None:
if data is None:
raise ValueError("Cannot guess optimum bin width without data.")
min_ = data.min().item()
max_ = data.max().item()
else:
min_, max_ = range
if bin_count is None:
if data is None:
raise ValueError("Cannot guess optimum bin count without data.")
bin_count = ideal_bin_count(data)
raw_width = (max_ - min_) / bin_count
bin_width = find_human_width(raw_width, kind=kind)
if min_bin_width:
bin_width = max(bin_width, min_bin_width)
if max_bin_width:
bin_width = min(bin_width, max_bin_width)
return fixed_width_binning(bin_width=bin_width, data=data, range=range, **kwargs)
@register_binning()
def quantile_binning(
data: Optional[np.ndarray],
*,
bin_count: Optional[int] = None,
q: Optional[Sequence[float]] = None,
qrange: Optional[RangeTuple] = None,
**kwargs,
) -> StaticBinning:
"""Binning schema based on quantile ranges.
This binning finds equally spaced quantiles. This should lead to
all bins having roughly the same frequencies.
Note: weights are not (yet) take into account for calculating
quantiles.
Parameters
----------
bin_count: Number of bins
q: Sequence of quantiles to be used as edges (a la numpy)
qrange: Two floats as minimum and maximum quantile (default: 0.0, 1.0)
Returns
-------
StaticBinning
"""
if data is None:
raise ValueError("Cannot construct quantile binning without data.")
if (bin_count is not None and q is not None) or (bin_count is None and q is None):
raise ValueError("Exactly one of `bin_count` and `q` must be set.")
if bin_count:
if qrange is None:
qrange = (0.0, 1.0)
percentiles = np.linspace(qrange[0] * 100, qrange[1] * 100, bin_count + 1)
elif qrange is not None:
raise ValueError("Cannot set both `q` and `qrange`")
else:
percentiles = np.asarray(q) * 100.0
bins = np.percentile(data, percentiles)
return static_binning(bins=make_bin_array(bins), includes_right_edge=True)
@register_binning()
def static_binning(
data: Optional[np.ndarray] = None, *, bins: ArrayLike, **kwargs
) -> StaticBinning:
"""Construct static binning with whatever bins."""
# TODO: Fail with no bins!
return StaticBinning(bins=make_bin_array(bins), **kwargs)
@register_binning()
def integer_binning(data: Optional[np.ndarray] = None, **kwargs) -> FixedWidthBinning:
"""Construct fixed-width binning schema with bins centered around integers.
Parameters
----------
range: Optional[Tuple[int]]
min (included) and max integer (excluded) bin
bin_width: Optional[int]
group "bin_width" integers into one bin (not recommended)
"""
if "range" in kwargs:
kwargs["range"] = tuple(r - 0.5 for r in kwargs["range"])
return fixed_width_binning(
data=data,
bin_width=kwargs.pop("bin_width", 1),
align=True,
bin_shift=0.5,
**kwargs,
)
@register_binning()
def fixed_width_binning(
data: Optional[np.ndarray] = None,
bin_width: Union[float, int] = 1,
*,
range: Optional[RangeTuple] = None,
includes_right_edge: bool = False,
**kwargs,
) -> FixedWidthBinning:
"""Construct fixed-width binning schema.
Parameters
----------
bin_width: float
range: Optional[tuple]
(min, max)
align: Optional[float]
Must be multiple of bin_width
"""
result = FixedWidthBinning(
bin_width=bin_width, includes_right_edge=includes_right_edge, **kwargs
)
if range:
result._force_bin_existence(range[0])
result._force_bin_existence(range[1], includes_right_edge=True)
if not kwargs.get("adaptive"):
return result # Otherwise we want to adapt to data
if data is not None and data.shape[0]:
# print("Jo, tady")
result._force_bin_existence(
[np.min(data), np.max(data)], includes_right_edge=includes_right_edge
)
return result
@register_binning()
def exponential_binning(
data: Optional[np.ndarray] = None,
bin_count: Optional[int] = None,
*,
range: Optional[RangeTuple] = None,
**kwargs,
) -> ExponentialBinning:
"""Construct exponential binning schema.
Parameters
----------
bin_count: Number of bins
range: (min, max)
See also
--------
numpy.logspace - note that our range semantics is different
"""
if bin_count is None:
if data is None:
raise ValueError("Cannot find optimum bin count without data.")
bin_count = ideal_bin_count(data)
if range:
range = (np.log10(range[0]), np.log10(range[1]))
else:
if data is None:
raise ValueError("Cannot guess the range without data.")
range = (np.log10(data.min()), np.log10(data.max()))
log_width = (range[1] - range[0]) / bin_count
return ExponentialBinning(
log_min=range[0], log_width=log_width, bin_count=bin_count, **kwargs
)
with suppress(ImportError):
# If possible, import astropy's binning methods
# See: http://docs.astropy.org/en/stable/visualization/histogram.html
from astropy.stats.histogram import histogram as _astropy_histogram # noqa: F401
warnings.filterwarnings("ignore", module="astropy\\..*")
@register_binning(name="blocks")
def bayesian_blocks_binning(data, range=None, **kwargs) -> StaticBinning:
"""Binning schema based on Bayesian blocks (from astropy).
Computationally expensive for large data sets.
Parameters
----------
range: Optional[tuple]
See also
--------
astropy.stats.histogram.bayesian_blocks
astropy.stats.histogram.histogram
"""
from astropy.stats.histogram import bayesian_blocks
if range is not None:
data = data[(data >= range[0]) & (data <= range[1])]
edges = bayesian_blocks(data)
return StaticBinning(edges, **kwargs)
@register_binning()
def knuth_binning(data, range=None, **kwargs) -> StaticBinning:
"""Binning schema based on Knuth's rule (from astropy).
Computationally expensive for large data sets.
Parameters
----------
data: arraylike
range: Optional[tuple]
See also
--------
astropy.stats.histogram.knuth_bin_width
astropy.stats.histogram.histogram
"""
# TODO: Could we possibly use it with FixedWidthBinning?
from astropy.stats.histogram import knuth_bin_width
if range is not None:
data = data[(data >= range[0]) & (data <= range[1])]
_, edges = knuth_bin_width(data, True)
return StaticBinning(edges, **kwargs)