/
make-sql-bootstrap.R
233 lines (220 loc) · 6.44 KB
/
make-sql-bootstrap.R
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
#!/usr/bin/env Rscript
buildBootstrapSql <- function (
numReplicates,
dataTable,
dataTableIdColumn = 'id',
bootstrapKind = 'pure',
intervalType = 'percent',
dialect = 'pg',
schema = 'none'
) {
dataTableFrom <- if (schema == 'none')
dataTable
else
if (dialect == 'bq')
paste0('`', schema, '.', dataTable, '` ', dataTable)
else
paste0(schema, '.', dataTable, ' ', dataTable)
random <- if (dialect == 'bq') 'rand' else 'random'
# SQL to sample from Poisson(1) using inverse transform sampling.
buildPoissonSql <- function (variableName, indent = 4, maxN = 15) {
nEvents <- 0:(maxN - 1)
prEvents <- ppois(nEvents, lambda = 1)
indent <- paste0('\n', strrep(' ', 4))
paste0(
'CASE', indent,
paste(
'WHEN bootstrap_u <', prEvents, 'THEN', nEvents,
collapse = indent),
indent,
'ELSE ', maxN, ' END')
}
buildBootstrapIndexesSql <- function () {
if (dialect == 'pg')
paste0('SELECT generate_series(1, ',
numReplicates, ')', ' AS bootstrap_index')
else
paste0('SELECT * FROM UNNEST(generate_array(1, ',
numReplicates, ')) AS bootstrap_index')
}
buildPercentileSql <- function (quantile, expression, indent) {
if (dialect == 'pg')
paste0(
'percentile_cont(', quantile, ') WITHIN GROUP (ORDER BY',
indent, expression, ')')
else
paste0(
'percentile_cont(', expression, ',',
indent, quantile, ') OVER ()')
}
ctes <- paste0(
'WITH bootstrap_indexes AS (\n ', buildBootstrapIndexesSql(), '\n)'
)
if (bootstrapKind == 'pure') {
ctes <- c(
ctes,
paste0(
'bootstrap_data AS (\n',
' SELECT mass,',
' ROW_NUMBER() OVER (ORDER BY ', dataTableIdColumn, ') - 1',
' AS data_index\n',
' FROM ', dataTableFrom,
'\n)'
),
paste0(
'bootstrap_map AS (\n',
' SELECT floor(', random, '() * (\n',
' SELECT count(data_index) FROM bootstrap_data)) AS data_index,\n',
' bootstrap_index\n',
' FROM bootstrap_data\n',
' JOIN bootstrap_indexes ON TRUE',
'\n)'
),
paste0(
'bootstrap AS (\n',
' SELECT bootstrap_index,\n',
if (intervalType == 'percent') {
' avg(mass) AS mass_avg\n'
} else {
paste0(
' avg(mass) AS mass_avg,\n',
' stddev(mass) AS mass_sd\n'
)
},
' FROM bootstrap_map\n',
' JOIN bootstrap_data USING (data_index)\n',
' GROUP BY bootstrap_index',
'\n)'
)
)
} else {
ctes <- c(
ctes,
paste0(
'bootstrap_data AS (\n',
' SELECT mass, bootstrap_index, ',
random, '() AS bootstrap_u\n',
' FROM ', dataTableFrom, '\n',
' JOIN bootstrap_indexes ON TRUE',
'\n)'
),
paste0(
'bootstrap_weights AS (\n',
' SELECT bootstrap_data.*, (',
buildPoissonSql('bootstrap_u'), ') AS bootstrap_weight\n',
' FROM bootstrap_data',
'\n)'
),
if (intervalType == 'percent') {
paste0(
'bootstrap AS (\n',
' SELECT bootstrap_index,\n',
' sum(bootstrap_weight * mass) /',
' sum(bootstrap_weight) AS mass_avg\n',
' FROM bootstrap_weights\n',
' GROUP BY bootstrap_index',
'\n)'
)
} else {
c(
paste0(
'bootstrap_avg AS (\n',
' SELECT bootstrap_index,\n',
' sum(bootstrap_weight * mass) /',
' sum(bootstrap_weight) AS mass_avg\n',
' FROM bootstrap_weights\n',
' GROUP BY bootstrap_index',
'\n)'
),
paste0(
'bootstrap AS (\n',
' SELECT bootstrap_index,\n',
' max(mass_avg) AS mass_avg,\n',
' sqrt(sum(bootstrap_weight * power(mass - mass_avg, 2)) /\n',
' sum(bootstrap_weight)) AS mass_sd\n',
' FROM bootstrap_weights\n',
' JOIN bootstrap_avg USING (bootstrap_index)\n',
' GROUP BY bootstrap_index',
'\n)'
)
)
}
)
}
if (intervalType == 'percent') {
ctes <- c(
ctes,
paste0(
'bootstrap_ci AS (\n',
' SELECT\n',
' ', buildPercentileSql(0.025, 'mass_avg', ' '), ' AS mass_lo,\n',
' ', buildPercentileSql(0.975, 'mass_avg', ' '), ' AS mass_hi\n',
' FROM bootstrap',
if (dialect == 'bq') '\n LIMIT 1' else '',
'\n)'),
paste0(
'sample AS (\n',
' SELECT avg(mass) AS mass_avg\n',
' FROM ', dataTableFrom,
'\n)'
)
)
paste0(
paste(ctes, collapse = ',\n'),
'\n',
'SELECT *\n',
'FROM sample\n',
'JOIN bootstrap_ci ON TRUE;',
'\n'
)
} else {
indent <- '\n '
tSql <- '(bootstrap.mass_avg - sample.mass_avg) / bootstrap.mass_sd'
ctes <- c(
ctes,
paste0(
'sample AS (\n',
' SELECT avg(mass) AS mass_avg, stddev(mass) AS mass_sd\n',
' FROM ', dataTableFrom,
'\n)'
),
paste0(
'bootstrap_q AS (\n',
' SELECT\n',
' ', buildPercentileSql(0.025, tSql, indent), ' AS q_lo,\n',
' ', buildPercentileSql(0.975, tSql, indent), ' AS q_hi\n',
' FROM bootstrap\n',
' JOIN sample ON TRUE',
if (dialect == 'bq') '\n LIMIT 1' else '',
'\n)'
)
)
paste0(
paste(ctes, collapse = ',\n'),
'\n',
'SELECT sample.mass_avg,\n',
' sample.mass_avg - sample.mass_sd * q_hi AS mass_lo,\n',
' sample.mass_avg - sample.mass_sd * q_lo AS mass_hi\n',
'FROM sample\n',
'JOIN bootstrap_q ON TRUE;',
'\n'
)
}
}
if (sys.nframe() == 0L) {
args <- commandArgs(trailingOnly = TRUE)
stopifnot(grepl('^\\d+$', args[1]))
stopifnot(grepl('^cats', args[2]))
stopifnot(args[3] %in% c('pure', 'poisson'))
stopifnot(args[4] %in% c('percent', 'student'))
stopifnot(args[5] %in% c('pg', 'bq'))
stopifnot(args[6] %in% c('sql_bootstrap', 'none'))
cat(buildBootstrapSql(
numReplicates = as.numeric(args[1]),
dataTable = args[2],
bootstrapKind = args[3],
intervalType = args[4],
dialect = args[5],
schema = args[6]
))
}