shabbychef / madness

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

Reshape with array or matrix #16

Open ZTaylor205 opened 6 years ago

ZTaylor205 commented 6 years ago

Cbind and rbind appear to work, but not more complicated reshaping. In this example, I have a vector 1,2,3,4,5 and I would like to create a 5x5x3 array such that everything in row i has value i.

> x = c(1,2,3,4,5)
> xmad = madness(x)
Warning message:
In madness(x) : no dimension given, turning val into a column
> #what I want to use in a function:
> xarray = array(x,dim = c(I,I,K))
> xarray
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5

, , 3

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3
[4,]    4    4    4    4    4
[5,]    5    5    5    5    5

> xarray = array(xmad,dim = c(I,I,K))
Error in as.vector(data) : 
  no method for coercing this S4 class to a vector

> #something simpler
> xmatrix = matrix(xmad,nrow = 2)
Error in as.vector(data) : 
  no method for coercing this S4 class to a vector

> #out of curiosity
> as.vector(xmad)
Error in as.vector(xmad) : 
  no method for coercing this S4 class to a vector

#in the matrix case I could use cbind or rbind, but that won't help with the general case
> cbind(xmad,xmad)
class: madness 
        d cbind(x,x)
 calc: -------------- 
             d x
  val: 1 1 ...
 dvdx: 1 0 0 0 0 ...
 varx:  ...
> rbind(xmad,xmad)
class: madness 
        d rbind(x,x)
 calc: -------------- 
             d x
  val: 1 ...
 dvdx: 1 0 0 0 0 ...
 varx:  ...

Edit: I thought I might be able to replicate and then fill a matrix, but it turns out:

> rep(xmad,2)
Error in rep(xmad, 2) : attempt to replicate an object of type 'S4'
ZTaylor205 commented 6 years ago

It turns out that the madness-specific commands blockrep() and repto() will accomplish these functions, when combined with aperm(). I'm using them as a workaround at the moment.

ZTaylor205 commented 6 years ago

Unfortunately, I've discovered a problem with the workaround, along with a corresponding workaround. I will post two additional issues.

shabbychef commented 6 years ago

I think in your case you just need to use repto?

x < c(1,2,3,4,5)
xmad <- madness(x)

I <- 5
K <- 3
xarray = array(x,dim = c(I,I,K))

ymad <- repto(xmad,c(I,I,K))
# show that they are the same:
ymad@val - array(x,dim=c(I,I,K))

I am not sure aperm is needed for this?