-
Notifications
You must be signed in to change notification settings - Fork 5
/
_ddml_estimate_linear.ado
2336 lines (2181 loc) · 70.7 KB
/
_ddml_estimate_linear.ado
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
*! ddml v1.4.4
*! last edited: 30aug2024
*! authors: aa/ms
program _ddml_estimate_linear, eclass sortpreserve
version 16
syntax namelist(name=mname) [if] [in] , ///
[ ///
y(varname) /// for estimating by hand...
d(varlist) ///
z(varlist) ///
dh(varname) ///
stdstack /// re-standard-stack
shortstack /// re-short-stack
poolstack /// re-pool-stack
finalest(name) /// relevant only for re-stacking
stdfinalest(name) ///
ssfinalest(name) ///
psfinalest(name) ///
* ]
// default behavior if final estimators specified but stacking options are not
if "`stdfinalest'"~="" & "`stdstack'"=="" local stdstack stdstack
if "`ssfinalest'"~="" & "`shortstack'"=="" local shortstack shortstack
if "`psfinalest'"~="" & "`poolstack'"=="" local poolstack poolstack
if "`stdstack'`shortstack'`poolstack'"=="" & "`finalest'"~="" {
// default when just finalest(.) is specified is to re-stack whatever has been already stacked
mata: st_local("stdflag", strofreal(`mname'.stdflag))
mata: st_local("ssflag", strofreal(`mname'.ssflag))
mata: st_local("psflag", strofreal(`mname'.psflag))
if `stdflag' local stdstack stdstack
if `ssflag' local shortstack shortstack
if `psflag' local poolstack poolstack
}
// restacking
if "`stdstack'"~="" {
// restack
if "`stdfinalest'"=="" local stdfinalest `finalest'
_ddml_estimate_stacking `mname' `if' `in', std finalest(`stdfinalest') `options'
}
if "`shortstack'"~="" {
// restack
if "`ssfinalest'"=="" local ssfinalest `finalest'
_ddml_estimate_stacking `mname' `if' `in', ss finalest(`ssfinalest') `options'
}
if "`poolstack'"~="" {
// restack
if "`psfinalest'"=="" local psfinalest `finalest'
_ddml_estimate_stacking `mname' `if' `in', ps finalest(`psfinalest') `options'
}
// estimation
if "`y'`d'`z'`dh'"=="" {
// main program for estimation
_ddml_estimate_main `mname' `if' `in', `options'
}
else {
// a single user-specified estimation
_ddml_estimate_single `mname' `if' `in', y(`y') d(`d') z(`z') dh(`dh') `options'
}
end
// (re-)stack
program _ddml_estimate_stacking, eclass sortpreserve
version 16
syntax namelist(name=mname) [if] [in] , ///
[ ///
std ///
ss ///
ps ///
finalest(name) ///
NOIsily ///
* ///
]
// blank eqn - declare this way so that it's a struct and not transmorphic
// used multiple times below
tempname eqn
mata: `eqn' = init_eStruct()
if "`noisily'"=="" local qui qui
// macro `ts' is either "std", "ss" or "ts"
// macro `typestack' is either "shortstack" or "poolstack"
if "`std'"~="" {
// standard stacking
local stdflag = 1
local ssflag = 0
local psflag = 0
local typestack stdstack
local ts std
}
else if "`ss'"~="" {
// shortstacking
local stdflag = 0
local ssflag = 1
local psflag = 0
local typestack shortstack
local ts ss
}
else if "`ps'"~="" {
// poolstacking
local stdflag = 0
local ssflag = 0
local psflag = 1
local typestack poolstack
local ts ps
}
else {
// error
di as err "internal _ddml_estimate_stacking error - missing std, ss or ts option"
exit 198
}
marksample touse
mata: st_local("model",`mname'.model)
mata: st_local("nameY",`mname'.nameY)
mata: st_local("nameD",invtokens(`mname'.nameD))
mata: st_local("nameZ",invtokens((`mname'.nameZ)))
local numeqnD : word count `nameD'
local numeqnZ : word count `nameZ'
// reps = total number of reps; crossfitted = reps done so far (=0 if none)
mata: st_local("reps", strofreal(`mname'.nreps))
mata: st_local("kfolds", strofreal(`mname'.kfolds))
mata: st_local("crossfitted", strofreal(`mname'.crossfitted))
// fiv model doesn't support re-stacking
if "`model'"=="fiv" {
di as err "error - re-stacking not supported for model=fiv (flexible partially linear IV model)"
exit 198
}
// with pystacked, will always be a single vtilde and eqn struct for every variable
mata: `eqn' = (`mname'.eqnAA).get("`nameY'")
// used for checking
mata: st_local("pystackedmulti", strofreal(`eqn'.pystackedmulti))
if `pystackedmulti' {
mata: st_local("vtildeY",invtokens(`eqn'.vtlist))
local namelist `nameY'
local vtlist `vtildeY'
}
else {
di as err "error - restacking available only if pystacked is the only learner for each conditional expectation"
exit 198
}
// can be multiple D eqns for multiple D vars, and similarly for Z
foreach vname in `nameD' `nameZ' {
mata: `eqn' = (`mname'.eqnAA).get("`vname'")
// used for checking
mata: st_local("pystackedmulti", strofreal(`eqn'.pystackedmulti))
if `pystackedmulti' {
mata: st_local("vtilde",invtokens(`eqn'.vtlist))
local namelist `namelist' `vname'
local vtlist `vtlist' `vtilde'
}
else {
di as err "error - restacking available only if pystacked is the only learner for each conditional expectation"
exit 198
}
}
tempname sweights stdweights N_folds mse_folds
tempname tframe y_stacking_cv
local numvts : word count `vtlist'
// loop through vtildes
forvalues i=1/`numvts' {
local vname : word `i' of `namelist'
local vtilde : word `i' of `vtlist'
mata: `eqn' = (`mname'.eqnAA).get("`vname'")
mata: st_local("base_est",return_learner_item(`eqn',"`vtilde'","stack_base_est"))
mata: st_local("stype",return_learner_item(`eqn',"`vtilde'","stack_type"))
mata: st_local("etype",`eqn'.etype)
local nlearners : word count `base_est'
// check if previously stacked
if `ssflag' {
mata: st_local("shortstack", `eqn'.shortstack)
if "`shortstack'"=="" {
// not previously shortstacked, set local and struct field to default
local shortstack `etype'_`vname'
mata: `eqn'.shortstack = "`shortstack'"
local newstack 1
}
else {
local newstack 0
}
}
else if `psflag' {
mata: st_local("poolstack", `eqn'.poolstack)
if "`poolstack'"=="" {
// not previously poolstacked, set local and struct field to default
local poolstack `etype'_`vname'
mata: `eqn'.poolstack = "`poolstack'"
local newstack 1
}
else {
local newstack 0
}
}
else local newstack 0
// loop through reps
forvalues m=1/`reps' {
local fid `mname'_fid_`m'
tempvar fidtouse
// assemble learner list
// clear macro
local learner_list
forvalues j=1/`nlearners' {
local learner_list `learner_list' `vtilde'_L`j'_`m'
}
// get stacking weights
tempvar yhat yhat_k
if `ssflag' {
// shortstacking uses crossfit predictions
`qui' _ddml_nnls `vname' `learner_list' if `touse', finalest(`finalest') stype(`stype')
// since original finalest could be default (blank)
local finalest `e(finalest)'
mat `sweights' = e(b)
qui predict double `yhat'
}
else if `stdflag' {
// standard stacking uses stacking CV predictions, stored in a mata struct
qui gen double `yhat' = .
qui gen double `yhat_k' = .
// reset stdweights
cap mat drop `stdweights'
qui frame pwf
local cframe `r(currentframe)'
frame create `tframe'
frame change `tframe'
mata: `y_stacking_cv' = return_result_item(`eqn',"`vtilde'","y_stacking_cv", "`m'")
getmata (`fid' `fidtouse' `vname' `learner_list')=`y_stacking_cv', force replace
forvalues k=1/`kfolds' {
frame change `tframe'
`qui' _ddml_nnls `vname' `learner_list' if `fidtouse'==`k', finalest(`finalest') stype(`stype')
`qui' di as res "N=" e(N)
// since original finalest could be default (blank)
local finalest `e(finalest)'
mata: `sweights' = st_matrix("e(b)")
frame change `cframe'
mata: st_matrix("`sweights'",`sweights')
mat colnames `sweights' = `learner_list'
qui replace `yhat_k' = .
mat score `yhat_k' = `sweights' if `touse' & `mname'_fid_`m'==`k', replace
qui replace `yhat' = `yhat_k' if `mname'_fid_`m'==`k'
mat `stdweights' = nullmat(`stdweights') , `sweights''
}
frame change `cframe'
frame drop `tframe'
cap mata: mata drop `y_stacking_cv'
cap mata: mata drop `sweights'
}
else {
// poolstacking uses stacking CV predictions, stored in a mata struct
qui frame pwf
local cframe `r(currentframe)'
frame create `tframe'
frame change `tframe'
mata: `y_stacking_cv' = return_result_item(`eqn',"`vtilde'","y_stacking_cv", "`m'")
getmata (`fid' `fidtouse' `vname' `learner_list')=`y_stacking_cv', force replace
`qui' _ddml_nnls `vname' `learner_list', finalest(`finalest') stype(`stype')
`qui' di as res "N=" e(N)
// since original finalest could be default (blank)
local finalest `e(finalest)'
mata: `sweights' = st_matrix("e(b)")
frame change `cframe'
frame drop `tframe'
mata: st_matrix("`sweights'",`sweights')
mat colnames `sweights' = `learner_list'
mat score double `yhat' = `sweights' if `touse'
cap mata: mata drop `y_stacking_cv'
cap mata: mata drop `sweights'
}
// Name of newly-stacked variable depends on stacking method.
if `stdflag' {
local nvtilde `vtilde'
local labelmsg "Pred. values E[`vname'|X] using pystacked, rep `m'"
}
else {
local nvtilde ``typestack''_`ts'
local labelmsg "Pred. values E[`vname'|X] using `typestack'ing, rep `m'"
}
if `newstack' {
cap drop `nvtilde'_`m'
qui gen double `nvtilde'_`m' = `yhat'
label var `nvtilde'_`m' "`labelmsg'"
}
else {
if "`noisily'"~="" {
di
di "Existing vs new predicted values:"
sum `nvtilde'_`m' `yhat'
}
qui replace `nvtilde'_`m' = `yhat'
}
get_stack_stats if `touse', kfolds(`kfolds') fid(`mname'_fid_`m') vname(`vname') vhat(`yhat')
local N = r(N)
local mse = r(mse)
mat `N_folds' = r(N_folds)
mat `mse_folds' = r(mse_folds)
// store:
if `stdflag' {
// N and N_folds haven't changed
mata: add_result_item(`eqn',"`vtilde'","MSE", "`m'", `mse')
mata: add_result_item(`eqn',"`vtilde'","MSE_folds", "`m'", st_matrix("`mse_folds'"))
mata: add_result_item(`eqn',"`vtilde'","stack_weights", "`m'", st_matrix("`stdweights'"))
// final estimator used to stack is a learner item
mata: add_learner_item(`eqn',"`vtilde'","stack_final_est", "`finalest'")
// need base estimators as well
mata: add_learner_item(`eqn',"`vtilde'","stack_base_est", "`base_est'")
}
else {
mata: add_result_item(`eqn',"`nvtilde'","N", "`m'", `N')
mata: add_result_item(`eqn',"`nvtilde'","N_folds", "`m'", st_matrix("`N_folds'"))
mata: add_result_item(`eqn',"`nvtilde'","MSE", "`m'", `mse')
mata: add_result_item(`eqn',"`nvtilde'","MSE_folds", "`m'", st_matrix("`mse_folds'"))
mata: add_result_item(`eqn',"`nvtilde'","`ts'_weights", "`m'", st_matrix("`sweights'"))
// final estimator used to stack is a learner item
mata: add_learner_item(`eqn',"`nvtilde'","`ts'_final_est", "`finalest'")
// need base estimators as well
mata: add_learner_item(`eqn',"`nvtilde'","stack_base_est", "`base_est'")
}
// replace updated eqn
mata: (`mname'.eqnAA).put("`vname'",`eqn')
}
}
// update flag on mstruct
if `stdflag' mata: `mname'.stdflag = 1
else if `ssflag' mata: `mname'.ssflag = 1
else mata: `mname'.psflag = 1
// re-stacking means any previous model estimation results should be dropped
mata: clear_model_estimation(`mname')
// no longer needed
cap mata: mata drop `eqn'
end
// utility for stacking results
program get_stack_stats, rclass
version 16
syntax [anything] [if] [in] , [ kfolds(integer 2) fid(varname) vname(varname) vhat(varname) ]
marksample touse
markout `touse' `fid' `vname' `vhat'
tempname mse_folds N_folds mse_list N_list mse_folds_list N_folds_list
// calculate and return mspe and sample size
tempvar vres_sq
// stack macros have fitted values
qui gen double `vres_sq' = (`vname' - `vhat')^2
// additive-type model
qui sum `vres_sq' if `touse', meanonly
local mse = r(mean)
local N = r(N)
forvalues k = 1(1)`kfolds' {
qui sum `vres_sq' if `touse' & `fid'==`k', meanonly
mat `mse_folds' = (nullmat(`mse_folds'), r(mean))
qui count if `touse' & `fid'==`k' & `vres_sq'<.
mat `N_folds' = (nullmat(`N_folds'), r(N))
}
return scalar mse = `mse'
return scalar N = `N'
return mat mse_folds = `mse_folds'
return mat N_folds = `N_folds'
end
// a single user-specified estimation
program _ddml_estimate_single, eclass sortpreserve
version 16
syntax namelist(name=mname) [if] [in] , ///
[ ///
y(varname) /// for estimating by hand...
d(varlist) ///
z(varlist) ///
dh(varname) ///
ROBust ///
CLUster(varname) ///
vce(string) ///
NOConstant ///
* ]
mata: st_local("model",`mname'.model)
mata: st_local("nameY",`mname'.nameY)
mata: st_local("nameD",invtokens(`mname'.nameD))
mata: st_local("nameZ",invtokens((`mname'.nameZ)))
local numeqnD : word count `nameD'
local numeqnZ : word count `nameZ'
// checks
if "`y'"=="" {
di as err "option y(.) missing"
exit 198
}
if "`d'"=="" {
di as err "option d(.) missing"
exit 198
}
if "`model'"=="partial" {
if "`z'"~="" {
di as err "z(.) should be empty for model=partial"
exit 198
}
local numD : word count `d'
if `numD'~=`numeqnD' {
di as err "error - model has `numeqnD' D variables but `numD' specified"
exit 198
}
}
else if "`model'"=="iv" {
if "`z'"=="" {
di as err "option z(.) missing"
exit 198
}
}
else if "`model'"=="fiv" {
if "`z'"~="" {
di as err "z(.) should be empty for model=fiv"
exit 198
}
if "`dh'"=="" {
di as err "option dh(.) missing"
exit 198
}
}
else {
di as err "error - unknown model `model'"
exit 198
}
// residualization
tempvar yt
qui gen double `yt' = `nameY' - `y'
if "`model'"~="fiv" {
// applies to plm and iv models
forvalues i=1/`numeqnD' {
tempvar d_resid
local dname_i : word `i' of `nameD'
local dtilde_i : word `i' of `d'
qui gen double `d_resid' = `dname_i' - `dtilde_i'
local d_resid_list `d_resid_list' `d_resid'
}
// if plm model, won't enter
forvalues i=1/`numeqnZ' {
tempvar z_resid
local zname_i : word `i' of `nameZ'
local ztilde_i : word `i' of `z'
qui gen double `z_resid' = `zname_i' - `ztilde_i'
local z_resid_list `z_resid_list' `z_resid'
}
}
else {
// create new D and Z
tempvar d_resid_list z_resid_list
qui gen double `d_resid_list' = `nameD' - `dh'
qui gen double `z_resid_list' = `d' - `dh'
}
if "`robust'"!="" local vce robust
if "`cluster'"~="" local vce cluster `cluster'
tempname b V
tempvar esample
marksample touse
if "`model'"=="partial" {
qui reg `yt' `d_resid_list' if `touse', vce(`vce') `noconstant'
}
else {
qui reg `yt' `d_resid_list' (`z_resid_list') if `touse', vce(`vce') `noconstant'
}
mat `b'=e(b)
mat `V'=e(V)
local cnames `nameD'
if "`noconstant'"=="" {
local cnames `cnames' _cons
}
mat colnames `b' = `cnames'
mat colnames `V' = `cnames'
mat rownames `V' = `cnames'
local N=e(N)
local vcetype `e(vcetype)'
local clustvar `e(clustvar)'
qui gen byte `esample'=e(sample)
ereturn post `b' `V', depname(`nameY') obs(`N') esample(`esample')
ereturn local cmd ddml
ereturn local model `model'
ereturn local mname `mname'
ereturn local dh `dh'
ereturn local z `z'
ereturn local d `d'
ereturn local y `y'
ereturn local vce `vce'
ereturn local vcetype `vcetype'
di
di as text "y-E[y|X]" _col(11) "= " as res "`e(y)'" _c
di as text _col(52) "Number of obs =" _col(70) as res %9.0f `e(N)'
if "`e(model)'"~="fiv" {
di as text "D-E[D|X]" _col(11) "= " as res "`e(d)'"
}
else {
di as text "E[D|X,Z]" _col(11) "= " as res "`e(d)'"
}
if "`e(model)'" == "iv" {
di as text "Z-E[Z|X]" _col(11) "= " as res "`e(z)'"
}
else if "`e(model)'" == "fiv" {
di as text "E[D^|X]" _col(11) "= " as res "`e(dh)'"
}
if "`e(model)'" == "fiv" {
di as text "Orthogonalized D = D - E[D^|X]; optimal IV = E[D|X,Z] - E[D^|X]."
}
ereturn display
end
// main estimation program
program _ddml_estimate_main
version 16
syntax namelist(name=mname) [if] [in] , ///
[ ///
ROBust ///
CLUster(varname) ///
NOConstant /// suppress constant in estimation
SHOWConstant /// display constant in summary table
vce(string) ///
allcombos /// estimate and show all combinations (dfn changed below)
NOTable /// suppress summary table
clear /// deletes all tilde-variables (to be implemented)
spec(string) /// specification to post/display
REP(string) /// resampling iteration to post/display or mean/median
replay /// model has been estimated, just display results
debug ///
NOIsily ///
]
if "`debug'`noisily'"=="" local qui qui
** standard errors
// local vce is the argument to the Stata option vce(.)
if "`robust'"!="" local vce robust
if "`cluster'"~="" local vce cluster `cluster'
marksample touse
// consflag
local cons = ("`noconstant'"=="")
local showconsflag = ("`showconstant'"~="" & `cons') // ignored if nocons
// replay existing results
local replayflag = "`replay'"~=""
// display summary table
local tableflag = "`notable'"==""
// request estimation/reporting of all combinations
local doallcombos = "`allcombos'"~=""
// remaining macro flags
mata: st_local("nreps",strofreal(`mname'.nreps))
mata: st_local("crossfitted",strofreal(`mname'.crossfitted))
mata: st_local("stdflag",strofreal(`mname'.stdflag))
mata: st_local("ssflag",strofreal(`mname'.ssflag))
mata: st_local("psflag",strofreal(`mname'.psflag))
// can't estimate unless crossfitted first
if `crossfitted'==0 {
di as err "error - model must be crossfitted before final estimation"
exit 198
}
else if `crossfitted'<`nreps' {
di as err "error - total reps=`nreps' but only `crossfitted' reps crossfitted"
exit 198
}
// reestimation necessary unless replay specified
if `replayflag' {
// estimated macro =0/1 indicating estimation results exist
mata: st_local("estimated", strofreal(`mname'.estimated))
// initial ncombos; will be 0 if all combos not (yet) estimated
mata: st_local("ncombos", strofreal(`mname'.ncombos))
// error checks
if `estimated'==0 {
di as err "error - replay specified but model not yet estimated"
exit 198
}
if `ncombos'==0 & "`spec'"~="" & real("`spec'")<. & real("`spec'")>1 {
di as err "error - spec(`spec') not available; add 'allcombos' to estimate all combinations"
di as err "add 'replay' to retrieve one of the available estimations stored in memory"
exit 198
}
}
else {
// error checks
if `doallcombos'==0 & "`spec'"~="" & real("`spec'")<. & real("`spec'")>1 {
di as err "error - spec(`spec') not available; add 'allcombos' to estimate all combinations"
exit 198
}
mata: clear_model_estimation(`mname')
local estimated = 0
local ncombos = 0
}
// number of possible combos; if only one spec, will replace "mse" label
mata: st_local("poss_combos",strofreal(return_ncombos(`mname')))
if `doallcombos' & (`poss_combos'==1) {
di as text "only one possible combination of specifications; allcombos option ignored"
local doallcombos = 0
}
// blank eqn - declare this way so that it's a struct and not transmorphic
tempname eqn
mata: `eqn' = init_eStruct()
// locals used below
mata: st_local("model",`mname'.model)
mata: st_local("nameY",`mname'.nameY)
mata: st_local("nameD",invtokens(`mname'.nameD))
mata: st_local("nameZ",invtokens((`mname'.nameZ)))
local numeqnD : word count `nameD'
local numeqnZ : word count `nameZ'
local ivflag = "`model'"=="iv"
local fivflag = "`model'"=="fiv"
local allpystackedmulti = 1
foreach vname in `nameY' `nameD' `nameZ' {
mata: `eqn' = (`mname'.eqnAA).get("`vname'")
mata: st_local("pystackedmulti", strofreal(`eqn'.pystackedmulti))
local allpystackedmulti = `allpystackedmulti' & `pystackedmulti'
}
// reset stdflag (standard stacking) and psflag (pooled stacking)
// if not all eqns are pystacked multi-learners
// nb: stdflag may also be 0 if pystacked is used with voting to get short-stacked only
if `allpystackedmulti'==0 {
local stdflag =0
local psflag =0
}
// numspecflag=1 unless there is no numbered (i.e. not numbers, ss or ps) spec
// possible with all pystacked and only shortstacking
local numspecflag = (`allpystackedmulti'==0) | (`stdflag'==1) | (`psflag'==1)
// default specs, in order/if available: ss, ps, mse if ncombos>1, otherwise 1 since ncombos=1
if "`spec'"=="" {
if `ssflag' {
local spec "ss"
}
else if "`spec'"=="" & `poss_combos'>1 {
local spec "mse"
}
else if `stdflag' {
local spec st
}
else if "`spec'"=="" {
local spec 1
}
}
// allowed forms of spec and rep
if "`spec'"=="shortstack" local spec ss
if "`spec'"=="poolstack" local spec ps
if "`spec'"=="minmse" local spec mse
if "`rep'"=="mean" local rep mn
if "`rep'"=="median" local rep md
// if rep not specified, default is rep=1 when nreps==1; md if nreps>1
if "`rep'"=="" & `nreps'>1 {
local rep md
}
else if "`rep'"=="" & `nreps'==1 {
local rep 1
}
// checks
if "`spec'"~="ss" & "`spec'"~="ps" & "`spec'"~="mse" & "`spec'"~="st" & real("`spec'")==. {
di as err "error - invalid spec(`spec')"
exit 198
}
if real("`rep'")==. {
// rep is an integer or mn/md
if "`rep'"~="mn" & "`rep'"~="md" {
di as err "error - illegal rep(.) option `rep'"
exit 198
}
}
else {
if (real("`rep'")<1) | (real("`rep'")~=int(real("`rep'"))) {
di as err "error - illegal rep(.) option `rep'"
exit 198
}
}
// check that rep, if integer, isn't larger than nreps
if real("`rep'")!=. {
if `rep'>`nreps' {
di as err "rep() cannot be larger than `nreps' in current model specification"
exit 198
}
}
// shortstack and poolstack names
if `ssflag' {
mata: `eqn' = (`mname'.eqnAA).get("`nameY'")
mata: st_local("shortstack", `eqn'.shortstack)
local Yss `shortstack'_ss
foreach var in `nameD' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("shortstack", `eqn'.shortstack)
local Dss `Dss' `shortstack'_ss
}
if `fivflag' {
foreach var in `nameD' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("shortstack", `eqn'.shortstack)
local Zss `Zss' `shortstack'_h_ss
}
}
else {
foreach var in `nameZ' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("shortstack", `eqn'.shortstack)
local Zss `Zss' `shortstack'_ss
}
}
}
if `psflag' {
mata: `eqn' = (`mname'.eqnAA).get("`nameY'")
mata: st_local("poolstack", `eqn'.poolstack)
local Yps `poolstack'_ps
foreach var in `nameD' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("poolstack", `eqn'.poolstack)
local Dps `Dps' `poolstack'_ps
}
if `fivflag' {
foreach var in `nameD' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("poolstack", `eqn'.poolstack)
local Zps `Zps' `poolstack'_h_ps
}
}
else {
foreach var in `nameZ' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("poolstack", `eqn'.poolstack)
local Zps `Zps' `poolstack'_ps
}
}
}
// multiple specs
// text locals control messages and lookups
if `replayflag' {
local spectext `spec'
}
else if `poss_combos'>1 {
local msetext "min-mse "
local MSEtext "Min MSE "
local sttext
local STtext
local spectext mse
}
else if `stdflag' {
local msetext
local MSEtext
local sttext "stacking "
local STtext "Stacking "
local spectext st
}
else {
local msetext
local MSEtext
local sttext
local STtext
local spectext 1
}
************* ESTIMATE ************
if `estimated'==0 {
// enter if no estimates exist
// Loop over resamples and estimate/save the min mse and ss/ps models for each
forvalues m=1/`nreps' {
// text used in output below
// multiple reps
if `nreps'>1 {
local stext " (sample=`m')"
}
// reset locals
local Yopt
local Dopt
local Zopt
*** retrieve best model
mata: `eqn' = (`mname'.eqnAA).get("`nameY'")
mata: st_local("Yopt",return_learner_item(`eqn',"opt","`m'"))
foreach var in `nameD' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("oneDopt",return_learner_item(`eqn',"opt","`m'"))
local Dopt `Dopt' `oneDopt'
// DHopt is stored in list Zopt
if "`model'"=="fiv" {
mata: st_local("oneDHopt",return_learner_item(`eqn',"opt_h","`m'"))
local Zopt `Zopt' `oneDHopt'
}
}
// nameZ is empty for fiv model
foreach var in `nameZ' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("oneZopt",return_learner_item(`eqn',"opt","`m'"))
local Zopt `Zopt' `oneZopt'
}
// estimate optimal (or only numbered) spec for this rep
if `numspecflag' {
local title "`STtext'`MSEtext'DDML model`stext'"
`qui' estimate_and_store if `mname'_sample_`m' & `touse', ///
`noconstant' vce(`vce') ///
y(`Yopt') yname(`nameY') ///
d(`Dopt') dnames(`nameD') ///
z(`Zopt') znames(`nameZ') ///
mname(`mname') spec(`spectext') rep(`m') ///
title(`title')
}
// estimate shortstack for this rep
if `ssflag' {
local title "Shortstack DDML model`stext'"
`qui' estimate_and_store if `mname'_sample_`m' & `touse', ///
`noconstant' vce(`vce') ///
y(`Yss') yname(`nameY') ///
d(`Dss') dnames(`nameD') ///
z(`Zss') znames(`nameZ') ///
mname(`mname') spec(ss) rep(`m') ///
title(`title')
}
// estimate poolstack for this rep
if `psflag' {
local title "Poolstack DDML model`stext'"
`qui' estimate_and_store if `mname'_sample_`m' & `touse', ///
`noconstant' vce(`vce') ///
y(`Yps') yname(`nameY') ///
d(`Dps') dnames(`nameD') ///
z(`Zps') znames(`nameZ') ///
mname(`mname') spec(ps) rep(`m') ///
title(`title')
}
}
// have looped over reps to get each optimal model and shortstack per rep
// now aggregate over reps to get mean/median
// need to pass info about whether a constant was estimated; it won't be stored with med/mn results
if `nreps' > 1 {
// numbered/stacking estimates
if `numspecflag' {
local title "Mean over `nreps' `sttext'`msetext'resamples"
`qui' medmean_and_store, mname(`mname') spec(`spectext') medmean(mn) title(`title') `noconstant'
local title "Median over `nreps' `sttext'`msetext'resamples"
`qui' medmean_and_store, mname(`mname') spec(`spectext') medmean(md) title(`title') `noconstant'
}
// shortstack
if `ssflag' {
local title "Shortstack DDML model (mean over `nreps' resamples)"
`qui' medmean_and_store, mname(`mname') spec(ss) medmean(mn) title(`title') `noconstant'
local title "Shortstack DDML model (median over `nreps' resamples)"
`qui' medmean_and_store, mname(`mname') spec(ss) medmean(md) title(`title') `noconstant'
}
// poolstack
if `psflag' {
local title "Poolstack DDML model (mean over `nreps' resamples)"
`qui' medmean_and_store, mname(`mname') spec(ps) medmean(mn) title(`title') `noconstant'
local title "Poolstack DDML model (median over `nreps' resamples)"
`qui' medmean_and_store, mname(`mname') spec(ps) medmean(md) title(`title') `noconstant'
}
}
// Estimation of med/med/shortstack complete, mark as estimated.
mata: `mname'.estimated = 1
// (re-)set estimated
mata: st_local("estimated", strofreal(`mname'.estimated))
}
******************************************
if `ncombos' {
// all combos have already been estimated, so just recover matrices
tempname nmat bmat semat
mata: `nmat' = (`mname'.estAA).get(("nmat","all"))
mata: `bmat' = (`mname'.estAA).get(("bmat","all"))
mata: `semat' = (`mname'.estAA).get(("semat","all"))
// recover min MSE specs
forvalues m=1/`nreps' {
mata: check_spec(`mname',"optspec","`m'")
mata: st_local("optspec",(`mname'.estAA).get(("optspec","`m'")))
local optspec`m' = `optspec'
}
}
else if `doallcombos' {
// allcombos need to be estimated
// get varlists
_ddml_make_varlists, mname(`mname')
local yvars `r(yvars)'
local dvars `r(dvars)'
local zvars `r(zvars)'
local zpos `r(zpos_start)'
// obtain all combinations
_ddml_allcombos `yvars' - `dvars' - `zvars' , ///
`debug' ///
zpos(`zpos') ///
addprefix("")
local ncombos = r(ncombos)
local tokenlen = `ncombos'*2
local ylist `r(ystr)'
local Dlist `r(dstr)'
local Zlist `r(zstr)'
tempname nmat bmat semat
mata: `nmat' = J(`ncombos',3,"")
mata: `bmat' = J(`ncombos'*`nreps',`numeqnD'+`cons',.)
mata: `semat' = J(`ncombos'*`nreps',`numeqnD'+`cons',.)
// simplest if put into a Mata string matrix
tokenize `ylist' , parse("-")
forvalues i=1/`ncombos' {
local idx = 2*`i'-1
mata: `nmat'[`i',1] = strtrim("``idx''")
}
tokenize `Dlist' , parse("-")
forvalues i=1/`ncombos' {
local idx = 2*`i'-1
mata: `nmat'[`i',2] = strtrim("``idx''")
}
tokenize `Zlist' , parse("-")
forvalues i=1/`ncombos' {
local idx = 2*`i'-1
mata: `nmat'[`i',3] = strtrim("``idx''")
}
forvalues m=1/`nreps' {
// reset locals
local Yopt
local Dopt
local Zopt
*** retrieve best model
mata: `eqn' = (`mname'.eqnAA).get("`nameY'")
mata: st_local("Yopt",return_learner_item(`eqn',"opt","`m'"))
foreach var in `nameD' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("oneDopt",return_learner_item(`eqn',"opt","`m'"))
local Dopt `Dopt' `oneDopt'
// DHopt is stored in list Zopt
if "`model'"=="fiv" {
mata: st_local("oneDHopt",return_learner_item(`eqn',"opt_h","`m'"))
local Zopt `Zopt' `oneDHopt'
}
}
// nameZ is empty for fiv model
foreach var in `nameZ' {
mata: `eqn' = (`mname'.eqnAA).get("`var'")
mata: st_local("oneZopt",return_learner_item(`eqn',"opt","`m'"))
local Zopt `Zopt' `oneZopt'
}
// text used in output below
if `nreps'>1 {
local stext " (sample=`m')"
}
forvalues i = 1/`ncombos' {
mata: st_local("y",`nmat'[`i',1])
mata: st_local("d",`nmat'[`i',2])
mata: st_local("z",`nmat'[`i',3])
// check if opt for this resample; note === for D so order doesn't matter
local isopt
local isYopt : list Yopt == y
local isDopt : list Dopt === d
local isZopt : list Zopt === z
local title "DDML model, specification `i'`stext'"
if `isYopt' & `isDopt' & `isZopt' {
local optspec`m' = `i'
local isopt *
local title `MSEtext'`title'
// save in AA
mata: (`mname'.estAA).put(("optspec","`m'"),"`i'")
}
`qui' estimate_and_store if `mname'_sample_`m' & `touse', ///