forked from facebookresearch/balance
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
1949 lines (1739 loc) · 73.1 KB
/
test_cli.py
File metadata and controls
1949 lines (1739 loc) · 73.1 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 os.path
import tempfile
import warnings
from argparse import Namespace
from typing import Any
import balance.testutil
import numpy as np
import pandas as pd
from balance.cli import BalanceCLI, make_parser
from balance.util import _assert_type, _float_or_none
from numpy import dtype
from sklearn.linear_model import LogisticRegression
# Test constants
SAMPLE_SIZE_SMALL = 1000
SAMPLE_SIZE_LARGE = 2000
TEST_SEED = 2021
def check_some_flags(
flag: bool = True, the_flag_str: str = "--skip_standardize_types"
) -> dict[str, pd.DataFrame]:
"""
Helper function to test CLI flags with standardized input data.
Args:
flag: Whether to include the specified flag in CLI arguments
the_flag_str: The CLI flag string to test
Returns:
Dict containing input and output pandas DataFrames for comparison
"""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = (
"x,y,is_respondent,id,weight\n"
+ ("1.0,50,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("2.0,60,0,1,1\n" * SAMPLE_SIZE_SMALL)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
parser = make_parser()
args_to_parse = [
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
]
if flag:
args_to_parse.append(the_flag_str)
args = parser.parse_args(args_to_parse)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
pd_in = pd.read_csv(in_file.name)
pd_out = pd.read_csv(out_file)
return {"pd_in": pd_in, "pd_out": pd_out}
def _create_sample_and_target_data() -> pd.DataFrame:
"""
Helper function to create standardized sample and target datasets for testing.
Returns:
pd.DataFrame: Combined dataset with sample and target data, including
age, gender, id, weight, and is_respondent columns.
"""
np.random.seed(TEST_SEED)
n_sample = SAMPLE_SIZE_SMALL
n_target = SAMPLE_SIZE_LARGE
sample_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_sample),
"gender": np.random.choice((1, 2, 3, 4), n_sample),
"id": range(n_sample),
"weight": pd.Series((1,) * n_sample),
}
)
sample_df["is_respondent"] = True
target_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_target),
"gender": np.random.choice((1, 2, 3, 4), n_target),
"id": range(n_target),
"weight": pd.Series((1,) * n_target),
}
)
target_df["is_respondent"] = False
input_dataset = pd.concat([sample_df, target_df])
return input_dataset
class TestCli(
balance.testutil.BalanceTestCase,
):
def _make_cli(self, **overrides: str | None) -> BalanceCLI:
with tempfile.TemporaryDirectory() as temp_dir:
input_file = os.path.join(temp_dir, "input.csv")
output_file = os.path.join(temp_dir, "output.csv")
parser = make_parser()
args_to_parse = [
"--input_file",
input_file,
"--output_file",
output_file,
"--covariate_columns",
"covar_a,covar_b",
]
if overrides.get("outcome_columns") is not None:
args_to_parse.extend(
["--outcome_columns", str(overrides["outcome_columns"])]
)
args = parser.parse_args(args_to_parse)
return BalanceCLI(args)
def _make_batch_df(self) -> pd.DataFrame:
return pd.DataFrame(
{
"is_respondent": [1, 0],
"id": [1, 2],
"weight": [1.0, 1.0],
"covar_a": [1.0, 2.0],
"covar_b": [3.0, 4.0],
"outcome_b": [10.0, 20.0],
"outcome_a": [30.0, 40.0],
"extra": [5.0, 6.0],
}
)
def _recording_sample_cls(self) -> type[Any]:
class RecordingSample:
calls: list[tuple[str, ...] | None] = []
ignore_calls: list[list[str] | None] = []
def __init__(self, df: pd.DataFrame) -> None:
self.df = df
self._df_dtypes = df.dtypes
@classmethod
def from_frame(
cls,
df: pd.DataFrame,
id_column: str | None = None,
weight_column: str | None = None,
outcome_columns: tuple[str, ...] | None = None,
ignore_columns: list[str] | None = None,
**kwargs: object,
) -> "RecordingSample":
cls.calls.append(outcome_columns)
cls.ignore_calls.append(ignore_columns)
return cls(df)
def set_target(self, target: "RecordingSample") -> "RecordingSample":
return self
def adjust(self, **kwargs: object) -> "RecordingSample":
return self
def keep_only_some_rows_columns(
self,
rows_to_keep: str | None = None,
columns_to_keep: list[str] | None = None,
) -> "RecordingSample":
return self
def diagnostics(
self, weights_impact_on_outcome_method: str | None = "t_test"
) -> pd.DataFrame:
return pd.DataFrame()
return RecordingSample
def test_cli_unmentioned_columns_go_to_ignore(self) -> None:
RecordingSample = self._recording_sample_cls()
cli = self._make_cli()
cli.process_batch(
self._make_batch_df(),
sample_cls=RecordingSample,
sample_package_name="recording",
)
self.assertEqual(
RecordingSample.calls,
[None, None],
)
self.assertEqual(
RecordingSample.ignore_calls,
[
["is_respondent", "outcome_b", "outcome_a", "extra"],
["is_respondent", "outcome_b", "outcome_a", "extra"],
],
)
def test_cli_outcome_columns_explicit_selection(self) -> None:
RecordingSample = self._recording_sample_cls()
cli = self._make_cli(outcome_columns="outcome_a,outcome_b")
cli.process_batch(
self._make_batch_df(),
sample_cls=RecordingSample,
sample_package_name="recording",
)
self.assertEqual(
RecordingSample.calls,
[("outcome_a", "outcome_b"), ("outcome_a", "outcome_b")],
)
self.assertEqual(
RecordingSample.ignore_calls,
[["is_respondent", "extra"], ["is_respondent", "extra"]],
)
def test_cli_outcome_columns_missing_column_raises(self) -> None:
cli = self._make_cli(outcome_columns="missing")
with self.assertRaises(AssertionError):
cli.check_input_columns(self._make_batch_df().columns)
def test_cli_weights_impact_on_outcome_method(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
input_file = os.path.join(temp_dir, "input.csv")
output_file = os.path.join(temp_dir, "output.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file,
"--output_file",
output_file,
"--covariate_columns",
"covar_a,covar_b",
"--weights_impact_on_outcome_method",
"t_test",
]
)
cli = BalanceCLI(args)
self.assertEqual(cli.weights_impact_on_outcome_method(), "t_test")
args_default = parser.parse_args(
[
"--input_file",
input_file,
"--output_file",
output_file,
"--covariate_columns",
"covar_a,covar_b",
]
)
cli_default = BalanceCLI(args_default)
self.assertEqual(cli_default.weights_impact_on_outcome_method(), "t_test")
args_none = parser.parse_args(
[
"--input_file",
input_file,
"--output_file",
output_file,
"--covariate_columns",
"covar_a,covar_b",
"--weights_impact_on_outcome_method",
"none",
]
)
cli_none = BalanceCLI(args_none)
self.assertIsNone(cli_none.weights_impact_on_outcome_method())
def test_process_batch_returns_failure_payload_for_empty_sample(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
input_file = os.path.join(temp_dir, "input.csv")
output_file = os.path.join(temp_dir, "output.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file,
"--output_file",
output_file,
"--sample_column",
"is_respondent",
"--covariate_columns",
"x",
]
)
cli = BalanceCLI(args)
batch_df = pd.DataFrame(
{
"is_respondent": [0, 0],
"id": [1, 2],
"weight": [1.0, 1.0],
"x": [1.0, 2.0],
}
)
result = cli.process_batch(batch_df)
self.assertTrue(result["adjusted"].empty)
self.assertEqual(
result["diagnostics"].to_dict("records"),
[
{
"metric": "adjustment_failure",
"var": None,
"val": 1,
},
{
"metric": "adjustment_failure_reason",
"var": None,
"val": "No input data",
},
],
)
def test_load_and_check_input_reads_file_and_columns(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
input_file = os.path.join(temp_dir, "input.csv")
output_file = os.path.join(temp_dir, "output.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file,
"--output_file",
output_file,
"--sample_column",
"is_respondent",
"--covariate_columns",
"x",
"--keep_row_column",
"keep",
]
)
cli = BalanceCLI(args)
input_df = pd.DataFrame(
{
"is_respondent": [1, 0],
"id": [1, 2],
"weight": [1.0, 1.0],
"x": [1.0, 2.0],
"keep": [1, 0],
}
)
input_df.to_csv(input_file, index=False)
loaded = cli.load_and_check_input()
pd.testing.assert_frame_equal(loaded, input_df)
def test_write_outputs_skips_diagnostics_when_no_output_path(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
input_file = os.path.join(temp_dir, "input.csv")
output_file = os.path.join(temp_dir, "output.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file,
"--output_file",
output_file,
"--sample_column",
"is_respondent",
"--covariate_columns",
"x",
]
)
cli = BalanceCLI(args)
output_df = pd.DataFrame({"id": [1], "weight": [1.25]})
diagnostics_df = pd.DataFrame(
{"metric": ["adjustment_failure"], "var": [None], "val": [0]}
)
cli.write_outputs(output_df, diagnostics_df)
pd.testing.assert_frame_equal(
pd.read_csv(output_file, sep=","),
output_df,
)
self.assertIsNone(cli.args.diagnostics_output_file)
def test_cli_help(self) -> None:
"""Test that CLI help command executes without errors."""
parser = make_parser()
try:
parser.parse_args(["--help"])
# If we get here, something is wrong - help should have exited
self.fail("Expected SystemExit when parsing --help")
except SystemExit as e:
# Help command should exit with code 0
self.assertEqual(e.code, 0)
def test_cli_float_or_none(self) -> None:
"""Test the _float_or_none utility function with various inputs."""
self.assertEqual(_float_or_none(None), None)
self.assertEqual(_float_or_none("None"), None)
self.assertEqual(_float_or_none("13.37"), 13.37)
def test_cli_builds_logistic_regression_model(self) -> None:
"""Ensure CLI JSON kwargs are parsed into a configured LogisticRegression."""
args = Namespace(
ipw_logistic_regression_kwargs='{"solver": "liblinear", "max_iter": 321}',
method="ipw",
)
cli = BalanceCLI(args)
kwargs = cli.logistic_regression_kwargs()
assert kwargs is not None
self.assertEqual(kwargs["solver"], "liblinear")
self.assertEqual(kwargs["max_iter"], 321)
model = _assert_type(cli.logistic_regression_model())
self.assertIsInstance(model, LogisticRegression)
if isinstance(model, LogisticRegression):
self.assertEqual(model.solver, "liblinear")
self.assertEqual(model.max_iter, 321)
def test_cli_omits_logistic_regression_model_without_kwargs(self) -> None:
"""No kwargs should result in no model being constructed."""
cli = BalanceCLI(Namespace(ipw_logistic_regression_kwargs=None, method="ipw"))
self.assertIsNone(cli.logistic_regression_model())
def test_cli_rejects_non_mapping_logistic_regression_kwargs(self) -> None:
"""Invalid JSON structures should raise clear errors."""
cli = BalanceCLI(Namespace(ipw_logistic_regression_kwargs="[]", method="ipw"))
with self.assertRaises(ValueError):
cli.logistic_regression_kwargs()
def test_cli_accepts_mapping_logistic_regression_kwargs(self) -> None:
"""Dict inputs are forwarded directly without JSON parsing."""
cli = BalanceCLI(
Namespace(
ipw_logistic_regression_kwargs={"solver": "saga", "max_iter": 100},
method="ipw",
)
)
kwargs = cli.logistic_regression_kwargs()
assert kwargs is not None
self.assertEqual(kwargs["solver"], "saga")
self.assertEqual(kwargs["max_iter"], 100)
def test_cli_succeed_on_weighting_failure(self) -> None:
"""Test CLI behavior when weighting fails but succeed_on_weighting_failure flag is set."""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = "x,y,is_respondent,id,weight\na,b,1,1,1\na,b,0,1,1"
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--covariate_columns",
"x,y",
"--succeed_on_weighting_failure",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
def test_cli_works(self) -> None:
"""Test basic CLI functionality with sample data and diagnostics output."""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = (
"x,y,is_respondent,id,weight\n"
+ ("a,b,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("c,b,0,1,1\n" * SAMPLE_SIZE_SMALL)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
def test_cli_works_with_row_column_filters(self) -> None:
"""Test CLI functionality with row and column filtering for diagnostics."""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = (
"x,y,z,is_respondent,id,weight\n"
+ ("a,b,g,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("c,b,g,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("c,b,g,0,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("a,d,n,1,2,1\n" * SAMPLE_SIZE_SMALL)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--rows_to_keep_for_diagnostics",
"z == 'g'", # filtering condition
"--covariate_columns_for_diagnostics",
"x,y", # ignoring z
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name)
pd_out_file = pd.read_csv(out_file)
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file)
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on only 2k panelists (as required from the condition)
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"].iloc[0]), 2000)
# verify we get diagnostics only for x and y, and not z
ss = pd_diagnostics_out_file.eval("metric == 'covar_main_asmd_adjusted'")
output = pd_diagnostics_out_file[ss]["var"].to_list()
expected = ["x", "y", "mean(asmd)"]
self.assertEqual(output, expected)
def test_cli_empty_input(self) -> None:
"""Test CLI behavior with empty input data (header only)."""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = "x,y,is_respondent,id,weight\n"
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
def test_cli_empty_input_keep_row(self) -> None:
"""Test CLI behavior with empty input data when using keep_row and batch_columns."""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = "x,y,is_respondent,id,weight,keep_row,batch_column\n"
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y",
"--keep_row",
"keep_row",
"--batch_columns",
"batch_column",
]
)
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
def test_cli_sep_works(self) -> None:
"""Test CLI functionality with custom output file separators."""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = (
"x,y,z,is_respondent,id,weight\n"
+ ("a,b,g,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("c,b,g,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("c,b,g,0,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("a,d,n,1,2,1\n" * SAMPLE_SIZE_SMALL)
)
in_file.write(in_contents)
in_file.close()
# pd.read_csv(in_file)
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--sep_output_file",
";",
"--sep_diagnostics_output_file",
";",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name)
pd_out_file = pd.read_csv(out_file, sep=";")
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file, sep=";")
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on all 3k panelists
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"].iloc[0]), 3000)
def test_cli_sep_input_works(self) -> None:
"""Test CLI functionality with custom input file separators (TSV)."""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".tsv", delete=False) as in_file,
):
in_contents = (
"x\ty\tz\tis_respondent\tid\tweight\n"
+ ("a\tb\tg\t1\t1\t1\n" * SAMPLE_SIZE_SMALL)
+ ("c\tb\tg\t1\t1\t1\n" * SAMPLE_SIZE_SMALL)
+ ("c\tb\tg\t0\t1\t1\n" * SAMPLE_SIZE_SMALL)
+ ("a\td\tn\t1\t2\t1\n" * SAMPLE_SIZE_SMALL)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
in_file.name,
"--output_file",
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--sep_input_file",
"\t",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name, sep="\t")
pd_out_file = pd.read_csv(out_file)
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file)
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on all 3k panelists
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"].iloc[0]), 3000)
def test_cli_short_arg_names_works(self) -> None:
"""
Test CLI backward compatibility with partial argument names.
Some users used only partial arg names for their pipelines.
This test verifies new arguments would still be backward compatible.
"""
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as in_file,
):
in_contents = (
"x,y,z,is_respondent,id,weight\n"
+ ("a,b,g,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("c,b,g,1,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("c,b,g,0,1,1\n" * SAMPLE_SIZE_SMALL)
+ ("a,d,n,1,2,1\n" * SAMPLE_SIZE_SMALL)
)
in_file.write(in_contents)
in_file.close()
out_file = os.path.join(temp_dir, "out.csv")
diagnostics_out_file = os.path.join(temp_dir, "diagnostics_out.csv")
parser = make_parser()
args = parser.parse_args(
[
"--input",
in_file.name,
"--output", # instead of output_file
out_file,
"--diagnostics_output_file",
diagnostics_out_file,
"--covariate_columns",
"x,y,z",
"--sep_output",
";",
"--sep_diagnostics",
";",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
pd_in_file = pd.read_csv(in_file.name)
pd_out_file = pd.read_csv(out_file, sep=";")
pd_diagnostics_out_file = pd.read_csv(diagnostics_out_file, sep=";")
# test stuff
# Make sure we indeed got all the output files
self.assertTrue(os.path.isfile(out_file))
self.assertTrue(os.path.isfile(diagnostics_out_file))
# the original file had 4000 rows (1k target and 3k sample)
self.assertEqual(pd_in_file.shape, (4000, 6))
# the cli output includes only the panel (NOT the target)
# it also includes all the original columns
self.assertEqual(pd_out_file.shape, (3000, 6))
self.assertEqual(pd_out_file.is_respondent.mean(), 1)
# the diagnostics file shows it was calculated on all 3k panelists
ss = pd_diagnostics_out_file.eval(
"(metric == 'size') & (var == 'sample_obs')"
)
self.assertEqual(int(pd_diagnostics_out_file[ss]["val"].iloc[0]), 3000)
def test_method_works(self) -> None:
"""Test CLI functionality with different weighting methods (CBPS and IPW)."""
np.random.seed(TEST_SEED)
n_sample = SAMPLE_SIZE_SMALL
n_target = SAMPLE_SIZE_LARGE
sample_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_sample),
"gender": np.random.choice((1, 2, 3, 4), n_sample),
"id": range(n_sample),
"weight": pd.Series((1,) * n_sample),
}
)
sample_df["is_respondent"] = True
target_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_target),
"gender": np.random.choice((1, 2, 3, 4), n_target),
"id": range(n_target),
"weight": pd.Series((1,) * n_target),
}
)
target_df["is_respondent"] = False
input_dataset = pd.concat([sample_df, target_df])
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as input_file,
):
input_dataset.to_csv(path_or_buf=input_file)
input_file.close()
output_file = os.path.join(temp_dir, "weights_out.csv")
diagnostics_output_file = os.path.join(temp_dir, "diagnostics_out.csv")
features = "age,gender"
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--method=cbps",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "adjustment_method"][
"var"
].values,
np.array(["cbps"]),
)
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--method=ipw",
"--max_de=1.5",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()
cli.main()
# get the files created from cli to pandas to check them
diagnostics_output = pd.read_csv(diagnostics_output_file, sep=",")
self.assertEqual(
diagnostics_output[diagnostics_output["metric"] == "adjustment_method"][
"var"
].values,
np.array(["ipw"]),
)
def test_method_works_with_rake(self) -> None:
"""Test CLI functionality with raking weighting method."""
np.random.seed(TEST_SEED)
n_sample = SAMPLE_SIZE_SMALL
n_target = SAMPLE_SIZE_LARGE
sample_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_sample),
"gender": np.random.choice((1, 2, 3, 4), n_sample),
"id": range(n_sample),
"weight": pd.Series((1,) * n_sample),
}
)
sample_df["is_respondent"] = True
target_df = pd.DataFrame(
{
"age": np.random.uniform(0, 100, n_target),
"gender": np.random.choice((1, 2, 3, 4), n_target),
"id": range(n_target),
"weight": pd.Series((1,) * n_target),
}
)
target_df["is_respondent"] = False
input_dataset = pd.concat([sample_df, target_df])
with (
tempfile.TemporaryDirectory() as temp_dir,
tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False) as input_file,
):
input_dataset.to_csv(path_or_buf=input_file)
input_file.close()
output_file = os.path.join(temp_dir, "weights_out.csv")
diagnostics_output_file = os.path.join(temp_dir, "diagnostics_out.csv")
features = "age,gender"
parser = make_parser()
args = parser.parse_args(
[
"--input_file",
input_file.name,
"--output_file",
output_file,
"--diagnostics_output_file",
diagnostics_output_file,
"--covariate_columns",
features,
"--method=rake",
]
)
# run cli
cli = BalanceCLI(args)
cli.update_attributes_for_main_used_by_adjust()