# requires matrixStats package
require(matrixStats)

## function maxlinear: same as A %*% Z except replaces plus
## operation by max
maxlinear <- function(A,Z){
  d <- nrow(A)
  p <- ncol(A)
  if(class(Z)=="numeric"){
    Z <- matrix(Z,length(Z),1)
  }
  if(p != nrow(Z)) stop("non-conformable arguments")
  n <- ncol(Z)
  X <- matrix(rowMaxs(A[rep(1:d,n),]*t(Z[,rep(1:n,each = d)])),d,n)
  return(X)
}

## function frechetCRPS calculates the CRPS of a 1-Frechet 
## distribution with scale 'sigma' given observations 'obs'
frechetCRPS <- function(sigma, obs){
  q <- 1/obs
  C1 <- 1/(2*sigma + 1)
  C2 <- -2*(1 - exp(-(sigma + 1)*q))/(sigma + 1)
  C3 <- 1 - exp(-q)
  crps <- C1 + C2 + C3
  return(crps)
}

## function maxlinearCRPS: given the coefficient maxtrix 'A'
## of a max-linear model, observations 'x' and atoms 'U' of the
## CRPS weighting measure.  Returns the CRPS score.
## optionally one can specify 'U' as the number of atoms and
## 'seed' then the weigting measure will be randomly
## generated from the ncol(x) - 1 dimensional simplex with
## number of atoms 'U'.
maxlinearCRPS <- function(A, x, U = 100, seed = 1){
  d <- ncol(x)
  if(nrow(A) != d) stop("A and x non-conformable arguments")
  if(class(U) == "numeric"){
    if(seed >= 0) set.seed(seed)
    U <- t(apply(matrix(runif((d-1)*U),U,d-1),1,function(z){
      z <- diff(c(0,sort(z)))
      return(c(z,1-sum(z)))
    }))
  }
  if(ncol(U) != d) stop("U and x non-conformable arguments")
  n <- nrow(x)
  m <- nrow(U)
  V <- matrix(rowSums(maxlinear(1/U,A)),n,m,byrow = TRUE)
  M <- maxlinear(x, t(1/U))
  crps <- frechetCRPS(V,M)
  return(sum(crps))
}


## function fit.simple.maxlinear.  Fits a simple max-linear model given
## data 'x'. The user must supply the number of factors 'p' in the model.
## currently the only method implemented is the CRPS method.  Optionally
## one can supply the atoms of the weighting measure as 'U'.
fit.simple.maxlinear <- function(x, p = 2, U = 100, seed = 1, start = 0, method = "CRPS",
                                 optim.method = "Nelder-Mead", optim.control = list()){
  d <- ncol(x)
  if(class(U) == "numeric"){
    if(seed >= 0) set.seed(seed)
    U <- t(apply(matrix(runif((d-1)*U),U,d-1),1,function(z){
      z <- diff(c(0,sort(z)))
      return(c(z,1-sum(z)))
    }))
  }
  crpsOptFun <- function(aa,pp,xx,dd,UU){
    A <- matrix(aa,dd,pp-1)
    A <- cbind(A,1 - rowSums(A))
    return(maxlinearCRPS(A,xx,UU))
  }
  ui <- rbind(diag(d*(p-1)),-diag(d)[,rep(1:d,p-1)])
  ci <- c(rep(0,d*(p-1)),rep(-1, d))
  if(start >= 0) set.seed(start)
  A.start <- matrix(runif(d*p),d,p)
  A.start <- A.start/matrix(rep(rowSums(A.start),p),d,p)
  a.start <- c(A.start[,-p])
  copt <- constrOptim(theta = a.start, f = crpsOptFun, grad = NULL, 
                      ui = ui, ci = ci,
                      pp = p, xx = x, dd = d, UU = U)
  A.opt <- matrix(copt$par,d,p-1)
  A.opt <- cbind(A.opt, 1- rowSums(A.opt))
  return(list(A = A.opt, optim = copt))
}

## Examples

n <- 100 # number observations
d <- 4   # model dimension
p <- 3   # number of factors in max-linear model
m <- 1000 # number of atoms in CRPS weighting measure

set.seed(12)
A <- matrix(runif(d*p),d,p)
A <-  diag(1/rowSums(A)) %*% A
Z <- matrix(1/rexp(p*n),p,n)
x <- t(maxlinear(A,Z))

mlfit <- fit.simple.maxlinear(x = x, p = p, U = m, optim.control = list(maxit = 500))

maxlinearCRPS(mlfit$A,x)
maxlinearCRPS(A,x)

