-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathprofiler_options.py
1829 lines (1577 loc) · 69.6 KB
/
profiler_options.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
"""Specify the options when running the data profiler."""
from __future__ import annotations
import abc
import copy
import re
import warnings
from typing import Any, Generic, TypeVar, cast
from ..labelers.base_data_labeler import BaseDataLabeler
from ..plugins.__init__ import get_plugins
from . import profiler_utils
from .json_decoder import load_option
BaseOptionT = TypeVar("BaseOptionT", bound="BaseOption")
BooleanOptionT = TypeVar("BooleanOptionT", bound="BooleanOption")
NumericalOptionsT = TypeVar("NumericalOptionsT", bound="NumericalOptions")
BaseInspectorOptionsT = TypeVar("BaseInspectorOptionsT", bound="BaseInspectorOptions")
class BaseOption(Generic[BaseOptionT]):
"""For configuring options."""
@property
def properties(self) -> dict[str, BooleanOption]:
"""
Return a copy of the option properties.
:return: dictionary of the option's properties attr: value
:rtype: dict
"""
return copy.deepcopy(self.__dict__)
def _set_helper(self, options: dict[str, bool], variable_path: str) -> None:
"""
Set all the options.
Send in a dict that contains all of or a subset of
the appropriate options. Set the values of the options. Will raise error
if the formatting is improper.
:param options: dict containing the options you want to set.
:type options: dict
:param variable_path: current path to variable set.
:type variable_path: str
:return: None
"""
if not isinstance(options, dict):
raise ValueError("The options must be a dictionary.")
if not isinstance(variable_path, str):
raise ValueError("The variable path must be a string.")
for option in options:
option_list = option.split(".", 1)
option_name = option_list[0]
is_check_all = False
if option_name == "*":
option_list = option_list[1].split(".", 1)
option_name = option_list[0]
is_check_all = True
option_variable_path = (
variable_path + "." + option_name if variable_path else option_name
)
if option_name in self.properties:
option_prop = getattr(self, option_name)
if isinstance(option_prop, BaseOption):
option_key = option_list[1]
option_prop._set_helper(
{option_key: options[option]},
variable_path=option_variable_path,
)
elif len(option_list) > 1:
raise AttributeError(
"type object '{}' has no attribute '{}'".format(
option_variable_path, option_list[1]
)
)
else:
setattr(self, option_name, options[option])
elif len(option_list) > 1 or is_check_all:
for class_option_name in self.properties:
class_option = getattr(self, class_option_name)
if isinstance(class_option, BaseOption):
option_variable_path = (
variable_path + "." + class_option_name
if variable_path
else class_option_name
)
class_option._set_helper(
{option: options[option]},
variable_path=option_variable_path,
)
else:
error_path = variable_path if variable_path else self.__class__.__name__
raise AttributeError(
f"type object '{error_path}' has no attribute '{option}'"
)
def set(self, options: dict[str, bool]) -> None:
"""
Set all the options.
Send in a dict that contains all of or a subset of
the appropriate options. Set the values of the options. Will raise error
if the formatting is improper.
:param options: dict containing the options you want to set.
:type options: dict
:return: None
"""
if not isinstance(options, dict):
raise ValueError("The options must be a dictionary.")
self._set_helper(options, variable_path="")
@abc.abstractmethod
def _validate_helper(self, variable_path: str = "") -> list[str]:
"""
Validate the options don't cause errors and return possible errors.
:param variable_path: Current path to variable set.
:type variable_path: str
:return: List of errors (if raise_error is false)
:rtype: list(str)
"""
raise NotImplementedError()
def validate(self, raise_error: bool = True) -> list[str] | None:
"""
Validate the options do not conflict and cause errors.
Raises error/warning if so.
:param raise_error: Flag that raises errors if true. Returns errors if
false.
:type raise_error: bool
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
errors = self._validate_helper()
if raise_error and errors:
raise ValueError("\n".join(errors))
elif errors:
return errors
return None
@classmethod
def load_from_dict(cls, data, config: dict | None = None) -> BaseOption:
"""
Parse attribute from json dictionary into self.
:param data: dictionary with attributes and values.
:type data: dict[string, Any]
:param config: config to override loading options params from dictionary
:type config: Dict | None
:return: Options with attributes populated.
:rtype: BaseOption
"""
option = cls()
for attr, value in data.items():
if isinstance(value, dict) and "class" in value:
value = load_option(value, config)
setattr(option, attr, value)
return option
def __eq__(self, other: object) -> bool:
"""
Determine equality by ensuring equality of all attributes.
Some of the attributes may be Options objects themselves.
"""
if not isinstance(other, self.__class__):
return False
return self.__dict__ == other.__dict__
class BooleanOption(BaseOption[BooleanOptionT]):
"""For setting Boolean options."""
def __init__(self, is_enabled: bool = True) -> None:
"""
Initialize Boolean option.
:ivar is_enabled: boolean option to enable/disable the option.
:vartype is_enabled: bool
"""
self.is_enabled = is_enabled
def _validate_helper(self, variable_path: str = "BooleanOption") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
if not isinstance(variable_path, str):
raise ValueError("The variable path must be a string.")
errors: list[str] = []
if not isinstance(self.is_enabled, bool):
errors = [f"{variable_path}.is_enabled must be a Boolean."]
return errors
class HistogramAndQuantilesOption(BooleanOption["HistogramAndQuantilesOption"]):
"""For setting histogram options."""
def __init__(
self,
is_enabled: bool = True,
bin_count_or_method: str | int | list[str] = "auto",
num_quantiles: int = 1000,
) -> None:
"""
Initialize Options for histograms.
:ivar is_enabled: boolean option to enable/disable the option.
:vartype is_enabled: bool
:ivar bin_count_or_method: bin count or the method with which to
calculate histograms
:vartype bin_count_or_method: Union[str, int, list(str)]
:ivar num_quantiles: number of quantiles
:vartype num_quantiles: int
"""
self.bin_count_or_method = bin_count_or_method
self.num_quantiles = num_quantiles
super().__init__(is_enabled=is_enabled)
def _validate_helper(
self, variable_path: str = "HistogramAndQuantilesOption"
) -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
errors = super()._validate_helper(variable_path=variable_path)
if self.bin_count_or_method is not None:
valid_methods = ["auto", "fd", "doane", "scott", "rice", "sturges", "sqrt"]
value = self.bin_count_or_method
if isinstance(value, str):
value = [value]
if isinstance(value, int) and value >= 1:
pass # use errors below if not a passing int
elif (
not isinstance(value, list)
or len(value) < 1
or not all([isinstance(item, str) for item in value])
or not set(value).issubset(set(valid_methods))
):
errors.append(
"{}.bin_count_or_method must be an integer more "
"than 1, a string, or list of strings from the "
"following: {}.".format(variable_path, valid_methods)
)
if self.num_quantiles is not None and (
not isinstance(self.num_quantiles, int) or self.num_quantiles < 1
):
errors.append(f"{variable_path}.num_quantiles must be a positive integer.")
return errors
class ModeOption(BooleanOption["ModeOption"]):
"""For setting mode estimation options."""
def __init__(self, is_enabled: bool = True, max_k_modes: int = 5) -> None:
"""Initialize Options for mode estimation.
:ivar is_enabled: boolean option to enable/disable the option.
:vartype is_enabled: bool
:ivar max_k_modes: the max number of modes to return, if applicable
:vartype max_k_modes: int
"""
self.top_k_modes = max_k_modes
super().__init__(is_enabled=is_enabled)
def _validate_helper(self, variable_path: str = "ModeOption") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
errors = super()._validate_helper(variable_path=variable_path)
if self.top_k_modes is not None and (
not isinstance(self.top_k_modes, int) or self.top_k_modes < 1
):
errors.append(
"{}.top_k_modes must be either None"
" or a positive integer".format(variable_path)
)
return errors
class BaseInspectorOptions(BooleanOption[BaseInspectorOptionsT]):
"""For setting Base options."""
def __init__(self, is_enabled: bool = True) -> None:
"""
Initialize Base options for all the columns.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
"""
super().__init__(is_enabled=is_enabled)
def _validate_helper(
self, variable_path: str = "BaseInspectorOptions"
) -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
return super()._validate_helper(variable_path)
def is_prop_enabled(self, prop: str) -> bool:
"""
Check to see if a property is enabled or not and returns boolean.
:param prop: The option to check if it is enabled
:type prop: String
:return: Whether or not the property is enabled
:rtype: Boolean
"""
is_enabled = True
if prop not in self.properties:
raise AttributeError(
'Property "{}" does not exist in {}.'.format(
prop, self.__class__.__name__
)
)
option_prop = getattr(self, prop)
if isinstance(option_prop, bool):
is_enabled = option_prop
elif isinstance(option_prop, BooleanOption):
is_enabled = option_prop.is_enabled
return is_enabled
class NumericalOptions(BaseInspectorOptions[NumericalOptionsT]):
"""For configuring options for Numerican Stats Mixin."""
def __init__(self) -> None:
"""
Initialize Options for the Numerical Stats Mixin.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
:ivar min: boolean option to enable/disable min
:vartype min: BooleanOption
:ivar max: boolean option to enable/disable max
:vartype max: BooleanOption
:ivar mode: option to enable/disable mode and set return count
:vartype mode: ModeOption
:ivar median: option to enable/disable median
:vartype median: BooleanOption
:ivar sum: boolean option to enable/disable sum
:vartype sum: BooleanOption
:ivar variance: boolean option to enable/disable variance
:vartype variance: BooleanOption
:ivar skewness: boolean option to enable/disable skewness
:vartype skewness: BooleanOption
:ivar kurtosis: boolean option to enable/disable kurtosis
:vartype kurtosis: BooleanOption
:ivar histogram_and_quantiles: boolean option to enable/disable
histogram_and_quantiles
:vartype histogram_and_quantiles: BooleanOption
:ivar bias_correction : boolean option to enable/disable existence of bias
:vartype bias_correction: BooleanOption
:ivar num_zeros: boolean option to enable/disable num_zeros
:vartype num_zeros: BooleanOption
:ivar num_negatives: boolean option to enable/disable num_negatives
:vartype num_negatives: BooleanOption
:ivar is_numeric_stats_enabled: boolean to enable/disable all numeric
stats
:vartype is_numeric_stats_enabled: bool
"""
self.min: BooleanOption = BooleanOption(is_enabled=True)
self.max: BooleanOption = BooleanOption(is_enabled=True)
self.mode: ModeOption = ModeOption(is_enabled=True)
self.median: BooleanOption = BooleanOption(is_enabled=True)
self.sum: BooleanOption = BooleanOption(is_enabled=True)
self.variance: BooleanOption = BooleanOption(is_enabled=True)
self.skewness: BooleanOption = BooleanOption(is_enabled=True)
self.kurtosis: BooleanOption = BooleanOption(is_enabled=True)
self.median_abs_deviation: BooleanOption = BooleanOption(is_enabled=True)
self.num_zeros: BooleanOption = BooleanOption(is_enabled=True)
self.num_negatives: BooleanOption = BooleanOption(is_enabled=True)
self.histogram_and_quantiles: HistogramAndQuantilesOption = (
HistogramAndQuantilesOption()
)
# By default, we correct for bias
self.bias_correction: BooleanOption = BooleanOption(is_enabled=True)
BaseInspectorOptions.__init__(self)
@property
def is_numeric_stats_enabled(self) -> bool:
"""
Return the state of numeric stats being enabled / disabled.
If any numeric stats property is enabled it will return True,
otherwise it will return False.
:return: true if any numeric stats property is enabled, otherwise false
:rtype bool:
"""
if (
self.min.is_enabled
or self.max.is_enabled
or self.mode.is_enabled
or self.sum.is_enabled
or self.variance.is_enabled
or self.skewness.is_enabled
or self.kurtosis.is_enabled
or self.median.is_enabled
or self.median_abs_deviation.is_enabled
or self.histogram_and_quantiles.is_enabled
or self.num_zeros.is_enabled
or self.num_negatives.is_enabled
):
return True
return False
@is_numeric_stats_enabled.setter
def is_numeric_stats_enabled(self, value: bool) -> None:
"""
Enable or disable all numeric stats properties.
The properties are:
min, max, sum, variance, skewness, kurtosis, histogram_and_quantiles,
num_zeros, num_negatives
:param value: boolean to enable/disable all numeric stats properties
:type value: bool
:return: None
"""
self.min.is_enabled = value
self.max.is_enabled = value
self.mode.is_enabled = value
self.median.is_enabled = value
self.sum.is_enabled = value
self.variance.is_enabled = value
self.skewness.is_enabled = value
self.kurtosis.is_enabled = value
self.median_abs_deviation.is_enabled = value
self.num_zeros.is_enabled = value
self.num_negatives.is_enabled = value
self.histogram_and_quantiles.is_enabled = value
@property
def properties(self) -> dict[str, BooleanOption]:
"""
Include is_enabled.
is_enabled: Turns on or off the column.
"""
props: dict = super().properties
props["is_numeric_stats_enabled"] = self.is_numeric_stats_enabled
return props
def _validate_helper(self, variable_path: str = "NumericalOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
if not variable_path:
variable_path = self.__class__.__name__
errors = super()._validate_helper(variable_path=variable_path)
for item in [
"histogram_and_quantiles",
"min",
"max",
"sum",
"mode",
"median",
"variance",
"skewness",
"kurtosis",
"median_abs_deviation",
"bias_correction",
"num_zeros",
"num_negatives",
]:
if not isinstance(self.properties[item], BooleanOption):
errors.append(f"{variable_path}.{item} must be a BooleanOption.")
else:
errors += self.properties[item]._validate_helper(
variable_path=variable_path + "." + item
)
# Error checks for dependent calculations
sum_disabled = not self.properties["sum"].is_enabled
var_disabled = not self.properties["variance"].is_enabled
skew_disabled = not self.properties["skewness"].is_enabled
kurt_disabled = not self.properties["kurtosis"].is_enabled
mad_disabled = not self.properties["median_abs_deviation"].is_enabled
histogram_disabled = not self.properties["histogram_and_quantiles"].is_enabled
if sum_disabled and not var_disabled:
errors.append(
"{}: The numeric stats must toggle on the sum "
"if the variance is toggled on.".format(variable_path)
)
if (sum_disabled or var_disabled) and not skew_disabled:
errors.append(
"{}: The numeric stats must toggle on the "
"sum and variance if skewness is toggled on.".format(variable_path)
)
if (sum_disabled or var_disabled or skew_disabled) and not kurt_disabled:
errors.append(
"{}: The numeric stats must toggle on sum,"
" variance, and skewness if kurtosis is "
"toggled on.".format(variable_path)
)
if histogram_disabled and not mad_disabled:
errors.append(
"{}: The numeric stats must toggle on histogram "
"and quantiles if median absolute deviation is "
"toggled on.".format(variable_path)
)
mode_disabled = not self.properties["mode"].is_enabled
median_disabled = not self.properties["median"].is_enabled
histogram_disabled = not self.properties["histogram_and_quantiles"].is_enabled
if histogram_disabled:
if not mode_disabled:
errors.append(
"{}: The numeric stats must toggle on histogram "
"and quantiles if mode is "
"toggled on.".format(variable_path)
)
if not median_disabled:
errors.append(
"{}: The numeric stats must toggle on histogram "
"and quantiles if median is "
"toggled on.".format(variable_path)
)
# warn user if all stats are disabled
if not errors:
if not self.is_numeric_stats_enabled:
variable_path = (
variable_path + ".numeric_stats"
if variable_path
else self.__class__.__name__
)
warnings.warn(
"{}: The numeric stats are completely disabled.".format(
variable_path
)
)
return errors
class IntOptions(NumericalOptions["IntOptions"]):
"""For configuring options for Int Column."""
def __init__(self) -> None:
"""
Initialize Options for the Int Column.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
:ivar min: boolean option to enable/disable min
:vartype min: BooleanOption
:ivar max: boolean option to enable/disable max
:vartype max: BooleanOption
:ivar mode: option to enable/disable mode and set return count
:vartype mode: ModeOption
:ivar median: option to enable/disable median
:vartype median: BooleanOption
:ivar sum: boolean option to enable/disable sum
:vartype sum: BooleanOption
:ivar variance: boolean option to enable/disable variance
:vartype variance: BooleanOption
:ivar skewness: boolean option to enable/disable skewness
:vartype skewness: BooleanOption
:ivar kurtosis: boolean option to enable/disable kurtosis
:vartype kurtosis: BooleanOption
:ivar histogram_and_quantiles: boolean option to enable/disable
histogram_and_quantiles
:vartype histogram_and_quantiles: BooleanOption
:ivar bias_correction : boolean option to enable/disable existence of bias
:vartype bias_correction: BooleanOption
:ivar num_zeros: boolean option to enable/disable num_zeros
:vartype num_zeros: BooleanOption
:ivar num_negatives: boolean option to enable/disable num_negatives
:vartype num_negatives: BooleanOption
:ivar is_numeric_stats_enabled: boolean to enable/disable all numeric
stats
:vartype is_numeric_stats_enabled: bool
"""
NumericalOptions.__init__(self)
def _validate_helper(self, variable_path: str = "IntOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
return super()._validate_helper(variable_path)
class PrecisionOptions(BooleanOption["PrecisionOptions"]):
"""For configuring options for precision."""
def __init__(self, is_enabled: bool = True, sample_ratio: float = None) -> None:
"""
Initialize Options for precision.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
:ivar sample_ratio: float option to determine ratio of valid
float samples in determining percision.
This ratio will override any defaults.
:vartype sample_ratio: float
"""
self.sample_ratio = sample_ratio
super().__init__(is_enabled=is_enabled)
def _validate_helper(self, variable_path: str = "PrecisionOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: List of strings
"""
errors = super()._validate_helper(variable_path=variable_path)
if self.sample_ratio is not None:
if not isinstance(self.sample_ratio, float) and not isinstance(
self.sample_ratio, int
):
errors.append(f"{variable_path}.sample_ratio must be a float.")
if (
isinstance(self.sample_ratio, float)
or isinstance(self.sample_ratio, int)
) and (self.sample_ratio < 0 or self.sample_ratio > 1.0):
errors.append(
"{}.sample_ratio must be a float between 0 and 1.".format(
variable_path
)
)
return errors
class FloatOptions(NumericalOptions["FloatOptions"]):
"""For configuring options for Float Column."""
def __init__(self) -> None:
"""
Initialize Options for the Float Column.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
:ivar min: boolean option to enable/disable min
:vartype min: BooleanOption
:ivar max: boolean option to enable/disable max
:vartype max: BooleanOption
:ivar mode: option to enable/disable mode and set return count
:vartype mode: ModeOption
:ivar median: option to enable/disable median
:vartype median: BooleanOption
:ivar sum: boolean option to enable/disable sum
:vartype sum: BooleanOption
:ivar variance: boolean option to enable/disable variance
:vartype variance: BooleanOption
:ivar skewness: boolean option to enable/disable skewness
:vartype skewness: BooleanOption
:ivar kurtosis: boolean option to enable/disable kurtosis
:vartype kurtosis: BooleanOption
:ivar histogram_and_quantiles: boolean option to enable/disable
histogram_and_quantiles
:vartype histogram_and_quantiles: BooleanOption
:ivar bias_correction : boolean option to enable/disable existence of bias
:vartype bias_correction: BooleanOption
:ivar num_zeros: boolean option to enable/disable num_zeros
:vartype num_zeros: BooleanOption
:ivar num_negatives: boolean option to enable/disable num_negatives
:vartype num_negatives: BooleanOption
:ivar is_numeric_stats_enabled: boolean to enable/disable all numeric
stats
:vartype is_numeric_stats_enabled: bool
"""
NumericalOptions.__init__(self)
self.precision = PrecisionOptions(is_enabled=True)
def _validate_helper(self, variable_path: str = "FloatOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
errors = super()._validate_helper(variable_path=variable_path)
if not isinstance(self.precision, PrecisionOptions):
errors.append(f"{variable_path}.precision must be a PrecisionOptions.")
errors += self.precision._validate_helper(variable_path + ".precision")
return errors
class TextOptions(NumericalOptions["TextOptions"]):
"""For configuring options for Text Column."""
def __init__(self) -> None:
"""
Initialize Options for the Text Column.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
:ivar vocab: boolean option to enable/disable vocab
:vartype vocab: BooleanOption
:ivar min: boolean option to enable/disable min
:vartype min: BooleanOption
:ivar max: boolean option to enable/disable max
:vartype max: BooleanOption
:ivar mode: option to enable/disable mode and set return count
:vartype mode: ModeOption
:ivar median: option to enable/disable median
:vartype median: BooleanOption
:ivar sum: boolean option to enable/disable sum
:vartype sum: BooleanOption
:ivar variance: boolean option to enable/disable variance
:vartype variance: BooleanOption
:ivar skewness: boolean option to enable/disable skewness
:vartype skewness: BooleanOption
:ivar kurtosis: boolean option to enable/disable kurtosis
:vartype kurtosis: BooleanOption
:ivar bias_correction : boolean option to enable/disable existence of bias
:vartype bias_correction: BooleanOption
:ivar histogram_and_quantiles: boolean option to enable/disable
histogram_and_quantiles
:vartype histogram_and_quantiles: BooleanOption
:ivar num_zeros: boolean option to enable/disable num_zeros
:vartype num_zeros: BooleanOption
:ivar num_negatives: boolean option to enable/disable num_negatives
:vartype num_negatives: BooleanOption
:ivar is_numeric_stats_enabled: boolean to enable/disable all numeric
stats
:vartype is_numeric_stats_enabled: bool
"""
NumericalOptions.__init__(self)
self.vocab: BooleanOption = BooleanOption(is_enabled=True)
self.num_zeros: BooleanOption = BooleanOption(is_enabled=False)
self.num_negatives: BooleanOption = BooleanOption(is_enabled=False)
def _validate_helper(self, variable_path: str = "TextOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
Also validate that some options (num_zeros and num_negatives)
are set to be disabled by default.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
errors = super()._validate_helper(variable_path=variable_path)
if not isinstance(self.vocab, BooleanOption):
errors.append(f"{variable_path}.vocab must be a BooleanOption.")
errors += self.vocab._validate_helper(variable_path + ".vocab")
if self.properties["num_zeros"].is_enabled:
errors.append(
"{}.num_zeros should always be disabled,"
" num_zeros.is_enabled = False".format(variable_path)
)
if self.properties["num_negatives"].is_enabled:
errors.append(
"{}.num_negatives should always be disabled,"
" num_negatives.is_enabled = False".format(variable_path)
)
return errors
@property
def is_numeric_stats_enabled(self) -> bool:
"""
Return the state of numeric stats being enabled / disabled.
If any numeric stats property is enabled it will return True, otherwise
it will return False. Although it seems redundant, this method is needed
in order for the function below, the setter function
also called is_numeric_stats_enabled, to properly work.
:return: true if any numeric stats property is enabled, otherwise false
:rtype bool:
"""
if (
self.min.is_enabled
or self.max.is_enabled
or self.sum.is_enabled
or self.mode.is_enabled
or self.variance.is_enabled
or self.skewness.is_enabled
or self.kurtosis.is_enabled
or self.median.is_enabled
or self.median_abs_deviation.is_enabled
or self.histogram_and_quantiles.is_enabled
):
return True
return False
@is_numeric_stats_enabled.setter
def is_numeric_stats_enabled(self, value: bool) -> None:
"""
Enable or disable all numeric stats properties.
Those properties are:
min, max, sum, variance, skewness, kurtosis, histogram_and_quantiles,
:param value: boolean to enable/disable all numeric stats properties
:type value: bool
:return: None
"""
self.min.is_enabled = value
self.max.is_enabled = value
self.mode.is_enabled = value
self.median.is_enabled = value
self.sum.is_enabled = value
self.variance.is_enabled = value
self.skewness.is_enabled = value
self.kurtosis.is_enabled = value
self.median_abs_deviation.is_enabled = value
self.histogram_and_quantiles.is_enabled = value
class DateTimeOptions(BaseInspectorOptions["DateTimeOptions"]):
"""For configuring options for Datetime Column."""
def __init__(self) -> None:
"""
Initialize Options for the Datetime Column.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
"""
BaseInspectorOptions.__init__(self)
def _validate_helper(self, variable_path: str = "DateTimeOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
return super()._validate_helper(variable_path)
class OrderOptions(BaseInspectorOptions["OrderOptions"]):
"""For configuring options for Order Column."""
def __init__(self) -> None:
"""
Initialize options for the Order Column.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
"""
BaseInspectorOptions.__init__(self)
def _validate_helper(self, variable_path: str = "OrderOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
return super()._validate_helper(variable_path)
class CategoricalOptions(BaseInspectorOptions["CategoricalOptions"]):
"""For configuring options Categorical Column."""
def __init__(
self,
is_enabled: bool = True,
top_k_categories: int | None = None,
max_sample_size_to_check_stop_condition: int | None = None,
stop_condition_unique_value_ratio: float | None = None,
cms: bool = False,
cms_confidence: float | None = 0.95,
cms_relative_error: float | None = 0.01,
cms_max_num_heavy_hitters: int | None = 5000,
) -> None:
"""
Initialize options for the Categorical Column.
:ivar is_enabled: boolean option to enable/disable the column.
:vartype is_enabled: bool
:ivar top_k_categories: number of categories to be displayed when called
:vartype top_k_categories: [None, int]
:ivar max_sample_size_to_check_stop_condition: The maximum sample size
before categorical stop conditions are checked
:vartype max_sample_size_to_check_stop_condition: [None, int]
:ivar stop_condition_unique_value_ratio: The highest ratio of unique
values to dataset size that is to be considered a categorical type
:vartype stop_condition_unique_value_ratio: [None, float]
:ivar cms: boolean option for using count min sketch
:vartype cms: bool
:ivar cms_confidence: defines the number of hashes used in CMS.
eg. confidence = 1 - failure probability, default 0.95
:vartype cms_confidence: [None, float]
:ivar cms_relative_error: defines the number of buckets used in CMS,
default 0.01
:vartype cms_relative_error: [None, float]
:ivar cms_max_num_heavy_hitters: value used to define
the threshold for minimum frequency required by a category to be counted
:vartype cms_max_num_heavy_hitters: [None, int]
"""
BaseInspectorOptions.__init__(self, is_enabled=is_enabled)
self.top_k_categories = top_k_categories
self.max_sample_size_to_check_stop_condition = (
max_sample_size_to_check_stop_condition
)
self.stop_condition_unique_value_ratio = stop_condition_unique_value_ratio
self.cms = cms
self.cms_confidence = cms_confidence
self.cms_relative_error = cms_relative_error
self.cms_max_num_heavy_hitters = cms_max_num_heavy_hitters
def _validate_helper(self, variable_path: str = "CategoricalOptions") -> list[str]:
"""
Validate the options do not conflict and cause errors.
:param variable_path: current path to variable set.
:type variable_path: str
:return: list of errors (if raise_error is false)
:rtype: list(str)
"""
errors = super()._validate_helper(variable_path)
if self.top_k_categories is not None and (
not isinstance(self.top_k_categories, int) or self.top_k_categories < 1
):
errors.append(
"{}.top_k_categories must be either None"
" or a positive integer".format(variable_path)
)
if self.max_sample_size_to_check_stop_condition is not None and (
not isinstance(self.max_sample_size_to_check_stop_condition, int)
or self.max_sample_size_to_check_stop_condition < 0
):
errors.append(
"{}.max_sample_size_to_check_stop_condition must be either None"
" or a non-negative integer".format(variable_path)
)
if self.stop_condition_unique_value_ratio is not None and (
not isinstance(self.stop_condition_unique_value_ratio, float)
or self.stop_condition_unique_value_ratio < 0
or self.stop_condition_unique_value_ratio > 1.0
):
errors.append(
"{}.stop_condition_unique_value_ratio must be either None"
" or a float between 0 and 1".format(variable_path)
)
if (self.max_sample_size_to_check_stop_condition is None) ^ (
self.stop_condition_unique_value_ratio is None
):