-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathgcollapse.ado
2013 lines (1781 loc) · 74.5 KB
/
gcollapse.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
*! version 1.3.1 03Nov2021 Mauricio Caceres Bravo, mauricio.caceres.bravo@gmail.com
*! -collapse- implementation using C for faster processing
capture program drop gcollapse
program gcollapse, rclass
version 13.1
global GTOOLS_USER_VARABBREV `c(varabbrev)'
local 00 `0'
* Grab some free timers
FreeTimer
local t97: copy local FreeTimer
global GTOOLS_T97: copy local t97
gtools_timer on `t97'
FreeTimer
local t96: copy local FreeTimer
if ( `t96' == 0 ) {
disp as txt "(note: at least one timer required; overriding timer 96)"
local t96 96
}
global GTOOLS_T96: copy local t96
gtools_timer on `t96'
global GTOOLS_CALLER gcollapse
syntax [anything(equalok)] /// Main function call:
/// [(stat)] varlist [ [(stat)] ... ]
/// [(stat)] target = source [target = source ...] [ [(stat)] ...]
[if] [in] /// [if condition] [in start / end]
[aw fw iw pw] , /// [weight type = exp]
[ ///
by(str) /// Collapse by variabes: [+|-]varname [[+|-]varname ...]
cw /// Drop ocase-wise bservations where sources are missing.
fast /// Do not preserve and restore the original dataset. Saves speed
/// but leaves data unusable if the user hits Break.
///
merge /// Merge statistics back to original data, replacing if applicable
replace /// Allow replacing existing variables with output with merge
noinit /// Do not initialize targets with missing values
freq(passthru) /// Include frequency count with observations per group
///
LABELFormat(passthru) /// Custom label engine: (#stat#) #sourcelabel# is the default
LABELProgram(passthru) /// Program to parse labelformat (see examples)
///
missing /// Preserve missing values for sums
rawstat(passthru) /// Ignore weights for selected variables
///
///
recast /// Recast source variables to save memory
WILDparse /// parse assuming wildcard renaming
unsorted /// Do not sort the data; faster
forceio /// Use disk temp drive for writing/reading collapsed data
forcemem /// Use memory for writing/reading collapsed data
double /// Generate all targets as doubles
sumcheck /// Check whether sum will overflow
NODS DS /// Parse - as varlist (ds) or negative (nods)
///
compress /// Try to compress strL variables
forcestrl /// Force reading strL variables (stata 14 and above only)
Verbose /// Print info during function execution
_subtract /// (Undocumented) Subtract result from source variable
_CTOLerance(passthru) /// (Undocumented) Counting sort tolerance; default is radix
BENCHmark /// print function benchmark info
BENCHmarklevel(int 0) /// print plugin benchmark info
HASHmethod(passthru) /// Hashing method: 0 (default), 1 (biject), 2 (spooky)
oncollision(passthru) /// error|fallback: On collision, use native command or throw error
///
debug /// (internal) Debug
DEBUG_level(int 0) /// (internal) Debug (passed to internals)
debug_replaceby /// (internal) Allow replacing by variables with output
debug_io_read(int 1) /// (internal) Read IO data using mata or C
debug_io_check(real 1e6) /// (internal) Threshold to check for I/O speed gains
debug_io_threshold(real 10) /// (internal) Threshold to switch to I/O instead of RAM
]
* Pre-option parsing
* ------------------
if ( "`debug'" != "" ) local debug_level 9
if ( `benchmarklevel' > 0 ) local benchmark benchmark
local benchmarklevel benchmarklevel(`benchmarklevel')
if ( "`missing'" != "" ) {
local keepmissing keepmissing
disp "Option -missing- is deprecated. Use (nansum) or (rawnansum) instead."
}
local replaceby = cond("`debug_replaceby'" == "", "", "replaceby")
local gfallbackok = `"`replaceby'`replace'`init'`freq'`merge'`labelformat'`labelprogram'`rawstat'"' == `""'
if ( ("`ds'" != "") & ("`nods'" != "") ) {
di as err "-ds- and -nods- mutually exclusive"
exit 198
}
* Parse by call (make sure varlist is valid)
* ------------------------------------------
if ( `"`by'"' != "" ) {
local clean_by: copy local by
local clean_by: subinstr local clean_by "+" " ", all
if ( strpos(`"`clean_by'"', "-") & ("`ds'`nods'" == "") ) {
disp as txt "'-' interpreted as negative; use option -ds- to interpret as varlist"
disp as txt "(to suppress this warning, use option -nods-)"
}
if ( "`ds'" != "" ) {
local clean_by `clean_by'
if ( "`clean_by'" == "" ) {
di as err "Invalid varlist: `by'"
clean_all 198
exit 198
}
cap ds `clean_by'
if ( _rc ) {
cap noi ds `clean_by'
local rc = _rc
clean_all `rc'
exit `rc'
}
local clean_by `r(varlist)'
}
else {
local clean_by: subinstr local clean_by "-" " ", all
local clean_by `clean_by'
if ( "`clean_by'" == "" ) {
di as err "Invalid list: `by'"
di as err "Syntax: [+|-]varname [[+|-]varname ...]"
CleanExit
exit 198
}
cap ds `clean_by'
if ( _rc ) {
local notfound
foreach var of local clean_by {
cap ds `var'
if ( _rc ) {
local notfound `notfound' `var'
}
}
if ( `:list sizeof notfound' > 0 ) {
if ( `:list sizeof notfound' > 1 ) {
di as err "Variables not found: `notfound'"
}
else {
di as err "Variable `notfound' not found"
}
}
CleanExit
exit 111
}
qui ds `clean_by'
local clean_by `r(varlist)'
}
}
if ( "`ds'" == "" ) local nods nods
if ( `debug_level' ) {
disp as txt `""'
disp as txt "Running {cmd:gcollapse} with debug level `debug_level'"
disp as txt "{hline 72}"
disp as txt `""'
disp as txt `" anything: `anything'"'
disp as txt `" [if] [in]: `if' `in'"'
disp as txt `""'
disp as txt `" by: `by'"'
disp as txt `" cw: `cw'"'
disp as txt `" fast: `fast'"'
disp as txt `""'
disp as txt `" merge: `merge'"'
disp as txt `" replace: `replace'"'
disp as txt `" compress: `compress'"'
disp as txt `" forcestrl: `forcestrl'"'
disp as txt `" freq: `freq'"'
disp as txt `" labelformat: `labelformat'"'
disp as txt `" labelprogram: `labelprogram'"'
disp as txt `" unsorted: `unsorted'"'
disp as txt `" forceio: `forceio'"'
disp as txt `" forcemem: `forcemem'"'
disp as txt `" double: `double'"'
disp as txt `""'
disp as txt `" verbose: `verbose'"'
disp as txt `" benchmark: `benchmark'"'
disp as txt `" benchmarklevel: `benchmarklevel'"'
disp as txt `" hashmethod: `hashmethod'"'
disp as txt `" oncollision: `oncollision'"'
disp as txt `""'
disp as txt `" debug_replaceby: `debug_replaceby'"'
disp as txt `" debug_io_read: `debug_io_read'"'
disp as txt `" debug_io_check: `debug_io_check'"'
disp as txt `" debug_io_threshold: `debug_io_threshold'"'
disp as txt "{hline 72}"
disp as txt `""'
}
* Parse options
* -------------
if ( ("`forceio'" != "") & ("`merge'" != "") ) {
di as err "{opt merge} with {opt forceio} is" ///
" inefficient and hence not allowed."
CleanExit
exit 198
}
if ( ("`forceio'" != "") & ("`forcemem'" != "") ) {
di as err "only specify one of {opt forceio} and {opt forcemem};" ///
" cannot do both at the same time."
CleanExit
exit 198
}
local verb = ( "`verbose'" != "" )
local bench = ( "`benchmark'" != "" )
if ( "`fast'" == "" ) preserve
* Parse collapse statement to get sources, targets, and stats
* -----------------------------------------------------------
cap noi parse_vars `anything' `if' `in', ///
`labelformat' `labelprogram' `freq' `wildparse'
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
local __gtools_gc_uniq_targets : list uniq __gtools_gc_targets
local nonunique: list __gtools_gc_targets - __gtools_gc_uniq_targets
if ( `:list sizeof nonunique' != 0 ) {
di as err "Repeat targets not allowed: `:list uniq nonunique'"
CleanExit
exit 198
}
foreach var of local __gtools_gc_uniq_vars {
cap noi confirm numeric variable `var'
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
}
if ( `debug_level' ) {
disp as txt `""'
disp as txt "{cmd:gcollapse} debug level `debug_level'"
disp as txt "{hline 72}"
disp as txt `"parse_vars"'
disp as txt `" anything: `anything'"'
disp as txt `" [if] [in]: `if' `in'"'
disp as txt `""'
disp as txt `" cw: `cw'"'
disp as txt `" fast: `fast'"'
disp as txt `""'
disp as txt `" freq: `freq'"'
disp as txt `" labelformat: `labelformat'"'
disp as txt `" labelprogram: `labelprogram'"'
disp as txt `""'
disp as txt " __gtools_gc_targets: `__gtools_gc_targets'"
disp as txt " __gtools_gc_vars: `__gtools_gc_vars'"
disp as txt " __gtools_gc_stats: `__gtools_gc_stats'"
disp as txt " __gtools_gc_uniq_vars: `__gtools_gc_uniq_vars'"
disp as txt " __gtools_gc_uniq_stats: `__gtools_gc_uniq_stats'"
disp as txt `""'
disp as txt "{hline 72}"
disp as txt `""'
}
* Parse weights
* -------------
if ( `:list posof "count" in __gtools_gc_uniq_stats' > 0 ) {
if ( `"`weight'"' == "aweight" ) {
local awnote 1
}
else local awnote 0
}
else if ( `:list posof "nmissing" in __gtools_gc_uniq_stats' > 0 ) {
if ( `"`weight'"' == "aweight" ) {
local awnote 1
}
else local awnote 0
}
else local awnote 0
if ( `:list posof "variance" in __gtools_gc_uniq_stats' > 0 ) {
if ( `"`weight'"' == "pweight" ) {
di as err "variance not allowed with pweights"
exit 135
}
}
if ( `:list posof "cv" in __gtools_gc_uniq_stats' > 0 ) {
if ( `"`weight'"' == "pweight" ) {
di as err "cv not allowed with pweights"
exit 135
}
}
if ( `:list posof "sd" in __gtools_gc_uniq_stats' > 0 ) {
if ( `"`weight'"' == "pweight" ) {
di as err "sd not allowed with pweights"
exit 135
}
}
if ( `:list posof "semean" in __gtools_gc_uniq_stats' > 0 ) {
if ( inlist(`"`weight'"', "pweight", "iweight") ) {
di as err "semean not allowed with `weight's"
exit 135
}
}
if ( `:list posof "sebinomial" in __gtools_gc_uniq_stats' > 0 ) {
if ( inlist(`"`weight'"', "aweight", "iweight", "pweight") ) {
di as err "sebinomial not allowed with `weight's"
exit 135
}
}
if ( `:list posof "sepoisson" in __gtools_gc_uniq_stats' > 0 ) {
if ( inlist(`"`weight'"', "aweight", "iweight", "pweight") ) {
di as err "sepoisson not allowed with `weight's"
exit 135
}
}
if ( regexm("^select", `"`__gtools_gc_uniq_stats'"') ) {
if ( inlist(`"`weight'"', "iweight") ) {
di as err "select not allowed with `weight's"
exit 135
}
}
if ( `"`weight'"' != "" ) {
tempvar w
qui gen double `w' `exp' `if' `in'
local wgt `"[`weight'=`w']"'
local weights weights(`weight' `w')
}
else local weights
* Subset if requested
* -------------------
if ( (`"`if'`wgt'"' != `""') | ("`cw'" != "") ) {
* marksample touse, strok novarlist
tempvar touse
mark `touse' `if' `in' `wgt'
if ( "`cw'" != "" ) {
markout `touse' `__gtools_gc_uniq_vars', strok
}
if ( "`merge'" == "" ) {
qui keep if `touse'
local ifin ""
}
else local ifin if `touse' `in'
}
else {
local ifin `in'
}
if ( `=_N' == 0 ) {
di as err "no observations"
CleanExit
exit 2000
}
* Parse variables to keep, drop, rename, recast
* ---------------------------------------------
* Parse variables to keep (by variables, sources) and drop (all else).
* Also parse which source variables to recast (see below; we try to use
* source variables as their first target to save memory)
set varabbrev off
cap noi parse_keep_drop, by(`clean_by') `double' ///
`merge' `replace' `replaceby' `sumcheck' `weights' ///
__gtools_gc_targets(`__gtools_gc_targets') ///
__gtools_gc_vars(`__gtools_gc_vars') ///
__gtools_gc_stats(`__gtools_gc_stats') ///
__gtools_gc_uniq_vars(`__gtools_gc_uniq_vars') ///
__gtools_gc_uniq_stats(`__gtools_gc_uniq_stats')
set varabbrev ${GTOOLS_USER_VARABBREV}
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
local dropme ""
local keepvars "`r(keepvars)' `w'"
local added "`r(added)'"
local memvars "`r(memvars)'"
local check_recast "`r(check_recast)'"
scalar __gtools_gc_k_targets = `:list sizeof __gtools_gc_targets'
scalar __gtools_gc_k_vars = `:list sizeof __gtools_gc_vars'
scalar __gtools_gc_k_stats = `:list sizeof __gtools_gc_stats'
scalar __gtools_gc_k_uniq_vars = `:list sizeof __gtools_gc_uniq_vars'
scalar __gtools_gc_k_uniq_stats = `:list sizeof __gtools_gc_uniq_stats'
mata: gtools_vars = tokens(`"`__gtools_gc_vars'"')
mata: gtools_targets = tokens(`"`__gtools_gc_targets'"')
mata: gtools_stats = tokens(`"`__gtools_gc_stats'"')
cap noi CheckMatsize `clean_by'
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
cap noi CheckMatsize `__gtools_gc_vars'
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
cap noi CheckMatsize `__gtools_gc_targets'
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
cap noi CheckMatsize `__gtools_gc_stats'
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
if ( `debug_level' ) {
disp as txt `""'
disp as txt "{cmd:gcollapse} debug level `debug_level'"
disp as txt "{hline 72}"
disp as txt `"parse_keep_drop"'
disp as txt `""'
disp as txt `" by: `by'"'
disp as txt `" clean_by: `clean_by'"'
disp as txt `""'
disp as txt `" merge: `merge'"'
disp as txt `" double: `double'"'
disp as txt `" replace: `replace'"'
disp as txt `" compress: `compress'"'
disp as txt `" forcestrl: `forcestrl'"'
disp as txt `" replaceby: `replaceby'"'
disp as txt `""'
disp as txt `" __gtools_gc_targets: `__gtools_gc_targets'"'
disp as txt `" __gtools_gc_vars: `__gtools_gc_vars'"'
disp as txt `" __gtools_gc_stats: `__gtools_gc_stats'"'
disp as txt `" __gtools_gc_uniq_vars: `__gtools_gc_uniq_vars'"'
disp as txt `" __gtools_gc_uniq_stats: `__gtools_gc_uniq_stats'"'
disp as txt `""'
disp as txt `" dropme: `dropme'"'
disp as txt `" keepvars: `keepvars'"'
disp as txt `" added: `added'"'
disp as txt `" memvars: `memvars'"'
disp as txt `" check_recast: `check_recast'"'
disp as txt `""'
disp as txt `" scalar __gtools_gc_k_targets = `=scalar(__gtools_gc_k_targets)'"'
disp as txt `" scalar __gtools_gc_k_vars = `=scalar(__gtools_gc_k_vars)'"'
disp as txt `" scalar __gtools_gc_k_stats = `=scalar(__gtools_gc_k_stats)'"'
disp as txt `" scalar __gtools_gc_k_uniq_vars = `=scalar(__gtools_gc_k_uniq_vars)'"'
disp as txt `" scalar __gtools_gc_k_uniq_stats = `=scalar(__gtools_gc_k_uniq_stats)'"'
disp as txt `""'
disp as txt "{hline 72}"
disp as txt `""'
}
* Timers!
* -------
local msg "Parsed by variables, sources, and targets"
gtools_timer info `t97' `"`msg'"', prints(`bench')
***********************************************************************
* Recast variables to save memory *
***********************************************************************
* Recast sources, if applicable
mata: st_numscalar("__gtools_gc_k_recast", cols(__gtools_gc_recastvars))
if ( `=scalar(__gtools_gc_k_recast)' > 0 ) {
local gtools_recastvars ""
local gtools_recastsrc ""
forvalues k = 1 / `=scalar(__gtools_gc_k_recast)' {
mata: st_local("var", __gtools_gc_recastvars[`k'])
tempvar dropvar
rename `var' `dropvar'
local dropme `dropme' `dropvar'
local gtools_recastvars `gtools_recastvars' `var'
local gtools_recastsrc `gtools_recastsrc' `dropvar'
}
qui mata: st_addvar(__gtools_gc_recasttypes, __gtools_gc_recastvars, 1)
if ( `=_N > 0' ) {
cap noi _gtools_internal, ///
recast(targets(`gtools_recastvars') sources(`gtools_recastsrc'))
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
}
local msg `"Recast source variables to save memory"'
gtools_timer info `t97' `"`msg'"', prints(`bench')
}
if ( `debug_level' ) {
disp as txt `""'
disp as txt "{cmd:gcollapse} debug level `debug_level'"
disp as txt "{hline 72}"
disp as txt `"recast"'
disp as txt `""'
disp as txt `" gtools_recastvars `gtools_recastvars'"'
disp as txt `" gtools_recastsrc `gtools_recastsrc'"'
disp as txt `""'
disp as txt "{hline 72}"
disp as txt `""'
}
***********************************************************************
* Reorder *
***********************************************************************
local _: list memvars - __gtools_gc_uniq_vars
local memorder: list memvars - _
mata: gtools_vars_mem = tokens("`memorder'")
mata: gtools_pos = gtools_vars :== gtools_targets
mata: gtools_io_order = selectindex(gtools_pos), selectindex(!gtools_pos)
* First, make sure that the sources used as targets appear first
mata: gtools_vars = gtools_vars [gtools_io_order]
mata: gtools_targets = gtools_targets [gtools_io_order]
mata: gtools_stats = gtools_stats [gtools_io_order]
mata: __gtools_gc_labels = __gtools_gc_labels [gtools_io_order]
mata: __gtools_gc_formats = __gtools_gc_formats [gtools_io_order]
* Now make sure that the sources are in memory order
tempname k1 k2 ord
mata: `k1' = cols(gtools_vars_mem)
mata: `k2' = cols(gtools_vars)
mata: `ord' = gtools_vars[1::`k1']
mata: gtools_mem_order = J(1, 0, .)
mata: for(k = 1; k <= `k1'; k++) gtools_mem_order = gtools_mem_order, selectindex(gtools_vars_mem[k] :== `ord')
mata: gtools_mem_order = (`k2' > `k1')? gtools_mem_order, ((`k1' + 1)::`k2')': gtools_mem_order
cap mata: mata drop `k'
cap mata: mata drop `ord'
mata: gtools_vars = gtools_vars [gtools_mem_order]
mata: gtools_targets = gtools_targets [gtools_mem_order]
mata: gtools_stats = gtools_stats [gtools_mem_order]
mata: __gtools_gc_labels = __gtools_gc_labels [gtools_mem_order]
mata: __gtools_gc_formats = __gtools_gc_formats [gtools_mem_order]
* At each step we reordered stats, soruces, and targets!
local __gtools_gc_order `__gtools_gc_targets'
local __gtools_gc_vars ""
local __gtools_gc_targets ""
local __gtools_gc_stats ""
forvalues k = 1 / `=scalar(__gtools_gc_k_targets)' {
mata: st_local("var", gtools_vars [`k'])
mata: st_local("targ", gtools_targets[`k'])
mata: st_local("stat", gtools_stats [`k'])
local __gtools_gc_vars `__gtools_gc_vars' `var'
local __gtools_gc_targets `__gtools_gc_targets' `targ'
local __gtools_gc_stats `__gtools_gc_stats' `stat'
}
local __gtools_gc_uniq_stats: list uniq __gtools_gc_stats
local __gtools_gc_uniq_vars: list uniq __gtools_gc_vars
***********************************************************************
* I/O switch *
***********************************************************************
if ( `"${GTOOLS_TEMPDIR}"' == "" ) {
tempfile __gtools_gc_file
}
else {
GcollapseTempFile __gtools_gc_file
}
scalar __gtools_gc_k_extra = __gtools_gc_k_targets - __gtools_gc_k_uniq_vars
local sources sources(`__gtools_gc_vars')
local stats stats(`__gtools_gc_stats')
local targets targets(`__gtools_gc_targets')
local opts missing replace `init' `keepmissing' `compress' `forcestrl' `_subtract' `_ctolerance'
local opts `opts' `verbose' `benchmark' `benchmarklevel' `hashmethod' `ds' `nods'
local opts `opts' `oncollision' debug(`debug_level') `rawstat'
local action `sources' `targets' `stats'
local switch = (`=scalar(__gtools_gc_k_extra)' > 3) & (`debug_io_check' < `=_N')
local mem = ("`forcemem'" != "") ///
| ("`merge'" != "") ///
| (`=scalar(__gtools_gc_k_extra)' == 0)
local io = ("`forceio'" != "") & (`=scalar(__gtools_gc_k_extra)' > 0)
if ( `io' ) {
* Drop rest of vars
local plugvars `clean_by' `__gtools_gc_uniq_vars'
local dropme `dropme' `:list memvars - keepvars'
local dropme `:list dropme - plugvars'
if ( "`dropme'" != "" ) mata: st_dropvar(tokens(`"`dropme'"'))
local gcollapse gcollapse(forceio, fname(`__gtools_gc_file'))
local action `action' fill(data) `unsorted'
}
else if ( !`mem' & `switch' ) {
* Replace source vars in memory, since they already exist
local plugvars `clean_by' `__gtools_gc_uniq_vars'
* It will be faster to add targets with fewer variables in
* memory. Dropping superfluous variables also saves memory.
local dropme `dropme' `:list memvars - keepvars'
local dropme `:list dropme - plugvars'
* Drop extra vars
if ( "`dropme'" != "" ) mata: st_dropvar(tokens(`"`dropme'"'))
local msg `"Dropped superfluous variables"'
gtools_timer info `t97' `"`msg'"', prints(`bench')
* Benchmark adding 2 variables to gauge how long it might take to
* add __gtools_gc_k_extra targets.
tempvar __gtools_gc_index __gtools_gc_ix __gtools_gc_info
cap noi benchmark_memvars, ///
index(`__gtools_gc_index') ///
ix(`__gtools_gc_ix') ///
info(`__gtools_gc_info')
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
local st_time = `r(st_time)'
gtools_timer info `t97' `"`r(st_str)'"', prints(`bench')
if ( `st_time' > 0 ) {
* Call the plugin with switch option
* ----------------------------------
local st_time st_time(`=`st_time' / `debug_io_threshold'')
local ixinfo ixinfo(`__gtools_gc_index' `__gtools_gc_ix' `__gtools_gc_info')
local gcollapse gcollapse(switch, `st_time' fname(`__gtools_gc_file') `ixinfo')
local action `action' fill(data) `unsorted'
}
else {
* If benchmark was 0, add the vars right now
* ------------------------------------------
qui mata: st_addvar(__gtools_gc_addtypes, __gtools_gc_addvars, 1)
local msg "Generated additional targets"
gtools_timer info `t97' `"`msg'"', prints(`bench')
local gcollapse gcollapse(memory)
local action `action' fill(data) `unsorted'
}
}
else {
local plugvars `clean_by' `__gtools_gc_uniq_vars'
if ( "`merge'" == "" ) local dropme `dropme' `:list memvars - keepvars'
local dropme `:list dropme - plugvars'
if ( "`dropme'" != "" ) mata: st_dropvar(tokens(`"`dropme'"'))
local msg `"Dropped superfluous variables"'
gtools_timer info `t97' `"`msg'"', prints(`bench')
if ( ("`forceio'" == "forceio") & (`=scalar(__gtools_gc_k_extra)' == 0) ) {
if ( `verb' ) {
di as text "(ignored -forceio- because sources are being used as targets)"
}
}
if ( "`added'" != "" ) {
qui mata: st_addvar(__gtools_gc_addtypes, __gtools_gc_addvars, 1)
}
local msg "Generated additional targets"
gtools_timer info `t97' `"`msg'"', prints(`bench')
local gcollapse gcollapse(memory, `merge')
local action `action' `:di cond("`merge'" == "", "fill(data)", "unsorted")'
}
if ( `debug_level' ) {
disp as txt `""'
disp as txt "{cmd:gcollapse} debug level `debug_level'"
disp as txt "{hline 72}"
disp as txt `"recast"'
disp as txt `""'
disp as txt `" scalar __gtools_gc_k_extra = `=scalar(__gtools_gc_k_extra)'"'
disp as txt `""'
disp as txt `" plugvars: `plugvars'"'
disp as txt `" dropme: `dropme'"'
disp as txt `" memvars: `memvars'"'
disp as txt `""'
disp as txt `" sources: `sources'"'
disp as txt `" stats: `stats'"'
disp as txt `" targets: `targets'"'
disp as txt `" unsorted: `unsorted'"'
disp as txt `" opts: `opts'"'
disp as txt `""'
disp as txt `" switch: `switch'"'
disp as txt `" mem: `mem'"'
disp as txt `" io: `io'"'
disp as txt `""'
disp as txt `" gtools_stats: `gtools_stats'"'
disp as txt `""'
disp as txt `" action: `action'"'
disp as txt `" gcollapse: `gcollapse'"'
disp as txt `""'
disp as txt "{hline 72}"
disp as txt `""'
disp `"_gtools_internal `by' `ifin', `opts' `weights' `action' `gcollapse' gfunction(collapse)"'
}
local msg `"Ready for plugin execution"'
gtools_timer info `t97' `"`msg'"', prints(`bench')
cap noi _gtools_internal `by' `ifin', `opts' `weights' `action' `gcollapse' gfunction(collapse)
if ( _rc == 17999 ) {
if ( "`gfallbackok'" != "" ) {
di as err "Cannot use fallback with gtools-only options"
exit 17000
}
local 0 `00'
syntax [anything(equalok)] [if] [in] , [ by(passthru) cw fast *]
collapse `anything' `if' `in', `by' `cw' `fast'
exit 0
}
else if ( _rc == 17001 ) {
local rc = _rc
CleanExit
error 2000
}
else if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
local used_io = `r(used_io)'
local r_N = `r(N)'
local r_J = `r(J)'
local r_minJ = `r(minJ)'
local r_maxJ = `r(maxJ)'
matrix __gtools_invert = r(invert)
* Return values
* -------------
return scalar N = `r_N'
return scalar J = `r_J'
return scalar minJ = `r_minJ'
return scalar maxJ = `r_maxJ'
***********************************************************************
* Finish *
***********************************************************************
gtools_timer on `t97'
if ( "`merge'" == "" ) {
* Keep only the collapsed data
* ----------------------------
qui {
if ( `=`r_J' > 0' ) keep in 1 / `:di %32.0f `r_J''
else if ( `=`r_J' == 0' ) {
keep in 1
drop in 1
}
else if ( `=`r_J' < 0' ) {
di as err "The plugin returned a negative number of groups."
di as err `"This is a bug. Please report to {browse "`website_url'":`website_disp'}"'
CleanExit
exit 17200
}
ds *
}
if ( `=_N' == 0 ) di as txt "(no observations)"
* Make sure no extra variables are present
* ----------------------------------------
local memvars `r(varlist)'
local keepvars `clean_by' `__gtools_gc_targets'
local dropme `:list memvars - keepvars'
if ( "`dropme'" != "" ) mata: st_dropvar(tokens(`"`dropme'"'))
* If we collapsed to disk, read back the data
* -------------------------------------------
local ifcond (`=_N > 0') ///
& (`=scalar(__gtools_gc_k_extra)' > 0) ///
& ( `used_io' | ("`forceio'" == "forceio") )
if ( `ifcond' ) {
qui mata: st_addvar(__gtools_gc_addtypes, __gtools_gc_addvars, 1)
gtools_timer info `t97' `"Added extra targets after collapse"', prints(`bench')
local __gtools_gc_iovars: list __gtools_gc_targets - __gtools_gc_uniq_vars
local gcollapse gcollapse(read, fname(`__gtools_gc_file'))
if ( `debug_io_read' ) {
cap noi _gtools_internal, `gcollapse' `action' gfunction(collapse)
if ( _rc ) {
local rc = _rc
CleanExit
exit `rc'
}
}
else {
local nrow = `=_N'
local ncol = `=scalar(__gtools_gc_k_extra)'
mata: __gtools_gc_data = gtools_get_collapsed (`"`__gtools_gc_file'"', `nrow', `ncol')
mata: st_store(., tokens(`"`__gtools_gc_iovars'"'), __gtools_gc_data)
cap mata: mata drop __gtools_gc_data
}
gtools_timer info `t97' `"Read extra targets from disk"', prints(`bench')
}
* Order variables if they are not in user-requested order
* -------------------------------------------------------
local order = 0
qui ds *
local varorder `r(varlist)'
local varsort `clean_by' `__gtools_gc_order'
foreach varo in `varorder' {
gettoken svar varsort: varsort
if ("`varo'" != "`vars'") local order = 1
}
if ( `order' ) order `clean_by' `__gtools_gc_order'
* Label the things in the style of collapse
* -----------------------------------------
forvalues k = 1 / `:list sizeof __gtools_gc_targets' {
mata: st_varlabel(gtools_targets[`k'], __gtools_gc_labels[`k'])
mata: GtoolsFormatDefaultFallback(gtools_targets[`k'], __gtools_gc_formats[`k'])
}
}
else {
forvalues k = 1 / `:list sizeof __gtools_gc_targets' {
mata: st_varlabel(gtools_targets[`k'], __gtools_gc_labels[`k'])
mata: GtoolsFormatDefaultFallback(gtools_targets[`k'], __gtools_gc_formats[`k'])
}
}
***********************************************************************
* Program Exit *
***********************************************************************
if ( ("`unsorted'" == "") & ("`merge'" == "") ) {
mata: st_local("invert", strofreal(sum(st_matrix("__gtools_invert"))))
if ( `invert' ) {
mata: st_numscalar("__gtools_first_inverted", ///
selectindex(st_matrix("__gtools_invert"))[1])
if ( `=scalar(__gtools_first_inverted)' > 1 ) {
local sortvars ""
forvalues i = 1 / `=scalar(__gtools_first_inverted) - 1' {
local sortvars `sortvars' `:word `i' of `clean_by''
}
sort `sortvars'
}
}
else if ( "`clean_by'" != "" ) {
sort `clean_by'
}
}
if ( "`fast'" == "" ) restore, not
local msg "Program exit executed"
gtools_timer info `t97' `"`msg'"', prints(`bench') off
if ( `awnote' ) {
di as txt "(note: {bf:aweight}s not used to compute {bf:count}s or {bf:nmissing})"
}
CleanExit
exit 0
end
***********************************************************************
* Generic helpers *
***********************************************************************
capture program drop gtools_timer
program gtools_timer, rclass
syntax anything, [prints(int 0) end off]
tokenize `"`anything'"'
local what `1'
local timer `2'
local msg `"`3'; "'
* If timer is 0, then there were no free timers; skip this benchmark
if ( `timer' == 0 ) exit 0
if ( inlist("`what'", "start", "on") ) {
cap timer off `timer'
cap timer clear `timer'
timer on `timer'
}
else if ( inlist("`what'", "info") ) {
timer off `timer'
qui timer list
return scalar t`timer' = `r(t`timer')'
return local pretty`timer' = trim("`:di %21.4gc r(t`timer')'")
if ( `prints' ) di `"`msg'`:di trim("`:di %21.4gc r(t`timer')'")' seconds"'
timer off `timer'
timer clear `timer'
timer on `timer'
}
if ( "`end'`off'" != "" ) {
timer off `timer'
timer clear `timer'
}
end
capture program drop FreeTimer
program FreeTimer
qui {
timer list
local i = 99
while ( (`i' > 0) & ("`r(t`i')'" != "") ) {
local --i
}
}
c_local FreeTimer `i'
end
***********************************************************************
* Gcollapse helpers *
***********************************************************************
cap mata: mata drop gtools_get_collapsed()
mata
real matrix function gtools_get_collapsed(
string scalar fname,
real scalar nrow,
real scalar ncol)
{
real scalar fh
real matrix X
colvector C
fh = fopen(fname, "r")
C = bufio()
X = fbufget(C, fh, "%8z", nrow, ncol)
fclose(fh)
return (X)
}
end
capture program drop parse_vars
program parse_vars
syntax [anything(equalok)] ///
[if] [in] , /// subset
[ ///
WILDparse /// parse assuming wildcard renaming
freq(str) /// include number of observations in group
labelformat(str) /// label prefix
labelprogram(str) /// label prefix
]
* Parse gcollapse call into list of sources, targets, stats
* ---------------------------------------------------------
if ( "`anything'" == "" ) {
di as err "invalid syntax"
exit 198
}
else {
if ( "`wildparse'" != "" ) {
local rc = 0
ParseListWild `anything', loc(__gtools_gc_call)
local __gtools_bak_stats `__gtools_gc_stats'
local __gtools_bak_vars `__gtools_gc_vars'
local __gtools_bak_targets `__gtools_gc_targets'
local __gtools_bak_uniq_stats `__gtools_gc_uniq_stats'
local __gtools_bak_uniq_vars `__gtools_gc_uniq_vars'
ParseList `__gtools_gc_call'
cap assert ("`__gtools_gc_stats'" == "`__gtools_bak_stats'")
local rc = max(_rc, `rc')
cap assert ("`__gtools_gc_vars'" == "`__gtools_bak_vars'")
local rc = max(_rc, `rc')
cap assert ("`__gtools_gc_targets'" == "`__gtools_bak_targets'")
local rc = max(_rc, `rc')
cap assert ("`__gtools_gc_uniq_stats'" == "`__gtools_bak_uniq_stats'")
local rc = max(_rc, `rc')