forked from facebookresearch/balance
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_stats_and_plots.py
More file actions
3502 lines (2962 loc) · 134 KB
/
test_stats_and_plots.py
File metadata and controls
3502 lines (2962 loc) · 134 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
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from __future__ import annotations
import warnings
from typing import Any, cast
import balance.testutil
import numpy as np
import pandas as pd
from balance.sample_class import Sample
from balance.stats_and_plots import weighted_comparisons_stats
from balance.util import _assert_type
class TestBalance_weights_stats(
balance.testutil.BalanceTestCase,
):
def test__check_weights_are_valid(self) -> None:
"""Test validation of weight arrays for statistical calculations.
Verifies that _check_weights_are_valid correctly validates different
weight input formats (list, numpy array, pandas Series/DataFrame)
and raises appropriate errors for invalid inputs like negative weights
or non-numeric values.
"""
from balance.stats_and_plots.weights_stats import _check_weights_are_valid
w = [np.inf, 1, 2, 1.0, 0]
# Test various valid input formats
self.assertEqual(_check_weights_are_valid(w), None)
self.assertEqual(_check_weights_are_valid(np.array(w)), None)
self.assertEqual(_check_weights_are_valid(pd.Series(w)), None)
self.assertEqual(_check_weights_are_valid(pd.DataFrame(w)), None)
self.assertEqual(_check_weights_are_valid(pd.DataFrame({"a": w})), None)
self.assertEqual(
_check_weights_are_valid(pd.DataFrame({"a": w, "b": [str(x) for x in w]})),
None,
) # checking only the first column
# Test invalid weight types
with self.assertRaisesRegex(TypeError, "weights \\(w\\) must be a number.*"):
_check_weights_are_valid([str(x) for x in w])
with self.assertRaisesRegex(TypeError, "weights \\(w\\) must be a number.*"):
invalid_w = ["a", "b"]
_check_weights_are_valid(invalid_w)
# Test invalid weight values (negative)
with self.assertRaisesRegex(
ValueError, "weights \\(w\\) must all be non-negative values."
):
negative_w = [-1, 0, 1]
_check_weights_are_valid(negative_w)
# Test invalid weights (all zeros) when positive weights are required
with self.assertRaisesRegex(
ValueError, "weights \\(w\\) must include at least one positive value."
):
zero_w = [0, 0, 0]
_check_weights_are_valid(zero_w, require_positive=True)
# Zeros are allowed when positive weights are not required
self.assertEqual(_check_weights_are_valid([0, 0, 0]), None)
# Empty weights should fail as non-numeric inputs
with self.assertRaisesRegex(TypeError, "weights \\(w\\) must be a number.*"):
_check_weights_are_valid([], require_positive=True)
# All-NaN weights should fail when positive weights are required
with self.assertRaisesRegex(
ValueError, "weights \\(w\\) must include at least one positive value."
):
_check_weights_are_valid([np.nan, np.nan], require_positive=True)
# DataFrame with no columns should fail fast with a clear error
with self.assertRaisesRegex(
TypeError, "weights \\(w\\) DataFrame must include at least one column."
):
_check_weights_are_valid(pd.DataFrame(index=[0, 1]))
# Validation should always use first DataFrame column, even if later columns are valid
with self.assertRaisesRegex(TypeError, "weights \\(w\\) must be a number.*"):
_check_weights_are_valid(
pd.DataFrame(
{
"bad_first": ["a", "b", "c"],
"good_second": [1.0, 2.0, 3.0],
}
)
)
def test_design_effect(self) -> None:
"""Test calculation of design effect for weighted samples.
Design effect measures the loss of precision due to weighting.
Tests with equal weights (design effect = 1) and unequal weights
to verify correct calculation and return type.
"""
from balance.stats_and_plots.weights_stats import design_effect
self.assertEqual(design_effect(pd.Series((1, 1, 1, 1))), 1)
self.assertEqual(
design_effect(pd.Series((0, 1, 2, 3))),
1.555_555_555_555_555_6,
)
self.assertEqual(type(design_effect(pd.Series((0, 1, 2, 3)))), np.float64)
with self.assertRaisesRegex(
ValueError, "weights \\(w\\) must include at least one positive value."
):
design_effect(pd.Series((0, 0, 0)))
def test_nonparametric_skew(self) -> None:
"""Test calculation of nonparametric skewness measure.
Tests skewness calculation for various distributions including
symmetric (skew = 0), single values, and right-skewed distributions
to verify correct nonparametric skewness computation.
"""
from balance.stats_and_plots.weights_stats import nonparametric_skew
self.assertEqual(nonparametric_skew(pd.Series((1, 1, 1, 1))), 0)
self.assertEqual(nonparametric_skew(pd.Series((1))), 0)
self.assertEqual(nonparametric_skew(pd.Series((1, 2, 3, 4))), 0)
self.assertEqual(nonparametric_skew(pd.Series((1, 1, 1, 2))), 0.5)
def test_prop_above_and_below(self) -> None:
"""Test calculation of proportions above and below thresholds.
Tests the prop_above_and_below function with default thresholds,
custom thresholds, and different return formats to ensure correct
proportion calculations and proper handling of edge cases.
"""
from balance.stats_and_plots.weights_stats import prop_above_and_below
# Test with identical values
result1 = prop_above_and_below(pd.Series((1, 1, 1, 1)))
self.assertIsNotNone(result1)
result1 = _assert_type(result1, pd.Series) # Type narrowing for pyre
self.assertEqual(
result1.astype(int).to_list(),
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
)
# Test with varying values
result2 = prop_above_and_below(pd.Series((1, 2, 3, 4)))
self.assertIsNotNone(result2)
result2 = _assert_type(result2, pd.Series) # Type narrowing for pyre
self.assertEqual(
result2.to_list(),
[0.0, 0.0, 0.0, 0.25, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0],
)
# Test custom thresholds
result = prop_above_and_below(
pd.Series((1, 2, 3, 4)), below=(0.1, 0.5), above=(2, 3)
)
self.assertIsNotNone(result)
result = _assert_type(result, pd.Series) # Type narrowing for pyre
self.assertEqual(result.to_list(), [0.0, 0.25, 0.0, 0.0])
self.assertEqual(
result.index.to_list(),
["prop(w < 0.1)", "prop(w < 0.5)", "prop(w >= 2)", "prop(w >= 3)"],
)
# Test with None parameters
self.assertEqual(
prop_above_and_below(pd.Series((1, 2, 3, 4)), above=None, below=None), None
)
# Test with only below=None
result_only_above = prop_above_and_below(
pd.Series((1, 2, 3, 4)), above=(1, 2), below=None
)
self.assertIsNotNone(result_only_above)
result_only_above = _assert_type(result_only_above, pd.Series)
# Should only have above values, no below values
self.assertEqual(len(result_only_above), 2)
self.assertTrue(
all(
"above" in str(idx) or "prop(w >=" in idx
for idx in result_only_above.index
)
)
# Test with only above=None
result_only_below = prop_above_and_below(
pd.Series((1, 2, 3, 4)), above=None, below=(0.5, 1)
)
self.assertIsNotNone(result_only_below)
result_only_below = _assert_type(result_only_below, pd.Series)
# Should only have below values, no above values
self.assertEqual(len(result_only_below), 2)
self.assertTrue(
all(
"below" in str(idx) or "prop(w <" in idx
for idx in result_only_below.index
)
)
# Test return_as_series = False
result_dict = prop_above_and_below(
pd.Series((1, 2, 3, 4)), return_as_series=False
)
self.assertIsNotNone(result_dict)
result_dict = _assert_type(result_dict)
expected = {
"below": [0.0, 0.0, 0.0, 0.25, 0.5],
"above": [0.5, 0.0, 0.0, 0.0, 0.0],
}
self.assertEqual({k: v.to_list() for k, v in result_dict.items()}, expected)
def test_prop_above_and_below_edge_cases(self) -> None:
"""Cover edge combinations for thresholds and return formats."""
from balance.stats_and_plots.weights_stats import prop_above_and_below
weights = pd.Series((1.0, 2.0, 3.0, 4.0))
# Empty threshold iterables should return an empty Series in series mode.
result_empty = prop_above_and_below(weights, below=(), above=())
self.assertIsNotNone(result_empty)
result_empty = _assert_type(result_empty, pd.Series)
self.assertEqual(result_empty.to_list(), [])
self.assertEqual(result_empty.index.to_list(), [])
# Dict mode should preserve None for omitted threshold groups.
result_dict_only_above = prop_above_and_below(
weights,
below=None,
above=(1, 2),
return_as_series=False,
)
self.assertIsNotNone(result_dict_only_above)
result_dict_only_above = _assert_type(result_dict_only_above)
self.assertIsNone(result_dict_only_above["below"])
self.assertEqual(
result_dict_only_above["above"].index.to_list(),
["prop(w >= 1)", "prop(w >= 2)"],
)
result_dict_only_below = prop_above_and_below(
weights,
below=(0.5, 1),
above=None,
return_as_series=False,
)
self.assertIsNotNone(result_dict_only_below)
result_dict_only_below = _assert_type(result_dict_only_below)
self.assertEqual(
result_dict_only_below["below"].index.to_list(),
["prop(w < 0.5)", "prop(w < 1)"],
)
self.assertIsNone(result_dict_only_below["above"])
# If both groups are omitted, function should return None in all modes.
self.assertIsNone(
prop_above_and_below(
weights,
below=None,
above=None,
return_as_series=False,
)
)
def test_weights_diagnostics_accept_list_and_ndarray_input(self) -> None:
"""Ensure diagnostics are equivalent across list/ndarray/Series inputs."""
from balance.stats_and_plots.weights_stats import (
design_effect,
nonparametric_skew,
prop_above_and_below,
weighted_median_breakdown_point,
)
w_list = [1.0, 2.0, 3.0, 4.0]
w_array = np.array(w_list)
w_series = pd.Series(w_list)
self.assertEqual(design_effect(w_list), design_effect(w_series))
self.assertEqual(design_effect(w_array), design_effect(w_series))
self.assertEqual(nonparametric_skew(w_list), nonparametric_skew(w_series))
self.assertEqual(nonparametric_skew(w_array), nonparametric_skew(w_series))
self.assertEqual(
weighted_median_breakdown_point(w_list),
weighted_median_breakdown_point(w_series),
)
self.assertEqual(
weighted_median_breakdown_point(w_array),
weighted_median_breakdown_point(w_series),
)
list_prop = prop_above_and_below(w_list)
array_prop = prop_above_and_below(w_array)
series_prop = prop_above_and_below(w_series)
self.assertIsNotNone(list_prop)
self.assertIsNotNone(array_prop)
self.assertIsNotNone(series_prop)
pd.testing.assert_series_equal(
_assert_type(list_prop, pd.Series), _assert_type(series_prop, pd.Series)
)
pd.testing.assert_series_equal(
_assert_type(array_prop, pd.Series), _assert_type(series_prop, pd.Series)
)
def test_weights_diagnostics_dataframe_first_column_errors(self) -> None:
"""Ensure diagnostics consistently evaluate the first DataFrame column only."""
from balance.stats_and_plots.weights_stats import (
design_effect,
nonparametric_skew,
prop_above_and_below,
weighted_median_breakdown_point,
)
bad_first_col_df = pd.DataFrame(
{
"bad_first": ["a", "b", "c"],
"good_second": [1.0, 2.0, 3.0],
}
)
for fn in (
design_effect,
nonparametric_skew,
prop_above_and_below,
weighted_median_breakdown_point,
):
with self.assertRaisesRegex(
TypeError, "weights \\(w\\) must be a number.*"
):
fn(bad_first_col_df)
empty_df = pd.DataFrame(index=[0, 1])
for fn in (
design_effect,
nonparametric_skew,
prop_above_and_below,
weighted_median_breakdown_point,
):
with self.assertRaisesRegex(
TypeError,
"weights \\(w\\) DataFrame must include at least one column.",
):
fn(empty_df)
def test_weights_diagnostics_accept_dataframe_input(self) -> None:
"""Ensure weight diagnostics consume DataFrame input via first column."""
from balance.stats_and_plots.weights_stats import (
design_effect,
nonparametric_skew,
prop_above_and_below,
weighted_median_breakdown_point,
)
w_series = pd.Series((1.0, 2.0, 3.0, 4.0), name="weights")
w_df = pd.DataFrame(
{
"weights": w_series,
# This second column should be ignored by diagnostic helpers.
"other": (100.0, 100.0, 100.0, 100.0),
}
)
self.assertEqual(design_effect(w_df), design_effect(w_series))
self.assertEqual(nonparametric_skew(w_df), nonparametric_skew(w_series))
self.assertEqual(
weighted_median_breakdown_point(w_df),
weighted_median_breakdown_point(w_series),
)
df_prop = prop_above_and_below(w_df)
series_prop = prop_above_and_below(w_series)
self.assertIsNotNone(df_prop)
self.assertIsNotNone(series_prop)
pd.testing.assert_series_equal(
_assert_type(df_prop, pd.Series),
_assert_type(series_prop, pd.Series),
)
class TestImpactOfWeightsOnOutcome(
balance.testutil.BalanceTestCase,
):
def test_weights_impact_on_outcome_ss(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
weights_impact_on_outcome_ss,
)
y = pd.Series([1.0, 2.0, 3.0, 4.0])
w0 = pd.Series([1.0, 1.0, 1.0, 1.0])
w1 = pd.Series([1.0, 2.0, 1.0, 2.0])
result = weights_impact_on_outcome_ss(y, w0, w1, method="t_test")
self.assertAlmostEqual(result["mean_yw0"], 2.5)
self.assertAlmostEqual(result["mean_yw1"], 8 / 3)
self.assertAlmostEqual(result["mean_diff"], 1 / 6)
self.assertLess(result["diff_ci_lower"], result["mean_diff"])
self.assertGreater(result["diff_ci_upper"], result["mean_diff"])
def test_weights_impact_on_outcome_ss_length_mismatch(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
weights_impact_on_outcome_ss,
)
with self.assertRaisesRegex(
ValueError, "Outcome and weights must have the same number of observations."
):
weights_impact_on_outcome_ss([1.0, 2.0], [1.0], [1.0, 1.0])
def test_weights_impact_on_outcome_ss_invalid_method(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
weights_impact_on_outcome_ss,
)
with self.assertRaisesRegex(ValueError, "Unsupported method"):
weights_impact_on_outcome_ss(
[1.0, 2.0], [1.0, 1.0], [1.0, 1.0], method="bad"
)
def test_weights_impact_on_outcome_ss_invalid_conf_level(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
weights_impact_on_outcome_ss,
)
with self.assertRaisesRegex(ValueError, "conf_level must be between 0 and 1."):
weights_impact_on_outcome_ss(
[1.0, 2.0], [1.0, 1.0], [1.0, 1.0], conf_level=1.0
)
with self.assertRaisesRegex(ValueError, "conf_level must be between 0 and 1."):
weights_impact_on_outcome_ss(
[1.0, 2.0], [1.0, 1.0], [1.0, 1.0], conf_level=0.0
)
def test_weights_impact_on_outcome_ss_requires_finite_values(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
weights_impact_on_outcome_ss,
)
with self.assertRaisesRegex(
ValueError, "Outcome and weights must contain at least one finite value."
):
weights_impact_on_outcome_ss([float("inf")], [float("inf")], [float("inf")])
def test_weights_impact_on_outcome_ss_single_observation(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
weights_impact_on_outcome_ss,
)
result = weights_impact_on_outcome_ss([1.0], [1.0], [2.0])
self.assertTrue(np.isnan(result["diff_ci_lower"]))
self.assertTrue(np.isnan(result["diff_ci_upper"]))
def test_weights_impact_on_outcome_ss_scalar_invariance(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
weights_impact_on_outcome_ss,
)
y = pd.Series([1.0, 2.0, 3.0, 4.0])
w0 = pd.Series([1.0, 1.0, 1.0, 1.0])
w1 = pd.Series([1.0, 2.0, 1.0, 2.0])
result_base = weights_impact_on_outcome_ss(y, w0, w1, method="t_test")
result_scaled = weights_impact_on_outcome_ss(
y, w0 * 5, w1 * 10, method="t_test"
)
self.assertAlmostEqual(result_base["mean_yw0"], result_scaled["mean_yw0"])
self.assertAlmostEqual(result_base["mean_yw1"], result_scaled["mean_yw1"])
self.assertAlmostEqual(result_base["mean_diff"], result_scaled["mean_diff"])
self.assertAlmostEqual(
result_base["diff_ci_lower"], result_scaled["diff_ci_lower"]
)
self.assertAlmostEqual(
result_base["diff_ci_upper"], result_scaled["diff_ci_upper"]
)
def test_compare_adjusted_weighted_outcome_ss(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
sample = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2, 3],
"x": [0.1, 0.2, 0.3],
"weight": [1.0, 1.0, 1.0],
"outcome": [1.0, 2.0, 3.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
)
target = Sample.from_frame(
pd.DataFrame(
{
"id": [4, 5, 6],
"x": [0.1, 0.2, 0.3],
"weight": [1.0, 1.0, 1.0],
"outcome": [1.0, 2.0, 3.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
)
adjusted0 = sample.set_target(target).adjust(method="null")
adjusted1 = sample.set_target(target).adjust(method="null")
impact = compare_adjusted_weighted_outcome_ss(adjusted0, adjusted1)
self.assertIn("mean_diff", impact.columns)
self.assertEqual(list(impact.index), ["outcome"])
def test_compare_adjusted_weighted_outcome_ss_invalid_inputs(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
with self.assertRaisesRegex(
ValueError, "compare_adjusted_weighted_outcome_ss expects Sample inputs."
):
compare_adjusted_weighted_outcome_ss("nope", "nope") # type: ignore[arg-type]
def test_compare_adjusted_weighted_outcome_ss_missing_outcomes(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
sample = Sample.from_frame(
pd.DataFrame({"id": [1, 2], "x": [0.1, 0.2], "weight": [1.0, 1.0]}),
id_column="id",
weight_column="weight",
standardize_types=False,
)
target = Sample.from_frame(
pd.DataFrame({"id": [1, 2], "x": [0.1, 0.2], "weight": [1.0, 1.0]}),
id_column="id",
weight_column="weight",
standardize_types=False,
)
adjusted0 = sample.set_target(target).adjust(method="null")
adjusted1 = sample.set_target(target).adjust(method="null")
with self.assertRaisesRegex(ValueError, "Both Samples must include outcomes."):
compare_adjusted_weighted_outcome_ss(adjusted0, adjusted1)
def test_compare_adjusted_weighted_outcome_ss_mismatched_outcomes(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
sample = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
sample_alt = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome_alt": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome_alt",),
standardize_types=False,
)
target_alt = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome_alt": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome_alt",),
standardize_types=False,
)
adjusted0 = sample.set_target(target).adjust(method="null")
adjusted1 = sample_alt.set_target(target_alt).adjust(method="null")
with self.assertRaisesRegex(
ValueError, "Outcome columns must match between adjusted Samples."
):
compare_adjusted_weighted_outcome_ss(adjusted0, adjusted1)
def test_compare_adjusted_weighted_outcome_ss_duplicate_ids(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
sample = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 1],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
check_id_uniqueness=False,
standardize_types=False,
)
target = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 1],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
check_id_uniqueness=False,
standardize_types=False,
)
adjusted0 = sample.set_target(target).adjust(method="null")
adjusted1 = sample.set_target(target).adjust(method="null")
with self.assertRaisesRegex(
ValueError, "Samples must have unique ids to compare outcomes."
):
compare_adjusted_weighted_outcome_ss(adjusted0, adjusted1)
def test_compare_adjusted_weighted_outcome_ss_no_common_ids(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
sample_a = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target_a = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
sample_b = Sample.from_frame(
pd.DataFrame(
{
"id": [3, 4],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target_b = Sample.from_frame(
pd.DataFrame(
{
"id": [3, 4],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
adjusted0 = sample_a.set_target(target_a).adjust(method="null")
adjusted1 = sample_b.set_target(target_b).adjust(method="null")
with self.assertRaisesRegex(ValueError, "Samples do not share any common ids."):
compare_adjusted_weighted_outcome_ss(adjusted0, adjusted1)
def test_compare_adjusted_weighted_outcome_ss_outcome_mismatch(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
sample_a = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target_a = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
sample_b = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [10.0, 20.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target_b = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [10.0, 20.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
adjusted0 = sample_a.set_target(target_a).adjust(method="null")
adjusted1 = sample_b.set_target(target_b).adjust(method="null")
with self.assertRaisesRegex(
ValueError, "Outcome values differ between adjusted Samples for common ids."
):
compare_adjusted_weighted_outcome_ss(adjusted0, adjusted1)
def test_compare_adjusted_weighted_outcome_ss_missing_weights(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
compare_adjusted_weighted_outcome_ss,
)
sample = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
adjusted0 = sample.set_target(target).adjust(method="null")
adjusted1 = sample.set_target(target).adjust(method="null")
adjusted1.set_weights(pd.Series([np.nan, np.nan], index=adjusted1.df.index))
with self.assertRaisesRegex(
ValueError,
"Samples do not share any common ids with non-missing weights in adjusted1.",
):
compare_adjusted_weighted_outcome_ss(adjusted0, adjusted1)
def test_validate_adjusted_samples_not_adjusted(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
_validate_adjusted_samples,
)
sample = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target = Sample.from_frame(
pd.DataFrame(
{
"id": [3, 4],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
adjusted = sample.set_target(target).adjust(method="null")
with self.assertRaisesRegex(ValueError, "This is not an adjusted Sample"):
_validate_adjusted_samples(sample, adjusted)
with self.assertRaisesRegex(ValueError, "This is not an adjusted Sample"):
_validate_adjusted_samples(adjusted, sample)
def test_validate_adjusted_samples_success(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
_validate_adjusted_samples,
)
sample = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target = Sample.from_frame(
pd.DataFrame(
{
"id": [3, 4],
"x": [0.1, 0.2],
"weight": [1.0, 1.0],
"outcome": [1.0, 2.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
adjusted0 = sample.set_target(target).adjust(method="null")
adjusted1 = sample.set_target(target).adjust(method="null")
y0, y1 = _validate_adjusted_samples(adjusted0, adjusted1)
self.assertIsInstance(y0, pd.DataFrame)
self.assertIsInstance(y1, pd.DataFrame)
self.assertEqual(list(y0.columns), list(y1.columns))
self.assertIn("outcome", y0.columns)
def test_align_samples_by_id_success(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
_align_samples_by_id,
_validate_adjusted_samples,
)
sample = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2, 3],
"x": [0.1, 0.2, 0.3],
"weight": [1.0, 1.0, 1.0],
"outcome": [1.0, 2.0, 3.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target = Sample.from_frame(
pd.DataFrame(
{
"id": [4, 5, 6],
"x": [0.1, 0.2, 0.3],
"weight": [1.0, 1.0, 1.0],
"outcome": [1.0, 2.0, 3.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
adjusted0 = sample.set_target(target).adjust(method="null")
adjusted1 = sample.set_target(target).adjust(method="null")
adjusted1.set_weights(pd.Series([2.0, 3.0, 4.0], index=adjusted1.df.index))
y0, y1 = _validate_adjusted_samples(adjusted0, adjusted1)
y_aligned, w0, w1 = _align_samples_by_id(adjusted0, adjusted1, y0, y1)
self.assertEqual(len(y_aligned), 3)
self.assertEqual(len(w0), 3)
self.assertEqual(len(w1), 3)
np.testing.assert_array_equal(w1, [2.0, 3.0, 4.0])
def test_align_samples_by_id_partial_overlap(self) -> None:
from balance.stats_and_plots.impact_of_weights_on_outcome import (
_align_samples_by_id,
_validate_adjusted_samples,
)
sample_a = Sample.from_frame(
pd.DataFrame(
{
"id": [1, 2, 3],
"x": [0.1, 0.2, 0.3],
"weight": [1.0, 1.0, 1.0],
"outcome": [1.0, 2.0, 3.0],
}
),
id_column="id",
weight_column="weight",
outcome_columns=("outcome",),
standardize_types=False,
)
target_a = Sample.from_frame(
pd.DataFrame(
{
"id": [10, 11, 12],
"x": [0.1, 0.2, 0.3],
"weight": [1.0, 1.0, 1.0],
"outcome": [1.0, 2.0, 3.0],