File: vcov.mppm.R

package info (click to toggle)
r-cran-spatstat.core 2.4-4-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 6,440 kB
  • sloc: ansic: 4,402; sh: 13; makefile: 5
file content (292 lines) | stat: -rw-r--r-- 10,044 bytes parent folder | download | duplicates (3)
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
#  Variance-covariance matrix for mppm objects
#
# $Revision: 1.23 $ $Date: 2021/12/29 07:50:32 $
#
#

vcov.mppm <- local({

  errhandler <- function(whinge, err) {
    switch(err,
           fatal=stop(whinge),
           warn={
             warning(whinge)
             return(NA)
           },
           null= return(NULL),
           stop(paste("Unrecognised option: err=", dQuote(err))))
  }
    
  vcov.mppm <- function(object, ..., what="vcov", err="fatal") {

    what <- match.arg(what,
                      c("vcov", "corr", "fisher", "Fisher", "internals", "all"))
    if(what == "Fisher") what <- "fisher"
    
    if(is.poisson.mppm(object) && object$Fit$fitter == "glm")
      return(vcmPois(object, ..., what=what, err=err))

    return(vcmGibbs(object, ..., what=what, err=err))
  }

  vcmPois <- function(object, ..., what, err,
                      nacoef.action=c("warn", "fatal", "silent"),
                      new.coef=NULL
                      ) {
    #' legacy algorithm for Poisson case

    #' detect NA coefficients
    if(missing(nacoef.action) && !missing(err) && !is.null(err)) {
      nacoef.action <- err
    } else {
      nacoef.action <- match.arg(nacoef.action)
    }
    if(!all(is.finite(coef(object)))) {
      gripe <- "Cannot compute variance; some coefficients are NA, NaN or Inf"
      switch(nacoef.action,
             fatal = stop(gripe, call.=FALSE),
             warn = warning(gripe, call.=FALSE),
             silent = {})
      return(NULL)
    }

    #' get to work
    gf <- object$Fit$FIT
    gd <- object$Fit$moadf
    wt <- gd$.mpl.W

    fo <- object$trend
    if(is.null(fo)) fo <- (~1)

    mof <- model.frame(fo, gd)
    mom <- model.matrix(fo, mof)
    momnames <- dimnames(mom)[[2]]

    ## fitted intensity
    if(!is.null(new.coef) && inherits(gf, c("gam", "lme"))) {
      warn.once("vcovGAMnew", "'new.coef' is not supported by vcov.mppm for GAM or LME models; ignored")
      new.coef <- NULL
    }
    fi <- if(is.null(new.coef)) fitted(gf) else GLMpredict(gf, gd, new.coef, changecoef=TRUE, type="response")

    fisher <- sumouter(mom, fi * wt)
    dimnames(fisher) <- list(momnames, momnames)

    switch(what,
           fisher = { return(fisher) },
           vcov   = {
             vc <- try(solve(fisher), silent=(err == "null"))
             if(inherits(vc, "try-error"))
               return(errhandler("Fisher information is singular", err))
             else
               return(vc)
           },
           corr={
             co <- try(solve(fisher), silent=(err == "null"))
             if(inherits(co, "try-error"))
               return(errhandler("Fisher information is singular", err))
             sd <- sqrt(diag(co))
             return(co / outer(sd, sd, "*"))
           })
  }

  vcmGibbs <- function(object, ..., what, err,
                       matrix.action=c("warn", "fatal", "silent"),
                       gam.action=c("warn", "fatal", "silent"),
                       logi.action=c("warn", "fatal", "silent"),
                       nacoef.action=c("warn", "fatal", "silent"),
                       new.coef=NULL
                       ) {
    if(!missing(err)) {
      if(err == "null") err <- "silent" 
      matrix.action <-
        if(missing(matrix.action)) err else match.arg(matrix.action)
      gam.action <- if(missing(gam.action)) err else match.arg(gam.action)
      logi.action <- if(missing(logi.action)) err else match.arg(logi.action)
      nacoef.action <- if(missing(nacoef.action)) err else match.arg(nacoef.action)
    } else {
      matrix.action <- match.arg(matrix.action)
      gam.action <- match.arg(gam.action)
      logi.action <- match.arg(logi.action)
      nacoef.action <- match.arg(nacoef.action)
    }
    #' detect NA coefficients
    if(!all(is.finite(as.matrix(coef(object))))) {
      gripe <- "Cannot compute variance; some coefficients are NA, NaN or Inf"
      switch(nacoef.action,
             fatal = stop(gripe, call.=FALSE),
             warn = warning(gripe, call.=FALSE),
             silent = {})
      return(NULL)
    }
    #' extract stuff from fitted model
    Inter        <- object$Inter
    interaction  <- Inter$interaction
    itags        <- Inter$itags
    Vnamelist    <- object$Fit$Vnamelist
    Isoffsetlist <- object$Fit$Isoffsetlist
    glmdata      <- object$Fit$moadf
    fitter       <- object$Fit$fitter
    fitobj       <- object$Fit$FIT
    #' compute fitted intensity
    if(is.null(new.coef)) {
      fi <- fitted(fitobj)
    } else if(fitter != "glm") {
      warn.once("vcovMppmGAMnew", "'new.coef' is not supported by vcov.mppm for GAM or LME models; ignored")
      new.coef <- NULL
      fi <- fitted(fitobj)
    } else {
      fi <- GLMpredict(fitobj, glmdata, new.coef, changecoef=TRUE, type="response")
    }
    #' initialise
    cnames <- names(fixed.effects(object))
    nc <- length(cnames)
    A2 <- A3 <- matrix(0, nc, nc, dimnames=list(cnames, cnames))    
    #' (1) Compute matrix A1 directly
    glmsub  <- glmdata$.mpl.SUBSET
    wt      <- glmdata$.mpl.W
    mom <- model.matrix(object)
    lam <- unlist(fitted(object, new.coef=new.coef))
    A1 <- sumouter(mom, lam * wt * glmsub)
    #' (2) compute matrices A2 and A3 for submodels
    #' compute submodels 
    subs <- subfits(object, what="basicmodels", new.coef=new.coef)
    n <- length(subs)
    #' identify the (unique) active interaction in each row
    activeinter <- active.interactions(object)
    ## compute A2 and A3 for each submodel
    guts <- lapply(subs,
                   vcov,
                   what="internals",
                   matrix.action=matrix.action,
                   gam.action=gam.action,
                   logi.action=logi.action,
                   dropcoef=TRUE,
                   ...)
    a2   <- lapply(guts, getElement, name="A2")
    a3   <- lapply(guts, getElement, name="A3")
    #' (3) Determine map from interaction variables of subfits
    #'     to canonical variables of 'object'
    maps <- mapInterVars(object, subs, mom)
    #' (4) Process each row, summing A2 and A3
    for(i in seq_len(n)) {
      subi <- subs[[i]]
      cmap <- maps[[i]]
      #' contributes to second order terms only if non-Poisson
      if(!is.poisson(subi)) {
        cnames.i <- names(coef(subi))
        a2i <- a2[[i]]
        a3i <- a3[[i]]
        #' the (unique) tag name of the interaction in this model
        tagi <- colnames(activeinter)[activeinter[i,]]
        #' the corresponding canonical variable name(s) for this interaction
        vni <- Vnamelist[[tagi]]
        #' ignore offset variables
        iso <- Isoffsetlist[[tagi]]
        vni <- vni[!iso]
        if(length(vni)) {
          #' retain only interaction rows & columns (the rest are zero anyway)
          e <- cnames.i %in% vni
          a2ie <- a2i[e, e, drop=FALSE]
          a3ie <- a3i[e, e, drop=FALSE]
          #' all possible mappings 
          mappings <- do.call(expand.grid,
                              append(cmap, list(stringsAsFactors=FALSE)))
          nmappings <- nrow(mappings)
          if(nmappings == 0) {
            warning("Internal error: Unable to map submodel to full model")
          } else {
            for(irow in 1:nmappings) {
              for(jcol in 1:nmappings) {
                cmi <- as.character(mappings[irow,])
                cmj <- as.character(mappings[jcol,])
                if(anyDuplicated(cmi) || anyDuplicated(cmj)) {
                  warning("Internal error: duplicated labels in submodel map")
                } else if(!is.null(a2ie)) {
                  A2[cmi,cmj] <- A2[cmi,cmj] + a2ie
                  A3[cmi,cmj] <- A3[cmi,cmj] + a2ie
                }
              }
            }
          }
        }
      }
    }
    #' (5) pack up
    internals <- list(A1=A1, A2=A2, A3=A3)
    if(what %in% c("internals", "all"))
      internals <- c(internals, list(suff=mom))
    if(what %in% c("vcov", "corr", "all")) {
      #' variance-covariance matrix required
      U <- checksolve(A1, matrix.action, , "variance")
      vc <- if(is.null(U)) NULL else (U %*% (A1 + A2 + A3) %*% U)
    }
    out <- switch(what,
                  fisher = A1 + A2 + A3,
                  vcov   = vc,
                  corr   = {
                    if(is.null(vc)) return(NULL)
                    sd <- sqrt(diag(vc))
                    vc / outer(sd, sd, "*")
                  },
                  internals = internals,
                  all = list(internals=internals,
                             fisher=A1+A2+A3,
                             varcov=vc,
                             invgrad=A1)
                  )
    return(out)
  }

  addsubmatrix <- function(A, B, guessnames) {
    if(is.null(B)) return(A)
    if(is.null(colnames(B)) && !missing(guessnames)) {
      if(is.character(guessnames))
        guessnames <- list(guessnames, guessnames)
      if(all(lengths(guessnames) == dim(B)))
        colnames(B) <- guessnames
    }
    if(is.null(colnames(B))) {
      #' unusual
      if(!all(dim(A) == dim(B))) 
        stop("Internal error: no column names, and matrices non-conformable")
      A <- A + B
      return(A)
    }
    j <- match(colnames(B), colnames(A))
    if(anyNA(j)) 
      stop("Internal error: unmatched column name(s)")
    A[j,j] <- A[j,j] + B
    return(A)
  }

  bindsubmatrix <- function(A, B) {
    if(is.null(B)) return(A)
    if(is.null(colnames(B))) {
      if(ncol(A) != ncol(B))
        stop("Internal error: no column names, and matrices non-conformable")
      A <- rbind(A, B)
      return(A)
    }
    j <- match(colnames(B), colnames(A))
    if(anyNA(j))
      stop("Internal error: unmatched column name(s)")
    BB <- matrix(0, nrow(B), ncol(A))
    BB[,j] <- B
    A <- rbind(A, BB)
    return(A)
  }

  mergeAlternatives <- function(A, B) {
    okA <- !sapply(A, is.null)
    okB <- !sapply(B, is.null)
    if(any(override <- !okA & okB))
      A[override] <- B[override]
    return(A)
  }

##  notallzero <- function(df) { apply(df != 0, 2, any) }
  
  vcov.mppm
  
})