############################################################################ # # # Program to perform the 3-step GLS algorithm: # # # # (i) Get OLS estimate # # (ii) Form estimated weights # # (iii) Do WLS with weights from (ii) # # # # The user must define 3 functions below: # # # # f(x,b) the nonlinear regression model depending on a (n x k) # # matrix of predictor variables and a (p x 1) regression # # parameter b # # # # fb(x,b) the (n x p) matrix of derivatives of f wrt b # # # # g(b,theta,z) the variance model with variance parameters theta # # # # The user must also provide the following: # # # # y (n x 1) data vector # # # # x (n x k) precictor values # # # # bstart starting value for b # # # # theta the fixed, known value for theta # # # # tol convergence criterion for WLS --if 2 iterates of b # # are within tol of each other relative to the current # # value, declare that the algorithm has converged # # # # imax maximum number of iterations to perform in WLS # # # # cmax number of GLS iterations to perform # # # ############################################################################ # Functions defining f, fb, g f <- function(x,b){ dose <- 5.50 ka <- exp(b[1]) cl <- exp(b[2]) v <- exp(b[3]) ke <- cl/v kk <- ka-ke f1 <- dose*ka*(exp(-ke*x)-exp(-ka*x))/(v*kk) f1 } fb <- function(x,b){ n <- length(x) p <- length(b) dose <- 5.50 ka <- exp(b[1]) cl <- exp(b[2]) v <- exp(b[3]) ke <- cl/v kk <- ka-ke f1 <- dose*ka*(exp(-ke*x)-exp(-ka*x))/(v*kk) tt <- dose*x*ka/(v*kk) fb1 <- matrix(0,n,p) fb1[,1] <- -f1*(ke/kk)+tt*ka*exp(-ka*x) fb1[,2] <- f1*(ke/kk)-tt*ke*exp(-ke*x) fb1[,3] <- -f1*(ka/kk)+tt*ke*exp(-ke*x) fb1 } # power variance function g <- function(b,theta,z){ g1 <- exp(theta*log(f(z,b))) g1 } # data thedat <- matrix(scan("theo10.dat"),ncol=2,byrow=T) x <- thedat[,1] y <- thedat[,2] # starting value for beta bstart <- log(c(0.75,0.05,0.50)) # values of theta to consider tvec <- c(0.0,0.5,1.0) # convergence tolerance and max number of iterations for WLS routine tol <- 1e-8 imax <- 500 # number of iterations of GLS algorithm to perform cmax <- 20 # name of output file outfile <- "theo10.glsfit" cat("FITS OF SUBJECT 10 THEOPHYLLINE DATA BY 3-STEP GLS FOR DIFFERENT THETA VALUES", file=outfile,"\n","\n",append=F) ######################################################################## # generic code to perform wls and compute sigma n <- length(x) p <- length(bstart) # function specifying convergence criterion converged <- function(tol,db,iter,imax){ bmax <- max(abs(db)) gmax <- iter==imax bmax <- bmax