File: nonlinear.R

package info (click to toggle)
r-cran-lava 1.8.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,816 kB
  • sloc: sh: 13; makefile: 2
file content (152 lines) | stat: -rw-r--r-- 4,824 bytes parent folder | download | duplicates (4)
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
##' @export
"nonlinear<-" <- function(object,...,value) UseMethod("nonlinear<-")

##' @export
"nonlinear" <- function(object,...) UseMethod("nonlinear")

naturalcubicspline <- function(x, knots=stats::median(x,na.rm=TRUE), boundary=range(x,na.rm=TRUE)) {
    ## C2 functions, piecewise cubic
    breaks <- c(boundary[1],knots,boundary[2])
    K <- length(breaks)
    g <- function(x,tau) (x-tau)^3*((x-tau)>0)
    gg <- matrix(0,nrow=length(x),ncol=K)
    for (i in seq(K)) {
        gg[,i] <- g(x,breaks[i])
    }
    B <- matrix(0,nrow=length(x),ncol=K-2)
    for (i in seq(K-2)) {
        B[,i] <- gg[,i] -
            (breaks[K]-breaks[i])/(breaks[K]-breaks[K-1])*gg[,K-1] +
            (breaks[K-1]-breaks[i])/(breaks[K]-breaks[K-1])*gg[,K]
    }
    cbind(x,B)
}

ncspred <- function(mu, var, knots=c(-5,0,5)) {
    breaks <- knots
    K <- length(breaks)

    v <- as.vector(var)
    k <- sqrt(v/(2*pi))
    g <- function(x,tau) {
        x0 <- (x-tau)
        x2 <- x0^2
        p0 <- 1-pnorm(-x0/sqrt(v)) # P(x>tau|...)
        k*(2*v + x2)*exp(-(x0/(sqrt(2*v)))^2) +
            x0*(x2+3*v)*p0
    }
    n <- NROW(mu)
    gg <- matrix(0,nrow=n,ncol=K)
    for (i in seq(K)) {
        gg[,i] <- g(mu,breaks[i])
    }
    B <- matrix(0,nrow=n,ncol=K-2)
    for (i in seq(K-2)) {
        B[,i] <- gg[,i] -
            (breaks[K]-breaks[i])/(breaks[K]-breaks[K-1])*gg[,K-1] +
            (breaks[K-1]-breaks[i])/(breaks[K]-breaks[K-1])*gg[,K]
    }
    cbind(mu,B)
}


##' @export
nonlinear.lvm <- function(object, to, from=NULL, type=c("quadratic"), knots=c(-5,0,5), names, ...) {
    if (missing(to)) {
        return(object$attributes$nonlinear)
    }
    if (inherits(to,"formula")) {
        yy <- decomp.specials(getoutcome(to))
        myvars <- all.vars(to)
        from <- setdiff(myvars,yy)
        to <- yy
    }
    if (length(to)>1) stop("Supply only one response variable")
    if (length(from)>1) stop("Supply only one explanatory variable")
    object <- cancel(object, c(from,to))
    variance(object) <- to
    f <- pred <- NULL

    if (tolower(type)[1]%in%c("ncs","spline","naturalspline","cubicspline","natural cubic spline")) {
        if (is.null(knots)) stop("Need cut-points ('knots')")
        if (length(knots)<3) {
            warning("Supply at least three knots (one interior and boundaries)")
            ## Fall-back to linear
            type <- "linear"
        }
        if (missing(names)) names <- paste0(from,"_",seq(length(knots)-1))
        f <- function(p,x) {
            B <- cbind(1,naturalcubicspline(x,knots=knots[-c(1,length(knots))],boundary=knots[c(1,length(knots))]))
            colnames(B) <- c("(Intercept)",names)
            as.vector(B%*%p)
        }
        pred <- function(mu,var,...) {
            B <- ncspred(mu,var,knots=knots)
            structure(B,dimnames=list(NULL,names))
        }
    }

    
    if (tolower(type)[1]=="linear") {
        if (missing(names)) names <- from
        f <- function(p,x) p[1] + p[2]*x
        pred <- function(mu,var,...) {            
            structure(cbind(mu[,1]),dimnames=list(NULL,names))
        }
    }
    
    if (tolower(type)[1]=="quadratic") {
        if (missing(names)) names <- paste0(from,"_",1:2)
        f <- function(p,x) p[1] + p[2]*x + p[3]*(x*x)
        pred <- function(mu,var,...) {
            structure(cbind(mu[,1],mu[,1]^2+var[1]),dimnames=list(NULL,names))
        }
    }

    if (tolower(type)[1]%in%c("piecewise","piecewise linear","linear")) {
        if (is.null(knots)) stop("Need cut-points ('knots')")
    }

    if (tolower(type)[1]%in%c("exp","exponential")) {
        if (missing(names)) names <- paste0(from,"_",1:2)
        f <- function(p,x) p[1] + p[2]*x + p[3]*exp(x)
        pred <- function(mu,var,...) {
            structure(cbind(mu[,1], exp(0.5*var[1] + mu[,1])),dimnames=list(NULL,names))
        }
    }

    if (tolower(type)[1]%in%c("exp0")) {
        if (missing(names)) names <- paste0(from,"_",1)
        f <- function(p,x) p[1] + p[2]*exp(x)
        pred <- function(mu,var,...) {
            structure(cbind(exp(0.5*var[1] + mu[,1])),dimnames=list(NULL,names))
        }
    }

    object$attributes$nonlinear[[to]] <- list(x=from, p=length(names)+1, newx=names, f=f, pred=pred, type=tolower(type[1]))
    return(object)
}

##' @export
nonlinear.lvmfit <- function(object, to, ...) {
    if (missing(to)) {
        return(Model(object)$attributes$nonlinear)
    }
    Model(object) <- nonlinear(Model(object),to=to,...)
    return(object)
}

##' @export
nonlinear.twostage.lvm <- function(object, ...) {
    return(object$nonlinear)
}

##' @export
nonlinear.lvmfit <- function(object, ...) {
    return(object$nonlinear)
}

##' @export
`nonlinear<-.lvm` <- function(object, ..., type="quadratic", value) {
    nonlinear(object,to=value,type=type,...)
}