forked from ianfiske/unmarked
-
Notifications
You must be signed in to change notification settings - Fork 25
/
unmarkedEstimate.R
312 lines (259 loc) · 8.42 KB
/
unmarkedEstimate.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
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
setClassUnion("matrixOrVector", c("matrix","numeric"))
# Class to store actual parameter estimates
setClass("unmarkedEstimate",
representation(
name = "character",
short.name = "character",
estimates = "numeric",
covMat = "matrix",
fixed = "numeric",
covMatBS = "optionalMatrix",
invlink = "character",
invlinkGrad = "character",
randomVarInfo= "list"),
validity = function(object) {
errors <- character(0)
if(nrow(object@covMat) != length(object@estimates)) {
errors <- c(errors,
"Size of covMat does not match length of estimates.")
}
if(length(errors) > 0)
errors
else
TRUE
})
setClass("unmarkedEstimateList",
representation(estimates = "list"),
validity = function(object) {
errors <- character(0)
for(est in object@estimates) {
if(!is(est, "unmarkedEstimate")) {
errors <- c("At least one element of unmarkedEstimateList is not an unmarkedEstimate.")
break
}
}
if(length(errors) == 0) {
return(TRUE)
} else {
return(errors)
}
})
setMethod("show", "unmarkedEstimateList",
function(object) {
for(est in object@estimates) {
show(est)
cat("\n")
}
})
setMethod("summary", "unmarkedEstimateList",
function(object)
{
sumList <- list()
for(i in 1:length(object@estimates)) {
sumList[[i]] <- summary(object@estimates[[i]])
cat("\n")
}
names(sumList) <- names(object@estimates)
invisible(sumList)
})
setGeneric("estimates",
function(object) {
standardGeneric("estimates")
})
setMethod("estimates", "unmarkedEstimate",
function(object) {
object@estimates
})
setMethod("estimates", "unmarkedEstimateList",
function(object) {
object@estimates
})
unmarkedEstimateList <- function(l) {
new("unmarkedEstimateList", estimates = l)
}
unmarkedEstimate <- function(name, short.name, estimates, covMat, fixed=NULL,
invlink, invlinkGrad, randomVarInfo=list())
{
if(is.null(fixed)) fixed <- 1:length(estimates)
new("unmarkedEstimate",
name = name,
short.name = short.name,
estimates = estimates,
covMat = covMat,
fixed = fixed,
invlink = invlink,
invlinkGrad = invlinkGrad,
randomVarInfo = randomVarInfo)
}
setMethod("show", signature(object = "unmarkedEstimate"),
function(object)
{
has_random <- methods::.hasSlot(object, "randomVarInfo") &&
length(object@randomVarInfo) > 0
fixed <- 1:length(object@estimates)
if(methods::.hasSlot(object, "fixed")) fixed <- object@fixed
ests <- object@estimates[fixed]
SEs <- SE(object)[fixed]
Z <- ests/SEs
p <- 2*pnorm(abs(Z), lower.tail = FALSE)
printRowNames <- !(length(ests) == 1 |
identical(names(ests), "(Intercept)") |
identical(names(ests), "1"))
cat(object@name,":\n", sep="")
if(has_random){
print_randvar_info(object@randomVarInfo)
cat("\nFixed effects:\n")
}
outDF <- data.frame(Estimate = ests, SE = SEs, z = Z, "P(>|z|)" = p,
check.names = FALSE)
print(outDF, row.names = printRowNames, digits = 3)
})
setMethod("summary", signature(object = "unmarkedEstimate"),
function(object)
{
fixed <- 1:length(object@estimates)
if(methods::.hasSlot(object, "fixed")) fixed <- object@fixed
ests <- object@estimates[fixed]
SEs <- SE(object)[fixed]
Z <- ests/SEs
p <- 2*pnorm(abs(Z), lower.tail = FALSE)
printRowNames <-
!(length(ests) == 1 | identical(names(ests), "(Intercept)") | identical(names(ests), "1"))
invlink <- object@invlink
link <- switch(invlink,
exp = "log",
logistic = "logit",
cloglog = "cloglog")
cat(object@name, " (", link, "-scale)", ":\n", sep="")
has_random <- methods::.hasSlot(object, "randomVarInfo") &&
length(object@randomVarInfo) > 0
if(has_random){
print_randvar_info(object@randomVarInfo)
cat("\nFixed effects:\n")
}
outDF <- data.frame(Estimate = ests, SE = SEs, z = Z, "P(>|z|)" = p,
check.names = FALSE)
print(outDF, row.names = printRowNames, digits = 3)
invisible(outDF)
})
# Compute linear combinations of estimates in unmarkedEstimate objects.
setMethod("linearComb",
signature(obj = "unmarkedEstimate", coefficients = "matrixOrVector"),
function(obj, coefficients, offset = NULL, re.form = NULL)
{
if(!is(coefficients, "matrix"))
coefficients <- t(as.matrix(coefficients))
est <- obj@estimates
covMat <- obj@covMat
if(!is.null(re.form) & .hasSlot(obj, "fixed")){
est <- est[obj@fixed]
covMat <- covMat[obj@fixed, obj@fixed, drop=FALSE]
}
stopifnot(ncol(coefficients) == length(est))
if (is.null(offset))
offset <- rep(0, nrow(coefficients))
e <- as.vector(coefficients %*% est) + offset
v <- coefficients %*% covMat %*% t(coefficients)
if (!is.null(obj@covMatBS)) {
v.bs <- coefficients %*% obj@covMatBS %*% t(coefficients)
} else {
v.bs <- NULL
}
umelc <- new("unmarkedLinComb", parentEstimate = obj,
estimate = e, covMat = v, covMatBS = v.bs,
coefficients = coefficients)
umelc
})
# Transform an unmarkedEstimate object to it's natural scale.
#setMethod("backTransform",
# signature(obj = "unmarkedEstimate"),
# function(obj) {
# stopifnot(length(obj@estimates) == 1)
# e <- eval(call(obj@invlink,obj@estimates))
# v <- (eval(call(obj@invlinkGrad,obj@estimates)))^2 * obj@covMat
#
# if(is(obj, "unmarkedEstimateLinearComb")) {
# coef <- obj@coefficients
# orig <- obj@originalEstimate
# } else {
# coef <- 1
# orig <- obj
# }
#
# umebt <- new("unmarkedEstimateBackTransformed",
# name = paste(obj@name,"transformed to native scale"),
# estimates = e, covMat = v,
# invlink = "identity", invlinkGrad = "identity",
# originalEstimate = orig, coefficients = coef,
# transformation = obj@invlink)
# umebt
# })
# backTransform is only valid for an unmarkedEstimate of length = 1.
# can backtranform a fit directly if it has length 1
# o.w. give error
setMethod("backTransform", "unmarkedEstimate", function(obj)
{
if(length(obj@estimates) == 1) {
lc <- linearComb(obj, 1)
return(backTransform(lc))
} else {
stop("Cannot directly back-transform an unmarkedEstimate with length > 1.\nUse linearComb() and then backTransform() the resulting scalar linear combination.")
}
})
# Compute standard error of an unmarkedEstimate object.
setMethod("SE", signature(obj = "unmarkedEstimate"), function(obj, fixedOnly=TRUE)
{
sqrt(diag(vcov(obj, fixedOnly=fixedOnly)))
})
setMethod("[", signature("unmarkedEstimateList"),
function(x, i, j, drop)
{
x@estimates[[i]]
})
setMethod("names", "unmarkedEstimateList",
function(x)
{
names(x@estimates)
})
setMethod("coef", "unmarkedEstimate",
function(object, altNames = TRUE, fixedOnly=TRUE, ...)
{
coefs <- object@estimates
if(fixedOnly){
fixed <- 1:length(coefs)
if(methods::.hasSlot(object, "fixed")) fixed <- object@fixed
coefs <- coefs[fixed]
}
names(coefs)[names(coefs) == "(Intercept)"] <- "Int"
if(altNames) {
names(coefs) <- paste(object@short.name, "(", names(coefs), ")",
sep="")
}
coefs
})
setMethod("vcov", "unmarkedEstimate",
function(object, fixedOnly=TRUE, ...)
{
v <- object@covMat
if(fixedOnly){
fixed <- 1:nrow(v)
if(methods::.hasSlot(object, "fixed")) fixed <- object@fixed
v <- as.matrix(v[fixed,fixed])
}
rownames(v) <- colnames(v) <- names(coef(object, fixedOnly=fixedOnly))
v
})
setMethod("confint", "unmarkedEstimate",
function(object, parm, level = 0.95)
{
if(missing(parm)) parm <- object@fixed
ests <- object@estimates[parm]
ses <- SE(object)[parm]
z <- qnorm((1-level)/2, lower.tail = FALSE)
lower.lim <- ests - z*ses
upper.lim <- ests + z*ses
ci <- as.matrix(cbind(lower.lim, upper.lim))
rownames(ci) <- names(coef(object))[parm]
colnames(ci) <- c((1-level)/2, 1- (1-level)/2)
ci
})