-
Notifications
You must be signed in to change notification settings - Fork 32
/
test_vs_fixest.py
1081 lines (896 loc) · 33.4 KB
/
test_vs_fixest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import numpy as np
import pandas as pd
import pytest
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
# rpy2 imports
from rpy2.robjects.packages import importr
import pyfixest as pf
from pyfixest.estimation.estimation import feols
from pyfixest.estimation.FixestMulti_ import FixestMulti
from pyfixest.utils.set_rpy2_path import update_r_paths
from pyfixest.utils.utils import get_data, ssc
update_r_paths()
pandas2ri.activate()
fixest = importr("fixest")
stats = importr("stats")
broom = importr("broom")
# note: tolerances are lowered below for
# fepois inference as it is not as precise as feols
# effective tolerances for fepois are 1e-04 and 1e-03
# (the latter only for CRV inferece)
rtol = 1e-08
atol = 1e-08
iwls_maxiter = 25
iwls_tol = 1e-08
ols_fmls = [
("Y~X1"),
("Y~X1+X2"),
("Y~X1|f2"),
("Y~X1|f2+f3"),
("Y ~ X1 + exp(X2)"),
("Y ~ X1 + C(f1)"),
("Y ~ X1 + i(f1, ref = 1)"),
("Y ~ X1 + C(f1)"),
("Y ~ X1 + i(f2, ref = 2.0)"),
("Y ~ X1 + C(f1) + C(f2)"),
("Y ~ X1 + C(f1) | f2"),
("Y ~ X1 + i(f1, ref = 3.0) | f2"),
("Y ~ X1 + C(f1) | f2 + f3"),
("Y ~ X1 + i(f1, ref = 1) | f2 + f3"),
("Y ~ X1 + i(f1) + i(f2)"),
("Y ~ X1 + i(f1, ref = 1) + i(f2, ref = 2)"),
# ("Y ~ X1 + C(f1):C(fe2)"), # currently does not work as C():C() translation not implemented
# ("Y ~ X1 + C(f1):C(fe2) | f3"), # currently does not work as C():C() translation not implemented
("Y ~ X1 + X2:f1"),
("Y ~ X1 + X2:f1 | f3"),
("Y ~ X1 + X2:f1 | f3 + f1"),
# ("log(Y) ~ X1:X2 | f3 + f1"), # currently, causes big problems for Fepois (takes a long time)
# ("log(Y) ~ log(X1):X2 | f3 + f1"), # currently, causes big problems for Fepois (takes a long time)
# ("Y ~ X2 + exp(X1) | f3 + f1"), # currently, causes big problems for Fepois (takes a long time)
("Y ~ X1 + i(f1,X2)"),
("Y ~ X1 + i(f1,X2) + i(f2, X2)"),
("Y ~ X1 + i(f1,X2, ref =1) + i(f2)"),
("Y ~ X1 + i(f1,X2, ref =1) + i(f2, X1, ref =2)"),
("Y ~ X1 + i(f2,X2)"),
("Y ~ X1 + i(f1,X2) | f2"),
("Y ~ X1 + i(f1,X2) | f2 + f3"),
("Y ~ X1 + i(f1,X2, ref=1.0)"),
("Y ~ X1 + i(f2,X2, ref=2.0)"),
("Y ~ X1 + i(f1,X2, ref=3.0) | f2"),
("Y ~ X1 + i(f1,X2, ref=4.0) | f2 + f3"),
# ("Y ~ C(f1):X2"), # currently does not work as C():X translation not implemented
# ("Y ~ C(f1):C(f2)"), # currently does not work
("Y ~ X1 + I(X2 ** 2)"),
("Y ~ X1 + I(X1 ** 2) + I(X2**4)"),
("Y ~ X1*X2"),
("Y ~ X1*X2 | f1+f2"),
# ("Y ~ X1/X2"), # currently does not work as X1/X2 translation not implemented
# ("Y ~ X1/X2 | f1+f2"), # currently does not work as X1/X2 translation not implemented
("Y ~ X1 + poly(X2, 2) | f1"),
]
ols_but_not_poisson_fml = [
("log(Y) ~ X1"),
("Y~X1|f2^f3"),
("Y~X1|f1 + f2^f3"),
("Y~X1|f2^f3^f1"),
]
empty_models = [
("Y ~ 1 | f1"),
("Y ~ 1 | f1 + f2"),
("Y ~ 0 | f1"),
("Y ~ 0 | f1 + f2"),
]
iv_fmls = [
# IV starts here
("Y ~ 1 | X1 ~ Z1"),
"Y ~ X2 | X1 ~ Z1",
"Y ~ X2 + C(f1) | X1 ~ Z1",
"Y2 ~ 1 | X1 ~ Z1",
"Y2 ~ X2 | X1 ~ Z1",
"Y2 ~ X2 + C(f1) | X1 ~ Z1",
# "log(Y) ~ 1 | X1 ~ Z1",
# "log(Y) ~ X2 | X1 ~ Z1",
# "log(Y) ~ X2 + C(f1) | X1 ~ Z1",
"Y ~ 1 | f1 | X1 ~ Z1",
"Y ~ 1 | f1 + f3 | X1 ~ Z1",
"Y ~ 1 | f1^f2 | X1 ~ Z1",
"Y ~ X2| f3 | X1 ~ Z1",
# tests of overidentified models
"Y ~ 1 | X1 ~ Z1 + Z2",
"Y ~ X2 | X1 ~ Z1 + Z2",
"Y ~ X2 + C(f3) | X1 ~ Z1 + Z2",
"Y ~ 1 | f1 | X1 ~ Z1 + Z2",
"Y2 ~ 1 | f1 + f3 | X1 ~ Z1 + Z2",
"Y2 ~ X2| f2 | X1 ~ Z1 + Z2",
]
@pytest.fixture
def data_feols(N=1000, seed=76540251, beta_type="2", error_type="2"):
return pf.get_data(
N=N, seed=seed, beta_type=beta_type, error_type=error_type, model="Feols"
)
@pytest.fixture
def data_fepois(N=1000, seed=7651, beta_type="2", error_type="2"):
return pf.get_data(
N=N, seed=seed, beta_type=beta_type, error_type=error_type, model="Fepois"
)
rng = np.random.default_rng(8760985)
def check_absolute_diff(x1, x2, tol, msg=None):
"Check for absolute differences."
if isinstance(x1, (int, float)):
x1 = np.array([x1])
if isinstance(x2, (int, float)):
x2 = np.array([x2])
msg = "" if msg is None else msg
# handle nan values
nan_mask_x1 = np.isnan(x1)
nan_mask_x2 = np.isnan(x2)
if not np.array_equal(nan_mask_x1, nan_mask_x2):
raise AssertionError(f"{msg}: NaN positions do not match")
valid_mask = ~nan_mask_x1 # Mask for non-NaN elements (same for x1 and x2)
assert np.all(np.abs(x1[valid_mask] - x2[valid_mask]) < tol), msg
def na_omit(arr):
mask = ~np.isnan(arr)
return arr[mask]
def check_relative_diff(x1, x2, tol, msg=None):
msg = "" if msg is None else msg
assert np.all(np.abs(x1 - x2) / np.abs(x1) < tol), msg
test_counter_feols = 0
test_counter_fepois = 0
test_counter_feiv = 0
# What is being tested in all tests:
# - pyfixest vs fixest
# - inference: iid, hetero, cluster
# - weights: None, "weights"
# - fmls
# Only tests for feols, not for fepois or feiv:
# - dropna: False, True
# - f3_type: "str", "object", "int", "categorical", "float"
# - adj: True
# - cluster_adj: True
@pytest.mark.slow
@pytest.mark.parametrize("dropna", [False, True])
@pytest.mark.parametrize("inference", ["iid", "hetero", {"CRV1": "group_id"}])
@pytest.mark.parametrize("weights", [None, "weights"])
@pytest.mark.parametrize("f3_type", ["str", "object", "int", "categorical", "float"])
@pytest.mark.parametrize("fml", ols_fmls + ols_but_not_poisson_fml)
@pytest.mark.parametrize("adj", [True])
@pytest.mark.parametrize("cluster_adj", [True])
def test_single_fit_feols(
data_feols,
dropna,
inference,
weights,
f3_type,
fml,
adj,
cluster_adj,
):
global test_counter_feols
test_counter_feols += 1
_skip_f3_checks(fml, f3_type)
_skip_dropna(test_counter_feols, dropna)
ssc_ = ssc(adj=adj, cluster_adj=cluster_adj)
data = data_feols.copy()
if dropna:
data = data.dropna()
# long story, but categories need to be strings to be converted to R factors,
# this then produces 'nan' values in the pd.DataFrame ...
data[data == "nan"] = np.nan
# test fixed effects that are not floats, but ints or categoricals, etc
data = _convert_f3(data, f3_type)
data_r = get_data_r(fml, data)
r_fml = _c_to_as_factor(fml)
r_inference = _get_r_inference(inference)
mod = pf.feols(fml=fml, data=data, vcov=inference, weights=weights, ssc=ssc_)
if weights is not None:
r_fixest = fixest.feols(
ro.Formula(r_fml),
vcov=r_inference,
data=data_r,
ssc=fixest.ssc(adj, "none", cluster_adj, "min", "min", False),
weights=ro.Formula("~" + weights),
)
else:
r_fixest = fixest.feols(
ro.Formula(r_fml),
vcov=r_inference,
data=data_r,
ssc=fixest.ssc(adj, "none", cluster_adj, "min", "min", False),
)
py_coef = mod.coef().xs("X1")
py_se = mod.se().xs("X1")
py_pval = mod.pvalue().xs("X1")
py_tstat = mod.tstat().xs("X1")
py_confint = mod.confint().xs("X1").values
py_vcov = mod._vcov[0, 0]
py_nobs = mod._N
py_resid = mod.resid()
df_X1 = _get_r_df(r_fixest)
r_coef = df_X1["estimate"]
r_se = df_X1["std.error"]
r_pval = df_X1["p.value"]
r_tstat = df_X1["statistic"]
r_confint = df_X1[["conf.low", "conf.high"]].values.astype(np.float64)
r_vcov = stats.vcov(r_fixest)[0, 0]
r_nobs = int(stats.nobs(r_fixest)[0])
if inference == "iid" and adj and cluster_adj:
py_resid = mod.resid()
r_resid = stats.residuals(r_fixest)
py_predict = mod.predict()
r_predict = stats.predict(r_fixest)
check_absolute_diff(py_nobs, r_nobs, 1e-08, "py_nobs != r_nobs")
check_absolute_diff(py_coef, r_coef, 1e-08, "py_coef != r_coef")
check_absolute_diff(
py_predict[0:5], r_predict[0:5], 1e-07, "py_predict != r_predict"
)
check_absolute_diff(
(py_resid)[0:5], (r_resid)[0:5], 1e-07, "py_resid != r_resid"
)
# currently, bug when using predict with newdata and i() or C() or "^" syntax
blocked_transforms = ["i(", "^", "poly("]
blocked_transform_found = any(bt in fml for bt in blocked_transforms)
if blocked_transform_found:
with pytest.raises(NotImplementedError):
py_predict_newsample = mod.predict(
newdata=data.iloc[0:100], atol=1e-08, btol=1e-08
)
else:
py_predict_newsample = mod.predict(
newdata=data.iloc[0:100], atol=1e-12, btol=1e-12
)
r_predict_newsample = stats.predict(r_fixest, newdata=data_r.iloc[0:100])
check_absolute_diff(
na_omit(py_predict_newsample)[0:5],
na_omit(r_predict_newsample)[0:5],
1e-07,
"py_predict_newdata != r_predict_newdata",
)
check_absolute_diff(py_vcov, r_vcov, 1e-08, "py_vcov != r_vcov")
check_absolute_diff(py_se, r_se, 1e-08, "py_se != r_se")
check_absolute_diff(py_pval, r_pval, 1e-08, "py_pval != r_pval")
check_absolute_diff(py_tstat, r_tstat, 1e-07, "py_tstat != r_tstat")
check_absolute_diff(py_confint, r_confint, 1e-08, "py_confint != r_confint")
if not weights:
py_r2 = mod._r2
py_r2_within = mod._r2_within
# py_adj_r2 = mod._adj_r2
# py_adj_r2_within = mod._adj_r2_within
r_r = fixest.r2(r_fixest)
r_r2 = r_r[1]
r_r2_within = r_r[5]
check_absolute_diff(py_r2, r_r2, 1e-08, "py_r2 != r_r2")
if not np.isnan(py_r2_within):
check_absolute_diff(
py_r2_within, r_r2_within, 1e-08, "py_r2_within != r_r2_within"
)
@pytest.mark.slow
@pytest.mark.parametrize("dropna", [False, True])
@pytest.mark.parametrize("weights", [None, "weights"])
@pytest.mark.parametrize("f3_type", ["str", "object", "int", "categorical", "float"])
@pytest.mark.parametrize("fml", empty_models)
def test_single_fit_feols_empty(
data_feols,
dropna,
weights,
f3_type,
fml,
):
data = data_feols
if dropna:
data = data.dropna()
# long story, but categories need to be strings to be converted to R factors,
# this then produces 'nan' values in the pd.DataFrame ...
data[data == "nan"] = np.nan
# test fixed effects that are not floats, but ints or categoricals, etc
data = _convert_f3(data, f3_type)
data_r = get_data_r(fml, data)
r_fml = _c_to_as_factor(fml)
mod = pf.feols(fml=fml, data=data, weights=weights)
if weights is not None:
r_fixest = fixest.feols(
ro.Formula(r_fml),
data=data_r,
weights=ro.Formula("~" + weights),
)
else:
r_fixest = fixest.feols(
ro.Formula(r_fml),
data=data_r,
)
py_nobs = mod._N
py_resid = mod.resid()
py_predict = mod.predict()
r_nobs = int(stats.nobs(r_fixest)[0])
r_resid = stats.residuals(r_fixest)
r_predict = stats.predict(r_fixest)
check_absolute_diff(py_nobs, r_nobs, 1e-08, "py_nobs != r_nobs")
check_absolute_diff((py_resid)[0:5], (r_resid)[0:5], 1e-07, "py_resid != r_resid")
check_absolute_diff(
py_predict[0:5], r_predict[0:5], 1e-07, "py_predict != r_predict"
)
assert mod._beta_hat.size == 0
@pytest.mark.slow
@pytest.mark.parametrize("dropna", [False])
@pytest.mark.parametrize("inference", ["iid", "hetero", {"CRV1": "group_id"}])
@pytest.mark.parametrize("f3_type", ["str"])
@pytest.mark.parametrize("fml", ols_fmls)
@pytest.mark.parametrize("adj", [True])
@pytest.mark.parametrize("cluster_adj", [True])
def test_single_fit_fepois(
data_fepois, dropna, inference, f3_type, fml, adj, cluster_adj
):
global test_counter_fepois
test_counter_fepois += 1
_skip_f3_checks(fml, f3_type)
_skip_dropna(test_counter_fepois, dropna)
ssc_ = ssc(adj=adj, cluster_adj=cluster_adj)
data = data_fepois
if dropna:
data = data.dropna()
# long story, but categories need to be strings to be converted to R factors,
# this then produces 'nan' values in the pd.DataFrame ...
data[data == "nan"] = np.nan
# test fixed effects that are not floats, but ints or categoricals, etc
data = _convert_f3(data, f3_type)
data_r = get_data_r(fml, data)
r_fml = _c_to_as_factor(fml)
r_inference = _get_r_inference(inference)
mod = pf.fepois(fml=fml, data=data, vcov=inference, ssc=ssc_, iwls_tol=1e-10)
r_fixest = fixest.fepois(
ro.Formula(r_fml),
vcov=r_inference,
data=data_r,
ssc=fixest.ssc(adj, "none", cluster_adj, "min", "min", False),
glm_tol=1e-10,
)
py_coef = mod.coef().xs("X1")
py_se = mod.se().xs("X1")
py_pval = mod.pvalue().xs("X1")
py_tstat = mod.tstat().xs("X1")
py_confint = mod.confint().xs("X1").values
py_nobs = mod._N
py_vcov = mod._vcov[0, 0]
py_deviance = mod.deviance
py_resid = mod.resid()
py_irls_weights = mod._irls_weights.flatten()
df_X1 = _get_r_df(r_fixest)
r_coef = df_X1["estimate"]
r_se = df_X1["std.error"]
r_pval = df_X1["p.value"]
r_tstat = df_X1["statistic"]
r_confint = df_X1[["conf.low", "conf.high"]].values.astype(np.float64)
r_nobs = int(stats.nobs(r_fixest)[0])
r_resid = stats.residuals(r_fixest)
r_vcov = stats.vcov(r_fixest)[0, 0]
r_deviance = r_fixest.rx2("deviance")
r_irls_weights = r_fixest.rx2("irls_weights")
if inference == "iid" and adj and cluster_adj:
check_absolute_diff(py_nobs, r_nobs, 1e-08, "py_nobs != r_nobs")
check_absolute_diff(py_coef, r_coef, 1e-08, "py_coef != r_coef")
check_absolute_diff((py_resid)[0:5], (r_resid)[0:5], 1e-07, "py_coef != r_coef")
# example failure case:
# x1 = array([1.20821485, 0.9602059 , 2. , 1.06451667, 0.97644541])
# x2 = array([1.20821485, 0.96020592, 2.00015315, 1.06451668, 0.97644542])
check_absolute_diff(
py_irls_weights[10:12],
r_irls_weights[10:12],
1e-02,
"py_irls_weights != r_irls_weights",
)
check_absolute_diff(py_vcov, r_vcov, 1e-06, "py_vcov != r_vcov")
check_absolute_diff(py_se, r_se, 1e-06, "py_se != r_se")
check_absolute_diff(py_pval, r_pval, 1e-06, "py_pval != r_pval")
check_absolute_diff(py_tstat, r_tstat, 1e-06, "py_tstat != r_tstat")
check_absolute_diff(py_confint, r_confint, 1e-06, "py_confint != r_confint")
check_absolute_diff(py_deviance, r_deviance, 1e-08, "py_deviance != r_deviance")
if not mod._has_fixef:
py_predict_response = mod.predict(type="response")
py_predict_link = mod.predict(type="link")
r_predict_response = stats.predict(r_fixest, type="response")
r_predict_link = stats.predict(r_fixest, type="link")
check_absolute_diff(
py_predict_response[0:5],
r_predict_response[0:5],
1e-07,
"py_predict_response != r_predict_response",
)
check_absolute_diff(
py_predict_link[0:5],
r_predict_link[0:5],
1e-07,
"py_predict_link != r_predict_link",
)
@pytest.mark.slow
@pytest.mark.parametrize("dropna", [False])
@pytest.mark.parametrize("weights", [None, "weights"])
@pytest.mark.parametrize("inference", ["iid", "hetero", {"CRV1": "group_id"}])
@pytest.mark.parametrize("f3_type", ["str"])
@pytest.mark.parametrize("fml", iv_fmls)
@pytest.mark.parametrize("adj", [True])
@pytest.mark.parametrize("cluster_adj", [True])
def test_single_fit_iv(
data_feols,
dropna,
inference,
weights,
f3_type,
fml,
adj,
cluster_adj,
):
global test_counter_feiv
test_counter_feiv += 1
_skip_f3_checks(fml, f3_type)
_skip_dropna(test_counter_feiv, dropna)
ssc_ = ssc(adj=adj, cluster_adj=cluster_adj)
data = data_feols
if dropna:
data = data.dropna()
# long story, but categories need to be strings to be converted to R factors,
# this then produces 'nan' values in the pd.DataFrame ...
data[data == "nan"] = np.nan
# test fixed effects that are not floats, but ints or categoricals, etc
# data = _convert_f3(data, f3_type)
# test fixed effects that are not floats, but ints or categoricals, etc
data = _convert_f3(data, f3_type)
data_r = get_data_r(fml, data)
r_fml = _c_to_as_factor(fml)
r_inference = _get_r_inference(inference)
mod = pf.feols(fml=fml, data=data, vcov=inference, ssc=ssc_, weights=weights)
if weights is not None:
r_fixest = fixest.feols(
ro.Formula(r_fml),
vcov=r_inference,
data=data_r,
ssc=fixest.ssc(adj, "none", cluster_adj, "min", "min", False),
weights=ro.Formula("~" + weights),
)
else:
r_fixest = fixest.feols(
ro.Formula(r_fml),
vcov=r_inference,
data=data_r,
ssc=fixest.ssc(adj, "none", cluster_adj, "min", "min", False),
)
py_coef = mod.coef().xs("X1")
py_se = mod.se().xs("X1")
py_pval = mod.pvalue().xs("X1")
py_tstat = mod.tstat().xs("X1")
py_confint = mod.confint().xs("X1").values
py_vcov = mod._vcov[0, 0]
py_nobs = mod._N
py_resid = mod.resid()
df_X1 = _get_r_df(r_fixest, is_iv=True)
r_coef = df_X1["estimate"]
r_se = df_X1["std.error"]
r_pval = df_X1["p.value"]
r_tstat = df_X1["statistic"]
r_confint = df_X1[["conf.low", "conf.high"]].values.astype(np.float64)
r_vcov = stats.vcov(r_fixest)[0, 0]
r_nobs = int(stats.nobs(r_fixest)[0])
r_resid = stats.resid(r_fixest)
# if inference == "iid" and adj and cluster_adj:
check_absolute_diff(py_nobs, r_nobs, 1e-08, "py_nobs != r_nobs")
check_absolute_diff(py_coef, r_coef, 1e-08, "py_coef != r_coef")
check_absolute_diff((py_resid)[0:5], (r_resid)[0:5], 1e-07, "py_resid != r_resid")
check_absolute_diff(py_vcov, r_vcov, 1e-07, "py_vcov != r_vcov")
check_absolute_diff(py_se, r_se, 1e-07, "py_se != r_se")
check_absolute_diff(py_pval, r_pval, 1e-06, "py_pval != r_pval")
check_absolute_diff(py_tstat, r_tstat, 1e-06, "py_tstat != r_tstat")
check_absolute_diff(py_confint, r_confint, 1e-06, "py_confint != r_confint")
@pytest.mark.slow
@pytest.mark.parametrize("N", [100])
@pytest.mark.parametrize("seed", [17021])
@pytest.mark.parametrize("beta_type", ["1"])
@pytest.mark.parametrize("error_type", ["3"])
@pytest.mark.parametrize("dropna", [False, True])
@pytest.mark.parametrize(
"fml_multi",
[
("Y~ sw(X1, X2)"),
("Y~ sw(X1, X2) |f1 "),
("Y~ csw(X1, X2)"),
("Y~ csw(X1, X2) | f2"),
("Y~ I(X1**2) + csw(f1,f2)"),
("Y~ X1 + csw(f1, f2) | f3"),
("Y~ X1 + csw0(X2, f3)"),
("Y~ csw0(X2, f3) + X2"),
("Y~ X1 + csw0(X2, f3) + X2"),
("Y ~ X1 + csw0(f1, f2) | f3"),
("Y ~ X1 | csw0(f1,f2)"),
("Y ~ X1 + sw(X2, f1, f2)"),
("Y ~ csw(X1, X2, f3)"),
# ("Y ~ X2 + csw0(, X2, X2)"),
("Y ~ sw(X1, X2) | csw0(f1,f2,f3)"),
("Y ~ C(f2):X2 + sw0(X1, f3)"),
("Y + Y2 ~X1"),
("Y + log(Y2) ~X1+X2"),
("Y + Y2 ~X1|f1"),
("Y + Y2 ~X1|f1+f2"),
("Y + Y2 ~X2|f2+f3"),
("Y + Y2 ~ sw(X1, X2)"),
("Y + Y2 ~ sw(X1, X2) |f1 "),
("Y + Y2 ~ csw(X1, X2)"),
("Y + Y2 ~ csw(X1, X2) | f2"),
("Y + Y2 ~ I(X1**2) + csw(f1,f2)"),
("Y + Y2 ~ X1 + csw(f1, f2) | f3"),
("Y + Y2 ~ X1 + csw0(X2, f3)"),
("Y + Y2 ~ X1 + csw0(f1, f2) | f3"),
("Y + Y2 ~ X1 | csw0(f1,f2)"),
("Y + log(Y2) ~ sw(X1, X2) | csw0(f1,f2,f3)"),
("Y ~ C(f2):X2 + sw0(X1, f3)"),
# ("Y ~ i(f1,X2) | csw0(f2)"),
# ("Y ~ i(f1,X2) | sw0(f2)"),
# ("Y ~ i(f1,X2) | csw(f2, f3)"),
# ("Y ~ i(f1,X2) | sw(f2, f3)"),
# ("Y ~ i(f1,X2, ref = -5) | sw(f2, f3)"),
# ("Y ~ i(f1,X2, ref = -8) | csw(f2, f3)"),
],
)
def test_multi_fit(N, seed, beta_type, error_type, dropna, fml_multi):
"""Test pyfixest against fixest_multi objects."""
data = get_data(N=N, seed=seed, beta_type=beta_type, error_type=error_type)
data[data == "nan"] = np.nan
if dropna:
data = data.dropna()
# suppress correction for fixed effects
fixest.setFixest_ssc(fixest.ssc(True, "none", True, "min", "min", False))
r_fml = _py_fml_to_r_fml(fml_multi)
try:
pyfixest = feols(fml=fml_multi, data=data)
assert isinstance(pyfixest, FixestMulti)
except ValueError as e:
if "is not of type 'O' or 'category'" in str(e):
data["f1"] = pd.Categorical(data.f1.astype(str))
data["f2"] = pd.Categorical(data.f2.astype(str))
data["f3"] = pd.Categorical(data.f3.astype(str))
data[data == "nan"] = np.nan
pyfixest = feols(fml=fml_multi, data=data)
else:
raise ValueError("Code fails with an uninformative error message.")
r_fixest = fixest.feols(
ro.Formula(r_fml),
data=data,
ssc=fixest.ssc(True, "none", True, "min", "min", False),
)
for x in range(0):
mod = pyfixest.fetch_model(x)
py_coef = mod.coef().values
py_se = mod.se().values
# sort py_coef, py_se
py_coef, py_se = (np.sort(x) for x in [py_coef, py_se])
fixest_object = r_fixest.rx2(x + 1)
fixest_coef = fixest_object.rx2("coefficients")
fixest_se = fixest_object.rx2("se")
# fixest_coef = stats.coef(r_fixest)
# fixest_se = fixest.se(r_fixest)
# sort fixest_coef, fixest_se
fixest_coef, fixest_se = (np.sort(x) for x in [fixest_coef, fixest_se])
np.testing.assert_allclose(
py_coef, fixest_coef, rtol=rtol, atol=atol, err_msg="Coefs are not equal."
)
np.testing.assert_allclose(
py_se, fixest_se, rtol=rtol, atol=atol, err_msg="SEs are not equal."
)
@pytest.mark.slow
@pytest.mark.parametrize("N", [100])
@pytest.mark.parametrize("seed", [31])
@pytest.mark.parametrize("beta_type", ["1"])
@pytest.mark.parametrize("error_type", ["3"])
@pytest.mark.parametrize("dropna", [False, True])
@pytest.mark.parametrize(
"fml_multi",
["Y ~ X1", "Y ~ X1 | f2", "Y ~ sw(X1, X2)", "Y ~ 1 | X1 ~ Z1"],
)
@pytest.mark.parametrize("split", [None, "f1"])
@pytest.mark.parametrize("fsplit", [None, "f1"])
def test_split_fit(N, seed, beta_type, error_type, dropna, fml_multi, split, fsplit):
if split is not None and split == fsplit:
pytest.skip("split and fsplit are the same.")
if split is None and fsplit is None:
pytest.skip("split and fsplit are both None.")
data = get_data(N=N, seed=seed, beta_type=beta_type, error_type=error_type)
data[data == "nan"] = np.nan
if dropna:
data = data.dropna()
# suppress correction for fixed effects
fixest.setFixest_ssc(fixest.ssc(True, "none", True, "min", "min", False))
r_fml = _py_fml_to_r_fml(fml_multi)
try:
pyfixest = feols(fml=fml_multi, data=data, split=split, fsplit=fsplit)
assert isinstance(pyfixest, FixestMulti)
except ValueError as e:
if "is not of type 'O' or 'category'" in str(e):
data["f1"] = pd.Categorical(data.f1.astype(str))
data["f2"] = pd.Categorical(data.f2.astype(str))
data["f3"] = pd.Categorical(data.f3.astype(str))
data[data == "nan"] = np.nan
pyfixest = feols(fml=fml_multi, data=data)
else:
raise ValueError("Code fails with an uninformative error message.")
r_fixest = fixest.feols(
ro.Formula(r_fml),
data=data,
ssc=fixest.ssc(True, "none", True, "min", "min", False),
**({"split": ro.Formula("~" + split)} if split is not None else {}),
**({"fsplit": ro.Formula("~" + fsplit)} if fsplit is not None else {}),
)
for x in range(0):
mod = pyfixest.fetch_model(x)
py_coef = mod.coef().values
py_se = mod.se().values
# sort py_coef, py_se
py_coef, py_se = (np.sort(x) for x in [py_coef, py_se])
fixest_object = r_fixest.rx2(x + 1)
fixest_coef = fixest_object.rx2("coefficients")
fixest_se = fixest_object.rx2("se")
# fixest_coef = stats.coef(r_fixest)
# fixest_se = fixest.se(r_fixest)
# sort fixest_coef, fixest_se
fixest_coef, fixest_se = (np.sort(x) for x in [fixest_coef, fixest_se])
np.testing.assert_allclose(
py_coef, fixest_coef, rtol=rtol, atol=atol, err_msg="Coefs are not equal."
)
np.testing.assert_allclose(
py_se, fixest_se, rtol=rtol, atol=atol, err_msg="SEs are not equal."
)
@pytest.mark.slow
def test_twoway_clustering():
data = get_data(N=500, seed=17021, beta_type="1", error_type="1").dropna()
cluster_adj_options = [True]
cluster_df_options = ["min", "conventional"]
for cluster_adj in cluster_adj_options:
for cluster_df in cluster_df_options:
fit1 = feols(
"Y ~ X1 + X2 ",
data=data,
vcov={"CRV1": "f1 +f2"},
ssc=ssc(cluster_adj=cluster_adj, cluster_df=cluster_df),
)
fit2 = feols( # noqa: F841
"Y ~ X1 + X2 ",
data=data,
vcov={"CRV3": " f1+f2"},
ssc=ssc(cluster_adj=cluster_adj, cluster_df=cluster_df),
)
feols_fit1 = fixest.feols(
ro.Formula("Y ~ X1 + X2"),
data=data,
cluster=ro.Formula("~f1+f2"),
ssc=fixest.ssc(True, "none", cluster_adj, cluster_df, "min", False),
)
# test vcov's
np.testing.assert_allclose(
fit1._vcov,
stats.vcov(feols_fit1),
rtol=1e-04,
atol=1e-04,
err_msg=f"CRV1-vcov: cluster_adj = {cluster_adj}, cluster_df = {cluster_df}",
)
# now test se's
np.testing.assert_allclose(
fit1.se(),
fixest.se(feols_fit1),
rtol=1e-04,
atol=1e-04,
err_msg=f"CRV1-se: cluster_adj = {cluster_adj}, cluster_df = {cluster_df}",
)
# now test pvalues
np.testing.assert_allclose(
fit1.pvalue(),
fixest.pvalue(feols_fit1),
rtol=1e-04,
atol=1e-04,
err_msg=f"CRV1-pvalue: cluster_adj = {cluster_adj}, cluster_df = {cluster_df}",
)
@pytest.mark.slow
def test_wls_na():
"""Special tests for WLS and NA values."""
data = get_data()
data = data.dropna()
# case 1: NA in weights
data["weights"].iloc[0] = np.nan
fit_py = feols("Y ~ X1", data=data, weights="weights")
fit_r = fixest.feols(
ro.Formula("Y ~ X1"),
data=data,
weights=ro.Formula("~ weights"),
ssc=fixest.ssc(True, "none", True, "min", "min", False),
)
np.testing.assert_allclose(
fit_py.coef(),
stats.coef(fit_r),
rtol=1e-04,
atol=1e-04,
err_msg="WLS: Coefs are not equal.",
)
# case 2: NA in weights and X1
data["X1"].iloc[0] = np.nan
fit_py = feols("Y ~ X1", data=data, weights="weights")
fit_r = fixest.feols(
ro.Formula("Y ~ X1"),
data=data,
weights=ro.Formula("~ weights"),
ssc=fixest.ssc(True, "none", True, "min", "min", False),
)
np.testing.assert_allclose(
fit_py.coef(),
stats.coef(fit_r),
rtol=1e-04,
atol=1e-04,
err_msg="WLS: Coefs are not equal.",
)
# case 3: more NAs in X1:
data["X1"].iloc[0:10] = np.nan
fit_py = feols("Y ~ X1", data=data, weights="weights")
fit_r = fixest.feols(
ro.Formula("Y ~ X1"),
data=data,
weights=ro.Formula("~ weights"),
ssc=fixest.ssc(True, "none", True, "min", "min", False),
)
np.testing.assert_allclose(
fit_py.coef(),
stats.coef(fit_r),
rtol=1e-04,
atol=1e-04,
err_msg="WLS: Coefs are not equal.",
)
def _py_fml_to_r_fml(py_fml):
"""
Covernt pyfixest formula.
pyfixest multiple estimation fml syntax to fixest multiple depvar
syntax converter,
i.e. 'Y1 + X2 ~ X' -> 'c(Y1, Y2) ~ X'
"""
py_fml = py_fml.replace(" ", "").replace("C(", "as.factor(")
fml2 = py_fml.split("|")
fml_split = fml2[0].split("~")
depvars = fml_split[0]
depvars = f"c({','.join(depvars.split('+'))})"
if len(fml2) == 1:
return f"{depvars}~{fml_split[1]}"
elif len(fml2) == 2:
return f"{depvars}~{fml_split[1]}|{fml2[1]}"
else:
return f"{depvars}~fml_split{1} | {'|'.join(fml2[1:])}"
def _c_to_as_factor(py_fml):
"""Transform formulaic C-syntax for categorical variables into R's as.factor."""
# Define a regular expression pattern to match "C(variable)"
pattern = r"C\((.*?)\)"
# Define the replacement string
replacement = r"factor(\1, exclude = NA)"
# Use re.sub() to perform the replacement
r_fml = re.sub(pattern, replacement, py_fml)
return r_fml
def get_data_r(fml, data):
# small intermezzo, as rpy2 does not drop NAs from factors automatically
# note that fixes does this correctly
# this currently does not yet work for C() interactions
vars = fml.split("~")[1].split("|")[0].split("+")
factor_vars = []
for var in vars:
if "C(" in var:
var = var.replace(" ", "")
var = var[2:-1]
factor_vars.append(var)
# if factor_vars is not empty
data_r = data[~data[factor_vars].isna().any(axis=1)] if factor_vars else data
return data_r
@pytest.mark.slow
@pytest.mark.parametrize(
"fml",
[
# ("dep_var ~ treat"),
# ("dep_var ~ treat + unit"),
("dep_var ~ treat | unit"),
("dep_var ~ treat + unit | year"),
("dep_var ~ treat | year + unit"),
],
)
@pytest.mark.parametrize("data", [(pd.read_csv("pyfixest/did/data/df_het.csv"))])
@pytest.mark.skip("Wald tests will be released with pyfixest 0.14.0.")
def test_wald_test(fml, data):
fit1 = feols(fml, data)
fit1.wald_test()
fit_r = fixest.feols(
ro.Formula(fml),
data=data,
ssc=fixest.ssc(True, "none", True, "min", "min", False),
)
wald_r = fixest.wald(fit_r)
wald_stat_r = wald_r[0]
wald_pval_r = wald_r[1] # noqa: F841
np.testing.assert_allclose(fit1._f_statistic, wald_stat_r)
# np.testing.assert_allclose(fit1._f_statistic_pvalue, wald_pval_r)
@pytest.mark.slow
def test_singleton_dropping():
data = get_data()
# create a singleton fixed effect
data["f1"].iloc[data.shape[0] - 1] = 999999
fit_py = feols("Y ~ X1 | f1", data=data, fixef_rm="singleton")
fit_py2 = feols("Y ~ X1 | f1", data=data, fixef_rm="none")
fit_r = fixest.feols(
ro.Formula("Y ~ X1 | f1"),
data=data,
ssc=fixest.ssc(True, "none", True, "min", "min", False),
fixef_rm="singleton",
)
# test that coefficients match
coef_py = fit_py.coef().values
coef_py2 = fit_py2.coef().values
coef_r = stats.coef(fit_r)
np.testing.assert_allclose(
coef_py,
coef_py2,
err_msg="singleton dropping leads to different coefficients",
)