gam.fit4.r 56 KB
 Dirk Eddelbuettel committed Apr 10, 2018 1 ``````## (c) Simon N. Wood (2013-2015). Provided under GPL 2. `````` Dirk Eddelbuettel committed Apr 10, 2018 2 3 ``````## Routines for gam estimation beyond exponential family. `````` Dirk Eddelbuettel committed Apr 10, 2018 4 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 5 6 7 8 9 10 ``````dDeta <- function(y,mu,wt,theta,fam,deriv=0) { ## What is available directly from the family are derivatives of the ## deviance and link w.r.t. mu. This routine converts these to the ## required derivatives of the deviance w.r.t. eta. ## deriv is the order of derivative of the smoothing parameter score ## required. `````` Dirk Eddelbuettel committed Apr 10, 2018 11 12 ``````## This version is based on ratios of derivatives of links rather ## than raw derivatives of links. g2g = g''/g'^2, g3g = g'''/g'^3 etc `````` Dirk Eddelbuettel committed Apr 10, 2018 13 14 15 16 17 18 `````` r <- fam\$Dd(y, mu, theta, wt, level=deriv) d <- list(Deta=0,Dth=0,Dth2=0,Deta2=0,EDeta2=0,Detath=0, Deta3=0,Deta2th=0,Detath2=0, Deta4=0,Deta3th=0,Deta2th2=0) if (fam\$link=="identity") { ## don't waste time on transformation d\$Deta <- r\$Dmu;d\$Deta2 <- r\$Dmu2 `````` Dirk Eddelbuettel committed Apr 10, 2018 19 20 `````` d\$EDeta2 <- r\$EDmu2;d\$Deta.Deta2 <- r\$Dmu/r\$Dmu2 d\$Deta.EDeta2 <- r\$Dmu/r\$EDmu2 `````` Dirk Eddelbuettel committed Apr 10, 2018 21 22 23 24 25 26 27 28 29 30 31 32 `````` if (deriv>0) { d\$Dth <- r\$Dth; d\$Detath <- r\$Dmuth d\$Deta3 <- r\$Dmu3; d\$Deta2th <- r\$Dmu2th } if (deriv>1) { d\$Deta4 <- r\$Dmu4; d\$Dth2 <- r\$Dth2; d\$Detath2 <- r\$Dmuth2 d\$Deta2th2 <- r\$Dmu2th2; d\$Deta3th <- r\$Dmu3th } return(d) } ig1 <- fam\$mu.eta(fam\$linkfun(mu)) `````` Dirk Eddelbuettel committed Apr 10, 2018 33 34 35 36 37 `````` ig12 <- ig1^2 g2g <- fam\$g2g(mu) ## ig12 <- ig1^2;ig13 <- ig12 * ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 38 39 `````` d\$Deta <- r\$Dmu * ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 40 `````` d\$Deta2 <- r\$Dmu2*ig12 - r\$Dmu*g2g*ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 41 `````` d\$EDeta2 <- r\$EDmu2*ig12 `````` Dirk Eddelbuettel committed Apr 10, 2018 42 43 `````` d\$Deta.Deta2 <- r\$Dmu/(r\$Dmu2*ig1 - r\$Dmu*g2g) d\$Deta.EDeta2 <- r\$Dmu/(r\$EDmu2*ig1) `````` Dirk Eddelbuettel committed Apr 10, 2018 44 `````` if (deriv>0) { `````` Dirk Eddelbuettel committed Apr 10, 2018 45 `````` ig13 <- ig12 * ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 46 47 `````` d\$Dth <- r\$Dth d\$Detath <- r\$Dmuth * ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 48 49 50 `````` g3g <- fam\$g3g(mu) d\$Deta3 <- r\$Dmu3*ig13 - 3*r\$Dmu2 * g2g * ig12 + r\$Dmu * (3*g2g^2 - g3g)*ig1 d\$Deta2th <- r\$Dmu2th*ig12 - r\$Dmuth*g2g*ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 51 52 `````` } if (deriv>1) { `````` Dirk Eddelbuettel committed Apr 10, 2018 53 54 55 `````` g4g <- fam\$g4g(mu) d\$Deta4 <- ig12^2*r\$Dmu4 - 6*r\$Dmu3*ig13*g2g + r\$Dmu2*(15*g2g^2-4*g3g)*ig12 - r\$Dmu*(15*g2g^3-10*g2g*g3g +g4g)*ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 56 57 `````` d\$Dth2 <- r\$Dth2 d\$Detath2 <- r\$Dmuth2 * ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 58 59 `````` d\$Deta2th2 <- ig12*r\$Dmu2th2 - r\$Dmuth2*g2g*ig1 d\$Deta3th <- ig13*r\$Dmu3th - 3 *r\$Dmu2th*g2g*ig12 + r\$Dmuth*(3*g2g^2-g3g)*ig1 `````` Dirk Eddelbuettel committed Apr 10, 2018 60 61 `````` } d `````` Dirk Eddelbuettel committed Apr 10, 2018 62 ``````} ## dDeta `````` Dirk Eddelbuettel committed Apr 10, 2018 63 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 64 ``````fetad.test <- function(y,mu,wt,theta,fam,eps = 1e-7,plot=TRUE) { `````` Dirk Eddelbuettel committed Apr 10, 2018 65 66 67 68 69 70 71 72 ``````## test family derivatives w.r.t. eta dd <- dDeta(y,mu,wt,theta,fam,deriv=2) dev <- fam\$dev.resids(y, mu, wt,theta) mu1 <- fam\$linkinv(fam\$linkfun(mu)+eps) dev1 <- fam\$dev.resids(y,mu1, wt,theta) Deta.fd <- (dev1-dev)/eps cat("Deta: rdiff = ",range(dd\$Deta-Deta.fd)," cor = ",cor(dd\$Deta,Deta.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 73 74 75 `````` plot(dd\$Deta,Deta.fd);abline(0,1) nt <- length(theta) for (i in 1:nt) { `````` Dirk Eddelbuettel committed Apr 10, 2018 76 `````` th1 <- theta;th1[i] <- th1[i] + eps `````` Dirk Eddelbuettel committed Apr 10, 2018 77 `````` dev1 <- fam\$dev.resids(y, mu, wt,th1) `````` Dirk Eddelbuettel committed Apr 10, 2018 78 `````` Dth.fd <- (dev1-dev)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 79 80 81 `````` um <- if (nt>1) dd\$Dth[,i] else dd\$Dth cat("Dth[",i,"]: rdiff = ",range(um-Dth.fd)," cor = ",cor(um,Dth.fd),"\n") plot(um,Dth.fd);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 82 83 84 85 86 `````` } ## second order up... dd1 <- dDeta(y,mu1,wt,theta,fam,deriv=2) Deta2.fd <- (dd1\$Deta - dd\$Deta)/eps cat("Deta2: rdiff = ",range(dd\$Deta2-Deta2.fd)," cor = ",cor(dd\$Deta2,Deta2.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 87 `````` plot(dd\$Deta2,Deta2.fd);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 88 89 `````` Deta3.fd <- (dd1\$Deta2 - dd\$Deta2)/eps cat("Deta3: rdiff = ",range(dd\$Deta3-Deta3.fd)," cor = ",cor(dd\$Deta3,Deta3.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 90 `````` plot(dd\$Deta3,Deta3.fd);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 91 92 `````` Deta4.fd <- (dd1\$Deta3 - dd\$Deta3)/eps cat("Deta4: rdiff = ",range(dd\$Deta4-Deta4.fd)," cor = ",cor(dd\$Deta4,Deta4.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 93 `````` plot(dd\$Deta4,Deta4.fd);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 94 `````` ## and now the higher derivs wrt theta... `````` Dirk Eddelbuettel committed Apr 10, 2018 95 96 `````` ind <- 1:nt for (i in 1:nt) { `````` Dirk Eddelbuettel committed Apr 10, 2018 97 98 `````` th1 <- theta;th1[i] <- th1[i] + eps dd1 <- dDeta(y,mu,wt,th1,fam,deriv=2) `````` Dirk Eddelbuettel committed Apr 10, 2018 99 100 101 102 `````` Detath.fd <- (dd1\$Deta - dd\$Deta)/eps um <- if (nt>1) dd\$Detath[,i] else dd\$Detath cat("Detath[",i,"]: rdiff = ",range(um-Detath.fd)," cor = ",cor(um,Detath.fd),"\n") plot(um,Detath.fd);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 103 `````` Deta2th.fd <- (dd1\$Deta2 - dd\$Deta2)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 104 105 106 `````` um <- if (nt>1) dd\$Deta2th[,i] else dd\$Deta2th cat("Deta2th[",i,"]: rdiff = ",range(um-Deta2th.fd)," cor = ",cor(um,Deta2th.fd),"\n") plot(um,Deta2th.fd);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 107 `````` Deta3th.fd <- (dd1\$Deta3 - dd\$Deta3)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 108 109 110 `````` um <- if (nt>1) dd\$Deta3th[,i] else dd\$Deta3th cat("Deta3th[",i,"]: rdiff = ",range(um-Deta3th.fd)," cor = ",cor(um,Deta3th.fd),"\n") plot(um,Deta3th.fd);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 111 `````` ## now the 3 second derivative w.r.t. theta terms `````` Dirk Eddelbuettel committed Apr 10, 2018 112 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 113 `````` Dth2.fd <- (dd1\$Dth - dd\$Dth)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 114 115 116 117 `````` um <- if (nt>1) dd\$Dth2[,ind] else dd\$Dth2 er <- if (nt>1) Dth2.fd[,i:nt] else Dth2.fd cat("Dth2[",i,",]: rdiff = ",range(um-er)," cor = ",cor(as.numeric(um),as.numeric(er)),"\n") plot(um,er);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 118 `````` Detath2.fd <- (dd1\$Detath - dd\$Detath)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 119 120 121 122 123 124 `````` um <- if (nt>1) dd\$Detath2[,ind] else dd\$Detath2 er <- if (nt>1) Detath2.fd[,i:nt] else Detath2.fd cat("Detath2[",i,",]: rdiff = ",range(um-er)," cor = ",cor(as.numeric(um),as.numeric(er)),"\n") ## cat("Detath2[",i,",]: rdiff = ",range(dd\$Detath2-Detath2.fd)," cor = ",cor(dd\$Detath2,Detath2.fd),"\n") plot(um,er);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 125 `````` Deta2th2.fd <- (dd1\$Deta2th - dd\$Deta2th)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 126 127 128 129 130 131 `````` um <- if (nt>1) dd\$Deta2th2[,ind] else dd\$Deta2th2 er <- if (nt>1) Deta2th2.fd[,i:nt] else Deta2th2.fd cat("Deta2th2[",i,",]: rdiff = ",range(um-er)," cor = ",cor(as.numeric(um),as.numeric(er)),"\n") ## cat("Deta2th2[",i,",]: rdiff = ",range(dd\$Deta2th2-Deta2th2.fd)," cor = ",cor(dd\$Deta2th2,Deta2th2.fd),"\n") ind <- max(ind)+1:(nt-i) plot(um,er);abline(0,1) `````` Dirk Eddelbuettel committed Apr 10, 2018 132 133 134 135 136 137 138 139 140 141 `````` } } ## fetad.test fmud.test <- function(y,mu,wt,theta,fam,eps = 1e-7) { ## test family deviance derivatives w.r.t. mu dd <- fam\$Dd(y, mu, theta, wt, level=2) dev <- fam\$dev.resids(y, mu, wt,theta) dev1 <- fam\$dev.resids(y, mu+eps, wt,theta) Dmu.fd <- (dev1-dev)/eps cat("Dmu: rdiff = ",range(dd\$Dmu-Dmu.fd)," cor = ",cor(dd\$Dmu,Dmu.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 142 143 `````` nt <- length(theta) for (i in 1:nt) { `````` Dirk Eddelbuettel committed Apr 10, 2018 144 145 146 `````` th1 <- theta;th1[i] <- th1[i] + eps dev1 <- fam\$dev.resids(y, mu, wt,th1) Dth.fd <- (dev1-dev)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 147 148 `````` um <- if (nt>1) dd\$Dth[,i] else dd\$Dth cat("Dth[",i,"]: rdiff = ",range(um-Dth.fd)," cor = ",cor(um,Dth.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 149 150 151 152 153 154 155 156 157 158 `````` } ## second order up... dd1 <- fam\$Dd(y, mu+eps, theta, wt, level=2) Dmu2.fd <- (dd1\$Dmu - dd\$Dmu)/eps cat("Dmu2: rdiff = ",range(dd\$Dmu2-Dmu2.fd)," cor = ",cor(dd\$Dmu2,Dmu2.fd),"\n") Dmu3.fd <- (dd1\$Dmu2 - dd\$Dmu2)/eps cat("Dmu3: rdiff = ",range(dd\$Dmu3-Dmu3.fd)," cor = ",cor(dd\$Dmu3,Dmu3.fd),"\n") Dmu4.fd <- (dd1\$Dmu3 - dd\$Dmu3)/eps cat("Dmu4: rdiff = ",range(dd\$Dmu4-Dmu4.fd)," cor = ",cor(dd\$Dmu4,Dmu4.fd),"\n") ## and now the higher derivs wrt theta `````` Dirk Eddelbuettel committed Apr 10, 2018 159 160 `````` ind <- 1:nt for (i in 1:nt) { `````` Dirk Eddelbuettel committed Apr 10, 2018 161 162 163 `````` th1 <- theta;th1[i] <- th1[i] + eps dd1 <- fam\$Dd(y, mu, th1, wt, level=2) Dmuth.fd <- (dd1\$Dmu - dd\$Dmu)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 164 165 `````` um <- if (nt>1) dd\$Dmuth[,i] else dd\$Dmuth cat("Dmuth[",i,"]: rdiff = ",range(um-Dmuth.fd)," cor = ",cor(um,Dmuth.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 166 `````` Dmu2th.fd <- (dd1\$Dmu2 - dd\$Dmu2)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 167 168 `````` um <- if (nt>1) dd\$Dmu2th[,i] else dd\$Dmu2th cat("Dmu2th[",i,"]: rdiff = ",range(um-Dmu2th.fd)," cor = ",cor(um,Dmu2th.fd),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 169 `````` Dmu3th.fd <- (dd1\$Dmu3 - dd\$Dmu3)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 170 171 172 173 174 `````` um <- if (nt>1) dd\$Dmu3th[,i] else dd\$Dmu3th cat("Dmu3th[",i,"]: rdiff = ",range(um-Dmu3th.fd)," cor = ",cor(um,Dmu3th.fd),"\n") ## now the 3 second derivative w.r.t. theta terms... `````` Dirk Eddelbuettel committed Apr 10, 2018 175 `````` Dth2.fd <- (dd1\$Dth - dd\$Dth)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 176 177 178 179 `````` um <- if (nt>1) dd\$Dth2[,ind] else dd\$Dth2 er <- if (nt>1) Dth2.fd[,i:nt] else Dth2.fd cat("Dth2[",i,",]: rdiff = ",range(um-er)," cor = ",cor(as.numeric(um),as.numeric(er)),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 180 `````` Dmuth2.fd <- (dd1\$Dmuth - dd\$Dmuth)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 181 182 183 184 `````` um <- if (nt>1) dd\$Dmuth2[,ind] else dd\$Dmuth2 er <- if (nt>1) Dmuth2.fd[,i:nt] else Dmuth2.fd cat("Dmuth2[",i,",]: rdiff = ",range(um-er)," cor = ",cor(as.numeric(um),as.numeric(er)),"\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 185 `````` Dmu2th2.fd <- (dd1\$Dmu2th - dd\$Dmu2th)/eps `````` Dirk Eddelbuettel committed Apr 10, 2018 186 187 188 189 `````` um <- if (nt>1) dd\$Dmu2th2[,ind] else dd\$Dmu2th2 er <- if (nt>1) Dmu2th2.fd[,i:nt] else Dmu2th2.fd cat("Dmu2th2[",i,",]: rdiff = ",range(um-er)," cor = ",cor(as.numeric(um),as.numeric(er)),"\n") ind <- max(ind)+1:(nt-i) `````` Dirk Eddelbuettel committed Apr 10, 2018 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 `````` } } gam.fit4 <- function(x, y, sp, Eb,UrS=list(), weights = rep(1, nobs), start = NULL, etastart = NULL, mustart = NULL, offset = rep(0, nobs),U1=diag(ncol(x)), Mp=-1, family = gaussian(), control = gam.control(), deriv=2, scale=1,scoreType="REML",null.coef=rep(0,ncol(x)),...) { ## Routine for fitting GAMs beyond exponential family. ## Inputs as gam.fit3 except that family is of class "extended.family", while ## sp contains the vector of extended family parameters, followed by the log smoothing parameters, ## followed by the log scale parameter if scale < 0 `````` Dirk Eddelbuettel committed Apr 10, 2018 205 206 207 208 209 `````` ## some families have second derivative of deviance, and hence iterative weights ## very close to zero for some data. This can lead to poorly scaled sqrt(w)z ## and it is better to base everything on wz... if (is.null(family\$use.wz)) family\$use.wz <- FALSE `````` Dirk Eddelbuettel committed Apr 10, 2018 210 `````` if (family\$n.theta>0) { ## there are extra parameters to estimate `````` Dirk Eddelbuettel committed Apr 10, 2018 211 212 213 214 `````` ind <- 1:family\$n.theta theta <- sp[ind] ## parameters of the family family\$putTheta(theta) sp <- sp[-ind] ## log smoothing parameters `````` Dirk Eddelbuettel committed Apr 10, 2018 215 216 `````` } else theta <- family\$getTheta() ## fixed value `````` Dirk Eddelbuettel committed Apr 10, 2018 217 `````` ## penalized <- if (length(UrS)>0) TRUE else FALSE `````` Dirk Eddelbuettel committed Apr 10, 2018 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 `````` if (scale>0) scale.known <- TRUE else { ## unknown scale parameter, trial value supplied as ## final element of sp. scale.known <- FALSE nsp <- length(sp) scale <- exp(sp[nsp]) sp <- sp[-nsp] } x <- as.matrix(x) nSp <- length(sp) rank.tol <- .Machine\$double.eps*100 ## tolerance to use for rank deficiency q <- ncol(x) n <- nobs <- nrow(x) xnames <- dimnames(x)[[2]] ynames <- if (is.matrix(y)) rownames(y) else names(y) ## Now a stable re-parameterization is needed.... if (length(UrS)) { rp <- gam.reparam(UrS,sp,deriv) T <- diag(q) T[1:ncol(rp\$Qs),1:ncol(rp\$Qs)] <- rp\$Qs T <- U1%*%T ## new params b'=T'b old params null.coef <- t(T)%*%null.coef if (!is.null(start)) start <- t(T)%*%start ## form x%*%T in parallel `````` Dirk Eddelbuettel committed Apr 10, 2018 249 `````` x <- .Call(C_mgcv_pmmult2,x,T,0,0,control\$nthreads) `````` Dirk Eddelbuettel committed Apr 10, 2018 250 251 252 253 254 255 256 257 258 259 260 `````` rS <- list() for (i in 1:length(UrS)) { rS[[i]] <- rbind(rp\$rS[[i]],matrix(0,Mp,ncol(rp\$rS[[i]]))) } ## square roots of penalty matrices in current parameterization Eb <- Eb%*%T ## balanced penalty matrix rows.E <- q-Mp Sr <- cbind(rp\$E,matrix(0,nrow(rp\$E),Mp)) St <- rbind(cbind(rp\$S,matrix(0,nrow(rp\$S),Mp)),matrix(0,Mp,q)) } else { T <- diag(q); St <- matrix(0,q,q) `````` Dirk Eddelbuettel committed Apr 10, 2018 261 `````` rSncol <- rows.E <- Eb <- Sr <- 0 `````` Dirk Eddelbuettel committed Apr 10, 2018 262 `````` rS <- list(0) `````` Dirk Eddelbuettel committed Apr 10, 2018 263 `````` rp <- list(det=0,det1 = 0,det2 = 0,fixed.penalty=FALSE) `````` Dirk Eddelbuettel committed Apr 10, 2018 264 265 266 267 268 269 270 271 272 `````` } ## re-parameterization complete. Initialization.... nvars <- ncol(x) if (nvars==0) stop("emtpy models not available") if (is.null(weights)) weights <- rep.int(1, nobs) if (is.null(offset)) offset <- rep.int(0, nobs) `````` Dirk Eddelbuettel committed Apr 10, 2018 273 274 275 276 277 278 279 280 281 `````` linkinv <- family\$linkinv valideta <- family\$valideta validmu <- family\$validmu dev.resids <- family\$dev.resids ## need an initial `null deviance' to test for initial divergence... ## if (!is.null(start)) null.coef <- start - can be on edge of feasible - not good null.eta <- as.numeric(x%*%null.coef + as.numeric(offset)) `````` Dirk Eddelbuettel committed Apr 10, 2018 282 283 284 285 286 287 `````` #old.pdev <- sum(dev.resids(y, linkinv(null.eta), weights,theta)) + t(null.coef)%*%St%*%null.coef #if (!is.null(start)) { ## check it's at least better than null.coef # pdev <- sum(dev.resids(y, linkinv(x%*%start+as.numeric(offset)), weights,theta)) + t(start)%*%St%*%start # if (pdev>old.pdev) start <- mustart <- etastart <- NULL #} `````` Dirk Eddelbuettel committed Apr 10, 2018 288 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 289 290 291 292 `````` ## call the families initialization code... if (is.null(mustart)) { eval(family\$initialize) `````` Dirk Eddelbuettel committed Apr 10, 2018 293 `````` mukeep <- NULL `````` Dirk Eddelbuettel committed Apr 10, 2018 294 295 296 `````` } else { mukeep <- mustart eval(family\$initialize) `````` Dirk Eddelbuettel committed Apr 10, 2018 297 `````` #mustart <- mukeep `````` Dirk Eddelbuettel committed Apr 10, 2018 298 `````` } `````` Dirk Eddelbuettel committed Apr 10, 2018 299 300 301 302 303 304 305 306 307 308 `````` old.pdev <- sum(dev.resids(y, linkinv(null.eta), weights,theta)) + t(null.coef)%*%St%*%null.coef if (!is.null(start)) { ## check it's at least better than null.coef pdev <- sum(dev.resids(y, linkinv(x%*%start+as.numeric(offset)), weights,theta)) + t(start)%*%St%*%start if (pdev>old.pdev) start <- mukeep <- etastart <- NULL } if (!is.null(mukeep)) mustart <- mukeep `````` Dirk Eddelbuettel committed Apr 10, 2018 309 310 311 312 313 314 315 316 317 318 319 320 321 322 `````` ## and now finalize initialization of mu and eta... eta <- if (!is.null(etastart)) etastart else if (!is.null(start)) if (length(start) != nvars) stop("Length of start should equal ", nvars, " and correspond to initial coefs for ", deparse(xnames)) else { coefold <- start etaold <- offset + as.vector(if (NCOL(x) == 1) x * start else x %*% start) } else family\$linkfun(mustart) `````` Dirk Eddelbuettel committed Apr 10, 2018 323 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 324 `````` mu <- linkinv(eta);etaold <- eta `````` Dirk Eddelbuettel committed Apr 10, 2018 325 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 326 `````` coefold <- null.coef `````` Dirk Eddelbuettel committed Apr 10, 2018 327 `````` conv <- boundary <- FALSE `````` Dirk Eddelbuettel committed Apr 10, 2018 328 329 330 331 332 333 `````` dd <- dDeta(y,mu,weights,theta,family,0) ## derivatives of deviance w.r.t. eta w <- dd\$Deta2 * .5; wz <- w*(eta-offset) - .5*dd\$Deta z <- (eta-offset) - dd\$Deta.Deta2 good <- is.finite(z)&is.finite(w) `````` Dirk Eddelbuettel committed Apr 10, 2018 334 335 `````` for (iter in 1:control\$maxit) { ## start of main fitting iteration if (control\$trace) cat(iter," ") `````` Dirk Eddelbuettel committed Apr 10, 2018 336 337 338 339 340 `````` # dd <- dDeta(y,mu,weights,theta,family,0) ## derivatives of deviance w.r.t. eta # w <- dd\$Deta2 * .5; # wz <- w*(eta-offset) - .5*dd\$Deta # z <- (eta-offset) - dd\$Deta.Deta2 # good <- is.finite(z)&is.finite(w) `````` Dirk Eddelbuettel committed Apr 10, 2018 341 `````` if (control\$trace&sum(!good)>0) cat("\n",sum(!good)," not good\n") `````` Dirk Eddelbuettel committed Apr 10, 2018 342 `````` if (sum(!good)) { `````` Dirk Eddelbuettel committed Apr 10, 2018 343 344 345 346 `````` use.wy <- TRUE good <- is.finite(w)&is.finite(wz) z[!is.finite(z)] <- 0 ## avoid NaN in .C call - unused anyway } else use.wy <- family\$use.wz `````` Dirk Eddelbuettel committed Apr 10, 2018 347 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 348 349 `````` oo <- .C(C_pls_fit1, y=as.double(z[good]),X=as.double(x[good,]),w=as.double(w[good]),wy = as.double(wz[good]), `````` Dirk Eddelbuettel committed Apr 10, 2018 350 351 352 `````` E=as.double(Sr),Es=as.double(Eb),n=as.integer(sum(good)), q=as.integer(ncol(x)),rE=as.integer(rows.E),eta=as.double(z), penalty=as.double(1),rank.tol=as.double(rank.tol), `````` Dirk Eddelbuettel committed Apr 10, 2018 353 `````` nt=as.integer(control\$nthreads),use.wy=as.integer(use.wy)) `````` Dirk Eddelbuettel committed Apr 10, 2018 354 355 `````` posdef <- oo\$n >= 0 if (!posdef) { ## then problem is indefinite - switch to +ve weights for this step `````` Dirk Eddelbuettel committed Apr 10, 2018 356 357 358 359 360 361 `````` if (control\$trace) cat("**using positive weights\n") # problem is that Fisher can be very poor for zeroes ## index weights that are finite and positive good <- is.finite(dd\$Deta2) good[good] <- dd\$Deta2[good]>0 `````` Dirk Eddelbuettel committed Apr 10, 2018 362 363 364 365 366 367 368 369 370 `````` w[!good] <- 0 wz <- w*(eta-offset) - .5*dd\$Deta z <- (eta-offset) - dd\$Deta.Deta2 good <- is.finite(z)&is.finite(w) if (sum(!good)) { use.wy <- TRUE good <- is.finite(w)&is.finite(wz) z[!is.finite(z)] <- 0 ## avoid NaN in .C call - unused anyway } else use.wy <- family\$use.wz `````` Dirk Eddelbuettel committed Apr 10, 2018 371 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 372 `````` oo <- .C(C_pls_fit1, ##C_pls_fit1, `````` Dirk Eddelbuettel committed Apr 10, 2018 373 `````` y=as.double(z[good]),X=as.double(x[good,]),w=as.double(w[good]),wy = as.double(wz[good]), `````` Dirk Eddelbuettel committed Apr 10, 2018 374 375 376 `````` E=as.double(Sr),Es=as.double(Eb),n=as.integer(sum(good)), q=as.integer(ncol(x)),rE=as.integer(rows.E),eta=as.double(z), penalty=as.double(1),rank.tol=as.double(rank.tol), `````` Dirk Eddelbuettel committed Apr 10, 2018 377 `````` nt=as.integer(control\$nthreads),use.wy=as.integer(use.wy)) `````` Dirk Eddelbuettel committed Apr 10, 2018 378 379 380 381 `````` } start <- oo\$y[1:ncol(x)] ## current coefficient estimates penalty <- oo\$penalty ## size of penalty `````` Dirk Eddelbuettel committed Apr 10, 2018 382 `````` eta <- drop(x%*%start) ## the linear predictor (less offset) `````` Dirk Eddelbuettel committed Apr 10, 2018 383 384 385 386 387 `````` if (any(!is.finite(start))) { ## test for breakdown conv <- FALSE warning("Non-finite coefficients at iteration ", iter) `````` Dirk Eddelbuettel committed Apr 10, 2018 388 `````` return(list(REML=NA)) ## return immediately signalling failure `````` Dirk Eddelbuettel committed Apr 10, 2018 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 `````` } mu <- linkinv(eta <- eta + offset) dev <- sum(dev.resids(y, mu, weights,theta)) ## now step halve under non-finite deviance... if (!is.finite(dev)) { if (is.null(coefold)) { if (is.null(null.coef)) stop("no valid set of coefficients has been found:please supply starting values", call. = FALSE) ## Try to find feasible coefficients from the null.coef and null.eta coefold <- null.coef etaold <- null.eta } `````` Dirk Eddelbuettel committed Apr 10, 2018 404 405 `````` #warning("Step size truncated due to divergence", # call. = FALSE) `````` Dirk Eddelbuettel committed Apr 10, 2018 406 407 408 409 410 411 412 413 414 `````` ii <- 1 while (!is.finite(dev)) { if (ii > control\$maxit) stop("inner loop 1; can't correct step size") ii <- ii + 1 start <- (start + coefold)/2 eta <- (eta + etaold)/2 mu <- linkinv(eta) dev <- sum(dev.resids(y, mu, weights,theta)) `````` Dirk Eddelbuettel committed Apr 10, 2018 415 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 416 417 `````` } boundary <- TRUE `````` Dirk Eddelbuettel committed Apr 10, 2018 418 `````` penalty <- t(start)%*%St%*%start ## reset penalty too `````` Dirk Eddelbuettel committed Apr 10, 2018 419 420 421 422 423 424 `````` if (control\$trace) cat("Step halved: new deviance =", dev, "\n") } ## end of infinite deviance correction ## now step halve if mu or eta are out of bounds... if (!(valideta(eta) && validmu(mu))) { `````` Dirk Eddelbuettel committed Apr 10, 2018 425 426 `````` #warning("Step size truncated: out of bounds", # call. = FALSE) `````` Dirk Eddelbuettel committed Apr 10, 2018 427 428 429 430 431 432 433 434 435 436 437 `````` ii <- 1 while (!(valideta(eta) && validmu(mu))) { if (ii > control\$maxit) stop("inner loop 2; can't correct step size") ii <- ii + 1 start <- (start + coefold)/2 eta <- (eta + etaold)/2 mu <- linkinv(eta) } boundary <- TRUE dev <- sum(dev.resids(y, mu, weights)) `````` Dirk Eddelbuettel committed Apr 10, 2018 438 `````` penalty <- t(start)%*%St%*%start ## need to reset penalty too `````` Dirk Eddelbuettel committed Apr 10, 2018 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 `````` if (control\$trace) cat("Step halved: new deviance =", dev, "\n") } ## end of invalid mu/eta handling ## now check for divergence of penalized deviance.... pdev <- dev + penalty ## the penalized deviance if (control\$trace) cat("penalized deviance =", pdev, "\n") div.thresh <- 10*(.1+abs(old.pdev))*.Machine\$double.eps^.5 if (pdev-old.pdev>div.thresh) { ## solution diverging ii <- 1 ## step halving counter if (iter==1) { ## immediate divergence, need to shrink towards zero etaold <- null.eta; coefold <- null.coef } while (pdev -old.pdev > div.thresh) { ## step halve until pdev <= old.pdev if (ii > 100) stop("inner loop 3; can't correct step size") ii <- ii + 1 start <- (start + coefold)/2 eta <- (eta + etaold)/2 mu <- linkinv(eta) dev <- sum(dev.resids(y, mu, weights,theta)) pdev <- dev + t(start)%*%St%*%start ## the penalized deviance if (control\$trace) cat("Step halved: new penalized deviance =", pdev, "\n") } } ## end of pdev divergence `````` Dirk Eddelbuettel committed Apr 10, 2018 470 471 472 473 474 475 `````` ## get new weights and pseudodata (needed now for grad testing)... dd <- dDeta(y,mu,weights,theta,family,0) ## derivatives of deviance w.r.t. eta w <- dd\$Deta2 * .5; wz <- w*(eta-offset) - .5*dd\$Deta z <- (eta-offset) - dd\$Deta.Deta2 good <- is.finite(z)&is.finite(w) `````` Dirk Eddelbuettel committed Apr 10, 2018 476 `````` ## convergence testing... `````` Dirk Eddelbuettel committed Apr 10, 2018 477 `````` if (posdef && abs(pdev - old.pdev)/(0.1 + abs(pdev)) < control\$epsilon) { `````` Dirk Eddelbuettel committed Apr 10, 2018 478 479 `````` ## Need to check coefs converged adequately, to ensure implicit differentiation ## ok. Testing coefs unchanged is problematic under rank deficiency (not guaranteed to `````` Dirk Eddelbuettel committed Apr 10, 2018 480 `````` ## drop same parameter every iteration!) `````` Dirk Eddelbuettel committed Apr 10, 2018 481 `````` grad <- 2 * t(x[good,])%*%((w[good]*(x%*%start)[good]-wz[good]))+ 2*St%*%start `````` Dirk Eddelbuettel committed Apr 10, 2018 482 `````` if (max(abs(grad)) > control\$epsilon*max(abs(start+coefold))/2) { `````` Dirk Eddelbuettel committed Apr 10, 2018 483 484 485 `````` old.pdev <- pdev ## not converged quite enough coef <- coefold <- start etaold <- eta `````` Dirk Eddelbuettel committed Apr 10, 2018 486 `````` ##muold <- mu `````` Dirk Eddelbuettel committed Apr 10, 2018 487 488 489 490 491 492 493 494 495 496 497 498 499 500 `````` } else { ## converged conv <- TRUE coef <- start break } } else { ## not converged old.pdev <- pdev coef <- coefold <- start etaold <- eta } } ## end of main loop ## so at this stage the model has been fully estimated coef <- as.numeric(T %*% coef) `````` Dirk Eddelbuettel committed Apr 10, 2018 501 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 502 `````` ## now obtain derivatives, if these are needed... `````` Dirk Eddelbuettel committed Apr 10, 2018 503 504 505 506 507 508 509 `````` check.derivs <- FALSE while (check.derivs) { ## debugging code to check derivatives eps <- 1e-7 fmud.test(y,mu,weights,theta,family,eps = eps) fetad.test(y,mu,weights,theta,family,eps = eps) } `````` Dirk Eddelbuettel committed Apr 10, 2018 510 `````` dd <- dDeta(y,mu,weights,theta,family,deriv) `````` Dirk Eddelbuettel committed Apr 10, 2018 511 `````` w <- dd\$Deta2 * .5 `````` Dirk Eddelbuettel committed Apr 10, 2018 512 `````` z <- (eta-offset) - dd\$Deta.Deta2 ## - .5 * dd\$Deta[good] / w `````` Dirk Eddelbuettel committed Apr 10, 2018 513 `````` wf <- pmax(0,dd\$EDeta2 * .5) ## Fisher type weights `````` Dirk Eddelbuettel committed Apr 10, 2018 514 515 516 517 518 519 520 521 `````` wz <- w*(eta-offset) - 0.5*dd\$Deta ## Wz finite when w==0 gdi.type <- if (any(abs(w)<.Machine\$double.xmin*1e20)||any(!is.finite(z))) 1 else 0 good <- is.finite(wz)&is.finite(w) residuals <- z - (eta - offset) residuals[!is.finite(residuals)] <- NA z[!is.finite(z)] <- 0 ## avoid passing NA etc to C code `````` Dirk Eddelbuettel committed Apr 10, 2018 522 523 524 `````` ntot <- length(theta) + length(sp) rSncol <- unlist(lapply(UrS,ncol)) `````` Dirk Eddelbuettel committed Apr 10, 2018 525 `````` ## Now drop any elements of dd that have been dropped in fitting... `````` Dirk Eddelbuettel committed Apr 10, 2018 526 527 `````` if (sum(!good)>0) { ## drop !good from fields of dd, weights and pseudodata z <- z[good]; w <- w[good]; wz <- wz[good]; wf <- wf[good] `````` Dirk Eddelbuettel committed Apr 10, 2018 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 `````` dd\$Deta <- dd\$Deta[good];dd\$Deta2 <- dd\$Deta2[good] dd\$EDeta2 <- dd\$EDeta2[good] if (deriv>0) dd\$Deta3 <- dd\$Deta3[good] if (deriv>1) dd\$Deta4 <- dd\$Deta4[good] if (length(theta)>1) { if (deriv>0) { dd\$Dth <- dd\$Dth[good,]; dd\$Detath <- dd\$Detath[good,]; dd\$Deta2th <- dd\$Deta2th[good,] if (deriv>1) { dd\$Detath2 <- dd\$Detath2[good,]; dd\$Deta3th <- dd\$Deta3th[good,] dd\$Deta2th2 <- dd\$Deta2th2[good,];dd\$Dth2 <- dd\$Dth2[good,] } } } else { if (deriv>0) { dd\$Dth <- dd\$Dth[good]; dd\$Detath <- dd\$Detath[good]; dd\$Deta2th <- dd\$Deta2th[good] if (deriv>1) { dd\$Detath2 <- dd\$Detath2[good]; dd\$Deta3th <- dd\$Deta3th[good] dd\$Deta2th2 <- dd\$Deta2th2[good]; dd\$Dth2 <- dd\$Dth2[good] } } } } `````` Dirk Eddelbuettel committed Apr 10, 2018 552 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 553 554 555 `````` oo <- .C(C_gdi2, X=as.double(x[good,]),E=as.double(Sr),Es=as.double(Eb),rS=as.double(unlist(rS)), U1 = as.double(U1),sp=as.double(exp(sp)),theta=as.double(theta), `````` Dirk Eddelbuettel committed Apr 10, 2018 556 557 `````` z=as.double(z),w=as.double(w),wz=as.double(wz),wf=as.double(wf),Dth=as.double(dd\$Dth), Det=as.double(dd\$Deta), `````` Dirk Eddelbuettel committed Apr 10, 2018 558 559 560 `````` Det2=as.double(dd\$Deta2),Dth2=as.double(dd\$Dth2),Det.th=as.double(dd\$Detath), Det2.th=as.double(dd\$Deta2th),Det3=as.double(dd\$Deta3),Det.th2 = as.double(dd\$Detath2), Det4 = as.double(dd\$Deta4),Det3.th=as.double(dd\$Deta3th), Deta2.th2=as.double(dd\$Deta2th2), `````` Dirk Eddelbuettel committed Apr 10, 2018 561 `````` beta=as.double(coef),b1=as.double(rep(0,ntot*ncol(x))),w1=as.double(rep(0,ntot*length(z))), `````` Dirk Eddelbuettel committed Apr 10, 2018 562 `````` D1=as.double(rep(0,ntot)),D2=as.double(rep(0,ntot^2)), `````` Dirk Eddelbuettel committed Apr 10, 2018 563 564 565 566 567 568 569 570 `````` P=as.double(0),P1=as.double(rep(0,ntot)),P2 = as.double(rep(0,ntot^2)), ldet=as.double(1-2*(scoreType=="ML")),ldet1 = as.double(rep(0,ntot)), ldet2 = as.double(rep(0,ntot^2)), rV=as.double(rep(0,ncol(x)^2)), rank.tol=as.double(.Machine\$double.eps^.75),rank.est=as.integer(0), n=as.integer(sum(good)),q=as.integer(ncol(x)),M=as.integer(nSp), n.theta=as.integer(length(theta)), Mp=as.integer(Mp),Enrow=as.integer(rows.E), rSncol=as.integer(rSncol),deriv=as.integer(deriv), `````` Dirk Eddelbuettel committed Apr 10, 2018 571 `````` fixed.penalty = as.integer(rp\$fixed.penalty),nt=as.integer(control\$nthreads), `````` Dirk Eddelbuettel committed Apr 10, 2018 572 `````` type=as.integer(gdi.type),dVkk=as.double(rep(0,nSp^2))) `````` Dirk Eddelbuettel committed Apr 10, 2018 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 ``````## test code used to ensure type 0 and type 1 produce identical results, when both should work. # oot <- .C(C_gdi2, # X=as.double(x[good,]),E=as.double(Sr),Es=as.double(Eb),rS=as.double(unlist(rS)), # U1 = as.double(U1),sp=as.double(exp(sp)),theta=as.double(theta), # z=as.double(z),w=as.double(w),wz=as.double(wz),wf=as.double(wf),Dth=as.double(dd\$Dth), # Det=as.double(dd\$Deta), # Det2=as.double(dd\$Deta2),Dth2=as.double(dd\$Dth2),Det.th=as.double(dd\$Detath), # Det2.th=as.double(dd\$Deta2th),Det3=as.double(dd\$Deta3),Det.th2 = as.double(dd\$Detath2), # Det4 = as.double(dd\$Deta4),Det3.th=as.double(dd\$Deta3th), Deta2.th2=as.double(dd\$Deta2th2), # beta=as.double(coef),b1=as.double(rep(0,ntot*ncol(x))),w1=rep(0,ntot*length(z)), # D1=as.double(rep(0,ntot)),D2=as.double(rep(0,ntot^2)), # P=as.double(0),P1=as.double(rep(0,ntot)),P2 = as.double(rep(0,ntot^2)), # ldet=as.double(1-2*(scoreType=="ML")),ldet1 = as.double(rep(0,ntot)), # ldet2 = as.double(rep(0,ntot^2)), # rV=as.double(rep(0,ncol(x)^2)), # rank.tol=as.double(.Machine\$double.eps^.75),rank.est=as.integer(0), # n=as.integer(sum(good)),q=as.integer(ncol(x)),M=as.integer(nSp), # n.theta=as.integer(length(theta)), Mp=as.integer(Mp),Enrow=as.integer(rows.E), # rSncol=as.integer(rSncol),deriv=as.integer(deriv), # fixed.penalty = as.integer(rp\$fixed.penalty),nt=as.integer(control\$nthreads), # type=as.integer(1)) `````` Dirk Eddelbuettel committed Apr 10, 2018 594 595 `````` rV <- matrix(oo\$rV,ncol(x),ncol(x)) ## rV%*%t(rV)*scale gives covariance matrix rV <- T %*% rV `````` Dirk Eddelbuettel committed Apr 10, 2018 596 597 `````` ## derivatives of coefs w.r.t. sps etc... db.drho <- if (deriv) T %*% matrix(oo\$b1,ncol(x),ntot) else NULL `````` Dirk Eddelbuettel committed Apr 10, 2018 598 `````` dw.drho <- if (deriv) matrix(oo\$w1,length(z),ntot) else NULL `````` Dirk Eddelbuettel committed Apr 10, 2018 599 600 601 602 603 604 605 606 607 608 609 610 611 612 `````` Kmat <- matrix(0,nrow(x),ncol(x)) Kmat[good,] <- oo\$X ## rV%*%t(K)%*%(sqrt(wf)*X) = F; diag(F) is edf array D2 <- matrix(oo\$D2,ntot,ntot); ldet2 <- matrix(oo\$ldet2,ntot,ntot) bSb2 <- matrix(oo\$P2,ntot,ntot) ## compute the REML score... ls <- family\$ls(y,weights,n,theta,scale) nt <- length(theta) lsth1 <- ls\$lsth1[1:nt]; lsth2 <- as.matrix(ls\$lsth2)[1:nt,1:nt] ## exclude any derivs w.r.t log scale here REML <- (dev+oo\$P)/(2*scale) - ls\$ls + (oo\$ldet - rp\$det)/2 - as.numeric(scoreType=="REML") * Mp * log(2*pi*scale)/2 REML1 <- REML2 <- NULL if (deriv) { `````` Dirk Eddelbuettel committed Apr 10, 2018 613 614 615 616 617 `````` det1 <- oo\$ldet1 if (nSp) { ind <- 1:nSp + length(theta) det1[ind] <- det1[ind] - rp\$det1 } `````` Dirk Eddelbuettel committed Apr 10, 2018 618 619 620 `````` REML1 <- (oo\$D1+oo\$P1)/(2*scale) - c(lsth1,rep(0,length(sp))) + (det1)/2 if (deriv>1) { ls2 <- D2*0;ls2[1:nt,1:nt] <- lsth2 `````` Dirk Eddelbuettel committed Apr 10, 2018 621 `````` if (nSp) ldet2[ind,ind] <- ldet2[ind,ind] - rp\$det2 `````` Dirk Eddelbuettel committed Apr 10, 2018 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 `````` REML2 <- (D2+bSb2)/(2*scale) - ls2 + ldet2/2 } } if (!scale.known&&deriv) { ## need derivatives wrt log scale, too Dp <- dev + oo\$P dlr.dlphi <- -Dp/(2 *scale) - ls\$lsth1[nt+1] - Mp/2 d2lr.d2lphi <- Dp/(2*scale) - ls\$lsth2[nt+1,nt+1] d2lr.dspphi <- -(oo\$D1+oo\$P1)/(2*scale) d2lr.dspphi[1:nt] <- d2lr.dspphi[1:nt] - ls\$lsth2[nt+1,1:nt] REML1 <- c(REML1,dlr.dlphi) if (deriv==2) { REML2 <- rbind(REML2,as.numeric(d2lr.dspphi)) REML2 <- cbind(REML2,c(as.numeric(d2lr.dspphi),d2lr.d2lphi)) } } `````` Dirk Eddelbuettel committed Apr 10, 2018 638 639 640 641 642 643 644 `````` nth <- length(theta) if (deriv>0&&family\$n.theta==0&&nth>0) { ## need to drop derivs for fixed theta REML1 <- REML1[-(1:nth)] if (deriv>1) REML2 <- REML2[-(1:nth),-(1:nth)] db.drho <- db.drho[,-(1:nth),drop=FALSE] } `````` Dirk Eddelbuettel committed Apr 10, 2018 645 646 647 `````` names(coef) <- xnames names(residuals) <- ynames `````` Dirk Eddelbuettel committed Apr 10, 2018 648 `````` wtdmu <- sum(weights * mu)/sum(weights) ## changed from y `````` Dirk Eddelbuettel committed Apr 10, 2018 649 `````` nulldev <- sum(dev.resids(y, rep(wtdmu,length(y)), weights)) `````` Dirk Eddelbuettel committed Apr 10, 2018 650 651 `````` n.ok <- nobs - sum(weights == 0) nulldf <- n.ok `````` Dirk Eddelbuettel committed Apr 10, 2018 652 `````` ww <- wt <- rep.int(0, nobs) `````` Dirk Eddelbuettel committed Apr 10, 2018 653 `````` wt[good] <- wf `````` Dirk Eddelbuettel committed Apr 10, 2018 654 `````` ww[good] <- w `````` Dirk Eddelbuettel committed Apr 10, 2018 655 656 657 658 659 `````` if (deriv && nrow(dw.drho)!=nrow(x)) { w1 <- dw.drho dw.drho <- matrix(0,nrow(x),ncol(w1)) dw.drho[good,] <- w1 } `````` Dirk Eddelbuettel committed Apr 10, 2018 660 661 662 663 664 `````` aic.model <- family\$aic(y, mu, theta, weights, dev) # note: incomplete 2*edf needs to be added list(coefficients = coef,residuals=residuals,fitted.values = mu, family=family, linear.predictors = eta,deviance=dev, `````` Dirk Eddelbuettel committed Apr 10, 2018 665 666 `````` null.deviance=nulldev,iter=iter, weights=wt, ## note that these are Fisher type weights `````` Dirk Eddelbuettel committed Apr 10, 2018 667 `````` prior.weights=weights, `````` Dirk Eddelbuettel committed Apr 10, 2018 668 `````` working.weights = ww, ## working weights `````` Dirk Eddelbuettel committed Apr 10, 2018 669 670 671 `````` df.null = nulldf, y = y, converged = conv, boundary = boundary, REML=REML,REML1=REML1,REML2=REML2, `````` Dirk Eddelbuettel committed Apr 10, 2018 672 `````` rV=rV,db.drho=db.drho,dw.drho=dw.drho, `````` Dirk Eddelbuettel committed Apr 10, 2018 673 674 675 `````` scale.est=scale,reml.scale=scale, aic=aic.model, rank=oo\$rank.est, `````` Dirk Eddelbuettel committed Apr 10, 2018 676 677 `````` K=Kmat,control=control, dVkk = matrix(oo\$dVkk,nSp,nSp) `````` Dirk Eddelbuettel committed Apr 10, 2018 678 679 680 681 `````` #,D1=oo\$D1,D2=D2, #ldet=oo\$ldet,ldet1=oo\$ldet1,ldet2=ldet2, #bSb=oo\$P,bSb1=oo\$P1,bSb2=bSb2, #ls=ls\$ls,ls1=ls\$lsth1,ls2=ls\$lsth2 `````` Dirk Eddelbuettel committed Apr 10, 2018 682 683 684 685 686 687 688 689 `````` ) } ## gam.fit4 gam.fit5 <- function(x,y,lsp,Sl,weights=NULL,offset=NULL,deriv=2,family, control=gam.control(),Mp=-1,start=NULL){ `````` Dirk Eddelbuettel committed Apr 10, 2018 690 ``````## NOTE: offset handling - needs to be passed to ll code `````` Dirk Eddelbuettel committed Apr 10, 2018 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 ``````## fit models by general penalized likelihood method, ## given doubly extended family in family. lsp is log smoothing parameters ## Stabilization strategy: ## 1. Sl.repara ## 2. Hessian diagonally pre-conditioned if +ve diagonal elements ## (otherwise indefinite anyway) ## 3. Newton fit with perturbation of any indefinite hessian ## 4. At convergence test fundamental rank on balanced version of ## penalized Hessian. Drop unidentifiable parameters and ## continue iteration to adjust others. ## 5. All remaining computations in reduced space. ## ## Idea is that rank detection takes care of structural co-linearity, ## while preconditioning and step 1 take care of extreme smoothing parameters ## related problems. `````` Dirk Eddelbuettel committed Apr 10, 2018 707 `````` penalized <- if (length(Sl)>0) TRUE else FALSE `````` Dirk Eddelbuettel committed Apr 10, 2018 708 709 710 `````` nSp <- length(lsp) q <- ncol(x) `````` Dirk Eddelbuettel committed Apr 10, 2018 711 `````` nobs <- length(y) `````` Dirk Eddelbuettel committed Apr 10, 2018 712 713 714 `````` if (penalized) { Eb <- attr(Sl,"E") ## balanced penalty sqrt `````` Dirk Eddelbuettel committed Apr 10, 2018 715 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 `````` ## the stability reparameterization + log|S|_+ and derivs... rp <- ldetS(Sl,rho=lsp,fixed=rep(FALSE,length(lsp)),np=q,root=TRUE) x <- Sl.repara(rp\$rp,x) ## apply re-parameterization to x Eb <- Sl.repara(rp\$rp,Eb) ## root balanced penalty St <- crossprod(rp\$E) ## total penalty matrix E <- rp\$E ## root total penalty attr(E,"use.unscaled") <- TRUE ## signal initialization code that E not to be further scaled if (!is.null(start)) start <- Sl.repara(rp\$rp,start) ## re-para start ## NOTE: it can be that other attributes need re-parameterization here ## this should be done in 'family\$initialize' - see mvn for an example. } else { ## unpenalized so no derivatives required deriv <- 0 rp <- list(ldetS=0,rp=list()) St <- matrix(0,q,q) E <- matrix(0,0,q) ## can be needed by initialization code } `````` Dirk Eddelbuettel committed Apr 10, 2018 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 `````` ## now call initialization code, but make sure that any ## supplied 'start' vector is not overwritten... start0 <- start ## Assumption here is that the initialization code is fine with ## re-parameterized x... eval(family\$initialize) if (!is.null(start0)) start <- start0 coef <- as.numeric(start) if (is.null(weights)) weights <- rep.int(1, nobs) if (is.null(offset)) offset <- rep.int(0, nobs) `````` Dirk Eddelbuettel committed Apr 10, 2018 749 `````` ## get log likelihood, grad and Hessian (w.r.t. coefs - not s.p.s) ... `````` Dirk Eddelbuettel committed Apr 10, 2018 750 `````` llf <- family\$ll `````` Dirk Eddelbuettel committed Apr 10, 2018 751 `````` ll <- llf(y,x,coef,weights,family,offset=offset,deriv=1) `````` Dirk Eddelbuettel committed Apr 10, 2018 752 `````` ll0 <- ll\$l - (t(coef)%*%St%*%coef)/2 `````` Dirk Eddelbuettel committed Apr 10, 2018 753 754 755 756 `````` rank.checked <- FALSE ## not yet checked the intrinsic rank of problem rank <- q;drop <- NULL eigen.fix <- FALSE converged <- FALSE `````` Dirk Eddelbuettel committed Apr 10, 2018 757 758 759 `````` check.deriv <- FALSE; eps <- 1e-5 drop <- NULL;bdrop <- rep(FALSE,q) ## by default nothing dropped perturbed <- 0 ## counter for number of times perturbation tried on possible saddle `````` Dirk Eddelbuettel committed Apr 10, 2018 760 761 `````` for (iter in 1:(2*control\$maxit)) { ## main iteration ## get Newton step... `````` Dirk Eddelbuettel committed Apr 10, 2018 762 763 764 765 `````` if (check.deriv) { fdg <- ll\$lb*0; fdh <- ll\$lbb*0 for (k in 1:length(coef)) { coef1 <- coef;coef1[k] <- coef[k] + eps `````` Dirk Eddelbuettel committed Apr 10, 2018 766 `````` ll.fd <- llf(y,x,coef1,weights,family,offset=offset,deriv=1) `````` Dirk Eddelbuettel committed Apr 10, 2018 767 768 769 770 `````` fdg[k] <- (ll.fd\$l-ll\$l)/eps fdh[,k] <- (ll.fd\$lb-ll\$lb)/eps } } `````` Dirk Eddelbuettel committed Apr 10, 2018 771 772 773 774 775 776 777 `````` grad <- ll\$lb - St%*%coef Hp <- -ll\$lbb+St D <- diag(Hp) indefinite <- FALSE if (sum(D <= 0)) { ## Hessian indefinite, for sure D <- rep(1,ncol(Hp)) if (eigen.fix) { `````` Dirk Eddelbuettel committed Apr 10, 2018 778 779 `````` eh <- eigen(Hp,symmetric=TRUE); ev <- abs(eh\$values) `````` Dirk Eddelbuettel committed Apr 10, 2018 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 `````` Hp <- eh\$vectors%*%(ev*t(eh\$vectors)) } else { Ib <- diag(rank)*abs(min(D)) Ip <- diag(rank)*abs(max(D)*.Machine\$double.eps^.5) Hp <- Hp + Ip + Ib } indefinite <- TRUE } else { ## Hessian could be +ve def in which case Choleski is cheap! D <- D^-.5 ## diagonal pre-conditioner Hp <- D*t(D*Hp) ## pre-condition Hp Ip <- diag(rank)*.Machine\$double.eps^.5 } L <- suppressWarnings(chol(Hp,pivot=TRUE)) mult <- 1 while (attr(L,"rank") < rank) { ## rank deficient - add ridge penalty if (eigen.fix) { eh <- eigen(Hp,symmetric=TRUE);ev <- eh\$values thresh <- max(min(ev[ev>0]),max(ev)*1e-6)*mult mult <- mult*10 ev[ev0) { ## limit step length to .1 of coef length s.norm <- sqrt(sum(step^2)) c.norm <- sqrt(c.norm) if (s.norm > .1*c.norm) step <- step*0.1*c.norm/s.norm } ## try the Newton step... coef1 <- coef + step `````` Dirk Eddelbuettel committed Apr 10, 2018 821 `````` ll <- llf(y,x,coef1,weights,family,offset=offset,deriv=1) `````` Dirk Eddelbuettel committed Apr 10, 2018 822 `````` ll1 <- ll\$l - (t(coef1)%*%St%*%coef1)/2 `````` Dirk Eddelbuettel committed Apr 10, 2018 823 `````` khalf <- 0;fac <- 2 `````` Dirk Eddelbuettel committed Apr 10, 2018 824 `````` while ((!is.finite(ll1)||ll1 < ll0) && khalf < 25) { ## step halve until it succeeds... `````` Dirk Eddelbuettel committed Apr 10, 2018 825 `````` step <- step/fac;coef1 <- coef + step `````` Dirk Eddelbuettel committed Apr 10, 2018 826 `````` ll <- llf(y,x,coef1,weights,family,offset=offset,deriv=0) `````` Dirk Eddelbuettel committed Apr 10, 2018 827 828 `````` ll1 <- ll\$l - (t(coef1)%*%St%*%coef1)/2 if (ll1>=ll0) { `````` Dirk Eddelbuettel committed Apr 10, 2018 829 `````` ll <- llf(y,x,coef1,weights,family,offset=offset,deriv=1) `````` Dirk Eddelbuettel committed Apr 10, 2018 830 831 `````` } else { ## abort if step has made no difference if (max(abs(coef1-coef))==0) khalf <- 100 `````` Dirk Eddelbuettel committed Apr 10, 2018 832 833 `````` } khalf <- khalf + 1 `````` Dirk Eddelbuettel committed Apr 10, 2018 834 `````` if (khalf>5) fac <- 5 `````` Dirk Eddelbuettel committed Apr 10, 2018 835 `````` } ## end step halve `````` Dirk Eddelbuettel committed Apr 10, 2018 836 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 837 `````` if (!is.finite(ll1) || ll1 < ll0) { ## switch to steepest descent... `````` Dirk Eddelbuettel committed Apr 10, 2018 838 839 840 841 `````` step <- -.5*drop(grad)*mean(abs(coef))/mean(abs(grad)) khalf <- 0 } `````` Dirk Eddelbuettel committed Apr 10, 2018 842 `````` while ((!is.finite(ll1)||ll1 < ll0) && khalf < 25) { ## step cut until it succeeds... `````` Dirk Eddelbuettel committed Apr 10, 2018 843 `````` step <- step/10;coef1 <- coef + step `````` Dirk Eddelbuettel committed Apr 10, 2018 844 `````` ll <- llf(y,x,coef1,weights,family,offset=offset,deriv=0) `````` Dirk Eddelbuettel committed Apr 10, 2018 845 846 `````` ll1 <- ll\$l - (t(coef1)%*%St%*%coef1)/2 if (ll1>=ll0) { `````` Dirk Eddelbuettel committed Apr 10, 2018 847 `````` ll <- llf(y,x,coef1,weights,family,offset=offset,deriv=1) `````` Dirk Eddelbuettel committed Apr 10, 2018 848 849 850 851 852 `````` } else { ## abort if step has made no difference if (max(abs(coef1-coef))==0) khalf <- 100 } khalf <- khalf + 1 } `````` Dirk Eddelbuettel committed Apr 10, 2018 853 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 854 `````` if ((is.finite(ll1)&&ll1 >= ll0)||iter==control\$maxit) { ## step ok. Accept and test `````` Dirk Eddelbuettel committed Apr 10, 2018 855 `````` coef <- coef + step `````` Dirk Eddelbuettel committed Apr 10, 2018 856 857 858 859 860 861 862 863 864 865 `````` ## convergence test... ok <- (iter==control\$maxit||(abs(ll1-ll0) < control\$epsilon*abs(ll0) && max(abs(grad)) < .Machine\$double.eps^.5*abs(ll0))) if (ok) { ## appears to have converged if (indefinite) { ## not a well defined maximum if (perturbed==5) stop("indefinite penalized likelihood in gam.fit5 ") if (iter<4||rank.checked) { perturbed <- perturbed + 1 coef <- coef*(1+(runif(length(coef))*.02-.01)*perturbed) + (runif(length(coef)) - 0.5 ) * mean(abs(coef))*1e-5*perturbed `````` Dirk Eddelbuettel committed Apr 10, 2018 866 `````` ll <- llf(y,x,coef,weights,family,offset=offset,deriv=1) `````` Dirk Eddelbuettel committed Apr 10, 2018 867 `````` ll0 <- ll\$l - (t(coef)%*%St%*%coef)/2 `````` Dirk Eddelbuettel committed Apr 10, 2018 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 `````` } else { rank.checked <- TRUE if (penalized) { Sb <- crossprod(Eb) ## balanced penalty Hb <- -ll\$lbb/norm(ll\$lbb,"F")+Sb/norm(Sb,"F") ## balanced penalized hessian } else Hb <- -ll\$lbb/norm(ll\$lbb,"F") ## apply pre-conditioning, otherwise badly scaled problems can result in ## wrong coefs being dropped... D <- abs(diag(Hb)) D[D<1e-50] <- 1;D <- D^-.5 Hb <- t(D*Hb)*D qrh <- qr(Hb,LAPACK=TRUE) rank <- Rrank(qr.R(qrh)) if (rank < q) { ## rank deficient. need to drop and continue to adjust other params drop <- sort(qrh\$pivot[(rank+1):q]) ## set these params to zero bdrop <- 1:q %in% drop ## TRUE FALSE version ## now drop the parameters and recompute ll0... lpi <- attr(x,"lpi") `````` Dirk Eddelbuettel committed Apr 10, 2018 886 887 `````` xat <- attributes(x) xat\$dim <- xat\$dimnames <- NULL `````` Dirk Eddelbuettel committed Apr 10, 2018 888 889 890 891 `````` coef <- coef[-drop] St <- St[-drop,-drop] x <- x[,-drop] ## dropping columns from model matrix if (!is.null(lpi)) { ## need to adjust column indexes as well `````` Dirk Eddelbuettel committed Apr 10, 2018 892 893 `````` ii <- (1:q)[!bdrop];ij <- rep(NA,q) ij[ii] <- 1:length(ii) ## col i of old model matrix is col ij[i] of new `````` Dirk Eddelbuettel committed Apr 10, 2018 894 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 895 `````` for (i in 1:length(lpi)) { `````` Dirk Eddelbuettel committed Apr 10, 2018 896 `````` lpi[[i]] <- ij[lpi[[i]][!(lpi[[i]]%in%drop)]] # drop and shuffle up `````` Dirk Eddelbuettel committed Apr 10, 2018 897 898 `````` } } ## lpi adjustment done `````` Dirk Eddelbuettel committed Apr 10, 2018 899 `````` if (length(xat)>0) for (i in 1:length(xat)) attr(x,names(xat)[i]) <- xat[[i]] `````` Dirk Eddelbuettel committed Apr 10, 2018 900 `````` attr(x,"lpi") <- lpi `````` Dirk Eddelbuettel committed Apr 10, 2018 901 `````` attr(x,"drop") <- drop ## useful if family has precomputed something from x `````` Dirk Eddelbuettel committed Apr 10, 2018 902 `````` ll <- llf(y,x,coef,weights,family,offset=offset,deriv=1) `````` Dirk Eddelbuettel committed Apr 10, 2018 903 904 `````` ll0 <- ll\$l - (t(coef)%*%St%*%coef)/2 } `````` Dirk Eddelbuettel committed Apr 10, 2018 905 `````` } `````` Dirk Eddelbuettel committed Apr 10, 2018 906 907 908 909 910 911 `````` } else { ## not indefinite really converged converged <- TRUE break } } else ll0 <- ll1 ## step ok but not converged yet `````` Dirk Eddelbuettel committed Apr 10, 2018 912 913 `````` } else { ## step failed. converged <- FALSE `````` Dirk Eddelbuettel committed Apr 10, 2018 914 `````` if (is.null(drop)) bdrop <- rep(FALSE,q) `````` Dirk Eddelbuettel committed Apr 10, 2018 915 916 917 918 `````` warning(paste("step failed: max abs grad =",max(abs(grad)))) break } } ## end of main fitting iteration `````` Dirk Eddelbuettel committed Apr 10, 2018 919 920 `````` ## at this stage the Hessian (of pen lik. w.r.t. coefs) should be +ve definite, `````` Dirk Eddelbuettel committed Apr 10, 2018 921 `````` ## so that the pivoted Choleski factor should exist... `````` Dirk Eddelbuettel committed Apr 10, 2018 922 923 `````` if (iter == 2*control\$maxit&&converged==FALSE) warning(gettextf("iteration limit reached: max abs grad = %g",max(abs(grad)))) `````` Dirk Eddelbuettel committed Apr 10, 2018 924 925 926 927 928 929 930 `````` ldetHp <- 2*sum(log(diag(L))) - 2 * sum(log(D)) ## log |Hp| if (!is.null(drop)) { ## create full version of coef with zeros for unidentifiable fcoef <- rep(0,length(bdrop));fcoef[!bdrop] <- coef } else fcoef <- coef `````` Dirk Eddelbuettel committed Apr 10, 2018 931 `````` dVkk <- d1l <- d2l <- d1bSb <- d2bSb <- d1b <- d2b <- d1ldetH <- d2ldetH <- d1b <- d2b <- NULL `````` Dirk Eddelbuettel committed Apr 10, 2018 932 933 `````` if (deriv>0) { ## Implicit differentiation for derivs... `````` Dirk Eddelbuettel committed Apr 10, 2018 934 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 935 936 937 938 939 `````` m <- nSp d1b <- matrix(0,rank,m) Sib <- Sl.termMult(rp\$Sl,fcoef,full=TRUE) ## list of penalties times coefs if (nSp) for (i in 1:m) d1b[,i] <- -D*(backsolve(L,forwardsolve(t(L),(D*Sib[[i]][!bdrop])[piv]))[ipiv]) `````` Dirk Eddelbuettel committed Apr 10, 2018 940 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 941 942 943 `````` ## obtain the curvature check matrix... dVkk <- crossprod(L[,ipiv]%*%(d1b/D)) `````` Dirk Eddelbuettel committed Apr 10, 2018 944 945 946 947 `````` if (!is.null(drop)) { ## create full version of d1b with zeros for unidentifiable fd1b <- matrix(0,q,m) fd1b[!bdrop,] <- d1b } else fd1b <- d1b `````` Dirk Eddelbuettel committed Apr 10, 2018 948 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 949 950 `````` ## Now call the family again to get first derivative of Hessian w.r.t ## smoothing parameters, in list d1H... `````` Dirk Eddelbuettel committed Apr 10, 2018 951 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 952 953 `````` ll <- llf(y,x,coef,weights,family,offset=offset,deriv=3,d1b=d1b) # d1l <- colSums(ll\$lb*d1b) # cancels `````` Dirk Eddelbuettel committed Apr 10, 2018 954 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 955 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 956 `````` if (deriv>1) { ## Implicit differentiation for the second derivatives is now possible... `````` Dirk Eddelbuettel committed Apr 10, 2018 957 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 958 959 960 961 962 963 964 965 `````` d2b <- matrix(0,rank,m*(m+1)/2) k <- 0 for (i in 1:m) for (j in i:m) { k <- k + 1 v <- -ll\$d1H[[i]]%*%d1b[,j] + Sl.mult(rp\$Sl,fd1b[,j],i)[!bdrop] + Sl.mult(rp\$Sl,fd1b[,i],j)[!bdrop] d2b[,k] <- -D*(backsolve(L,forwardsolve(t(L),(D*v)[piv]))[ipiv]) if (i==j) d2b[,k] <- d2b[,k] + d1b[,i] } `````` Dirk Eddelbuettel committed Apr 10, 2018 966 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 967 968 `````` ## Now call family for last time to get trHid2H the tr(H^{-1} d^2 H / drho_i drho_j)... `````` Dirk Eddelbuettel committed Apr 10, 2018 969 `````` llr <- llf(y,x,coef,weights,family,offset=offset,deriv=4,d1b=d1b,d2b=d2b, `````` Dirk Eddelbuettel committed Apr 10, 2018 970 971 972 973 `````` Hp=Hp,rank=rank,fh = L,D=D) ## Now compute Hessian of log lik w.r.t. log sps using chain rule `````` Dirk Eddelbuettel committed Apr 10, 2018 974 975 `````` # d2la <- colSums(ll\$lb*d2b) # cancels # k <- 0 `````` Dirk Eddelbuettel committed Apr 10, 2018 976 977 `````` d2l <- matrix(0,m,m) for (i in 1:m) for (j in i:m) { `````` Dirk Eddelbuettel committed Apr 10, 2018 978 979 980 `````` # k <- k + 1 d2l[j,i] <- d2l[i,j] <- # d2la[k] + # cancels t(d1b[,i])%*%ll\$lbb%*%d1b[,j] `````` Dirk Eddelbuettel committed Apr 10, 2018 981 982 983 `````` } } ## if (deriv > 1) } ## if (deriv > 0) `````` Dirk Eddelbuettel committed Apr 10, 2018 984 985 `````` ## Compute the derivatives of log|H+S|... `````` Dirk Eddelbuettel committed Apr 10, 2018 986 987 988 989 990 991 992 993 994 `````` if (deriv > 0) { d1ldetH <- rep(0,m) d1Hp <- list() for (i in 1:m) { A <- -ll\$d1H[[i]] + Sl.mult(rp\$Sl,diag(q),i)[!bdrop,!bdrop] d1Hp[[i]] <- D*(backsolve(L,forwardsolve(t(L),(D*A)[piv,]))[ipiv,]) d1ldetH[i] <- sum(diag(d1Hp[[i]])) } } ## if (deriv > 0) `````` Dirk Eddelbuettel committed Apr 10, 2018 995 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 996 997 998 999 1000 1001 1002 `````` if (deriv > 1) { d2ldetH <- matrix(0,m,m) k <- 0 for (i in 1:m) for (j in i:m) { k <- k + 1 d2ldetH[i,j] <- -sum(d1Hp[[i]]*t(d1Hp[[j]])) - llr\$trHid2H[k] if (i==j) { ## need to add term relating to smoothing penalty `````` Dirk Eddelbuettel committed Apr 10, 2018 1003 1004 1005 1006 1007 1008 1009 1010 `````` #A <- t(Sl.mult(rp\$Sl,diag(q),i,full=FALSE)) #bind <- rowSums(abs(A))!=0 ## FIX: abs 3/3/16 #ind <- which(bind) #bind <- bind[!bdrop] #A <- A[!bdrop,!bdrop[ind]] A <- Sl.mult(rp\$Sl,diag(q),i,full=TRUE)[!bdrop,!bdrop] bind <- rowSums(abs(A))!=0 ## row/cols of non-zero block A <- A[,bind] ## drop the zero columns `````` Dirk Eddelbuettel committed Apr 10, 2018 1011 1012 1013 1014 1015 `````` A <- D*(backsolve(L,forwardsolve(t(L),(D*A)[piv,]))[ipiv,]) d2ldetH[i,j] <- d2ldetH[i,j] + sum(diag(A[bind,])) } else d2ldetH[j,i] <- d2ldetH[i,j] } } ## if (deriv > 1) `````` Dirk Eddelbuettel committed Apr 10, 2018 1016 1017 1018 `````` ## Compute derivs of b'Sb... `````` Dirk Eddelbuettel committed Apr 10, 2018 1019 `````` if (deriv>0) { `````` Dirk Eddelbuettel committed Apr 10, 2018 1020 `````` # Sb <- St%*%coef `````` Dirk Eddelbuettel committed Apr 10, 2018 1021 1022 1023 1024 `````` Skb <- Sl.termMult(rp\$Sl,fcoef,full=TRUE) d1bSb <- rep(0,m) for (i in 1:m) { Skb[[i]] <- Skb[[i]][!bdrop] `````` Dirk Eddelbuettel committed Apr 10, 2018 1025 1026 `````` d1bSb[i] <- # 2*sum(d1b[,i]*Sb) + # cancels sum(coef*Skb[[i]]) `````` Dirk Eddelbuettel committed Apr 10, 2018 1027 `````` } `````` Dirk Eddelbuettel committed Apr 10, 2018 1028 1029 `````` } `````` Dirk Eddelbuettel committed Apr 10, 2018 1030 1031 `````` if (deriv>1) { d2bSb <- matrix(0,m,m) `````` Dirk Eddelbuettel committed Apr 10, 2018 1032 `````` # k <- 0 `````` Dirk Eddelbuettel committed Apr 10, 2018 1033 1034 1035 `````` for (i in 1:m) { Sd1b <- St%*%d1b[,i] for (j in i:m) { `````` Dirk Eddelbuettel committed Apr 10, 2018 1036 1037 `````` k <- k + 1 d2bSb[j,i] <- d2bSb[i,j] <- 2*sum( # d2b[,k]*Sb + # cancels `````` Dirk Eddelbuettel committed Apr 10, 2018 1038 `````` d1b[,i]*Skb[[j]] + d1b[,j]*Skb[[i]] + d1b[,j]*Sd1b) `````` Dirk Eddelbuettel committed Apr 10, 2018 1039 1040 `````` } d2bSb[i,i] <- d2bSb[i,i] + sum(coef*Skb[[i]]) `````` Dirk Eddelbuettel committed Apr 10, 2018 1041 1042 1043 1044 `````` } } ## get grad and Hessian of REML score... `````` Dirk Eddelbuettel committed Apr 10, 2018 1045 `````` REML <- -as.numeric(ll\$l - drop(t(coef)%*%St%*%coef)/2 + rp\$ldetS/2 - ldetHp/2 + Mp*log(2*pi)/2) `````` Dirk Eddelbuettel committed Apr 10, 2018 1046 `````` `````` Dirk Eddelbuettel committed Apr 10, 2018 1047 1048 1049 `````` REML1 <- if (deriv<1) NULL else -as.numeric( # d1l # cancels - d1bSb/2 + rp\$ldet1/2 - d1ldetH/2 ) `````` Dirk Eddelbuettel committed Apr 10, 2018 1050 1051 1052 1053 1054 `````` if (control\$trace) { cat("\niter =",iter," ll =",ll\$l," REML =",REML," bSb =",t(coef)%*%St%*%coef/2,"\n") cat("log|S| =",rp\$ldetS," log|H+S| =",ldetHp," n.drop =",length(drop),"\n") if (!is.null(REML1)) cat("REML1 =",REML1,"\n") } `````` Dirk Eddelbuettel committed Apr 10, 2018 1055 `````` REML2 <- if (deriv<2) NULL else -( d2l - d2bSb/2 + rp\$ldet2/2 - d2ldetH/2 ) `````` Dirk Eddelbuettel committed Apr 10, 2018 1056 `````` ## bSb <- t(coef)%*%St%*%coef `````` Dirk Eddelbuettel committed Apr 10, 2018 1057 1058 `````` lpi <- attr(x,"lpi") if (is.null(lpi)) { `````` Dirk Eddelbuettel committed Apr 10, 2018 1059 `````` linear.predictors <- if (is.null(offset)) as.numeric(x%*%coef) else as.numeric(x%*%coef+offset) `````` Dirk Eddelbuettel committed Apr 10, 2018 1060 1061 1062 `````` fitted.values <- family\$linkinv(linear.predictors) } else { fitted.values <- linear.predictors <- matrix(0,nrow(x),length(lpi)) `````` Dirk Eddelbuettel committed Apr 10, 2018 1063 `````` if (!is.null(offset)) offset[[length(lpi)+1]] <- 0 `````` Dirk Eddelbuettel committed Apr 10, 2018 1064 1065 `````` for (j in 1:length(lpi)) { linear.predictors[,j] <- as.numeric(x[,lpi[[j]],drop=FALSE] %*% coef[lpi[[j]]]) `````` Dirk Eddelbuettel committed Apr 10, 2018 1066 `````` if (!is.null(offset[[j]])) linear.predictors[,j] <- linear.predictors[,j] + offset[[j]] `````` Dirk Eddelbuettel committed Apr 10, 2018 1067 1068 1069 1070 1071 `````` fitted.values[,j] <- family\$linfo[[j]]\$linkinv( linear.predictors[,j]) } } coef <- Sl.repara(rp\$rp,fcoef,inverse=TRUE) ## undo re-parameterization of coef `````` Dirk Eddelbuettel committed Apr 10, 2018 1072 `````` if (!is.null(drop)&&!is.null(d1b)) { ## create full version of d1b with zeros for unidentifiable `````` Dirk Eddelbuettel committed Apr 10, 2018 1073 1074 1075 `````` db.drho <- matrix(0,length(bdrop),ncol(d1b));db.drho[!bdrop,] <- d1b } else db.drho <- d1b ## and undo re-para... `````` Dirk Eddelbuettel committed Apr 10, 2018 1076 `````` if (!is.null(d1b)) db.drho <- t(Sl.repara(rp\$rp,t(db.drho),inverse=TRUE,both.sides=FALSE)) `````` Dirk Eddelbuettel committed Apr 10, 2018 1077 1078 1079 `````` ret <- list(coefficients=coef,family=family,y=y,prior.weights=weights, fitted.values=fitted.values, linear.predictors=linear.predictors, `````` Dirk Eddelbuettel committed Apr 10, 2018 1080 `````` scale.est=1, ### NOTE: needed by newton, but what is sensible here? `````` Dirk Eddelbuettel committed Apr 10, 2018 1081 1082 `````` REML= REML,REML1= REML1,REML2=REML2, rank=rank,aic = -2*ll\$l, ## 2*edf needs to be added `````` Dirk Eddelbuettel committed Apr 10, 2018 1083 1084 `````` ##deviance = -2*ll\$l, l= ll\$l,## l1 =d1l,l2 =d2l, `````` Dirk Eddelbuettel committed Apr 10, 2018 1085 1086 1087 1088 1089 `````` lbb = ll\$lbb, ## Hessian of log likelihood L=L, ## chol factor of pre-conditioned penalized hessian bdrop=bdrop, ## logical index of dropped parameters D=D, ## diagonal preconditioning matrix St=St, ## total penalty matrix `````` Dirk Eddelbuettel committed Apr 10, 2018 1090 1091 1092 `````` rp = rp\$rp, db.drho = db.drho, ## derivative of penalty coefs w.r.t. log sps. #bSb = bSb, bSb1 = d1bSb,bSb2 = d2bSb, `````` Dirk Eddelbuettel committed Apr 10, 2018 1093 `````` S1=rp\$ldet1, `````` Dirk Eddelbuettel committed Apr 10, 2018 1094 1095 1096 `````` #S=rp\$ldetS,S1=rp\$ldet1,S2=rp\$ldet2, #Hp=ldetHp,Hp1=d1ldetH,Hp2=d2ldetH, #b2 = d2b) `````` Dirk Eddelbuettel committed Apr 10, 2018 1097 `````` niter=iter,H = ll\$lbb,dH = ll\$d1H,dVkk=dVkk)#,d2H=llr\$d2H) `````` Dirk Eddelbuettel committed Apr 10, 2018 1098 1099 1100 1101 1102 `````` ## debugging code to allow components of 2nd deriv of hessian w.r.t. sp.s ## to be passed to deriv.check.... #if (!is.null(ll\$ghost1)&&!is.null(ll\$ghost2)) { # ret\$ghost1 <- ll\$ghost1; ret\$ghost2 <- ret\$ghost2 #} `````` Dirk Eddelbuettel committed Apr 10, 2018 1103 `````` ret `````` Dirk Eddelbuettel committed Apr 10, 2018 1104 1105 ``````} ## end of gam.fit5 `````` Dirk Eddelbuettel committed Apr 10, 2018 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 ``````efsud <- function(x,y,lsp,Sl,weights=NULL,offset=NULL,family, control=gam.control(),Mp=-1,start=NULL) { ## Extended Fellner-Schall method ## tr(S^-S_j) is returned by ldetS as ldet1 - S1 from gam.fit5 ## b'S_jb is computed as d1bSb in gam.fit5 ## tr(V S_j) will need to be computed using Sl.termMult ## Sl returned by ldetS and Vb computed as in gam.fit5.postproc. tol <- 1e-6 lsp <- lsp + 2.5 mult <- 1 fit <- gam.fit5(x=x,y=y,lsp=lsp,Sl=Sl,weights=weights,offset=offset,deriv=0,family=family, control=control,Mp=Mp,start=start) score.hist <- rep(0,200) for (iter in 1:200) { start <- fit\$coefficients ## obtain Vb... ipiv <- piv <- attr(fit\$L,"pivot") p <- length(piv) ipiv[piv] <- 1:p Vb <- crossprod(forwardsolve(t(fit\$L),diag(fit\$D,nrow=p)[piv,,drop=FALSE])[ipiv,,drop=FALSE]) if (sum(fit\$bdrop)) { ## some coefficients were dropped... q <- length(fit\$bdrop) ibd <- !fit\$bdrop Vtemp <- Vb; Vb <- matrix(0,q,q) Vb[ibd,ibd] <- Vtemp } Vb <- Sl.repara(fit\$rp,Vb,inverse=TRUE) SVb <- Sl.termMult(Sl,Vb) ## this could be made more efficient trVS <- rep(0,length(SVb)) for (i in 1:length(SVb)) { ind <- attr(SVb[[i]],"ind") trVS[i] <- sum(diag(SVb[[i]][,ind])) } Sb <- Sl.termMult(Sl,start,full=TRUE) bSb <- rep(0,length(Sb)) for (i in 1:length(Sb)) { bSb[i] <- sum(start*Sb[[i]]) } a <- pmax(0,fit\$S1*exp(-lsp) - trVS) r <- a/pmax(0,bSb) r[a==0&bSb==0] <- 1 r[!is.finite(r)] <- 1e6 lsp1 <- pmin(lsp + log(r)*mult,12) old.reml <- fit\$REML fit <- gam.fit5(x=x,y=y,lsp=lsp1,Sl=Sl,weights=weights,offset=offset,deriv=0, family=family,control=control,Mp=Mp,start=start) ## some step length control... if (fit\$REML<=old.reml) { ## improvement if (max(abs(log(r))<.05)) { ## consider step extension lsp2 <- pmin(lsp + log(r)*mult*2,12) ## try extending step... fit2 <- gam.fit5(x=x,y=y,lsp=lsp2,Sl=Sl,weights=weights,offset=offset,deriv=0,family=family, control=control,Mp=Mp,start=start) if (fit2\$REML < fit\$REML) { ## improvement - accept extension fit <- fit2;lsp <- lsp2 mult <- mult * 2 } else { ## accept old step lsp <- lsp1 } } else lsp <- lsp1 } else { ## no improvement while (fit\$REML > old.reml&&mult>1) { ## don't contract below 1 as update doesn't have to improve REML mult <- mult/2 ## contract step lsp1 <- pmin(lsp + log(r)*mult,12) fit <- gam.fit5(x=x,y=y,lsp=lsp1,Sl=Sl,weights=weights,offset=offset,deriv=0,family=family, control=control,Mp=Mp,start=start) } lsp <- lsp1 if (mult<1) mult <- 1 } score.hist[iter] <- fit\$REML if (iter==1) old.ll <- fit\$l else { if (abs(old.ll-fit\$l)