-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.jl
executable file
·422 lines (317 loc) · 12.1 KB
/
solver.jl
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
#!/usr/bin/env julia
# Written in October 2021 by Brenton Horne
using StatsFuns, CSV, DataFrames, Statistics, SpecialFunctions
using LinearAlgebra
"""
getVars(group::Vector{Int64}, y::Vector{Float64})
Compute various required variables from the independent and dependent
variables.
Parameters
----------
`group::Vector{Int64}`: Contains values of the grouping (independent) variable.
`y::Vector{Float64}`: Contains values of the dependent (response) variable.
Returns
-------
`m::Int64`: number of groups.
`n::Int64`: total number of observations.
`ni::Int64`: maximum sample size.
`alphavec::Matrix{BigFloat}`: m x 1 matrix of initial guess values for the
maximum likelihood estimator (MLE) of ``\\alpha_i``.
`nvec::Matrix{Int64}`: m x 1 matrix of the sample sizes of each group.
`yarr::Matrix{BigFloat}`: m x ni matrix of the observations, with the m rows
corresponding to different values of the grouping variable.
`ybarvec::Matrix{BigFloat}`: m x 1 matrix of the mean of each group.
"""
function getVars(group, y)
# Number of groups should equal the number of unique values of the grouping
# variable
m = Int(length(unique(group)))
# nvec's elements should equal the number of observations for each value of
# the grouping variable.
nvec = zeros((m, 1))
for i=1:m
nvec[i, 1] = length(y[isequal.(group, i)])
end
nvec = Int.(nvec)
# Simpler to calculate variables
n = length(y)
ni = maximum(nvec)
# Put observations from y into rows based on the corresponding value of the
# grouping variable
yarr = BigFloat.(zeros((m, ni)))
for i=sort(unique(group))
for j=1:nvec[i, 1]
yarr[i,j] = y[isequal.(group, i)][j]
end
end
# Means
ybar = mean(y)
ybarvec = mean(yarr, dims=2)
ybarvec = reshape(ybarvec, m, 1)
# Let's use a simple initial guess for the MLE of alpha_i, we know it's
# greater than 0
alphavec = 10 * BigFloat.(ones((m, 1)))
return m, n, ni, alphavec, nvec, yarr, ybar, ybarvec
end
"""
funjacUnr(alphavec::Matrix{BigFloat}, nvec::Matrix{Int64},
yarr::Matrix{BigFloat}, ybarvec::Matrix{BigFloat})
Compute the inverse of the Jacobian and the matrix of function values for
computing the unrestricted maximum likelihood estiamtor (MLE) of ``\\alpha_i``.
Parameters
----------
`alphavec::Matrix{BigFloat}`: m x 1 matrix of values of our current estimate
of the MLE of ``\\alpha_i``.
`nvec::Matrix{Int64}`: m x 1 matrix of sample sizes of each group.
`yarr::Matrix{Float64}`: m x ni matrix of observations in rows that correspond
to different values of the grouping variable.
`ybarvec::Matrix{Float64}`: m x 1 matrix of sample means.
Returns
-------
`Jinv::Diagonal{BigFloat, Vector{BigFloat}}`: inverse of the Jacobian for the
unrestricted MLE problem.
`F::Matrix{BigFloat}`: m x 1 matrix of function values for the unrestricted MLE
problem.
"""
function funjacUnr(m, alphavec, nvec, yarr, ybarvec)
# Jinv is a diagonal matrix composed of elements of
# 1/(partial g_k/partial alpha_i)
# Alphavec must be converted to Float64 for polygamma,
# for some reason it cannot handle BigFloat.
Jinv = Diagonal(vec((nvec .* (alphavec.^(-1)-
polygamma.(1, Float64.(alphavec)))).^(-1)))
# Defining logsum to make F's definition shorter
logsum = reshape(sum(log.(yarr), dims=2), (m, 1))
F = - nvec .* (polygamma.(0, Float64.(alphavec)) +
log.(ybarvec .* alphavec.^(-1))) + logsum
return Jinv, F
end
"""
funjacNull(alpha::BigFloat, n::Int64, yarr::Matrix{BigFloat},
ybar::BigFloat)
Compute the derivative and function value required to compute the maximum
likelihood estimator (MLE) of ``\\alpha`` under the null hypothesis.
Parameters
----------
`alpha::BigFloat`: current estimate of the MLE of `\\alpha`.
`n::Int64`: total number of observations.
`yarr::Matrix{BigFloat}`: m x ni matrix of observations with different rows
corresponding to different values of the grouping variable.
`ybar::BigFloat`: mean of all observations.
Returns
-------
`J::BigFloat`: function derivative value.
`F::BigFloat`: function value.
"""
function funjacNull(alpha, n, yarr, ybar)
J = n * (1/alpha - polygamma(1, Float64(alpha)))
F = -n * (polygamma(0, Float64(alpha)) + log(ybar/alpha)) + sum(log.(yarr))
return J, F
end
"""
newtonsUnr(m::Int64, alphavec::Matrix{BigFloat}, nvec::Matrix{Int64},
yarr::Matrix{BigFloat}, ybarvec::Matrix{BigFloat}, itMax::Int64,
tol::Float64)
Estimate the unrestricted maximum likelihood estimator (MLE) of ``\\alpha_i``
using Newton's method.
Parameters
----------
`m::Int64`: number of groups.
`alphavec::Matrix{BigFloat}`: m x 1 matrix of values of our initial estimate
of the MLE of ``\\alpha_i``.
`nvec::Matrix{Int64}`: m x 1 matrix of sample sizes of each group.
`yarr::Matrix{Float64}`: m x ni matrix of observations in rows that correspond
to different values of the grouping variable.
`ybarvec::Matrix{Float64}`: m x 1 matrix of sample means.
`itMax::Int64`: maximum number of iterations of Newton's method that can be
used.
`tol::Float64`: relative error tolerance.
Returns
-------
`alphavec::Matrix{BigFloat}`: m x 1 matrix of values of our improved estimate
of the MLE of ``\\alpha_i``.
"""
function newtonsUnr(m, alphavec, nvec, yarr, ybarvec, itMax, tol)
# Obtain what vars we need for iteration 1
Jinv, F = funjacUnr(m, alphavec, nvec, yarr, ybarvec)
eps = -Jinv * F
epsRel = eps .* alphavec.^(-1)
diff = sqrt(sum(epsRel.^2)/m)
# Initialize our counter
iteration = 0
# Iterate until we get a satisfactorily accurate estimate for the MLE
while ((tol < diff) && (iteration < itMax))
alphavec += eps
Jinv, F = funjacUnr(m, alphavec, nvec, yarr, ybarvec)
eps = -Jinv * F
epsRel = eps .* alphavec.^(-1)
diff = sqrt(sum((epsRel.^2)/m))
iteration += 1
end
return alphavec
end
"""
newtonsNull(alpha::BigFloat, n::Int64, yarr::Matrix, ybar::Float64,
itMax::Int64, tol::Float64)
Estimate the maximum likelihood estimator (MLE) of alpha under the null using
Newton's method.
Parameters
----------
`alpha::BigFloat`: initial estimate of the MLE of `\\alpha`.
`n::Int64`: total number of observations.
`yarr::Matrix{BigFloat}`: m x ni matrix of observations with different rows
corresponding to different values of the grouping variable.
`ybar::BigFloat`: mean of all observations.
Returns
-------
`alpha::BigFloat`: improved estimate of the MLE of `\\alpha`.
"""
function newtonsNull(alpha, n, yarr, ybar, itMax, tol)
# Obtain what vars we need for iteration 1
J, F = funjacNull(alpha, n, yarr, ybar)
eps = -F/J
# Initialize iteration counter
iteration = 0
# Iterate until we get a satisfactorily accurate for the MLE
while ((tol < eps/alpha) && (iteration < itMax))
alpha += eps
J, F = funjacNull(alpha, n, yarr, ybar)
eps = -F/J
iteration +=1
end
return alpha
end
"""
gammaTest(m::Int64, n::Int64, ni::Int64, alphavec::Matrix{BigFloat},
nvec::Matrix{Int64}, group::Vector{Int64}, yarr::Matrix{BigFloat},
ybar::BigFloat, ybarvec::Matrix{BigFloat})
Perform the gamma likelihood-ratio test and return the maximum likelihood
estimator (MLEs), likelihood ratio, test statistic and p-value.
Parameters
----------
`m::Int64`: number of groups.
`n::Int64`: total number of observations.
`ni::Int64`: maximum sample size.
`alphavec::Matrix{BigFloat}`: m x 1 matrix of MLE of ``\\alpha_i``.
`nvec::Matrix{Int64}`: m x 1 matrix of sample sizes for each group.
`group::Vector{Int64}`: vector of values of the grouping variable.
`yarr::Matrix{BigFloat}`: m x ni matrix of observed values of dependent
variable.
`ybar::BigFloat`: overall mean of dependent variable.
`ybarvec::Matrix{BigFloat}`: m x 1 matrix of the mean of each sample
(treatment group).
Returns
-------
`alpha::BigFloat`: the MLE of ``\\alpha`` under the null.
`beta::BigFloat`: the MLE of ``\\beta`` under the null.
`alphavec::BigFloat`: the unrestricted MLE of ``\\alpha_i``.
`betavec::BigFloat`: the unrestricted MLE of ``\\beta_i``.
`lam::BigFloat`: ``\\lambda``, the likelihood-ratio.
`stat::BigFloat`: ``-2\\ln(\\lambda)``, our test statistic.
`pval::BigFloat`: p-value of our test.
"""
function gammaTest(m, n, ni, alphavec, nvec, group, yarr, ybar, ybarvec)
# Specify constraints of Newton's
itMax = 1e3
tol = 1e-13
# Estimate unrestricted MLEs
alphavec = newtonsUnr(m, alphavec, nvec, yarr, ybarvec, itMax, tol)
betavec = alphavec.^(-1) .* ybarvec
# Estimate MLEs under null
alpha = 1
alpha = newtonsNull(alpha, n, yarr, ybar, itMax, tol)
beta = ybar/alpha
# Likelihood ratio
lam = (gamma(alpha) * (ybar/alpha)^(alpha))^(-n)
lam *= prod(prod(yarr.^(alpha*ones(length(alphavec), 1)-alphavec), dims=2))
lam *= prod((gamma.(alphavec) .* (ybarvec.*alphavec.^(-1)).^(alphavec)).^(nvec))
# Test statistic, -2 ln(lambda)
stat = -2*log(lam)
# Obtain p-value keeping in mind that under the null our test statistic
# should asymptotically follow a chi-squared distribution with 2m-2 df
pval = 1-chisqcdf(2*m-2, Float64(stat))
return alpha, beta, alphavec, betavec, lam, stat, pval
end
"""
printGamma(m::Int64, alpha::BigFloat, beta::BigFloat,
alphavec::Matrix{BigFloat}, betavec::Matrix{BigFloat}, lam::BigFloat,
stat::BigFloat, pval::BigFloat)
Print the results of the gamma likelihood-ratio test.
Parameters
----------
`m::Int64`: the number of groups.
`alpha::BigFloat`: the maximum likelihood estimator (MLE) of ``\\alpha``
under the null.
`beta::BigFloat`: the MLE of ``\\beta`` under the null.
`alphavec::Matrix{BigFloat}`: m x 1 matrix of the unrestricted MLE of
``\\alpha_i``.
`betavec::Matrix{BigFloat}`: m x 1 matrix of the unrestricted MLE of
``\\beta_i``.
`lam::BigFloat`: ``\\lambda``, the likelihood-ratio.
`stat::BigFloat`: ``-2\\ln{\\lambda}``, the test statistic.
`pval::BigFloat`: p-value of our test.
Returns
-------
Nothing.
"""
function printGamma(m, alpha, beta, alphavec, betavec, lam, stat, pval)
# Printing important data
println("For gamma model:")
println("alpha (null) = ", Float64(alpha))
println("beta (null) = ", Float64(beta))
println("alpha_i = ", Float64.(alphavec))
println("beta_i = ", Float64.(betavec))
println("Lambda = ", lam)
println("Test statistic = ", Float64(stat))
println("Degrees of freedom = ", 2*m-2)
println("P-value = ", pval)
println("----------------------------------------------")
end
"""
printExp(m::Int64, n::Int64, nvec::Matrix{Int64}, ybar::BigFloat,
ybarvec::Matrix{BigFloat})
Print the results of the exponential likelihood-ratio test after performing it.
Parameters
----------
`m::Int64`: number of groups.
`n::Int64`: total number of observations.
`nvec::Matrix{Int64}`: m x 1 matrix of sample sizes.
`ybar::BigFloat`: overall mean of all observations.
`ybar::Matrix{BigFloat}`: m x 1 matrix of the mean of each sample (treatment
group).
Returns
-------
Nothing.
"""
function printExp(m, n, nvec, ybar, ybarvec)
# Exponential distribution test
statExp = 2*n*log(ybar) - 2*sum(nvec .* log.(ybarvec))
pvalExp = 1-chisqcdf(m-1, Float64(statExp))
println("For exponential model:")
println("Test statistic = ", Float64(statExp))
println("Degrees of freedom = ", m - 1)
println("P-value = ", pvalExp)
println("----------------------------------------------")
end
"""
main()
Calls other functions to extract the required data, perform hypothesis tests
and print the results.
"""
function main()
# Get problem data and parameters
csv_reader = CSV.File("ProjectData.csv")
dataF = DataFrame(csv_reader)
y = BigFloat.(dataF[:, 6])
group = dataF[:, 1]
m, n, ni, alphavec, nvec, yarr, ybar, ybarvec = getVars(group, y)
# Perform the gamma test
alpha, beta, alphavec, betavec, lam, stat, pval = gammaTest(m, n, ni,
alphavec, nvec, group, yarr, ybar, ybarvec)
# Print gamma and exp test MLEs and results
printGamma(m, alpha, beta, alphavec, betavec, lam, stat, pval)
printExp(m, n, nvec, ybar, ybarvec)
end
if isinteractive()
main()
end