shabbychef / madness

Multivariate Automatic Differentiation R package
GNU Lesser General Public License v3.0
31 stars 0 forks source link

aperm() causes error in toString() method #19

Closed ZTaylor205 closed 6 years ago

ZTaylor205 commented 6 years ago

When you aperm() a madness object and then try to print it, you get an error. However, it still creates a madness object with a proper value and (what seems like) a proper derivative.

> test = madness(matrix(c(1,2,3,4),nrow = 2))
> aperm(test,c(2,1))
class: madness 
Error in rep(achr, ceiling(alen)) : invalid 'times' argument
> test2 = aperm(test,c(2,1))
> test2
class: madness 
Error in rep(achr, ceiling(alen)) : invalid 'times' argument
> val(test2)
     [,1] [,2]
[1,]    1    2
[2,]    3    4
> dvdx(test2)
     [,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    0    0    1    0
[3,]    0    1    0    0
[4,]    0    0    0    1
shabbychef commented 6 years ago

This is the easiest one to fix. It looks like I did not properly turn the perm argument into a string. The following fix is in place as of 9503b2b:

.int2string <- function(xi) {
    paste0('c(',paste0(xi,collapse=','),')')
}

#' @rdname reshapes
#' @export 
#' @method aperm madness
#' @inheritParams base::aperm
#' @aliases aperm
aperm.madness <- function(a, perm=NULL, resize=TRUE, ...) {
    xtag <- a@xtag
    val <- aperm(a@val,perm=perm,resize=resize)
    oldids <- array(1:length(a@val),dim=dim(a@val))
    prmids <- aperm(oldids,perm=perm,resize=resize)
    dvdx <- a@dvdx[as.numeric(prmids),,drop=FALSE]
    vtag <- paste0('aperm(',a@vtag,', ',.int2string(perm),')')
    varx <- a@varx

    new("madness", val=val, dvdx=dvdx, vtag=vtag, xtag=xtag, varx=varx)
}

test = madness(matrix(c(1,2,3,4),nrow = 2))
test2 = aperm(test,c(2,1))
test2