-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathnumerical_column_stats.py
2057 lines (1808 loc) · 77 KB
/
numerical_column_stats.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
#!/usr/bin/env python
"""Build model for dataset by identifying col type along with its respective params."""
from __future__ import annotations
import abc
import copy
import itertools
import warnings
from typing import Any, Callable, TypeVar, cast
import numpy as np
import numpy.typing as npt
import pandas as pd
import scipy.stats
from . import float_column_profile, histogram_utils, profiler_utils
from .base_column_profilers import BaseColumnProfiler
from .profiler_options import NumericalOptions
class abstractstaticmethod(staticmethod):
"""For making function an abstract method."""
__slots__ = ()
def __init__(self, function: Callable) -> None:
"""Initialize abstract static method."""
super().__init__(function)
function.__isabstractmethod__ = True # type: ignore
__isabstractmethod__ = True
NumericStatsMixinT = TypeVar("NumericStatsMixinT", bound="NumericStatsMixin")
class NumericStatsMixin(BaseColumnProfiler[NumericStatsMixinT], metaclass=abc.ABCMeta):
"""
Abstract numerical column profile subclass of BaseColumnProfiler.
Represents column in the dataset which is a text column.
Has Subclasses itself.
"""
type: str | None = None
def __init__(self, options: NumericalOptions = None) -> None:
"""
Initialize column base properties and itself.
:param options: Options for the numerical stats.
:type options: NumericalOptions
"""
if options and not isinstance(options, NumericalOptions):
raise ValueError(
"NumericalStatsMixin parameter 'options' must be "
"of type NumericalOptions."
)
self.min: int | float | np.float64 | np.int64 | None = None
self.max: int | float | np.float64 | np.int64 | None = None
self._top_k_modes: int = 5 # By default, return at max 5 modes
self.sum: int | float | np.float64 | np.int64 = np.float64(0)
self._biased_variance: float | np.float64 = np.nan
self._biased_skewness: float | np.float64 = np.nan
self._biased_kurtosis: float | np.float64 = np.nan
self._median_is_enabled: bool = True
self._median_abs_dev_is_enabled: bool = True
self.max_histogram_bin: int = 100000
self.min_histogram_bin: int = 1000
self.histogram_bin_method_names: list[str] = [
"auto",
"fd",
"doane",
"scott",
"rice",
"sturges",
"sqrt",
]
self.histogram_selection: str | None = None
self.user_set_histogram_bin: int | None = None
self.bias_correction: bool = True # By default, we correct for bias
self._mode_is_enabled: bool = True
self.num_zeros: int | np.int64 = np.int64(0)
self.num_negatives: int | np.int64 = np.int64(0)
self._num_quantiles: int = 1000 # By default, we use 1000 quantiles
if options:
self.bias_correction = options.bias_correction.is_enabled
self._top_k_modes = options.mode.top_k_modes
self._median_is_enabled = options.median.is_enabled
self._median_abs_dev_is_enabled = options.median_abs_deviation.is_enabled
self._mode_is_enabled = options.mode.is_enabled
self._num_quantiles = options.histogram_and_quantiles.num_quantiles
bin_count_or_method = options.histogram_and_quantiles.bin_count_or_method
if isinstance(bin_count_or_method, str):
self.histogram_bin_method_names = [bin_count_or_method]
elif isinstance(bin_count_or_method, list):
self.histogram_bin_method_names = bin_count_or_method
elif isinstance(bin_count_or_method, int):
self.user_set_histogram_bin = bin_count_or_method
self.histogram_bin_method_names = ["custom"]
self.histogram_methods: dict = {}
self._stored_histogram: dict = {
"total_loss": np.float64(0.0),
"current_loss": np.float64(0.0),
"suggested_bin_count": self.min_histogram_bin,
"histogram": {"bin_counts": None, "bin_edges": None},
}
self._batch_history: list = []
for method in self.histogram_bin_method_names:
self.histogram_methods[method] = {
"total_loss": np.float64(0.0),
"current_loss": np.float64(0.0),
"suggested_bin_count": self.min_histogram_bin,
"histogram": {"bin_counts": None, "bin_edges": None},
}
self.quantiles: list[float] | None = None
self.__calculations = {
"min": NumericStatsMixin._get_min,
"max": NumericStatsMixin._get_max,
"sum": NumericStatsMixin._get_sum,
"variance": NumericStatsMixin._get_variance,
"skewness": NumericStatsMixin._get_skewness,
"kurtosis": NumericStatsMixin._get_kurtosis,
"histogram_and_quantiles": NumericStatsMixin._get_histogram_and_quantiles,
"num_zeros": NumericStatsMixin._get_num_zeros,
"num_negatives": NumericStatsMixin._get_num_negatives,
}
self.match_count: int # needed for mypy
self._filter_properties_w_options(self.__calculations, options)
def __getattribute__(self, name: str) -> Any:
"""Return computed attribute value."""
return super().__getattribute__(name)
def __getitem__(self, item: str) -> Any:
"""Return indexed item."""
return super().__getitem__(item) # type: ignore
@property
def _has_histogram(self) -> bool:
return self._stored_histogram["histogram"]["bin_counts"] is not None
@BaseColumnProfiler._timeit(name="histogram_and_quantiles")
def _add_helper_merge_profile_histograms(
self,
other1: NumericStatsMixin,
other2: NumericStatsMixin,
) -> None:
"""
Add histogram of two profiles together.
:param other1: profile1 being added to self
:type other1: NumericStatsMixin
:param other2: profile2 being added to self
:type other2: NumericStatsMixin
:return: None
"""
# get available bin methods and set to current
bin_methods = [
x
for x in other1.histogram_bin_method_names
if x in other2.histogram_bin_method_names
]
if not bin_methods:
raise ValueError(
"Profiles have no overlapping bin methods and "
"therefore cannot be added together."
)
elif other1.user_set_histogram_bin and other2.user_set_histogram_bin:
if other1.user_set_histogram_bin != other2.user_set_histogram_bin:
warnings.warn(
"User set histogram bin counts did not match. "
"Choosing the larger bin count."
)
self.user_set_histogram_bin = max(
other1.user_set_histogram_bin, other2.user_set_histogram_bin
)
# initial creation of the profiler creates all methods, but
# only the methods which intersect should exist.
self.histogram_bin_method_names = bin_methods
self.histogram_methods = dict()
# Set ideal bin count w/ if statement of some sort
ideal_count_of_bins = self.min_histogram_bin
if self.user_set_histogram_bin is not None:
ideal_count_of_bins = self.user_set_histogram_bin
for method in self.histogram_bin_method_names:
self.histogram_methods[method] = {
"total_loss": np.float64(0.0),
"current_loss": np.float64(0.0),
"histogram": {"bin_counts": None, "bin_edges": None},
}
# calculate the min of the first edge and the max of the last edge
# between two arrays
global_min_of_histogram_edges = (
float(self.min)
if self.min is not None
else min(
other1._stored_histogram["histogram"]["bin_edges"][0],
other2._stored_histogram["histogram"]["bin_edges"][0],
)
)
global_max_of_histogram_edges = (
float(self.max)
if self.max is not None
else max(
other1._stored_histogram["histogram"]["bin_edges"][-1],
other2._stored_histogram["histogram"]["bin_edges"][-1],
)
)
# Generate new bin edges
ideal_bin_edges = np.linspace(
global_min_of_histogram_edges,
global_max_of_histogram_edges,
ideal_count_of_bins + 1,
)
# Initialize new count by bin object for population
new_entity_count_by_bin = np.zeros((ideal_count_of_bins,))
# Generate new histograms
_, hist_loss1 = self._assimilate_histogram(
from_hist_entity_count_per_bin=other1._stored_histogram["histogram"][
"bin_counts"
],
from_hist_bin_edges=other1._stored_histogram["histogram"]["bin_edges"],
dest_hist_entity_count_per_bin=new_entity_count_by_bin,
dest_hist_bin_edges=ideal_bin_edges,
dest_hist_num_bin=ideal_count_of_bins,
)
# Ensure loss is calculated on second run of regenerate
_, hist_loss2 = self._assimilate_histogram(
from_hist_entity_count_per_bin=other2._stored_histogram["histogram"][
"bin_counts"
],
from_hist_bin_edges=other2._stored_histogram["histogram"]["bin_edges"],
dest_hist_entity_count_per_bin=new_entity_count_by_bin,
dest_hist_bin_edges=ideal_bin_edges,
dest_hist_num_bin=ideal_count_of_bins,
)
aggregate_histogram_loss = hist_loss1 + hist_loss2
self._stored_histogram["histogram"]["bin_counts"] = new_entity_count_by_bin
self._stored_histogram["histogram"]["bin_edges"] = ideal_bin_edges
self._stored_histogram["histogram"]["current_loss"] = aggregate_histogram_loss
self._stored_histogram["histogram"]["total_loss"] = aggregate_histogram_loss
if self.user_set_histogram_bin is None:
for method in self.histogram_bin_method_names:
self.histogram_methods[method]["suggested_bin_count"] = (
histogram_utils._calculate_bins_from_profile(self, method)
)
self._get_quantiles()
def _add_helper(
self,
other1: NumericStatsMixinT,
other2: NumericStatsMixinT,
) -> None:
"""
Help merge profiles.
:param other1: profile1 being added to self
:param other2: profile2 being added to self
:return: None
"""
BaseColumnProfiler._merge_calculations(
self._NumericStatsMixin__calculations,
other1._NumericStatsMixin__calculations,
other2._NumericStatsMixin__calculations,
)
# Check and potentially override bias correction computation
self.bias_correction = True
if not other1.bias_correction or not other2.bias_correction:
self.bias_correction = False
# Merge variance, histogram, min, max, and sum
if "variance" in self.__calculations.keys():
self._biased_variance = self._merge_biased_variance(
other1.match_count,
other1._biased_variance,
other1.mean,
other2.match_count,
other2._biased_variance,
other2.mean,
)
if "min" in self.__calculations.keys():
if other1.min is not None and other2.min is not None:
self.min = min(other1.min, other2.min)
elif other2.min is None:
self.min = other1.min
else:
self.min = other2.min
if "max" in self.__calculations.keys():
if other1.max is not None and other2.max is not None:
self.max = max(other1.max, other2.max)
elif other2.max is None:
self.max = other1.max
else:
self.max = other2.max
if "sum" in self.__calculations.keys():
self.sum = other1.sum + other2.sum
if "skewness" in self.__calculations.keys():
self._biased_skewness = self._merge_biased_skewness(
other1.match_count,
other1._biased_skewness,
other1._biased_variance,
other1.mean,
other2.match_count,
other2._biased_skewness,
other2._biased_variance,
other2.mean,
)
if "kurtosis" in self.__calculations.keys():
self._biased_kurtosis = self._merge_biased_kurtosis(
other1.match_count,
other1._biased_kurtosis,
other1._biased_skewness,
other1._biased_variance,
other1.mean,
other2.match_count,
other2._biased_kurtosis,
other2._biased_skewness,
other2._biased_variance,
other2.mean,
)
if "num_zeros" in self.__calculations.keys():
self.num_zeros = other1.num_zeros + other2.num_zeros
if "num_negatives" in self.__calculations.keys():
self.num_negatives = other1.num_negatives + other2.num_negatives
if "histogram_and_quantiles" in self.__calculations.keys():
if other1._has_histogram and other2._has_histogram:
self._add_helper_merge_profile_histograms(other1, other2)
elif not other2._has_histogram:
self.histogram_methods = other1.histogram_methods
self.quantiles = other1.quantiles
else:
self.histogram_methods = other2.histogram_methods
self.quantiles = other2.quantiles
# Merge max k mode count
self._top_k_modes = max(other1._top_k_modes, other2._top_k_modes)
# Merge median enable/disable option
self._median_is_enabled = (
other1._median_is_enabled and other2._median_is_enabled
)
# Merge mode enable/disable option
self._mode_is_enabled = other1._mode_is_enabled and other2._mode_is_enabled
# Merge median absolute deviation enable/disable option
self._median_abs_dev_is_enabled = (
other1._median_abs_dev_is_enabled and other2._median_abs_dev_is_enabled
)
def profile(self) -> dict:
"""
Return profile of the column.
:return:
"""
profile = dict(
min=self.np_type_to_type(self.min),
max=self.np_type_to_type(self.max),
mode=self.np_type_to_type(self.mode),
median=self.np_type_to_type(self.median),
sum=self.np_type_to_type(self.sum),
mean=self.np_type_to_type(self.mean),
variance=self.np_type_to_type(self.variance),
stddev=self.np_type_to_type(self.stddev),
skewness=self.np_type_to_type(self.skewness),
kurtosis=self.np_type_to_type(self.kurtosis),
histogram=self._get_best_histogram_for_profile(),
quantiles=self.quantiles,
median_abs_deviation=self.np_type_to_type(self.median_abs_deviation),
num_zeros=self.np_type_to_type(self.num_zeros),
num_negatives=self.np_type_to_type(self.num_negatives),
times=self.times,
)
return profile
def report(self, remove_disabled_flag: bool = False) -> dict:
"""
Call the profile and remove the disabled columns from profile's report.
"Disabled column" is defined as a column
that is not present in `self.__calculations` but is present
in the `self.profile`.
:var remove_disabled_flag: true/false value to tell the code to remove
values missing in __calculations
:type remove_disabled_flag: boolean
:return: Profile object pop'd based on values missing from __calculations
:rtype: Profile
"""
calcs_dict_keys = self._NumericStatsMixin__calculations.keys()
profile = self.profile()
if remove_disabled_flag:
profile_keys = list(profile.keys())
for profile_key in profile_keys:
if profile_key in ["mode", "quantiles", "histogram"]:
if "histogram_and_quantiles" in calcs_dict_keys:
continue
elif profile_key == "stddev" and "variance" in calcs_dict_keys:
continue
elif profile_key in calcs_dict_keys:
continue
elif profile_key == "times":
continue
profile.pop(profile_key)
return profile
def _reformat_numeric_stats_types_on_serialized_profiles(self):
"""Assistance function in the deserialization of profiler objects.
This function is to be used to enforce correct typing for attributes
associated with the NumericStatsMixin conversions when loading profiler
objects in from their serialized saved format
"""
def convert_histogram_key_types_to_np(histogram_info: dict):
if histogram_info["total_loss"] is not None:
histogram_info["total_loss"] = np.float64(histogram_info["total_loss"])
if histogram_info["current_loss"] is not None:
histogram_info["current_loss"] = np.float64(
histogram_info["current_loss"]
)
# Convert hist lists to numpy arrays
for key in histogram_info["histogram"].keys():
if histogram_info["histogram"][key] is not None:
histogram_info["histogram"][key] = np.array(
histogram_info["histogram"][key]
)
return histogram_info
self._stored_histogram = convert_histogram_key_types_to_np(
self._stored_histogram
)
# Convert hist method attributes to correct types
for key in self.histogram_methods.keys():
self.histogram_methods[key] = convert_histogram_key_types_to_np(
self.histogram_methods[key]
)
if self.min is not None:
self.min = np.float64(self.min)
if self.max is not None:
self.max = np.float64(self.max)
if self.sum is not None:
self.sum = np.float64(self.sum)
if self.num_zeros is not None:
self.num_zeros = np.int64(self.num_zeros)
if self.num_negatives is not None:
self.num_negatives = np.int64(self.num_negatives)
if not np.isnan(self._biased_variance):
self._biased_variance = np.float64(self._biased_variance)
if not np.isnan(self._biased_skewness):
self._biased_skewness = np.float64(self._biased_skewness)
if not np.isnan(self._biased_kurtosis):
self._biased_kurtosis = np.float64(self._biased_kurtosis)
def diff(
self,
other_profile: NumericStatsMixinT,
options: dict = None,
) -> dict:
"""
Find the differences for several numerical stats.
:param other_profile: profile to find the difference with
:type other_profile: NumericStatsMixin Profile
:return: the numerical stats differences
:rtype: dict
"""
cls = self.__class__
if not isinstance(other_profile, cls):
raise TypeError(
"Unsupported operand type(s) for diff: '{}' "
"and '{}'".format(cls.__name__, other_profile.__class__.__name__)
)
differences = {
"min": profiler_utils.find_diff_of_numbers(self.min, other_profile.min),
"max": profiler_utils.find_diff_of_numbers(self.max, other_profile.max),
"sum": profiler_utils.find_diff_of_numbers(self.sum, other_profile.sum),
"mean": profiler_utils.find_diff_of_numbers(self.mean, other_profile.mean),
"median": profiler_utils.find_diff_of_numbers(
self.median, other_profile.median
),
"mode": profiler_utils.find_diff_of_lists_and_sets(
self.mode, other_profile.mode
),
"median_absolute_deviation": profiler_utils.find_diff_of_numbers(
self.median_abs_deviation,
other_profile.median_abs_deviation,
),
"variance": profiler_utils.find_diff_of_numbers(
self.variance, other_profile.variance
),
"stddev": profiler_utils.find_diff_of_numbers(
self.stddev, other_profile.stddev
),
"t-test": self._perform_t_test(
self.mean,
self.variance,
self.match_count,
other_profile.mean,
other_profile.variance,
other_profile.match_count,
),
"psi": self._calculate_psi(
self.match_count,
self._stored_histogram["histogram"],
other_profile.match_count,
other_profile._stored_histogram["histogram"],
),
}
return differences
@property
def mean(self) -> float | np.float64:
"""Return mean value."""
if self.match_count == 0:
return 0.0
return self.sum / self.match_count
@property
def mode(self) -> list[float]:
"""
Find an estimate for the mode[s] of the data.
:return: the mode(s) of the data
:rtype: list(float)
"""
if not self._has_histogram or not self._mode_is_enabled:
return [np.nan]
return self._estimate_mode_from_histogram()
@property
def median(self) -> float:
"""
Estimate the median of the data.
:return: the median
:rtype: float
"""
if not self._has_histogram or not self._median_is_enabled:
return np.nan
return self._get_percentile([50])[0]
@property
def variance(self) -> float | np.float64:
"""Return variance."""
return (
self._biased_variance
if not self.bias_correction
else self._correct_bias_variance(self.match_count, self._biased_variance)
)
@property
def stddev(self) -> float | np.float64:
"""Return stddev value."""
if self.match_count == 0:
return np.nan
return cast(np.float64, np.sqrt(self.variance))
@property
def skewness(self) -> float | np.float64:
"""Return skewness value."""
return (
self._biased_skewness
if not self.bias_correction
else self._correct_bias_skewness(self.match_count, self._biased_skewness)
)
@property
def kurtosis(self) -> float | np.float64:
"""Return kurtosis value."""
return (
self._biased_kurtosis
if not self.bias_correction
else self._correct_bias_kurtosis(self.match_count, self._biased_kurtosis)
)
@staticmethod
def _perform_t_test(
mean1: float | np.float64,
var1: float | np.float64,
n1: int,
mean2: float | np.float64,
var2: float | np.float64,
n2: int,
) -> dict:
results: dict = {
"t-statistic": None,
"conservative": {"deg_of_free": None, "p-value": None},
"welch": {"deg_of_free": None, "p-value": None},
}
invalid_stats = False
if n1 <= 1 or n2 <= 1:
warnings.warn(
"Insufficient sample size. " "T-test cannot be performed.",
RuntimeWarning,
)
invalid_stats = True
if np.isnan(
[float(mean1), float(mean2), float(var1), float(var2)]
).any() or None in [
mean1,
mean2,
var1,
var2,
]:
warnings.warn(
"Null value(s) found in mean and/or variance values. "
"T-test cannot be performed.",
RuntimeWarning,
)
invalid_stats = True
if not var1 and not var2:
warnings.warn(
"Data were essentially constant. T-test cannot be performed.",
RuntimeWarning,
)
invalid_stats = True
if invalid_stats:
return results
s_delta = var1 / n1 + var2 / n2
t = (mean1 - mean2) / np.sqrt(s_delta)
conservative_deg_of_free = min(n1, n2) - 1
welch_deg_of_free = s_delta**2 / (
(var1 / n1) ** 2 / (n1 - 1) + (var2 / n2) ** 2 / (n2 - 1)
)
results["t-statistic"] = t
results["conservative"]["deg_of_free"] = float(conservative_deg_of_free)
results["welch"]["deg_of_free"] = float(welch_deg_of_free)
conservative_t = scipy.stats.t(conservative_deg_of_free)
conservative_p_val = (1 - conservative_t.cdf(abs(t))) * 2
welch_t = scipy.stats.t(welch_deg_of_free)
welch_p_val = (1 - welch_t.cdf(abs(t))) * 2
results["conservative"]["p-value"] = float(conservative_p_val)
results["welch"]["p-value"] = float(welch_p_val)
return results
def _preprocess_for_calculate_psi(
self,
self_histogram,
other_histogram,
):
new_self_histogram = {"bin_counts": None, "bin_edges": None}
new_other_histogram = {"bin_counts": None, "bin_edges": None}
regenerate_histogram = False
num_psi_bins = 10
if (
isinstance(self_histogram["bin_counts"], np.ndarray)
and isinstance(self_histogram["bin_edges"], np.ndarray)
and isinstance(other_histogram["bin_counts"], np.ndarray)
and isinstance(other_histogram["bin_edges"], np.ndarray)
):
regenerate_histogram = True
# calculate the min of the first edge and
# the max of the last edge between two arrays
min_min_edge = min(
self_histogram["bin_edges"][0],
other_histogram["bin_edges"][0],
)
max_max_edge = max(
self_histogram["bin_edges"][-1],
other_histogram["bin_edges"][-1],
)
if min_min_edge == max_max_edge:
return 0, 0
if regenerate_histogram:
new_self_histogram["bin_counts"] = self_histogram["bin_counts"]
new_self_histogram["bin_edges"] = self_histogram["bin_edges"]
new_other_histogram["bin_edges"] = other_histogram["bin_edges"]
new_other_histogram["bin_counts"] = other_histogram["bin_counts"]
len_self_bin_counts = len(self_histogram["bin_counts"])
# re-calculate `self` histogram
if len_self_bin_counts != num_psi_bins:
histogram, hist_loss = self._regenerate_histogram(
entity_count_per_bin=self_histogram["bin_counts"],
bin_edges=self_histogram["bin_edges"],
suggested_bin_count=num_psi_bins,
is_float_histogram=isinstance(
self, float_column_profile.FloatColumn
),
options={
"min_edge": min_min_edge,
"max_edge": max_max_edge,
},
)
new_self_histogram["bin_counts"] = histogram["bin_counts"]
new_self_histogram["bin_edges"] = histogram["bin_edges"]
# re-calculate `other_profile` histogram
histogram_edges_not_equal = False
all_array_values_equal = np.array_equal(
other_histogram["bin_edges"], self_histogram["bin_edges"]
)
if not all_array_values_equal:
histogram_edges_not_equal = True
if histogram_edges_not_equal:
histogram, hist_loss = self._regenerate_histogram(
entity_count_per_bin=other_histogram["bin_counts"],
bin_edges=other_histogram["bin_edges"],
suggested_bin_count=num_psi_bins,
is_float_histogram=isinstance(
self, float_column_profile.FloatColumn
),
options={
"min_edge": min_min_edge,
"max_edge": max_max_edge,
},
)
new_other_histogram["bin_edges"] = histogram["bin_edges"]
new_other_histogram["bin_counts"] = histogram["bin_counts"]
return new_self_histogram, new_other_histogram
def _calculate_psi(
self,
self_match_count: int,
self_histogram: np.ndarray,
other_match_count: int,
other_histogram: np.ndarray,
) -> float | None:
"""
Calculate PSI (Population Stability Index).
```
PSI = SUM((other_pcnt - self_pcnt) * ln(other_pcnt / self_pcnt))
```
PSI Breakpoint Thresholds:
- PSI < 0.1: no significant population change
- 0.1 < PSI < 0.2: moderate population change
- PSI >= 0.2: significant population change
:param self_match_count: self.match_count
:type self_match_count: int
:param self_histogram: self._stored_histogram["histogram"]
:type self_histogram: np.ndarray
:param self_match_count: other_profile.match_count
:type self_match_count: int
:param other_histogram: other_profile._stored_histogram["histogram"]
:type other_histogram: np.ndarray
:return: psi_value
:rtype: optional[float]
"""
psi_value = 0
new_self_histogram, new_other_histogram = self._preprocess_for_calculate_psi(
self_histogram=self_histogram,
other_histogram=other_histogram,
)
if new_self_histogram == 0 and new_other_histogram == 0:
return 0.0
if isinstance(new_other_histogram["bin_edges"], type(None)) or isinstance(
new_self_histogram["bin_edges"], type(None)
):
warnings.warn(
"No edges available in at least one histogram for calculating `PSI`",
RuntimeWarning,
)
return None
bin_count: int = 0 # required typing by mypy
for iter_value, bin_count in enumerate(new_self_histogram["bin_counts"]):
self_percent = bin_count / self_match_count
other_percent = (
new_other_histogram["bin_counts"][iter_value] / other_match_count
)
if (self_percent == other_percent) and self_percent == 0:
continue
iter_psi = (other_percent - self_percent) * np.log(
other_percent / self_percent
)
if iter_psi and iter_psi != float("inf"):
psi_value += iter_psi
return psi_value
def _update_variance(
self,
batch_mean: float,
batch_var: float,
batch_count: int,
) -> float | np.float64:
"""
Calculate combined biased variance of the current values and new dataset.
:param batch_mean: mean of new chunk
:param batch_var: biased variance of new chunk
:param batch_count: number of samples in new chunk
:return: combined biased variance
:rtype: float | np.float64
"""
return self._merge_biased_variance(
self.match_count,
self._biased_variance,
self.mean,
batch_count,
batch_var,
batch_mean,
)
@staticmethod
def _merge_biased_variance(
match_count1: int,
biased_variance1: float | np.float64,
mean1: float | np.float64,
match_count2: int,
biased_variance2: float | np.float64,
mean2: float | np.float64,
) -> float | np.float64:
"""
Calculate combined biased variance of the current values and new dataset.
:param match_count1: number of samples in new chunk 1
:param mean1: mean of chunk 1
:param biased_variance1: variance of chunk 1 without bias correction
:param match_count2: number of samples in new chunk 2
:param mean2: mean of chunk 2
:param biased_variance2: variance of chunk 2 without bias correction
:return: combined variance
:rtype: float | np.float64
"""
if match_count1 < 1:
return biased_variance2
elif match_count2 < 1:
return biased_variance1
elif np.isnan(biased_variance1) or np.isnan(biased_variance2):
return np.nan
curr_count = match_count1
delta = mean2 - mean1
m_curr = biased_variance1 * curr_count
m_batch = biased_variance2 * match_count2
M2 = (
m_curr
+ m_batch
+ delta**2 * curr_count * match_count2 / (curr_count + match_count2)
)
new_variance = M2 / (curr_count + match_count2)
return new_variance
@staticmethod
def _correct_bias_variance(
match_count: int, biased_variance: float | np.float64
) -> float | np.float64:
if match_count is None or biased_variance is None or match_count < 2:
warnings.warn(
"Insufficient match count to correct bias in variance. Bias correction "
"can be manually disabled by setting bias_correction.is_enabled to "
"False in ProfilerOptions.",
RuntimeWarning,
)
return np.nan
variance = match_count / (match_count - 1) * biased_variance
return variance
@staticmethod
def _merge_biased_skewness(
match_count1: int,
biased_skewness1: float | np.float64,
biased_variance1: float | np.float64,
mean1: float | np.float64,
match_count2: int,
biased_skewness2: float | np.float64,
biased_variance2: float | np.float64,
mean2: float | np.float64,
) -> float | np.float64:
"""
Calculate the combined skewness of two data chunks.
:param match_count1: # of samples in 1st chunk
:param biased_skewness1: skewness of 1st chunk without bias correction
:param biased_variance1: variance of 1st chunk without bias correction
:param mean1: mean of 1st chunk
:param match_count2: # of samples in 2nd chunk
:param biased_skewness2: skewness of 2nd chunk without bias correction
:param biased_variance2: variance of 2nd chunk without bias correction
:param mean2: mean of 2nd chunk
:return: combined skewness
:rtype: float
"""
if match_count1 < 1:
return biased_skewness2
elif match_count2 < 1:
return biased_skewness1
elif np.isnan(biased_skewness1) or np.isnan(biased_skewness2):
return np.nan
delta = mean2 - mean1
N = match_count1 + match_count2
M2_1 = match_count1 * biased_variance1
M2_2 = match_count2 * biased_variance2
M2 = M2_1 + M2_2 + delta**2 * match_count1 * match_count2 / N
if not M2:
return 0.0
M3_1 = biased_skewness1 * np.sqrt(M2_1**3) / np.sqrt(match_count1)
M3_2 = biased_skewness2 * np.sqrt(M2_2**3) / np.sqrt(match_count2)
first_term = M3_1 + M3_2
second_term = (
delta**3
* match_count1
* match_count2
* (match_count1 - match_count2)
/ N**2
)
third_term = 3 * delta * (match_count1 * M2_2 - match_count2 * M2_1) / N
M3 = first_term + second_term + third_term
biased_skewness: np.float64 = np.sqrt(N) * M3 / np.sqrt(M2**3)
return biased_skewness
@staticmethod
def _correct_bias_skewness(
match_count: int, biased_skewness: float | np.float64
) -> float | np.float64:
"""
Apply bias correction to skewness.
:param match_count: number of samples
:param biased_skewness: skewness without bias correction
:return: unbiased estimator of skewness
:rtype: NaN if sample size is too small, float otherwise
"""
if np.isnan(biased_skewness) or match_count < 3:
warnings.warn(
"Insufficient match count to correct bias in skewness. Bias correction "
"can be manually disabled by setting bias_correction.is_enabled to "
"False in ProfilerOptions.",
RuntimeWarning,
)
return np.nan
skewness: np.float64 = (
np.sqrt(match_count * (match_count - 1))
* biased_skewness
/ (match_count - 2)
)
return skewness
@staticmethod
def _merge_biased_kurtosis(
match_count1: int,
biased_kurtosis1: float | np.float64,
biased_skewness1: float | np.float64,
biased_variance1: float | np.float64,
mean1: float | np.float64,
match_count2: int,
biased_kurtosis2: float | np.float64,
biased_skewness2: float | np.float64,
biased_variance2: float | np.float64,
mean2: float | np.float64,
) -> float | np.float64:
"""
Calculate the combined kurtosis of two sets of data.
:param match_count1: # of samples in 1st chunk
:param biased_kurtosis1: kurtosis of 1st chunk without bias correction