Skip to content
Navigation Menu
{{ message }}
forked from igerber/diff-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_prep.py
More file actions
3776 lines (3258 loc) · 147 KB
/
Copy pathtest_prep.py
File metadata and controls
3776 lines (3258 loc) · 147 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
"""
Tests for data preparation utility functions.
"""
import numpy as np
import pandas as pd
import pytest
from diff_diff.prep import (
aggregate_survey,
aggregate_to_cohorts,
balance_panel,
create_event_time,
generate_did_data,
make_post_indicator,
make_treatment_indicator,
summarize_did_data,
validate_did_data,
wide_to_long,
)
from diff_diff.survey import SurveyDesign
class TestMakeTreatmentIndicator:
"""Tests for make_treatment_indicator function."""
def test_categorical_single_value(self):
"""Test treatment from single categorical value."""
df = pd.DataFrame({"group": ["A", "A", "B", "B"], "y": [1, 2, 3, 4]})
result = make_treatment_indicator(df, "group", treated_values="A")
assert result["treated"].tolist() == [1, 1, 0, 0]
def test_categorical_multiple_values(self):
"""Test treatment from multiple categorical values."""
df = pd.DataFrame({"group": ["A", "B", "C", "D"], "y": [1, 2, 3, 4]})
result = make_treatment_indicator(df, "group", treated_values=["A", "B"])
assert result["treated"].tolist() == [1, 1, 0, 0]
def test_threshold_above(self):
"""Test treatment from numeric threshold (above)."""
df = pd.DataFrame({"size": [10, 50, 100, 200], "y": [1, 2, 3, 4]})
result = make_treatment_indicator(df, "size", threshold=75)
assert result["treated"].tolist() == [0, 0, 1, 1]
def test_threshold_below(self):
"""Test treatment from numeric threshold (below)."""
df = pd.DataFrame({"size": [10, 50, 100, 200], "y": [1, 2, 3, 4]})
result = make_treatment_indicator(df, "size", threshold=75, above_threshold=False)
assert result["treated"].tolist() == [1, 1, 0, 0]
def test_custom_column_name(self):
"""Test custom output column name."""
df = pd.DataFrame({"group": ["A", "B"], "y": [1, 2]})
result = make_treatment_indicator(df, "group", treated_values="A", new_column="is_treated")
assert "is_treated" in result.columns
assert result["is_treated"].tolist() == [1, 0]
def test_original_unchanged(self):
"""Test that original DataFrame is not modified."""
df = pd.DataFrame({"group": ["A", "B"], "y": [1, 2]})
original_cols = df.columns.tolist()
make_treatment_indicator(df, "group", treated_values="A")
assert df.columns.tolist() == original_cols
def test_error_both_params(self):
"""Test error when both treated_values and threshold specified."""
df = pd.DataFrame({"x": [1, 2], "y": [1, 2]})
with pytest.raises(ValueError, match="Specify either"):
make_treatment_indicator(df, "x", treated_values=1, threshold=1.5)
def test_error_neither_param(self):
"""Test error when neither treated_values nor threshold specified."""
df = pd.DataFrame({"x": [1, 2], "y": [1, 2]})
with pytest.raises(ValueError, match="Must specify either"):
make_treatment_indicator(df, "x")
def test_error_column_not_found(self):
"""Test error when column doesn't exist."""
df = pd.DataFrame({"x": [1, 2]})
with pytest.raises(ValueError, match="not found"):
make_treatment_indicator(df, "missing", treated_values=1)
class TestMakePostIndicator:
"""Tests for make_post_indicator function."""
def test_post_periods_single(self):
"""Test post indicator from single period value."""
df = pd.DataFrame({"year": [2018, 2019, 2020, 2021], "y": [1, 2, 3, 4]})
result = make_post_indicator(df, "year", post_periods=2020)
assert result["post"].tolist() == [0, 0, 1, 0]
def test_post_periods_multiple(self):
"""Test post indicator from multiple period values."""
df = pd.DataFrame({"year": [2018, 2019, 2020, 2021], "y": [1, 2, 3, 4]})
result = make_post_indicator(df, "year", post_periods=[2020, 2021])
assert result["post"].tolist() == [0, 0, 1, 1]
def test_treatment_start(self):
"""Test post indicator from treatment start."""
df = pd.DataFrame({"year": [2018, 2019, 2020, 2021], "y": [1, 2, 3, 4]})
result = make_post_indicator(df, "year", treatment_start=2020)
assert result["post"].tolist() == [0, 0, 1, 1]
def test_datetime_column(self):
"""Test with datetime column."""
df = pd.DataFrame(
{"date": pd.to_datetime(["2020-01-01", "2020-06-01", "2021-01-01"]), "y": [1, 2, 3]}
)
result = make_post_indicator(df, "date", treatment_start="2020-06-01")
assert result["post"].tolist() == [0, 1, 1]
def test_custom_column_name(self):
"""Test custom output column name."""
df = pd.DataFrame({"year": [2018, 2019], "y": [1, 2]})
result = make_post_indicator(df, "year", post_periods=2019, new_column="after")
assert "after" in result.columns
def test_error_both_params(self):
"""Test error when both post_periods and treatment_start specified."""
df = pd.DataFrame({"year": [2018, 2019], "y": [1, 2]})
with pytest.raises(ValueError, match="Specify either"):
make_post_indicator(df, "year", post_periods=[2019], treatment_start=2019)
def test_error_neither_param(self):
"""Test error when neither parameter specified."""
df = pd.DataFrame({"year": [2018, 2019], "y": [1, 2]})
with pytest.raises(ValueError, match="Must specify either"):
make_post_indicator(df, "year")
class TestWideToLong:
"""Tests for wide_to_long function."""
def test_basic_conversion(self):
"""Test basic wide to long conversion."""
wide_df = pd.DataFrame(
{
"firm_id": [1, 2],
"sales_2019": [100, 150],
"sales_2020": [110, 160],
"sales_2021": [120, 170],
}
)
result = wide_to_long(
wide_df,
value_columns=["sales_2019", "sales_2020", "sales_2021"],
id_column="firm_id",
time_name="year",
value_name="sales",
)
assert len(result) == 6
assert set(result.columns) == {"firm_id", "year", "sales"}
def test_with_time_values(self):
"""Test with explicit time values."""
wide_df = pd.DataFrame({"id": [1], "t1": [10], "t2": [20]})
result = wide_to_long(
wide_df, value_columns=["t1", "t2"], id_column="id", time_values=[2020, 2021]
)
assert result["period"].tolist() == [2020, 2021]
def test_preserves_other_columns(self):
"""Test that other columns are preserved."""
wide_df = pd.DataFrame({"id": [1, 2], "group": ["A", "B"], "t1": [10, 20], "t2": [15, 25]})
result = wide_to_long(wide_df, value_columns=["t1", "t2"], id_column="id")
assert "group" in result.columns
assert result[result["id"] == 1]["group"].tolist() == ["A", "A"]
def test_error_empty_value_columns(self):
"""Test error with empty value columns."""
df = pd.DataFrame({"id": [1]})
with pytest.raises(ValueError, match="cannot be empty"):
wide_to_long(df, value_columns=[], id_column="id")
def test_error_mismatched_time_values(self):
"""Test error when time_values length doesn't match."""
df = pd.DataFrame({"id": [1], "t1": [10], "t2": [20]})
with pytest.raises(ValueError, match="length"):
wide_to_long(df, value_columns=["t1", "t2"], id_column="id", time_values=[2020])
class TestBalancePanel:
"""Tests for balance_panel function."""
def test_inner_balance(self):
"""Test inner balance (keep complete units only)."""
df = pd.DataFrame(
{
"unit": [1, 1, 1, 2, 2, 3, 3, 3],
"period": [1, 2, 3, 1, 2, 1, 2, 3],
"y": [10, 11, 12, 20, 21, 30, 31, 32],
}
)
result = balance_panel(df, "unit", "period", method="inner")
assert set(result["unit"].unique()) == {1, 3}
assert len(result) == 6
def test_outer_balance(self):
"""Test outer balance (include all combinations)."""
df = pd.DataFrame({"unit": [1, 1, 2], "period": [1, 2, 1], "y": [10, 11, 20]})
result = balance_panel(df, "unit", "period", method="outer")
assert len(result) == 4 # 2 units x 2 periods
def test_fill_with_value(self):
"""Test fill method with specific value."""
df = pd.DataFrame({"unit": [1, 1, 2], "period": [1, 2, 1], "y": [10.0, 11.0, 20.0]})
result = balance_panel(df, "unit", "period", method="fill", fill_value=0.0)
assert len(result) == 4
missing_row = result[(result["unit"] == 2) & (result["period"] == 2)]
assert missing_row["y"].values[0] == 0.0
def test_fill_forward_backward(self):
"""Test fill method with forward/backward fill."""
df = pd.DataFrame(
{
"unit": [1, 1, 1, 2, 2],
"period": [1, 2, 3, 1, 3], # Unit 2 missing period 2
"y": [10.0, 11.0, 12.0, 20.0, 22.0],
}
)
result = balance_panel(df, "unit", "period", method="fill", fill_value=None)
assert len(result) == 6
# Check that unit 2, period 2 was filled
filled_row = result[(result["unit"] == 2) & (result["period"] == 2)]
assert len(filled_row) == 1
assert filled_row["y"].values[0] == 20.0 # Forward filled from period 1
def test_error_invalid_method(self):
"""Test error with invalid method."""
df = pd.DataFrame({"unit": [1], "period": [1], "y": [10]})
with pytest.raises(ValueError, match="method must be"):
balance_panel(df, "unit", "period", method="invalid")
class TestValidateDidData:
"""Tests for validate_did_data function."""
def test_valid_data(self):
"""Test validation of valid data."""
df = pd.DataFrame(
{"y": [1.0, 2.0, 3.0, 4.0], "treated": [0, 0, 1, 1], "post": [0, 1, 0, 1]}
)
result = validate_did_data(df, "y", "treated", "post", raise_on_error=False)
assert result["valid"] is True
assert len(result["errors"]) == 0
def test_missing_column(self):
"""Test validation catches missing columns."""
df = pd.DataFrame({"y": [1, 2], "treated": [0, 1]})
result = validate_did_data(df, "y", "treated", "post", raise_on_error=False)
assert result["valid"] is False
assert any("not found" in e for e in result["errors"])
def test_non_numeric_outcome(self):
"""Test validation catches non-numeric outcome."""
df = pd.DataFrame(
{"y": ["a", "b", "c", "d"], "treated": [0, 0, 1, 1], "post": [0, 1, 0, 1]}
)
result = validate_did_data(df, "y", "treated", "post", raise_on_error=False)
assert result["valid"] is False
assert any("numeric" in e for e in result["errors"])
def test_non_binary_treatment(self):
"""Test validation catches non-binary treatment."""
df = pd.DataFrame({"y": [1.0, 2.0, 3.0], "treated": [0, 1, 2], "post": [0, 1, 0]})
result = validate_did_data(df, "y", "treated", "post", raise_on_error=False)
assert result["valid"] is False
assert any("binary" in e for e in result["errors"])
def test_missing_values(self):
"""Test validation catches missing values."""
df = pd.DataFrame(
{"y": [1.0, np.nan, 3.0, 4.0], "treated": [0, 0, 1, 1], "post": [0, 1, 0, 1]}
)
result = validate_did_data(df, "y", "treated", "post", raise_on_error=False)
assert result["valid"] is False
assert any("missing" in e for e in result["errors"])
def test_raises_on_error(self):
"""Test that validation raises when raise_on_error=True."""
df = pd.DataFrame({"y": [1], "treated": [0]}) # Missing post column
with pytest.raises(ValueError):
validate_did_data(df, "y", "treated", "post", raise_on_error=True)
def test_panel_validation(self):
"""Test panel-specific validation."""
df = pd.DataFrame(
{
"y": [1.0, 2.0, 3.0, 4.0],
"treated": [0, 0, 1, 1],
"post": [0, 1, 0, 1],
"unit": [1, 1, 2, 2],
}
)
result = validate_did_data(df, "y", "treated", "post", unit="unit", raise_on_error=False)
assert result["valid"] is True
assert result["summary"]["n_units"] == 2
class TestSummarizeDidData:
"""Tests for summarize_did_data function."""
def test_basic_summary(self):
"""Test basic summary statistics."""
df = pd.DataFrame(
{
"y": [10, 11, 12, 13, 20, 21, 22, 23],
"treated": [0, 0, 1, 1, 0, 0, 1, 1],
"post": [0, 1, 0, 1, 0, 1, 0, 1],
}
)
summary = summarize_did_data(df, "y", "treated", "post")
assert len(summary) == 5 # 4 groups + DiD estimate
def test_did_estimate_included(self):
"""Test that DiD estimate is calculated."""
df = pd.DataFrame(
{
"y": [10, 20, 15, 30], # Perfect DiD = 30-15 - (20-10) = 5
"treated": [0, 0, 1, 1],
"post": [0, 1, 0, 1],
}
)
summary = summarize_did_data(df, "y", "treated", "post")
assert "DiD Estimate" in summary.index
assert summary.loc["DiD Estimate", "mean"] == 5.0
class TestGenerateDidData:
"""Tests for generate_did_data function."""
def test_basic_generation(self):
"""Test basic data generation."""
data = generate_did_data(n_units=50, n_periods=4, seed=42)
assert len(data) == 200 # 50 units x 4 periods
assert set(data.columns) == {"unit", "period", "treated", "post", "outcome", "true_effect"}
def test_treatment_fraction(self):
"""Test that treatment fraction is respected."""
data = generate_did_data(n_units=100, treatment_fraction=0.3, seed=42)
n_treated_units = data.groupby("unit")["treated"].first().sum()
assert n_treated_units == 30
def test_treatment_effect_recovery(self):
"""Test that treatment effect can be roughly recovered."""
from diff_diff import DifferenceInDifferences
true_effect = 5.0
data = generate_did_data(
n_units=200, n_periods=4, treatment_effect=true_effect, noise_sd=0.5, seed=42
)
did = DifferenceInDifferences()
results = did.fit(data, outcome="outcome", treatment="treated", time="post")
# Effect should be within 1 unit of true effect
assert abs(results.att - true_effect) < 1.0
def test_reproducibility(self):
"""Test that seed produces reproducible data."""
data1 = generate_did_data(seed=123)
data2 = generate_did_data(seed=123)
pd.testing.assert_frame_equal(data1, data2)
def test_true_effect_column(self):
"""Test that true_effect column is correct."""
data = generate_did_data(n_units=10, n_periods=4, treatment_effect=3.0, seed=42)
# True effect should only be non-zero for treated units in post period
treated_post = data[(data["treated"] == 1) & (data["post"] == 1)]
not_treated_post = data[~((data["treated"] == 1) & (data["post"] == 1))]
assert (treated_post["true_effect"] == 3.0).all()
assert (not_treated_post["true_effect"] == 0.0).all()
class TestCreateEventTime:
"""Tests for create_event_time function."""
def test_basic_event_time(self):
"""Test basic event time calculation."""
df = pd.DataFrame(
{
"unit": [1, 1, 1, 2, 2, 2],
"year": [2018, 2019, 2020, 2018, 2019, 2020],
"treatment_year": [2019, 2019, 2019, 2020, 2020, 2020],
}
)
result = create_event_time(df, "year", "treatment_year")
assert result["event_time"].tolist() == [-1, 0, 1, -2, -1, 0]
def test_never_treated(self):
"""Test handling of never-treated units."""
df = pd.DataFrame(
{
"unit": [1, 1, 2, 2],
"year": [2019, 2020, 2019, 2020],
"treatment_year": [2020, 2020, np.nan, np.nan],
}
)
result = create_event_time(df, "year", "treatment_year")
assert result.loc[0, "event_time"] == -1
assert result.loc[1, "event_time"] == 0
assert pd.isna(result.loc[2, "event_time"])
assert pd.isna(result.loc[3, "event_time"])
def test_custom_column_name(self):
"""Test custom output column name."""
df = pd.DataFrame({"year": [2019, 2020], "treat_time": [2020, 2020]})
result = create_event_time(df, "year", "treat_time", new_column="rel_time")
assert "rel_time" in result.columns
class TestAggregateToCohorts:
"""Tests for aggregate_to_cohorts function."""
def test_basic_aggregation(self):
"""Test basic cohort aggregation."""
df = pd.DataFrame(
{
"unit": [1, 1, 2, 2, 3, 3, 4, 4],
"period": [0, 1, 0, 1, 0, 1, 0, 1],
"treated": [1, 1, 1, 1, 0, 0, 0, 0],
"y": [10, 15, 12, 17, 8, 10, 9, 11],
}
)
result = aggregate_to_cohorts(df, "unit", "period", "treated", "y")
assert len(result) == 4 # 2 treatment groups x 2 periods
assert "mean_y" in result.columns
assert "n_units" in result.columns
def test_with_covariates(self):
"""Test aggregation with covariates."""
df = pd.DataFrame(
{
"unit": [1, 1, 2, 2],
"period": [0, 1, 0, 1],
"treated": [1, 1, 0, 0],
"y": [10, 15, 8, 10],
"x": [1.0, 1.5, 0.5, 0.8],
}
)
result = aggregate_to_cohorts(df, "unit", "period", "treated", "y", covariates=["x"])
assert "x" in result.columns
class TestRankControlUnits:
"""Tests for rank_control_units function."""
def test_basic_ranking(self):
"""Test basic control unit ranking."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
)
assert "quality_score" in result.columns
assert "outcome_trend_score" in result.columns
assert "synthetic_weight" in result.columns
assert len(result) > 0
# Check sorted descending
assert result["quality_score"].is_monotonic_decreasing
def test_with_covariates(self):
"""Test ranking with covariate matching."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
# Add covariate
np.random.seed(42)
data["x1"] = np.random.randn(len(data))
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
covariates=["x1"],
)
assert not result["covariate_score"].isna().all()
def test_explicit_treated_units(self):
"""Test with explicitly specified treated units."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treated_units=[0, 1, 2],
)
# Should not include treated units in ranking
assert 0 not in result["unit"].values
assert 1 not in result["unit"].values
assert 2 not in result["unit"].values
def test_exclude_units(self):
"""Test unit exclusion."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
exclude_units=[15, 16, 17],
)
assert 15 not in result["unit"].values
assert 16 not in result["unit"].values
assert 17 not in result["unit"].values
def test_require_units(self):
"""Test required units are always included."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=30, n_periods=6, seed=42)
# Get control units (not treated)
control_units = data[data["treated"] == 0]["unit"].unique()
require = [control_units[-1], control_units[-2]] # Pick last two controls
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
require_units=require,
n_top=5,
)
# Required units should be present
for u in require:
assert u in result["unit"].values
# is_required flag should be set
assert result[result["unit"].isin(require)]["is_required"].all()
def test_n_top_limit(self):
"""Test limiting to top N controls."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=30, n_periods=6, seed=42)
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
n_top=10,
)
assert len(result) == 10
def test_suggest_treatment_candidates(self):
"""Test treatment candidate suggestion mode."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
# Remove treatment column to simulate unknown treatment
data = data.drop(columns=["treated"])
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
suggest_treatment_candidates=True,
n_treatment_candidates=5,
)
assert "treatment_candidate_score" in result.columns
assert len(result) == 5
def test_original_unchanged(self):
"""Test that original DataFrame is not modified."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
original_cols = data.columns.tolist()
rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
)
assert data.columns.tolist() == original_cols
def test_error_missing_column(self):
"""Test error when column doesn't exist."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=10, n_periods=4, seed=42)
with pytest.raises(ValueError, match="not found"):
rank_control_units(
data, unit_column="missing_col", time_column="period", outcome_column="outcome"
)
def test_error_both_treatment_specs(self):
"""Test error when both treatment specifications provided."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=10, n_periods=4, seed=42)
with pytest.raises(ValueError, match="Specify either"):
rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
treated_units=[0, 1],
)
def test_error_require_and_exclude_same_unit(self):
"""Test error when same unit is required and excluded."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=10, n_periods=4, seed=42)
with pytest.raises(ValueError, match="both required and excluded"):
rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
require_units=[5],
exclude_units=[5],
)
def test_synthetic_weight_sum(self):
"""Test that synthetic weights sum to approximately 1."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
)
# Synthetic weights should sum to approximately 1
assert abs(result["synthetic_weight"].sum() - 1.0) < 0.01
def test_pre_periods_explicit(self):
"""Test with explicitly specified pre-periods."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
pre_periods=[0, 1], # Only use first two periods
)
assert len(result) > 0
def test_weight_parameters(self):
"""Test different outcome/covariate weight settings."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
np.random.seed(42)
data["x1"] = np.random.randn(len(data))
# All weight on outcome
result1 = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
covariates=["x1"],
outcome_weight=1.0,
covariate_weight=0.0,
)
# All weight on covariates
result2 = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
covariates=["x1"],
outcome_weight=0.0,
covariate_weight=1.0,
)
# Rankings should differ
# (just check both work, exact comparison is data-dependent)
assert len(result1) > 0
assert len(result2) > 0
def test_unbalanced_panel(self):
"""Test handling of unbalanced panels with missing data."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=20, n_periods=6, seed=42)
# Remove some observations to create unbalanced panel
# Remove all pre-period data for one control unit
control_units = data[data["treated"] == 0]["unit"].unique()
unit_to_partially_remove = control_units[0]
mask = ~((data["unit"] == unit_to_partially_remove) & (data["period"] < 3))
unbalanced_data = data[mask].copy()
result = rank_control_units(
unbalanced_data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
)
# Should still work and exclude the unit with no pre-treatment data
assert len(result) > 0
# The unit with missing pre-treatment data should not be in results
assert unit_to_partially_remove not in result["unit"].values
def test_single_control_unit(self):
"""Test edge case with only one control unit."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=10, n_periods=6, seed=42)
# Keep only one control unit
treated_units = data[data["treated"] == 1]["unit"].unique()
control_units = data[data["treated"] == 0]["unit"].unique()
single_control = control_units[0]
filtered_data = data[
(data["unit"].isin(treated_units)) | (data["unit"] == single_control)
].copy()
result = rank_control_units(
filtered_data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
)
assert len(result) == 1
assert result["unit"].iloc[0] == single_control
# Single control should get score of 1.0 (best possible)
assert result["quality_score"].iloc[0] == 1.0
def test_extreme_Y_scale_synthetic_weight_column(self):
"""Finding #22 (post-audit cleanup): `synthetic_weight` column must
remain a valid non-degenerate simplex vector even at extreme Y
scale (Y ~ 1e9). The previous `compute_synthetic_weights` wrapper
had two bugs here: Rust PGD collapsed to a single vertex, Python
PGD stalled at uniform. The inlined Frank-Wolfe solver in
``rank_control_units`` handles both cases correctly."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=12, n_periods=8, seed=42)
# Shift outcomes to extreme scale — the exact condition the deleted
# wrapper mishandled.
data = data.copy()
data["outcome"] = data["outcome"] + 1e9
result = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
)
weights = result["synthetic_weight"].to_numpy()
# Valid simplex: non-negative, sums to 1.
assert np.all(weights >= 0), "synthetic_weight must be non-negative"
assert abs(weights.sum() - 1.0) < 1e-10, (
f"synthetic_weight should sum to 1.0, got {weights.sum()}"
)
# Non-degenerate: at least 2 controls receive non-trivial weight.
# This guards the Rust-PGD collapse-to-one-vertex bug that
# previously fired at Y ~ 1e9 under the deleted wrapper.
assert int(np.sum(weights > 1e-6)) >= 2, (
f"synthetic_weight collapsed to a single vertex at extreme Y "
f"scale; n_nonzero={int(np.sum(weights > 1e-6))}. weights={weights}"
)
def test_synthetic_weight_column_with_lambda_reg(self):
"""`rank_control_units(lambda_reg > 0)` regression. Non-zero
regularization must produce a valid simplex vector and should pull
weights toward a more uniform distribution vs `lambda_reg=0`."""
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=10, n_periods=8, seed=42)
res_unreg = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
lambda_reg=0.0,
)
res_reg = rank_control_units(
data,
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
lambda_reg=1.0,
)
w_unreg = res_unreg["synthetic_weight"].to_numpy()
w_reg = res_reg["synthetic_weight"].to_numpy()
for w, label in [(w_unreg, "unregularized"), (w_reg, "regularized")]:
assert np.all(w >= 0), f"{label} weights must be non-negative"
assert abs(w.sum() - 1.0) < 1e-10, (
f"{label} weights should sum to 1.0, got {w.sum()}"
)
# Regularization should increase entropy (pull toward uniform) or at
# least not collapse the simplex — a valid regularized solution must
# put non-trivial mass on at least as many donors as the unregularized
# one for a well-conditioned input.
assert int(np.sum(w_reg > 1e-6)) >= int(np.sum(w_unreg > 1e-6)) - 1, (
f"lambda_reg=1.0 should not collapse support vs lambda_reg=0; "
f"n_nonzero_reg={int(np.sum(w_reg > 1e-6))}, "
f"n_nonzero_unreg={int(np.sum(w_unreg > 1e-6))}"
)
def test_synthetic_weight_column_backend_parity(self):
"""Full-pipeline Rust/Python parity for `rank_control_units`. Forces
the Python FW path via `HAS_RUST_BACKEND=False` and verifies the
resulting `synthetic_weight` column agrees with the default (Rust
when available) path to a loose tolerance. Backend divergence on
this caller path was the trigger for deleting the old wrapper."""
from unittest.mock import patch
from diff_diff import utils as utils_mod
from diff_diff.prep import rank_control_units
data = generate_did_data(n_units=10, n_periods=8, seed=123)
kwargs = dict(
unit_column="unit",
time_column="period",
outcome_column="outcome",
treatment_column="treated",
)
res_default = rank_control_units(data, **kwargs)
with patch.object(utils_mod, "HAS_RUST_BACKEND", False):
res_python = rank_control_units(data, **kwargs)
# Align by unit id (ranking order is not a backend-parity property;
# the simplex values on common donors are).
merged = res_default[["unit", "synthetic_weight"]].merge(
res_python[["unit", "synthetic_weight"]],
on="unit",
suffixes=("_default", "_python"),
)
# FW stopping threshold is scale-dependent, so use a loose tolerance.
np.testing.assert_allclose(
merged["synthetic_weight_default"].to_numpy(),
merged["synthetic_weight_python"].to_numpy(),
atol=1e-4,
rtol=1e-4,
)
class TestGenerateStaggeredData:
"""Tests for generate_staggered_data function."""
def test_basic_generation(self):
"""Test basic staggered data generation."""
from diff_diff.prep import generate_staggered_data
data = generate_staggered_data(n_units=50, n_periods=8, seed=42)
assert len(data) == 400 # 50 units x 8 periods
assert set(data.columns) == {
"unit",
"period",
"outcome",
"first_treat",
"treated",
"treat",
"true_effect",
}
def test_never_treated_fraction(self):
"""Test that never_treated_frac is respected."""
from diff_diff.prep import generate_staggered_data
data = generate_staggered_data(n_units=100, never_treated_frac=0.3, seed=42)
n_never = (data.groupby("unit")["first_treat"].first() == 0).sum()
assert n_never == 30
def test_cohort_periods(self):
"""Test custom cohort periods."""
from diff_diff.prep import generate_staggered_data
data = generate_staggered_data(n_units=100, n_periods=10, cohort_periods=[4, 6], seed=42)
cohorts = data.groupby("unit")["first_treat"].first().unique()
assert set(cohorts) == {0, 4, 6}
def test_treatment_effect_direction(self):
"""Test that treatment effect is positive."""
from diff_diff.prep import generate_staggered_data
data = generate_staggered_data(n_units=100, treatment_effect=3.0, noise_sd=0.1, seed=42)
# Treated observations should have positive true_effect
treated_effects = data[data["treated"] == 1]["true_effect"]
assert (treated_effects > 0).all()
def test_dynamic_effects(self):
"""Test dynamic treatment effects."""
from diff_diff.prep import generate_staggered_data
data = generate_staggered_data(
n_units=50,
n_periods=10,
treatment_effect=2.0,
dynamic_effects=True,
effect_growth=0.1,
seed=42,
)
# Effects should grow over time since treatment
# Check a treated unit
treated_units = data[data["treat"] == 1]["unit"].unique()
unit_data = data[data["unit"] == treated_units[0]].sort_values("period")
first_treat = unit_data["first_treat"].iloc[0]
effects = unit_data[unit_data["period"] >= first_treat]["true_effect"].values
# Effects should be increasing (with dynamic effects)
assert all(effects[i] <= effects[i + 1] for i in range(len(effects) - 1))
def test_reproducibility(self):
"""Test seed produces reproducible data."""
from diff_diff.prep import generate_staggered_data
data1 = generate_staggered_data(seed=123)
data2 = generate_staggered_data(seed=123)
pd.testing.assert_frame_equal(data1, data2)
def test_invalid_cohort_period(self):
"""Test error on invalid cohort period."""
from diff_diff.prep import generate_staggered_data
with pytest.raises(ValueError, match="must be between"):
generate_staggered_data(n_periods=10, cohort_periods=[0, 5]) # 0 invalid
with pytest.raises(ValueError, match="must be between"):
generate_staggered_data(n_periods=10, cohort_periods=[5, 10]) # 10 invalid
class TestGenerateFactorData:
"""Tests for generate_factor_data function."""
def test_basic_generation(self):
"""Test basic factor data generation."""
from diff_diff.prep import generate_factor_data
data = generate_factor_data(n_units=30, n_pre=8, n_post=4, n_treated=5, seed=42)
assert len(data) == 360 # 30 units x 12 periods
assert set(data.columns) == {"unit", "period", "outcome", "treated", "treat", "true_effect"}
def test_treated_units_count(self):
"""Test that n_treated is respected."""
from diff_diff.prep import generate_factor_data
data = generate_factor_data(n_units=50, n_treated=10, seed=42)
n_treated = data.groupby("unit")["treat"].first().sum()
assert n_treated == 10
def test_treatment_in_post_only(self):
"""Test that treatment indicator is 1 only in post-treatment."""
from diff_diff.prep import generate_factor_data
data = generate_factor_data(n_pre=10, n_post=5, n_treated=10, seed=42)
# Pre-treatment observations should have treated=0
pre_data = data[data["period"] < 10]
assert (pre_data["treated"] == 0).all()
You can’t perform that action at this time.
