
### Adapted from software packages provided by Gui, Li, Zou, Hastie, Efron, Tibshirani
### Splus REQUIRED - will not run in R


"coef.lars" <-
function(object, ...)
{
	predict(object, type = "coefficient", ...)$coef
}

"cv.folds" <-
function(n, folds = 10)
{
	split(sample(1:n), rep(1:folds, length = n))
}

"cv.lars" <-
function(x, y, K = 10, fraction = seq(from = 0, to = 1, length = 100), 
           trace = FALSE, plot.it = TRUE, se = TRUE, ...)
{
  all.folds <- cv.folds(length(y), K)
  residmat <- matrix(0, length(fraction), K)
  for(i in seq(K)) {
    omit <- all.folds[[i]]
    fit <- lars(x[ - omit,  ], y[ - omit], trace = trace, ...)
    fit <- predict(fit, x[omit,  ,drop=FALSE], mode = "fraction", s = fraction
                   )$fit
    if(length(omit)==1)fit<-matrix(fit,nrow=1)
    residmat[, i] <- apply((y[omit] - fit)^2, 2, mean)
    if(trace)
      cat("\n CV Fold", i, "\n\n")
  }
  cv <- apply(residmat, 1, mean)
  cv.error <- sqrt(apply(residmat, 1, var)/K)
  object<-list(fraction = fraction, cv = cv, cv.error = cv.error)
  if(plot.it) plotCVLars(object,se=se)
  invisible(object)
}

"downdateR" <-
function(R, k = p)
{
	p <- dim(R)[1]
	if(p == 1)
		return(NULL)
	R <- delcol(R, rep(1, p), k)[[1]][ - p,  , drop = FALSE]
	attr(R, "rank") <- p - 1
	R	
}

"error.bars" <-
function(x, upper, lower, width = 0.02, ...)
{
	xlim <- range(x)
	barw <- diff(xlim) * width
	segments(x, upper, x, lower, ...)
	segments(x - barw, upper, x + barw, upper, ...)
	segments(x - barw, lower, x + barw, lower, ...)
	range(upper, lower)
}

"lars" <-
  function(x, y, type = c("lasso", "lar", "forward.stagewise"), trace = FALSE, Gram, 
           eps = .Machine$double.eps,  max.steps, use.Gram = TRUE)
{
### program automatically centers and standardizes predictors.
###
### Original program by Brad Efron September 2001
### Recoded by Trevor Hastie November 2001
### Computational efficiency December 22, 2001
### Bug fixes and singularities February 2003
### Conversion to R April 2003
### Copyright Brad Efron and Trevor Hastie
  call <- match.call()
  type <- match.arg(type)
  TYPE <- switch(type,
                 lasso = "LASSO",
                 lar = "LAR",
                 forward.stagewise = "Forward Stagewise")
  if(trace)
    cat(paste(TYPE, "sequence\n"))
  nm <- dim(x)
  n <- nm[1]
  m <- nm[2]
  im <- inactive <- seq(m)
  one <- rep(1, n)
  vn <- dimnames(x)[[2]]	
  meanx <- drop(one %*% x)/n
  x <- scale(x, meanx, FALSE)  
  normx <- sqrt(drop(one %*% (x^2)))
  nosignal<-normx/sqrt(n) < eps
  if(any(nosignal))
    {
    ignores<-im[nosignal]
    inactive<-im[-ignores]
    normx[nosignal]<-eps*sqrt(n)
    if(trace)
      cat("LARS Step 0 :\t", sum(nosignal), "Variables with Variance < \eps; dropped for good\n")	#
  }
  else ignores <- NULL 
  names(normx) <- NULL
  x <- scale(x, FALSE, normx)	
  if(use.Gram & missing(Gram)) {
    if(m > 500 && n < m)
      cat("There are more than 500 variables and n<m;\nYou may wish to restart and set use.Gram=FALSE\n"
          )
    if(trace)
      cat("Computing X'X .....\n")
    Gram <- t(x) %*% x	
  }
  mu <- mean(y)
  y <- drop(y - mu)
  Cvec <- drop(t(y) %*% x)
  ssy <- sum(y^2)	
  residuals <- y
  if(missing(max.steps))
    max.steps <- 8*min(m, n-1)
  beta <- matrix(0, max.steps + 1, m)	
  Gamrat <- NULL
  arc.length <- NULL
  R2 <- 1
  RSS <- ssy
  first.in <- integer(m)
  active <- NULL
  actions <- as.list(seq(max.steps))	
  drops <- FALSE	
  Sign <- NULL	
  R <- NULL	
  k <- 0
  while((k < max.steps) & (length(active) < min(m - length(ignores),n-1)) )
    {
      action <- NULL
      k <- k + 1
      C <- Cvec[inactive]	
      Cmax <- max(abs(C))	
      if(!any(drops)) {
        new <- abs(C) >= Cmax - eps
        C <- C[!new]	
        new <- inactive[new]	
        for(inew in new) {
          if(use.Gram) {
            R <- updateR(Gram[inew, inew], R, drop(Gram[
                                                        inew, active]), Gram = TRUE,eps=eps)
          }
          else {
            R <- updateR(x[, inew], R, x[, active], Gram
                         = FALSE,eps=eps)
          }
          if(attr(R, "rank") == length(active)) {
            nR <- seq(length(active))
            R <- R[nR, nR, drop = FALSE]
            attr(R, "rank") <- length(active)
            ignores <- c(ignores, inew)
            action <- c(action,  - inew)
            if(trace)
              cat("LARS Step", k, ":\t Variable", inew, 
                  "\tcollinear; dropped for good\n")	#
          }
          else {
            if(first.in[inew] == 0)
              first.in[inew] <- k
            active <- c(active, inew)
            Sign <- c(Sign, sign(Cvec[inew]))
            action <- c(action, inew)
            if(trace)
              cat("LARS Step", k, ":\t Variable", inew, 
                  "\tadded\n")	#
          }
        }
      }
      else action <-  - dropid
      Gi1 <- backsolve(R, backsolvet(R, Sign))	
      dropouts<-NULL
      if(type == "forward.stagewise") {
        directions <- Gi1 * Sign
        if(!all(directions > 0)) {
          if(use.Gram) {
            nnls.object <- nnls.lars(active, Sign, R, 
                                     directions, Gram[active, active], trace = 
                                     trace, use.Gram = TRUE,eps=eps)
          }
          else {
            nnls.object <- nnls.lars(active, Sign, R, 
                                     directions, x[, active], trace = trace, 
                                     use.Gram = FALSE,eps=eps)
          }
          positive <- nnls.object$positive
          dropouts <-active[-positive]
          action <- c(action, -dropouts)
          active <- nnls.object$active
          Sign <- Sign[positive]
          Gi1 <- nnls.object$beta[positive] * Sign
          R <- nnls.object$R
          C <- Cvec[ - c(active, ignores)]
        }
      }
      A <- 1/sqrt(sum(Gi1 * Sign))
      w <- A * Gi1	
      if(!use.Gram) u <- drop(x[, active, drop = FALSE] %*% w)	###
      if(length(active) >=  min(n-1, m - length(ignores) ) ) {
        gamhat <- Cmax/A
      }
      else {
        if(use.Gram) {
          a <- drop(w %*% Gram[active,  - c(active,ignores), drop = FALSE])
        }
        else {
          a <- drop(u %*% x[,  - c(active, ignores), drop=FALSE])
        }
        gam <- c((Cmax - C)/(A - a), (Cmax + C)/(A + a))	
        gamhat <- min(gam[gam > eps], Cmax/A)	
      }
      if(type == "lasso") {
        dropid <- NULL
        b1 <- beta[k, active]	
        z1 <-  - b1/w
        zmin <- min(z1[z1 > eps], gamhat)
        if(zmin < gamhat) {
          gamhat <- zmin
          drops <- z1 == zmin
        }
        else drops <- FALSE
      }
      beta[k + 1,  ] <- beta[k,  ]
      beta[k + 1, active] <- beta[k + 1, active] + gamhat * w
      if(use.Gram) {
        Cvec <- Cvec - gamhat * Gram[, active, drop = FALSE] %*% w
      }
      else {
        residuals <- residuals - gamhat * u
        Cvec <- drop(t(residuals) %*% x)
      }
      Gamrat <- c(Gamrat, gamhat/(Cmax/A))
      arc.length <- c(arc.length, gamhat)	
      if(type == "lasso" && any(drops)) {
        dropid <- seq(drops)[drops]	
        for(id in rev(dropid)) {
          if(trace)
            cat("Lasso Step", k+1, ":\t Variable", active[
                                                        id], "\tdropped\n")
          R <- downdateR(R, id)
        }
        dropid <- active[drops]	
        active <- active[!drops]
        Sign <- Sign[!drops]
      }
      if(!is.null(vn))
        names(action) <- vn[abs(action)]
      actions[[k]] <- action
      inactive <- im[ - c(active, ignores)]
    }
  beta <- beta[seq(k + 1),  ]	
  dimnames(beta) <- list(paste(0:k), vn)       
  if(trace)
    cat("Computing residuals, RSS etc .....\n")
  residuals <- y - x %*% t(beta)
  beta <- scale(beta, FALSE, normx)
  RSS <- apply(residuals^2, 2, sum)
  R2 <- 1 - RSS/RSS[1]
  Cp <- ((n - k - 1) * RSS)/rev(RSS)[1] - n + 2 * seq(k + 1)
  object <- list(call = call, type = TYPE, R2 = R2, RSS = RSS, Cp = Cp, 
                 actions = actions[seq(k)], entry = first.in, Gamrat = Gamrat, 
                 arc.length = arc.length, Gram = if(use.Gram) Gram else NULL, 
                 beta = beta, mu = mu, normx = normx, meanx = meanx)
  class(object) <- "lars"
  object
}

"nnls.lars" <-
  function(active, Sign, R, beta, Gram, eps = 1e-10, trace = FALSE, use.Gram = TRUE)
{
### Modified 05/15/03 to allow for more than one addition to the set
### Lawson and Hanson page 161
### Go back to the first positive coefficent vector; can assume its in order
### Note that X'y is constant for all these guys;
### we assume WOLOG this constant is 1
### We also assume we have come into this because we have a negative coeff  
### If use.Gram is FALSE, then Gram comes in as x
  if(!use.Gram) x <- Gram	# to avoid confusion
  M<-m <- length(active)
  im <- seq(m)
  positive <- im
  zero <- NULL
  while(m>1) {
    zero.old<-c(m,zero)
    R.old <- downdateR(R, m)
    beta0 <- backsolve(R.old, backsolvet(R.old, Sign[ - zero.old]))*Sign[-zero.old]
    beta.old <- c(beta0,rep(0,length(zero.old)))
    if(all(beta0 >0))break
    m <-m-1
    zero<-zero.old
    positive<-im[-zero]
    R<-R.old
    beta<-beta.old
  }
  while(TRUE) {
    while(!all(beta[positive] > 0)) {
      alpha0 <- beta.old/(beta.old - beta)
      alpha <- min(alpha0[positive][(beta <= 0)[positive]])
      beta.old <- beta.old + alpha * (beta - beta.old)
      dropouts<-match(alpha,alpha0[positive],0)
      for(i in rev(dropouts)) R <- downdateR(R, i)
      positive <- positive[ - dropouts]	
      zero <- im[ - positive]
      beta0 <- backsolve(R, backsolvet(R, Sign[positive])) * 
        Sign[positive]
      beta <- beta.old * 0
      beta[positive] <- beta0
    }
    if(use.Gram) {
      w <- 1 - Sign * drop(Gram %*% (Sign * beta))	
    }
    else {
      jw <- x %*% (Sign * beta)
      w <- 1 - Sign * drop(t(jw) %*% x)
    }
    if((length(zero) == 0) || all(w[zero] <= 0))
      break
    add <- order(w)[M]
    if(use.Gram) {
      R <- updateR(Gram[add, add], R, drop(Gram[add, 
                                                positive]), Gram = TRUE,eps=eps)
    }
    else {
      R <- updateR(x[, add], R, x[, positive], Gram = FALSE,eps=eps)
    }
    positive <- c(positive, add)
    zero <- setdiff(zero, add)
    beta0 <- backsolve(R, backsolvet(R, Sign[positive])) * Sign[
                                                        positive]
    beta[positive] <- beta0
  }
  if(trace)
    {
      dropouts<-active[-positive]
      for(i in dropouts){
          cat("NNLS Step:\t Variable", i, "\tdropped\n")
        }
    }
  list(active = active[positive], R = R, beta = beta, positive = positive
       )
}

"plotCVLars" <-
function(cv.lars.object,se=TRUE){
  attach(cv.lars.object)
      plot(fraction, cv, type = "b", ylim = range(cv, cv + cv.error, 
                                     cv - cv.error))
    if(se)
      error.bars(fraction, cv + cv.error, cv - cv.error, 
                 width = 1/length(fraction))
  detach(cv.lars.object)
  
invisible()
}

"plot.lars" <-
  function(x, xvar=c("norm","df","arc.length"), breaks = TRUE, plottype = c("coefficients", "Cp"), 
           omit.zeros = TRUE, eps = 1e-10, ...)
{
  object <- x
  plottype <- match.arg(plottype)
  xvar <- match.arg(xvar)
  coef1 <- object$beta	
  coef1 <- scale(coef1, FALSE, 1/object$normx)
  if(omit.zeros) {
    c1 <- drop(rep(1, nrow(coef1)) %*% abs(coef1))
    nonzeros <- c1 > eps
    cnums <- seq(nonzeros)[nonzeros]
    coef1 <- coef1[, nonzeros]
  }
  else cnums <- seq(ncol(coef1))
  s1<-switch(xvar,
             norm={
               s1 <- apply(abs(coef1), 1, sum)
               s1/max(s1)
             },
             df=seq(length(object$arc.length)+1),
             arc.length=cumsum(c(0,object$arc.length))
             )
  xname<-switch(xvar,
                norm="|beta|/max|beta|",
                df="Df",
                arc.length="Arc Length"
                )
                
  if(plottype == "Cp") {
    Cp <- object$Cp
    plot(s1, Cp, type = "b", xlab=xname,main = object$type, ...)
  }
  else {
      matplot(s1, coef1, xlab = xname, ..., type = "b", 
              pch = "*", ylab = "Standardized Coefficients")
      title(object$type,line=2.5)
      abline(h = 0, lty = 3)
      axis(4, at = coef1[nrow(coef1),  ], label = paste(cnums
                                            ), cex = 0.80000000000000004, adj = 0)
      if(breaks) {
        axis(3, at = s1, labels = paste(seq(s1)-1),cex=.8)
        abline(v = s1)
      }

  }
  invisible()
}


"predict.lars" <-
  function(object, newx, s, type = c("fit", "coefficients"), mode = c("step", 
                                                               "fraction", "norm"), ...)
{
  mode <- match.arg(mode)
  type <- match.arg(type)
  if(missing(newx) & type == "fit") {
    warning("Type=fit with no newx argument; type switched to coefficients"
            )
    type <- "coefficients"
  }
  betas <- object$beta
  sbetas <- scale(betas, FALSE, 1/object$normx)	
  kp <- dim(betas)
  k <- kp[1]
  p <- kp[2]
  steps <- seq(k)
  if(missing(s)) {
    s <- steps
    mode <- "step"
  }
  sbeta <- switch(mode,
                  step = {
                    if(any(s < 0) | any(s > k))
                      stop("Argument s out of range")
                    steps
                  }
                  ,
                  fraction = {
                    if(any(s > 1) | any(s < 0))
                      stop("Argument s out of range")
                    nbeta <- drop(abs(sbetas) %*% rep(1, p))
                    nbeta/nbeta[k]
                  }
                  ,
                  norm = {
                    nbeta <- drop(abs(sbetas) %*% rep(1, p))
                    if(any(s > nbeta[k]) | any(s < 0))
                      stop("Argument s out of range")
                    nbeta
                  }
                  )
  sfrac <- (s - sbeta[1])/(sbeta[k] - sbeta[1])
  sbeta <- (sbeta - sbeta[1])/(sbeta[k] - sbeta[1])
  usbeta<-unique(sbeta)
  useq<-match(usbeta,sbeta)
  sbeta<-sbeta[useq]
  betas<-betas[useq,]
  coord <- approx(sbeta, seq(sbeta), sfrac)$y
  left <- floor(coord)
  right <- ceiling(coord)
  newbetas <- ((sbeta[right] - sfrac) * betas[left,  , drop = FALSE] + (sfrac -
                                                         sbeta[left]) * betas[right,  , drop = FALSE])/(sbeta[right] - sbeta[
                                                                                          left])
  newbetas[left == right,  ] <- betas[left[left == right],  ]
  robject <- switch(type,
                    coefficients = list(s = s, fraction = sfrac, mode = mode, 
                      coefficients = drop(newbetas)),
                    fit = list(s = s, fraction = sfrac, mode = mode, fit = drop(
                                                                       scale(newx, object$meanx, FALSE) %*% t(newbetas)) + object$
                      mu))
  robject
}

"print.lars" <-
function(x, ...)
{
	cat("\nCall:\n")
	dput(x$call)
	cat("R-squared:", format(round(rev(x$R2)[1], 3)), "\n")
	actions <- x$actions
	jactions <- unlist(actions)
	jsteps <- rep(seq(along = actions), sapply(actions, length))
	actmat <- rbind(jsteps, jactions)
	vn <- names(jactions)
	if(is.null(vn))
		vn <- rep("", length(jactions))
	dimnames(actmat) <- list(c("Step", "Var"), vn)
	cat(paste("Sequence of", x$type, "moves:\n"))
	print(actmat[2:1,  ])
	invisible(x)
}

"updateR" <-
  function(xnew, R = NULL, xold, eps = .Machine$double.eps, Gram = FALSE)
{
  xtx <- if(Gram) xnew else sum(xnew^2)
  norm.xnew <- sqrt(xtx)
  if(is.null(R)) {
    R <- matrix(norm.xnew, 1, 1)
    attr(R, "rank") <- 1
    return(R)
  }
  Xtx <- if(Gram) xold else drop(t(xnew) %*% xold)
  r <- backsolvet(R, Xtx)
  rpp <- norm.xnew^2 - sum(r^2)
  rank <- attr(R, "rank")	
  if(rpp <= eps)
    rpp <- eps
  else {
    rpp <- sqrt(rpp)
    rank <- rank + 1
  }
  R <- cbind(rbind(R, 0), c(r, rpp))
  attr(R, "rank") <- rank
  R
}

"backsolvet"<-
function(r, x, k)
{
	if(missing(k))
		k <- nrow(r)
	r <- t(r)[k:1, k:1, drop = F]
	x <- as.matrix(x)[k:1,  , drop = F]
	x <- backsolve(r, x)
	drop(x[k:1,  ])
}


enet<-
function (x, y, lambda, max.steps, normalize = TRUE, intercept = TRUE, 
    trace = FALSE, eps = .Machine$double.eps) 
{
    call <- match.call()
    nm <- dim(x)
    n <- nm[1]
    m <- nm[2]
    im <- seq(m)
    one <- rep(1, n)
    vn <- dimnames(x)[[2]]
    meanx <- drop(one %*% x)/n
    if (intercept == FALSE) {
        meanx <- rep(0, m)
    }
    x <- scale(x, meanx, FALSE)
    normx <- sqrt(drop(one %*% (x^2)))
    if (normalize == FALSE) {
        normx <- rep(1, m)
    }
    if (any(normx < eps * sqrt(n))) 
        stop("Some of the columns of x have zero variance")
    names(normx) <- NULL
    x <- scale(x, FALSE, normx)
    mu <- mean(y)
    if (intercept == FALSE) {
        mu <- 0
    }
    y <- drop(y - mu)
    d1 <- sqrt(lambda)
    d2 <- 1/sqrt(1 + lambda)
    Cvec <- drop(t(y) %*% x) * d2
    ssy <- sum(y^2)
    residuals <- c(y, rep(0, m))
    if (lambda > 0) {
        maxvars <- m
    }
    if (lambda == 0) {
        maxvars <- min(m, n - 1)
    }
    if (missing(max.steps)) {
        max.steps <- 50 * maxvars
    }
    L1norm <- 0
    penalty <- max(abs(Cvec))
    beta <- rep(0, m)
    betactive <- list(NULL)
    first.in <- integer(m)
    active <- NULL
    Actset <- list(NULL)
    df <- 0
    if (lambda != 0) {
        Cp <- ssy
    }
    ignores <- NULL
    actions <- as.list(seq(max.steps))
    drops <- FALSE
    Sign <- NULL
    R <- NULL
    k <- 0
    beta.full <- array(0,dim=c(max.steps,m))
    while ((k < max.steps) & (length(active) < maxvars)) {
        action <- NULL
        k <- k + 1
        if (k == 1) inactive <- im
        if (k != 1) inactive <- im[-c(active, ignores)]
        C <- Cvec[inactive]
        Cmax <- max(abs(C))
        if (any(drops)==F) {
            new <- abs(C) == Cmax
            C <- C[new==F]
            new <- inactive[new]
            for (inew in new) {
                R <- updateRR(x[, inew], R, x[, active], lambda)
                if (attr(R, "rank") == length(active)) {
                  nR <- seq(length(active))
                  R <- R[nR, nR, drop = FALSE]
                  attr(R, "rank") <- length(active)
                  ignores <- c(ignores, inew)
                  action <- c(action, -inew)
                  if (trace) 
                    cat("LARS-EN Step", k, ":\t Variable", inew, 
                      "\tcollinear; dropped for good\n")
                }
                if (attr(R, "rank") != length(active)) {
                  if (first.in[inew] == 0) 
                    first.in[inew] <- k
                    active <- c(active, inew)
                    Sign <- c(Sign, sign(Cvec[inew]))
                    action <- c(action, inew)
                  if (trace) 
                    cat("LARS-EN Step", k, ":\t Variable", inew, 
                      "\tadded\n")
                }
            }
        }
        if (any(drops)==T) action <- -dropid
        Gi1 <- backsolve(R, backsolvet(R, Sign))
        A <- 1/sqrt(sum(Gi1 * Sign))
        w <- A * Gi1
        u1 <- drop(x[, active, drop = FALSE] %*% w * d2)
        u2 <- rep(0, m)
        u2[active] <- d1 * d2 * w
        u <- c(u1, u2)
        if (lambda > 0) {
            maxvars <- m - length(ignores)
        }
        if (lambda == 0) {
            maxvars <- min(m - length(ignores), n - 1)
        }
        if (length(active) >= maxvars) {
            gamhat <- Cmax/A
        }
        if (length(active) < maxvars) {
            a <- (drop(u1 %*% x[, -c(active, ignores)]) + d1 * 
                u2[-c(active, ignores)]) * d2
            gam <- c((Cmax - C)/(A - a), (Cmax + C)/(A + a))
            gamhat <- min(gam[gam > eps], Cmax/A)
            Cdrop <- c(C - gamhat * a, -C + gamhat * a) - (Cmax - 
                gamhat * A)
        }
        dropid <- NULL
        b1 <- beta[active]
        z1 <- -b1/w
        zmin <- min(z1[z1 > eps], gamhat)
        if (zmin < gamhat) {
            gamhat <- zmin
            drops <- z1 == zmin
        }
        if (zmin >= gamhat) drops <- FALSE 
        beta[active] <- beta[active] + gamhat * w

        betactive[[k]] <- beta[active]
        Actset[[k]] <- active
        residuals <- residuals - (gamhat * u)
        Cvec <- (drop(t(residuals[1:n]) %*% x) + d1 * residuals[-(1:n)]) * d2
        L1norm <- c(L1norm, sum(abs(beta[active]))/d2)
        penalty <- c(penalty, penalty[k] - abs(gamhat * A))
        if (any(drops)) {
            dropid <- seq(drops)[drops]
            for (id in rev(dropid)) {
                if (trace) 
                  cat("LARS-EN Step", k, ":\t Variable", active[id], 
                    "\tdropped\n")
                  R <- downdateR(R, id)
            }
            dropid <- active[drops]
            beta[dropid] <- 0
            active <- active[drops==F]
            Sign <- Sign[drops==F]
        }
        if (is.null(vn)==F) 
            names(action) <- vn[abs(action)]
        actions[[k]] <- action
        beta.full[k,] <- beta
      } 
    beta.0 <- 0
    for (jjj in 1:nrow(beta.full)) {
      if (sum(beta.full[jjj,] == 0) == ncol(beta.full)) {
        beta.0 <- beta.0 + 1
      }
      }
    beta.red <- rbind(rep(0,m),beta.full[1:(nrow(beta.full)-beta.0),])
    allset <- Actset[[1]]
    for (i in 2:k) {
        allset <- union(allset, Actset[[i]])
    }
    allset <- sort(allset)
    max.p <- length(allset)
    beta.pure <- matrix(0, k + 1, max.p)
    for (i in 2:(k + 1)) {
        for (j in 1:length(Actset[[i - 1]])) {
            l <- c(1:max.p)[allset == Actset[[i - 1]][j]]
            beta.pure[i, l] <- betactive[[i - 1]][j]
        }
    }
    beta.red <- beta.red/d2
    beta.pure <- beta.pure/d2
    dimnames(beta.red) <- list(paste(0:k), vn)
    dimnames(beta.pure) <- list(paste(0:k), vn[allset])
    k <- dim(beta.pure)[1]
    df <- 1:k
    for (i in 1:k) {
        a <- drop(beta.pure[i, ])
        df[i] <- 1 + length(a[a != 0])
    }
    residuals <- y - x[, allset, drop = FALSE] %*% t(beta.pure)
    beta.red <- scale(beta.red, FALSE, normx)
    beta.pure <- scale(beta.pure, FALSE, normx[allset])
    RSS <- apply(residuals^2, 2, sum)
    R2 <- 1 - RSS/RSS[1]
    Cp <- ((n - m - 1) * RSS)/rev(RSS)[1] - n + 2 * df
    object <- list(call = call, actions = actions[seq(k)], allset = allset, 
                   beta.pure = beta.red,
                   vn = vn, mu = mu,
                   normx = normx,
                   meanx = meanx,
                   lambda = lambda, L1norm = L1norm, 
        penalty = penalty * 2/d2, df = df, Cp = Cp, sigma2 = rev(RSS)[1]/(n - 
            m - 1))
    class(object) <- "enet"
    object
}


predict.enet<-
function (object, newx, sp, type = c("fit", "coefficients"), mode = c("step", 
    "fraction", "norm", "penalty"), naive = FALSE, ...) 
{
    mode <- match.arg(mode)
    type <- match.arg(type)
    if (missing(newx) & type == "fit") {
        warning("Type=fit with no newx argument; type switched to coefficients")
        type <- "coefficients"
    }
    betas <- object$beta.pure
    if (naive) {
        lambda <- object$lambda
        betas <- betas/(1 + lambda)
    }
    allset <- object$allset
    sbetas <- scale(betas, FALSE, 1/object$normx)
    kp <- dim(betas)
    k <- kp[1]
    p <- kp[2]
    steps <- seq(k)
    if (missing(sp)) {
        sp <- steps
        mode <- "step"
    }
    sbeta <- switch(mode, step = {
        if (any(sp < 0) | any(sp > k)) 
            stop("Argument sp out of range")
        steps
    }, fraction = {
        if (any(sp > 1) | any(sp < 0)) 
            stop("Argument sp out of range")
        nbeta <- drop(abs(sbetas) %*% rep(1, p))
        nbeta/nbeta[k]
    }, norm = {
        nbeta <- drop(abs(sbetas) %*% rep(1, p))
        if (any(sp > nbeta[k]) | any(sp < 0)) 
            stop("Argument sp out of range")
        nbeta
    }, penalty = {
        pen <- object$penalty
        if (any(sp > pen[1]) | any(sp < 0)) 
            stop("Argument sp out of range")
        pen
    })
    sfrac <- (sp - sbeta[1])/(sbeta[k] - sbeta[1])
    sbeta <- (sbeta - sbeta[1])/(sbeta[k] - sbeta[1])
    usbeta <- unique(sbeta)
    useq <- match(usbeta, sbeta)
    sbeta <- sbeta[useq]
    betas <- betas[useq, ]
    coord <- approx(sbeta, seq(sbeta), sfrac)$y
    left <- floor(coord)
    right <- ceiling(coord)
    newbetas <- ((sbeta[right] - sfrac) * betas[left, , drop = FALSE] + 
        (sfrac - sbeta[left]) * betas[right, , drop = FALSE])/(sbeta[right] - 
        sbeta[left])
    newbetas[left == right, ] <- betas[left[left == right], ]
    robject <- switch(type, coefficients = list(sp = sp, fraction = sfrac, 
        mode = mode, coefficients = drop(newbetas)), fit = list(sp = sp, 
        fraction = sfrac, mode = mode, fit = drop(scale(newx[, 
            allset], object$meanx, FALSE) %*% t(newbetas)) + 
            object$mu))
    robject
}

plot.enet<-
function (x, xvar=c("fraction","penalty","L1norm","step"),use.color = FALSE, ...) 
{
    object <- x
    xvar <- match.arg(xvar)
    vn <- object$vn
    allset <- object$allset
    vn <- vn[allset]
    coef1 <- object$beta
    coef1 <- scale(coef1, FALSE, 1/object$normx)
    cnums <- seq(ncol(coef1))
    m <- nrow(coef1)
    p <- ncol(coef1)
    s1 <- switch(xvar, fraction = {
        s1 <- object$L1norm
        s1 <- s1/max(s1)
    }, penalty = {
        s1 <- object$penalty
    }, L1norm = {
        s1 <- object$L1norm
    }, step = {
        s1 <- 1:m
    })
    xname <- switch(xvar, fraction = "|beta|/max|beta|", penalty = "lambda (Lasso)", L1norm = "L1norm", step = "Step")
            low <- min(coef1) - 0.01 * abs(min(coef1))
            up <- max(coef1) + 0.01 * abs(max(coef1))
            ylimit <- c(low, up)
        plot(s1, s1, xlab = xname, ylab = "Standardized Coefficients",
             ylim = ylimit, type = "n", ...)
        for (i in 1:p) {
            if (use.color) {
                lines(s1, coef1[, i], col = i, lty = 1)
            }
            else {
                lines(s1, coef1[, i], lty = 1)
            }
#
            if (is.null(vn)==F) {
             axis(4, at = coef1[nrow(coef1), ], label = vn, cex = 0.8, adj = 0)
            }
          }
        abline(h = 0, lty = 3)

    invisible()
}

print.enet<-      
function(x, ...)   
{ 
        cat("\nCall:\n")
        dput(x$call)
        if(x$lambda==0){
           cat("Cp statistics of the Lasso fit", "\n")
           cat("Cp:", format(round(x$Cp, 3)), "\n")
           cat("DF:", format(round(x$df,3)), "\n")
        }
                                                         
        actions <- x$actions                                                              
        jactions <- unlist(actions)
        jsteps <- rep(seq(along = actions), sapply(actions, length))
        actmat <- rbind(jsteps, jactions)
        vn <- names(jactions)
        if(is.null(vn))
                vn <- rep("", length(jactions))                        
        dimnames(actmat) <- list(c("Step", "Var"), vn)
        cat(paste("Sequence of", x$type, "moves:\n"))
        print(actmat[2:1,  ])
        invisible(x)
}

cv.enet<-
function(x, y, K = 10, lambda, s, mode, 
           trace = FALSE, plot.it = TRUE, se = TRUE, ...)
{
  all.folds <- cv.folds(length(y), K)
  residmat <- matrix(0, length(s), K)
  for(i in seq(K)) {
    omit <- all.folds[[i]]

    fit <- enet(x[ - omit,  ], y[ - omit], lambda=lambda, ...)
    fit <- predict(fit, x[omit,  ,drop=FALSE], s=s, mode = mode)$fit
    if(length(omit)==1){fit<-matrix(fit,nrow=1)}
    residmat[, i] <- apply((y[omit] - fit)^2, 2, mean)
    if(trace)
      cat("\n CV Fold", i, "\n\n")
  }
  cv <- apply(residmat, 1, mean)
  cv.error <- sqrt(apply(residmat, 1, var)/K)
  object<-list(s = s, cv = cv, cv.error = cv.error)
  if(plot.it) {
     plot(s, cv, type = "b", xlab=mode, ylim = range(cv, cv + cv.error, cv - cv.error))
     if (se) 
        error.bars(s, cv + cv.error, cv - cv.error, width = 1/length(s))
  }
  invisible(object)
}


updateRR<-
function(xnew, R = NULL, xold, lambda,eps = .Machine$double.eps)
{
    xtx <- (sum(xnew^2)+lambda)/(1+lambda)
    norm.xnew <- sqrt(xtx)
    if(is.null(R)) {
        R <- matrix(norm.xnew, 1, 1)
        attr(R, "rank") <- 1
        return(R)
    }
    Xtx <- drop(t(xnew) %*% xold)/(1+lambda)
    r <- backsolvet(R, Xtx)
    rpp <- norm.xnew^2 - sum(r^2)
    rank <- attr(R, "rank") 
    if(rpp <= eps)
        rpp <- eps
    else {
        rpp <- sqrt(rpp)
        rank <- rank + 1
    }
    R <- cbind(rbind(R, 0), c(r, rpp))
    attr(R, "rank") <- rank
    R
}


spca<-
function(x,K,para,type=c("predictor","Gram"),sparse=c("penalty","varnum"),use.corr=FALSE, 
         lambda,max.iter=200,trace=FALSE,eps.conv=1e-3)
{
      call <- match.call()
      type <- match.arg(type)
      sparse <- match.arg(sparse)
      vn <- dimnames(x)[[2]]
      x<-switch(type,
                predictor = {
                n<-dim(x)[1]
                p<-dim(x)[2]
                if (n/p>=100){
    cat("You may wish to restart and use a more efficient way \n")
    cat("let the argument x be the sample covariance/correlation matrix and set type=Gram \n")
    }
                 x<-scale(x,center=TRUE,scale=use.corr)
                      },
                Gram = {x<-rootmatrix(x)}
                )
      
      svdobj<-svd(x)
      v<-svdobj$v
      totalvariance<-sum((svdobj$d)^2)
      alpha<-as.matrix(v[,1:K,drop=FALSE])      
      beta<-alpha      
      for ( i in 1:K) {
         y<-drop(x%*%alpha[,i])
         beta[,i]<-solvebeta(x,y,paras=c(lambda,para[i]),sparse=sparse)
       }
      xtx<-t(x)%*%x
      temp<-beta
      normtemp<-sqrt(apply(temp^2,2,sum))
      normtemp[normtemp==0]<-1
      temp<-t(t(temp)/normtemp)
      k<-0
      diff<-1
      while((k<max.iter) & (diff>eps.conv)){
         k<-k+1
         alpha<-xtx%*%beta
         z<-svd(alpha)
         alpha<-(z$u)%*%t(z$v)
         for ( i in 1:K) {
            y<-drop(x%*%alpha[,i])
            beta[,i]<-solvebeta(x,y,paras=c(lambda,para[i]),sparse=sparse)       
         }
         normbeta<-sqrt(apply(beta^2,2,sum))
         normbeta[normbeta==0]<-1
         beta2<-t(t(beta)/normbeta)
         diff<-max(abs(beta2-temp))
         temp<-beta2
           if(trace){
              if (k%%10==0){
                  cat("iterations",k,fill=TRUE)
                 }
            }
         }
      normbeta<-sqrt(apply(beta^2,2,sum))
      normbeta[normbeta==0]<-1
      beta<-t(t(beta)/normbeta)
      dimnames(beta)<-list(vn,paste("PC",1:K,sep=""))
      u<-x%*%beta
      R<-qr.R(qr(u))
      pev<-diag(R^2)/totalvariance
      obj<-list(call = call, type=type, K=K,loadings=beta,pev=pev,var.all=totalvariance, vn=vn,para=para,lambda=lambda)
      class(obj) <- "spca"
      obj  
}

solvebeta<-function(x, y, paras, max.steps, sparse=c("penalty","varnum"), eps = .Machine$double.eps)
{
       sparse <- match.arg(sparse)
       if (missing(sparse)) sparse <- "penalty"
    nm <- dim(x)
    n <- nm[1]
    m <- nm[2]
    im <- seq(m)
    one <- rep(1, n)
    vn <- dimnames(x)[[2]]
        lambda<-paras[1]
        if(lambda>0){
       maxvars <- m
        }
        if (lambda==0) {
           maxvars <- min(m,n-1)
           if (m==n){
             maxvars<-m
           }
        }
    d1 <- sqrt(lambda)
    d2 <- 1/sqrt(1 + lambda)
    Cvec <- drop(t(y) %*% x) * d2
        ssy <- sum(y^2)
    residuals <- c(y, rep(0, m))
        if(missing(max.steps)) {max.steps <- 50 * maxvars}
        penalty<-max(abs(Cvec))
        if (sparse=="penalty" && penalty*2/d2<=paras[2])
          { 
           beta<-rep(0,m)
          }
        else {
               beta <- rep(0, m)
               first.in <- integer(m)
               active <- NULL
               ignores <- NULL
               actions <- as.list(seq(max.steps))
               drops <- FALSE
               Sign <- NULL
               R <- NULL
           k <- 0
           while((k < max.steps) & (length(active) < maxvars - length(ignores))) 
        {
         action <- NULL
         k <- k + 1
             inactive <- if(k == 1) im else im[ - c(active, ignores)]
         C <- Cvec[inactive]
         Cmax <- max(abs(C))
         if(any(drops)==F) {
            new <- abs(C) == Cmax 
            C <- C[new==F]
            new <- inactive[new]       
            for(inew in new) {
                        R <- updateRR(x[, inew], R, x[, active], lambda) 
                               if(attr(R, "rank") == length(active)) {
                    nR <- seq(length(active))
                    R <- R[nR, nR, drop = FALSE]
                    attr(R, "rank") <- length(active)
                    ignores <- c(ignores, inew)
                    action <- c(action,  - inew)
                }
                else {
                    if(first.in[inew] == 0)
                        first.in[inew] <- k
                    active <- c(active, inew)
                    Sign <- c(Sign, sign(Cvec[inew]))
                    action <- c(action, inew)
                }
            }
        }
        else action <-  - dropid
                Gi1 <- backsolve(R, backsolvet(R, Sign))
                A <- 1/sqrt(sum(Gi1 * Sign))
                w <- A * Gi1
                u1<-drop(x[,active,drop=FALSE]%*%w*d2)  
                u2<-rep(0,m)
                u2[active]<-d1*d2*w
                u<-c(u1,u2)
                if(lambda>0){
                maxvars <- m-length(ignores)
                           }
                if (lambda==0){
                    maxvars <- min(m-length(ignores),n-1)
                           }
            if(length(active) == maxvars - length(ignores)) {
            gamhat <- Cmax/A
        }
        else {
            a <- (drop(u1 %*% x[,  - c(active, ignores)]) + d1 *
                u2[ - c(active, ignores)]) * d2
                gam <- c((Cmax - C)/(A - a), (Cmax + C)/(A + a))
                gamhat <- min(gam[gam > eps], Cmax/A)                        
            Cdrop <- c(C - gamhat * a,  - C + gamhat * a) - (Cmax -
                gamhat * A)
        }
        dropid <- NULL
        b1 <- beta[active]
        z1 <-  - b1/w
        zmin <- min(z1[z1 > eps], gamhat)
        if(zmin < gamhat) {
            gamhat <- zmin
            drops <- z1 == zmin
        }
               else drops <- FALSE
               beta2<-beta          
               beta[active] <- beta[active] + gamhat * w
               residuals <- residuals - (gamhat*u)
               Cvec <- (drop(t(residuals[1:n]) %*% x) + d1 * residuals[ - (1:n)]) * d2
               penalty <- c(penalty,penalty[k]-abs(gamhat*A))
               if(sparse=="penalty" && rev(penalty)[1]*2/d2<=paras[2]){
                   s1<-rev(penalty)[1]*2/d2
                   s2<-rev(penalty)[2]*2/d2
                   beta<-(s2-paras[2])/(s2-s1)*beta+(paras[2]-s1)/(s2-s1)*beta2
                   beta<-beta*d2
                   break
               }
        if(any(drops)) {
            dropid <- seq(drops)[drops]
            for(id in rev(dropid)) {
                R <- downdateR(R, id)
                }
            dropid <- active[drops]
                        beta[dropid] <- 0
            active <- active[drops==F]
            Sign <- Sign[drops==F]
                      }
               if(sparse=="varnum" && length(active)>=paras[2]){
                 break
               }
           if(is.null(vn)==F)
            names(action) <- vn[abs(action)]
                    actions[[k]] <- action 
    }
             }
     
        return (beta)
}

rootmatrix<-function(x){
     x.eigen<-eigen(x)
     d<-x.eigen$values
     d<-(d+abs(d))/2
     v<-x.eigen$vectors
     return (v%*%diag(sqrt(d))%*%t(v))
} 


print.spca<-function(x, ...){
     cat("\nCall:\n")
     dput(x$call)
     K<-x$K
     cat("\n")
     cat(paste(K,"sparse PCs",sep=" "), "\n")
     cat("Pct. of exp. var. :", format(round(x$pev, 3)*100), "\n")
     v<-x$loadings
     k<-1:K
     for (j in 1:K){
        k[j]<-sum(v[,j]!=0)
     }
     cat("Num. of non-zero loadings : ",k,"\n")
     cat("Sparse loadings \n")
     print(round(x$loadings,3))
     type<-x$type
     if (type=="penalty"){
       cat("lambda_1:", format(round(x$para, 3)), "\n")
     }
}


arrayspc<-
function(x,K=1,para,use.corr=FALSE, max.iter=100,trace=FALSE,eps=1e-3)
{     call <- match.call()
      x<-scale(x,center=TRUE,scale=use.corr)
      svdobj<-svd(x)
      v<-svdobj$v
      totalvariance<-sum((svdobj$d)^2)      
      alpha<-as.matrix(v[,1:K,drop=FALSE])      
      beta<-alpha      
      for ( i in 1:K) {
         y<-drop(x%*%alpha[,i])
         beta[,i]<-soft(drop(t(x)%*%y),para=para[i])
         }
      temp<-beta
      normtemp<-sqrt(apply(temp^2,2,sum))
      normtemp[normtemp==0]<-1
      temp<-t(t(temp)/normtemp)
      k<-0
      diff<-1
      while((k<max.iter) & (diff>eps)){
         k<-k+1
         alpha<-x%*%beta
         alpha<-t(x)%*%alpha
         z<-svd(alpha)
         alpha<-(z$u)%*%t(z$v)
         for ( i in 1:K) {
           y<-drop(x%*%alpha[,i])
           beta[,i]<-soft(drop(t(x)%*%y),para=para[i])
         }     
         normbeta<-sqrt(apply(beta^2,2,sum))
         normbeta[normbeta==0]<-1
         beta2<-t(t(beta)/normbeta)
         diff<-max(abs(beta2-temp))
         temp<-beta2
          if(trace){
              if (k%%10==0){
                  cat("iterations",k,fill=TRUE)
                 }
            }
      } 
      normbeta<-sqrt(apply(beta^2,2,sum))
      normbeta[normbeta==0]<-1
      beta<-t(t(beta)/normbeta)
      u<-x%*%beta
      R<-qr.R(qr(u))
      pev<-diag(R^2)/totalvariance
      obj<-list(call = call, K=K,loadings=beta,pev=pev,var.all=totalvariance,para=para)
      class(obj) <- "arrayspc"
      obj 
}

soft<-function(a,para){
  b<-sort(abs(a))
  b<-abs(a)-para
  b<-(b+abs(b))/2
  b<-sign(a)*b
  b
}

print.arrayspc<-function(x, ...){
     cat("\nCall:\n")
     dput(x$call)
     K<-x$K
     cat("\n")
     cat(paste(K,"sparse PCs",sep=" "), "\n")
     cat("Pct. of exp. var. :", format(round(x$pev, 3)*100), "\n")
     v<-x$loadings
     k<-1:K
     for (j in 1:K){
        k[j]<-sum(v[,j]!=0)
     }
     cat("Num. of non-zero loadings : ",k,"\n")
}


ENcox <- function(x, time, surv.st, lambda, ss, normalize = FALSE, intercept = FALSE,
    trace = FALSE, eps = .Machine$double.eps, mode, max.steps) {

    ss <- ss + 2
    if(mode=="step") {
      max.steps <- max(ss)
    }
    nm <- dim(x)
    n <- nm[1]
    m <- nm[2]
    if (lambda > 0) {
        maxvars <- m
    }
    if (lambda == 0) {
        maxvars <- min(m, n - 1)
    }
    res1 <- matrix(0, m, (max.steps + 1))
    nvara <- 1
    ttt <- 2
    ii <- 1
    jjj <- 2
    ts <- length(lambda)
    res <- matrix(0, m, ts)
    eps <- .Machine$double.eps
    eps1 <- 1
    iii <- 2
    s.tot <- 0
    nvara1 <- 0
    while((ttt < max.steps) & (eps1 > eps) & (nvara <= maxvars) & (s.tot < 3)) {
        fft <- survENcox(x, time, surv.st, lambda = lambda, max.steps, normalize, intercept,
    trace = FALSE, eps = .Machine$double.eps, beta=res1[, ii], ttt)
        res1[, ii + 1] <- fft$beta
        nvara <- length(res1[abs(res1[, ii + 1]) >= 1e-005, ii + 1])
        if(fft$step + 1 == ttt || fft$step == 1) {
            ttt <- fft$step + 4 
        } else { ttt <- fft$step + 1 }
        ii <- ii + 1
        eps1 <- sum(abs(res1[,iii] - res1[,(iii-1)]))
        iii <- iii + 1
        s.tot <- sum(abs(res1[, ii]))
        cat("s=", sum(abs(res1[, ii])), "\n")
    }
    res1.b <- 1
    jjj <- 2
    for (jj in 1:ncol(res1)) {
      if((all(res1[,jj]==0))==F) {
        res1.b[jjj] <- jj
        jjj <- jjj + 1
      }
    }
    res.red <- res1[,res1.b]
    return(res.red)
}
 
survENcox <-
function(x, time, surv.st, lambda, max.steps, normalize, intercept,
    trace = FALSE, eps = .Machine$double.eps, beta, ttt)
{
    
    x <- as.matrix(x)
    nm <- dim(x)
    n <- nm[1]
    m <- nm[2]
    one <- rep(1, n)
    meanx <- drop(one %*% x)/n
    if (intercept==F) {
    meanx <- rep(0, m)
    }
    x <- scale(x, meanx, FALSE)
    normx <- sqrt(drop(one %*% (x^2)))
    if (normalize==F) {
    normx <- rep(1, m)
    }
    x <- scale(x, FALSE, normx)
    nosignal <- normx/sqrt(n) < 10^{-10}
    ignores <- NULL
    names(normx) <- NULL
    r <- rank(time)
    beta <- as.matrix(beta)
    ita <- x %*% beta
    epita <- exp(ita)
    d <- rep(0, n)
    dono <- rep(0, n)
    for(i in 1:n) {
        d[i] <- sum(surv.st[r == r[i]])
        dono[i] <- sum(epita[r >= r[i]])
    }
    risk <- d/dono
    risk1 <- d/dono^{2}
    culrisk1 <- culrisk <- rep(0, n)
    for(i in 1:n) {
        culrisk[i] <- sum(unique(risk[r <= r[i]]))
        culrisk1[i] <- sum(unique(risk1[r <= r[i]]))
    }
    mu <- c(surv.st) - c(epita) * c(culrisk)
    A <- matrix(0, n, n)
    for(i in 1:n) {
        A[i, i] <-  - epita[i] * culrisk[i] + epita[i]^{2} * culrisk1[i]
    }
    for(i in 2:n) {
        for(j in 1:i - 1) {
            A[i, j] <- epita[i] * epita[j] * sum(unique(risk1[r <= r[i] & r <= r[j]]))
            A[j, i] <- A[i, j]
        }
    }
    paA <- chol( - A)
    mu <- as.matrix(mu)
    y <- (paA) %*% (ita + ginverse( - A) %*% mu)
    fit.coxen <- enet(paA %*% x, y, lambda, max.steps, normalize=T, intercept=T, trace, eps)
    if (ttt <= nrow(fit.coxen$beta)) {
      beta1.coxen <- predict.enet(fit.coxen, sp = ttt, type = "coefficients", mode = "step")$coefficients
      beta1 <- t(scale(t(as.matrix(beta1.coxen)), FALSE, normx))
    }
    if (ttt > nrow(fit.coxen$beta)) {
      beta1 <- beta
    }
    cat("diff=", sum(abs(beta - beta1)), "\n")
    ttt1 <- ttt
    counter <- 0
    while((sum(abs(beta - beta1)) >= 1e-005 * (ttt - 1)) & (counter < 20) & (any(is.na(A))==F)) {
        counter <- counter + 1
        beta <- beta1
        ita <- x %*% beta
        epita <- exp(ita)
        d <- rep(0, n)
        dono <- rep(0, n)
        for(i in 1:n) {
            d[i] <- sum(surv.st[r == r[i]])
            dono[i] <- sum(epita[r >= r[i]])
        }
        risk <- d/dono
        risk1 <- d/dono^{2}
        culrisk1 <- culrisk <- rep(0, n)
        for(i in 1:n) {
            culrisk[i] <- sum(unique(risk[r <= r[i]]))
            culrisk1[i] <- sum(unique(risk1[r <= r[i]]))
        }
        mu <- c(surv.st) - c(epita) * c(culrisk)
        A <- matrix(0, n, n)
        for(i in 1:n) {
            A[i, i] <-  - epita[i] * culrisk[i] + epita[i]^{2} * culrisk1[i]
        }
        for(i in 2:n) {
            for(j in 1:i - 1) {
                A[i, j] <- epita[i] * epita[j] * sum(unique(risk1[r <= r[i] & r <= r[j]]))
                A[j, i] <- A[i, j]
            }
        }
        if (any(is.na(A))==T) break
        paA <- chol( - A)
        mu <- as.matrix(mu)
        y <- paA %*% (ita + ginverse( - A) %*% mu)
        fit.coxen <- enet(paA %*% x, y, lambda, max.steps, normalize=T, intercept=T, trace, eps)
        di <- dim(fit.coxen$beta)
        if (di[2]<ncol(x)) break
        backtt <- rep(100, di[1])
        normx1 <- rep(1,ncol(fit.coxen$beta))
        trasbeta <- scale(fit.coxen$beta, FALSE, normx1)
        active.b <- beta == 0
        trasbeta.b <- NA
        jjj <- 1
        for (jj in 1:nrow(trasbeta)) {
          if(all((trasbeta[jj,]==0) == active.b)) {
            trasbeta.b[jjj] <- jj
            jjj <- jjj + 1
          }
        }
        if ((length(trasbeta.b)==1) & (is.na(trasbeta.b)==F)) {
          ttt1 <- trasbeta.b
          beta1 <- (trasbeta[ttt1,  ])
          cat("diff=", sum(abs(beta - beta1)), "\n")

        }
        if (is.na(trasbeta.b)) {
          beta1 <- beta
          cat("diff=", sum(abs(beta - beta1)), "\n")
        }
        if (length(trasbeta.b) > 1) {
          beta.temp <- trasbeta[trasbeta.b,]
          for(i in 1:nrow(beta.temp)) {
            backtt[i] <- sum(abs(beta.temp[i,  ] - beta))
          }
          ttt1 <- (1:nrow(beta.temp))[backtt == min(backtt)]
          beta1 <- (trasbeta[ttt1,  ])
          cat("diff=", sum(abs(beta - beta1)), "\n")
        }
    }
    list(beta = beta1, step = ttt1)
}

