-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathtest_numerical.py
More file actions
2197 lines (1826 loc) · 71.8 KB
/
test_numerical.py
File metadata and controls
2197 lines (1826 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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
import re
from unittest import TestCase
from unittest.mock import Mock, patch
import copulas
import numpy as np
import pandas as pd
import pytest
from copulas import univariate
from pandas.api.types import is_float_dtype
from rdt.errors import InvalidDataError, TransformerInputError
from rdt.transformers.null import NullTransformer
from rdt.transformers.numerical import (
ClusterBasedNormalizer,
FloatFormatter,
GaussianNormalizer,
LogScaler,
)
class TestFloatFormatter(TestCase):
def test___init__super_attrs(self):
"""super() arguments are properly passed and set as attributes."""
nt = FloatFormatter(missing_value_replacement='mode', missing_value_generation='random')
assert nt.missing_value_replacement == 'mode'
assert nt.missing_value_generation == 'random'
def test__validate_values_within_bounds(self):
"""Test the ``_validate_values_within_bounds`` method.
If all values are correctly bounded, it shouldn't do anything.
Setup:
- instantiate ``FloatFormatter`` with ``computer_representation`` set to an int.
Input:
- a Dataframe.
"""
# Setup
data = pd.Series([15, None, 25])
transformer = FloatFormatter()
transformer.computer_representation = 'UInt8'
# Run
transformer._validate_values_within_bounds(data)
def test__validate_values_within_bounds_pyarrow(self):
"""Test it works with pyarrow."""
# Setup
try:
data = pd.Series(range(10), dtype='int64[pyarrow]')
except TypeError:
pytest.skip("Skipping as old numpy/pandas versions don't support arrow")
transformer = FloatFormatter()
transformer.computer_representation = 'UInt8'
# Run
transformer._validate_values_within_bounds(data)
def test__validate_values_within_bounds_under_minimum(self):
"""Test the ``_validate_values_within_bounds`` method.
Expected to crash if a value is under the bound.
Setup:
- instantiate ``FloatFormatter`` with ``computer_representation`` set to an int.
Input:
- a Dataframe.
Side Effect:
- raise ``ValueError``.
"""
# Setup
data = pd.Series([-15, None, 0], name='a')
transformer = FloatFormatter()
transformer.computer_representation = 'UInt8'
# Run / Assert
err_msg = re.escape(
"The minimum value in column 'a' is -15.0. All values represented by 'UInt8'"
' must be in the range [0, 255].'
)
with pytest.raises(ValueError, match=err_msg):
transformer._validate_values_within_bounds(data)
def test__validate_values_within_bounds_over_maximum(self):
"""Test the ``_validate_values_within_bounds`` method.
Expected to crash if a value is over the bound.
Setup:
- instantiate ``FloatFormatter`` with ``computer_representation`` set to an int.
Input:
- a Dataframe.
"""
# Setup
data = pd.Series([255, None, 256], name='a')
transformer = FloatFormatter()
transformer.computer_representation = 'UInt8'
# Run / Assert
err_msg = re.escape(
"The maximum value in column 'a' is 256.0. All values represented by 'UInt8'"
' must be in the range [0, 255].'
)
with pytest.raises(ValueError, match=err_msg):
transformer._validate_values_within_bounds(data)
def test__validate_values_within_bounds_floats(self):
"""Test the ``_validate_values_within_bounds`` method.
Expected to crash if float values are passed when ``computer_representation`` is an int.
Setup:
- instantiate ``FloatFormatter`` with ``computer_representation`` set to an int.
Input:
- a Dataframe.
"""
# Setup
data = pd.Series([249.2, None, 250.0, 10.2], name='a')
transformer = FloatFormatter()
transformer.computer_representation = 'UInt8'
# Run / Assert
err_msg = re.escape(
"The column 'a' contains float values [249.2, 10.2]."
" All values represented by 'UInt8' must be integers."
)
with pytest.raises(ValueError, match=err_msg):
transformer._validate_values_within_bounds(data)
def test__fit(self):
"""Test the ``_fit`` method.
Validate that the ``_dtype`` and ``.null_transformer.missing_value_replacement`` attributes
are set correctly.
Setup:
- initialize a ``FloatFormatter`` with the ``missing_value_replacement``
parameter set to ``'missing_value_replacement'``.
Input:
- a pandas series containing a None.
Side effect:
- it sets the ``null_transformer.missing_value_replacement``.
- it sets the ``_dtype``.
- it calls ``_validate_values_within_bounds``.
"""
# Setup
data = pd.Series([1.5, None, 2.5])
transformer = FloatFormatter(missing_value_replacement='missing_value_replacement')
transformer._validate_values_within_bounds = Mock()
# Run
transformer._fit(data)
# Asserts
expected = 'missing_value_replacement'
assert transformer.null_transformer._missing_value_replacement == expected
assert is_float_dtype(transformer._dtype)
assert transformer.output_properties == {
None: {'sdtype': 'float', 'next_transformer': None}
}
transformer._validate_values_within_bounds.assert_called_once_with(data)
assert transformer.output_properties == {
None: {'sdtype': 'float', 'next_transformer': None},
}
def test__fit_learn_rounding_scheme_false(self):
"""Test ``_fit`` with ``learn_rounding_scheme`` set to ``False``.
If the ``learn_rounding_scheme`` is set to ``False``, the ``_fit`` method
should not set its ``_rounding_digits`` instance variable.
Input:
- An array with floats rounded to one decimal and a None value
Side Effect:
- ``_rounding_digits`` should be ``None``
"""
# Setup
data = pd.Series([1.5, None, 2.5])
# Run
transformer = FloatFormatter(
missing_value_replacement='missing_value_replacement',
learn_rounding_scheme=False,
)
transformer._fit(data)
# Asserts
assert transformer._rounding_digits is None
def test__fit_learn_rounding_scheme_true(self):
"""Test ``_fit`` with ``learn_rounding_scheme`` set to ``True``.
If ``learn_rounding_scheme`` is set to ``True``, the ``_fit`` method
should set its ``_rounding_digits`` instance variable to what is learned
in the data.
Input:
- A Series with floats up to 4 decimals and a None value
Side Effect:
- ``_rounding_digits`` is set to 4
"""
# Setup
data = pd.Series([
1,
2.1,
3.12,
4.123,
5.1234,
6.123,
7.12,
8.1,
9,
None,
])
# Run
transformer = FloatFormatter(missing_value_replacement='mean', learn_rounding_scheme=True)
transformer._fit(data)
# Asserts
assert transformer._rounding_digits == 4
def test__fit_learn_rounding_scheme_true_max_decimals(self):
"""Test ``_fit`` with ``learn_rounding_scheme`` set to ``True``.
If the ``learn_rounding_scheme`` parameter is set to ``True``, ``_fit`` should learn
the ``_rounding_digits`` to be the max number of decimal places seen in the data.
The max amount of decimals that floats can be accurately compared with is 15.
If the input data has values with more than 14 decimals, we will not be able to
accurately learn the number of decimal places required, so we do not round.
Input:
- Series with a value that has 15 decimals
Side Effect:
- ``_rounding_digits`` is set to None
"""
# Setup
data = pd.Series([0.000000000000001])
# Run
transformer = FloatFormatter(missing_value_replacement='mean', learn_rounding_scheme=True)
transformer._fit(data)
# Asserts
assert transformer._rounding_digits is None
def test__fit_learn_rounding_scheme_true_inf(self):
"""Test ``_fit`` with ``learn_rounding_scheme`` set to ``True``.
If the ``learn_rounding_scheme`` parameter is set to ``True``, and the data
contains only integers or infinite values, ``_fit`` should learn
``_rounding_digits`` to be 0.
Input:
- Series with ``np.inf`` as a value
Side Effect:
- ``_rounding_digits`` is set to 0
"""
# Setup
data = pd.Series([15000, 4000, 60000, np.inf])
# Run
transformer = FloatFormatter(missing_value_replacement='mean', learn_rounding_scheme=True)
transformer._fit(data)
# Asserts
assert transformer._rounding_digits == 0
def test__fit_learn_rounding_scheme_true_max_zero(self):
"""Test ``_fit`` with ``learn_rounding_scheme`` set to ``True``.
If the ``learn_rounding_scheme`` parameter is set to ``True``, and the max
in the data is 0, ``_fit`` should learn the ``_rounding_digits`` to be 0.
Input:
- Series with 0 as max value
Side Effect:
- ``_rounding_digits`` is set to 0
"""
# Setup
data = pd.Series([0, 0, 0])
# Run
transformer = FloatFormatter(missing_value_replacement='mean', learn_rounding_scheme=True)
transformer._fit(data)
# Asserts
assert transformer._rounding_digits == 0
def test__fit_enforce_min_max_values_false(self):
"""Test ``_fit`` with ``enforce_min_max_values`` set to ``False``.
If the ``enforce_min_max_values`` parameter is set to ``False``,
the ``_fit`` method should not set its ``min`` or ``max``
instance variables.
Input:
- Series of floats and null values
Side Effect:
- ``_min_value`` and ``_max_value`` stay ``None``
"""
# Setup
data = pd.Series([1.5, None, 2.5])
# Run
transformer = FloatFormatter(missing_value_replacement='mean', enforce_min_max_values=False)
transformer._fit(data)
# Asserts
assert transformer._min_value is None
assert transformer._max_value is None
def test__fit_enforce_min_max_values_true(self):
"""Test ``_fit`` with ``enforce_min_max_values`` set to ``True``.
If the ``enforce_min_max_values`` parameter is set to ``True``,
the ``_fit`` method should learn the min and max values from the _fitted data.
Input:
- Series of floats and null values
Side Effect:
- ``_min_value`` and ``_max_value`` are learned
"""
# Setup
data = pd.Series([-100, -5000, 0, None, 100, 4000])
# Run
transformer = FloatFormatter(missing_value_replacement='mean', enforce_min_max_values=True)
transformer._fit(data)
# Asserts
assert transformer._min_value == -5000
assert transformer._max_value == 4000
def test__fit_missing_value_replacement_from_column(self):
"""Test output_properties contains 'is_null' column.
When ``missing_value_generation`` is ``from_column`` an output property ``is_null`` should
exist.
"""
# Setup
transformer = FloatFormatter(missing_value_generation='from_column')
data = pd.Series([1, np.nan])
# Run
transformer._fit(data)
# Assert
assert transformer.output_properties == {
None: {'sdtype': 'float', 'next_transformer': None},
'is_null': {'sdtype': 'float', 'next_transformer': None},
}
def test__transform(self):
"""Test the ``_transform`` method.
Validate that this method calls the ``self.null_transformer.transform`` method once.
Setup:
- create an instance of a ``FloatFormatter`` and set ``self.null_transformer``
to a ``NullTransformer``.
Input:
- a pandas series.
Output:
- the transformed numpy array.
"""
# Setup
data = pd.Series([1, 2, 3])
transformer = FloatFormatter()
transformer._validate_values_within_bounds = Mock()
transformer.null_transformer = Mock()
# Run
transformer._transform(data)
# Assert
transformer._validate_values_within_bounds.assert_called_once_with(data)
assert transformer.null_transformer.transform.call_count == 1
def test__reverse_transform_learn_rounding_scheme_false(self):
"""Test ``_reverse_transform`` when ``learn_rounding_scheme`` is ``False``.
The data should not be rounded at all.
Input:
- Random array of floats between 0 and 1
Output:
- Input array
"""
# Setup
data = np.random.random(10)
# Run
transformer = FloatFormatter()
transformer.learn_rounding_scheme = False
transformer._rounding_digits = None
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Assert
np.testing.assert_array_equal(result, data)
def test__reverse_transform_rounding_none_dtype_int(self):
"""Test ``_reverse_transform`` with ``_dtype`` as ``np.int64`` and no rounding.
The data should be rounded to 0 decimals and returned as integer values if the ``_dtype``
is ``np.int64`` even if ``_rounding_digits`` is ``None``.
Input:
- Array of multiple float values with decimals.
Output:
- Input array rounded an converted to integers.
"""
# Setup
data = np.array([0.0, 1.2, 3.45, 6.789])
# Run
transformer = FloatFormatter()
transformer._rounding_digits = None
transformer._dtype = np.int64
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Assert
expected = np.array([0, 1, 3, 7])
np.testing.assert_array_equal(result, expected)
def test__reverse_transform_rounding_none_with_nulls(self):
"""Test ``_reverse_transform`` when ``_rounding_digits`` is ``None`` and there are nulls.
The data should not be rounded at all.
Input:
- 2d Array of multiple float values with decimals and a column setting at least 1 null.
Output:
- First column of the input array as entered, replacing the indicated value with a
missing_value_replacement.
"""
# Setup
data = [
[0.0, 0.0],
[1.2, 0.0],
[3.45, 1.0],
[6.789, 0.0],
]
data = pd.DataFrame(data, columns=['a', 'b'])
# Run
transformer = FloatFormatter()
null_transformer = Mock()
null_transformer.reverse_transform.return_value = np.array([
0.0,
1.2,
np.nan,
6.789,
])
transformer.null_transformer = null_transformer
transformer.learn_rounding_scheme = False
transformer._rounding_digits = None
transformer._dtype = float
result = transformer._reverse_transform(data)
# Assert
expected = np.array([0.0, 1.2, np.nan, 6.789])
np.testing.assert_array_equal(result, expected)
def test__reverse_transform_rounding_none_with_nulls_dtype_int(self):
"""Test ``_reverse_transform`` rounding when dtype is int and there are nulls.
The data should be rounded to 0 decimals and returned as float values with
nulls in the right place.
Input:
- 2d Array of multiple float values with decimals and a column setting at least 1 null.
Output:
- First column of the input array rounded, replacing the indicated value with a
``NaN``, and kept as float values.
"""
# Setup
data = np.array([
[0.0, 0.0],
[1.2, 0.0],
[3.45, 1.0],
[6.789, 0.0],
])
# Run
transformer = FloatFormatter()
null_transformer = Mock()
null_transformer.reverse_transform.return_value = np.array([
0.0,
1.2,
np.nan,
6.789,
])
transformer.null_transformer = null_transformer
transformer.learn_rounding_digits = False
transformer._rounding_digits = None
transformer._dtype = int
result = transformer._reverse_transform(data)
# Assert
expected = np.array([0.0, 1.0, np.nan, 7.0])
np.testing.assert_array_equal(result, expected)
def test__reverse_transform_rounding_small_numbers(self):
"""Test ``_reverse_transform`` when ``_rounding_digits`` is positive.
The data should round to the maximum number of decimal places
set in the ``_rounding_digits`` value.
Input:
- Array with decimals
Output:
- Same array rounded to the provided number of decimal places
"""
# Setup
data = np.array([1.1111, 2.2222, 3.3333, 4.44444, 5.555555])
# Run
transformer = FloatFormatter()
transformer.learn_rounding_scheme = True
transformer._rounding_digits = 2
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Assert
expected_data = np.array([1.11, 2.22, 3.33, 4.44, 5.56])
np.testing.assert_array_equal(result, expected_data)
def test__reverse_transform_rounding_big_numbers_type_int(self):
"""Test ``_reverse_transform`` when ``_rounding_digits`` is negative.
The data should round to the number set in the ``_rounding_digits``
attribute and remain ints.
Input:
- Array with with floats above 100
Output:
- Same array rounded to the provided number of 0s
- Array should be of type int
"""
# Setup
data = np.array([2000.0, 120.0, 3100.0, 40100.0])
# Run
transformer = FloatFormatter()
transformer._dtype = int
transformer.learn_rounding_scheme = True
transformer._rounding_digits = -3
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Assert
expected_data = np.array([2000, 0, 3000, 40000])
np.testing.assert_array_equal(result, expected_data)
assert result.dtype == int
def test__reverse_transform_rounding_negative_type_float(self):
"""Test ``_reverse_transform`` when ``_rounding_digits`` is negative.
The data should round to the number set in the ``_rounding_digits``
attribute and remain floats.
Input:
- Array with with larger numbers
Output:
- Same array rounded to the provided number of 0s
- Array should be of type float
"""
# Setup
data = np.array([2000.0, 120.0, 3100.0, 40100.0])
# Run
transformer = FloatFormatter()
transformer.learn_rounding_scheme = True
transformer._rounding_digits = -3
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Assert
expected_data = np.array([2000.0, 0.0, 3000.0, 40000.0])
np.testing.assert_array_equal(result, expected_data)
assert result.dtype == float
def test__reverse_transform_rounding_zero_decimal_places(self):
"""Test ``_reverse_transform`` when ``_rounding_digits`` is 0.
The data should round to the number set in the ``_rounding_digits``
attribute.
Input:
- Array with with larger numbers
Output:
- Same array rounded to the 0s place
"""
# Setup
data = np.array([2000.554, 120.2, 3101, 4010])
# Run
transformer = FloatFormatter()
transformer.learn_rounding_scheme = True
transformer._rounding_digits = 0
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Assert
expected_data = np.array([2001, 120, 3101, 4010])
np.testing.assert_array_equal(result, expected_data)
def test__reverse_transform_enforce_min_max_values(self):
"""Test ``_reverse_transform`` with ``enforce_min_max_values`` set to ``True``.
The ``_reverse_transform`` method should clip any values above
the ``max_value`` and any values below the ``min_value``.
Input:
- Array with values above the max and below the min
Output:
- Array with out of bound values clipped to min and max
"""
# Setup
data = np.array([-np.inf, -5000, -301, -250, 0, 125, 401, np.inf])
# Run
transformer = FloatFormatter()
transformer.enforce_min_max_values = True
transformer._max_value = 400
transformer._min_value = -300
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Asserts
np.testing.assert_array_equal(result, np.array([-300, -300, -300, -250, 0, 125, 400, 400]))
def test__reverse_transform_enforce_min_max_values_with_nulls(self):
"""Test ``_reverse_transform`` with nulls and ``enforce_min_max_values`` set to ``True``.
The ``_reverse_transform`` method should clip any values above
the ``max_value`` and any values below the ``min_value``. Null values
should be replaced with ``np.nan``.
Input:
- 2d array where second column has some values over 0.5 representing null values
Output:
- Array with out of bounds values clipped and null values injected
"""
# Setup
data = np.array([
[-np.inf, 0],
[-5000, 0.1],
[-301, 0.8],
[-250, 0.4],
[0, 0],
[125, 1],
[401, 0.2],
[np.inf, 0.5],
])
expected_data = np.array([
-300,
-300,
np.nan,
-250,
0,
np.nan,
400,
400,
])
# Run
transformer = FloatFormatter(missing_value_replacement='mean')
transformer._max_value = 400
transformer._min_value = -300
transformer.enforce_min_max_values = True
transformer.null_transformer = Mock()
transformer.null_transformer.reverse_transform.return_value = expected_data
result = transformer._reverse_transform(data)
# Asserts
null_transformer_calls = transformer.null_transformer.reverse_transform.mock_calls
np.testing.assert_array_equal(null_transformer_calls[0][1][0], data)
np.testing.assert_array_equal(result, expected_data)
def test__reverse_transform_enforce_computer_representation(self):
"""Test ``_reverse_transform`` with ``computer_representation`` set to ``Int8``.
The ``_reverse_transform`` method should clip any values out of bounds.
Input:
- Array with values above the max and below the min
Output:
- Array with out of bound values clipped to min and max
"""
# Setup
data = np.array([
-np.inf,
np.nan,
-5000,
-301,
-100,
0,
125,
401,
np.inf,
])
# Run
transformer = FloatFormatter(computer_representation='Int8')
transformer.null_transformer = NullTransformer('mean')
result = transformer._reverse_transform(data)
# Asserts
np.testing.assert_array_equal(
result,
np.array([-128, np.nan, -128, -128, -100, 0, 125, 127, 127]),
)
def test__set_fitted_parameters(self):
"""Test ``_set_fitted_parameters`` sets the required parameters for transformer."""
# Setup
transformer = FloatFormatter(enforce_min_max_values=True)
column_name = 'mock'
null_transformer = NullTransformer('mean')
min_max_value = (0.0, 100.0)
rounding_digits = 3
dtype = 'Float'
error_msg = re.escape('Must provide min and max values for this transformer.')
# Run
with pytest.raises(TransformerInputError, match=error_msg):
transformer._set_fitted_parameters(
column_name=column_name,
null_transformer=null_transformer,
rounding_digits=rounding_digits,
dtype=dtype,
)
transformer._set_fitted_parameters(
column_name=column_name,
null_transformer=null_transformer,
rounding_digits=rounding_digits,
min_max_values=min_max_value,
dtype=dtype,
)
# Assert
assert transformer.columns == [column_name]
assert transformer.null_transformer == null_transformer
assert transformer._min_value == 0.0
assert transformer._max_value == 100.0
assert transformer._rounding_digits == rounding_digits
assert transformer._dtype == dtype
assert transformer.learn_rounding_scheme is True
def test__set_fitted_parameters_from_column(self):
"""Test ``_set_fitted_parameters`` sets the required parameters for transformer."""
# Setup
transformer = FloatFormatter(enforce_min_max_values=False)
column_name = 'mock'
bool_col_name = column_name + '.is_null'
null_transformer = NullTransformer('mean', 'from_column')
rounding_digits = 3
dtype = 'Float'
# Run
transformer._set_fitted_parameters(
column_name=column_name,
null_transformer=null_transformer,
rounding_digits=rounding_digits,
dtype=dtype,
)
# Assert
assert transformer.columns == [column_name]
assert transformer.output_columns == [column_name, bool_col_name]
assert transformer.null_transformer == null_transformer
assert transformer._min_value is None
assert transformer._max_value is None
assert transformer._rounding_digits == rounding_digits
assert transformer._dtype == dtype
class TestGaussianNormalizer:
def test___init__super_attrs(self):
"""super() arguments are properly passed and set as attributes."""
ct = GaussianNormalizer(
missing_value_generation='random',
learn_rounding_scheme=False,
enforce_min_max_values=False,
)
assert ct.missing_value_replacement == 'mean'
assert ct.missing_value_generation == 'random'
assert ct.learn_rounding_scheme is False
assert ct.enforce_min_max_values is False
def test___init__str_distr(self):
"""If distribution is a str, it is resolved using the _DISTRIBUTIONS dict."""
ct = GaussianNormalizer(distribution='gamma')
assert ct._distribution is copulas.univariate.GammaUnivariate
def test___init__non_distr(self):
"""If distribution is not an str, it is store as given."""
univariate = copulas.univariate.Univariate()
ct = GaussianNormalizer(distribution=univariate)
assert ct._distribution is univariate
def test___init__deprecated_distributions_warning(self):
"""Test it warns when using deprecated distributions."""
# Run and Assert
dists = zip(
['gaussian', 'student_t', 'truncated_gaussian'],
['norm', 't', 'truncnorm'],
)
for deprecated, distribution in dists:
err_msg = re.escape(
f"Future versions of RDT will not support '{deprecated}' as an option. "
f"Please use '{distribution}' instead."
)
with pytest.warns(FutureWarning, match=err_msg):
GaussianNormalizer(distribution=deprecated)
def test__get_distributions_copulas_not_installed(self):
"""Test the ``_get_distributions`` method when copulas is not installed.
Validate that this method raises the appropriate error message when copulas is
not installed.
Raise:
- ImportError('\n\nIt seems like `copulas` is not installed.\n'
'Please install it using:\n\n pip install rdt[copulas]')
"""
__py_import__ = __import__
def custom_import(name, *args):
if name == 'copulas':
raise ImportError('Simulate copulas not being importable.')
return __py_import__(name, *args)
with patch('builtins.__import__', side_effect=custom_import):
with pytest.raises(ImportError, match=r'pip install rdt\[copulas\]'):
GaussianNormalizer._get_distributions()
def test__get_distributions(self):
"""Test the ``_get_distributions`` method.
Validate that this method returns the correct dictionary of distributions.
Setup:
- instantiate a ``GaussianNormalizer``.
"""
# Setup
transformer = GaussianNormalizer()
# Run
distributions = transformer._get_distributions()
# Assert
expected = {
'gamma': univariate.GammaUnivariate,
'beta': univariate.BetaUnivariate,
'gaussian_kde': univariate.GaussianKDE,
'uniform': univariate.UniformUnivariate,
'truncnorm': univariate.TruncatedGaussian,
'norm': univariate.GaussianUnivariate,
't': univariate.StudentTUnivariate,
}
assert distributions == expected
def test__get_univariate_instance(self):
"""Test the ``_get_univariate`` method when the distribution is univariate.
Validate that a deepcopy of the distribution stored in ``self._distribution`` is returned.
Setup:
- create an instance of a ``GaussianNormalizer`` with ``distribution`` set
to ``univariate.Univariate``.
Output:
- a copy of the value stored in ``self._distribution``.
"""
# Setup
distribution = copulas.univariate.BetaUnivariate()
ct = GaussianNormalizer(distribution=distribution)
# Run
univariate = ct._get_univariate()
# Assert
assert univariate is not distribution
assert isinstance(univariate, copulas.univariate.Univariate)
assert dir(univariate) == dir(distribution)
def test__get_univariate_tuple(self):
"""Test the ``_get_univariate`` method when the distribution is a tuple.
When the distribution is passed as a tuple, it should return an instance
with the passed arguments.
Setup:
- create an instance of a ``GaussianNormalizer`` and set
``distribution`` to a tuple.
Output:
- an instance of ``copulas.univariate.Univariate`` with the passed arguments.
"""
# Setup
distribution = (
copulas.univariate.Univariate,
{'candidates': 'a_candidates_list'},
)
ct = GaussianNormalizer(distribution=distribution)
# Run
univariate = ct._get_univariate()
# Assert
assert isinstance(univariate, copulas.univariate.Univariate)
assert univariate.candidates == 'a_candidates_list'
def test__get_univariate_class(self):
"""Test the ``_get_univariate`` method when the distribution is a class.
When ``distribution`` is passed as a class, it should return an instance
without passing arguments.
Setup:
- create an instance of a ``GaussianNormalizer`` and set ``distribution``
to ``univariate.Univariate``.
Output:
- an instance of ``copulas.univariate.Univariate`` without any arguments.
"""
# Setup
distribution = copulas.univariate.BetaUnivariate
ct = GaussianNormalizer(distribution=distribution)
# Run
univariate = ct._get_univariate()
# Assert
assert isinstance(univariate, copulas.univariate.Univariate)
def test__get_univariate_error(self):
"""Test the ``_get_univariate`` method when ``distribution`` is invalid.
Validate that it raises an error if an invalid distribution is stored in
``distribution``.
Setup:
- create an instance of a ``GaussianNormalizer`` and set ``self._distribution``
improperly.
Raise:
- TypeError(f'Invalid distribution: {distribution}')
"""
# Setup
distribution = 123
ct = GaussianNormalizer(distribution=distribution)
# Run / Assert
with pytest.raises(TypeError):
ct._get_univariate()
def test__fit(self):
"""Test the ``_fit`` method.
Validate that ``_fit`` calls ``_get_univariate``.
Setup:
- create an instance of the ``GaussianNormalizer``.
- mock the ``_get_univariate`` method.
Input:
- a pandas series of float values.
Side effect:
- call the `_get_univariate`` method.
"""
# Setup
data = pd.Series([0.0, np.nan, 1.0])
ct = GaussianNormalizer()
ct._get_univariate = Mock()
# Run