rparticlesocean

Applying particles package in R to ocean velocity


I am trying to apply an example from R "particles" package to ocean velocity data (kinetic energy). Example data is as follows:

ke1<-c(0.394610137,0.203202814,0.12364389,0.069784589,0.048573241,0.043057494,0.03826768,0.034176417,0.032129359,0.03122394
)
ke2<-c(0.094138406,0.169889584,0.086677499,0.070593894,0.049883354,0.042339094,0.038856283,0.037967827,0.036562074,0.037240546
)
ke3<-c(0.054365572,0.096576959,0.10304369,0.061354585,0.053624138,0.042112421,0.040727202,0.039870735,0.042947762,0.043291345
)
ke4<-c(0.030527802,0.075901449,0.08003746,0.068991989,0.048506431,0.044592839,0.04071483,0.042985249,0.042403288,0.044974718
)
ke5<-c(0.021374704,0.047852065,0.070487022,0.059393879,0.051129311,0.042866949,0.040003292,0.040003441,0.044107087,0.04578279
)
ke<-cbind(ke1,ke2,ke3,ke4,ke5)

library(particles)
library(tidygraph)

kee<-as.numeric(unlist(ke))

sim <- create_empty(1000) %>% 
  simulate(alpha_decay = 0, setup = aquarium_genesis(vel_max = 1)) %>%
  wield(reset_force, xvel = 0, yvel = 0) %>% 
  wield(field_force, angle = kee, vel = kee , xlim = c(-5, 5), ylim = c(-5, 5)) %>% 
  evolve(1000, record)

I have applied the script in the particle package to the example data, but I got the following error.

Error in matrix(vel, ncol = ncol(angle), nrow = nrow(angle)) : 
  non-numeric matrix extent

I succeeded the resolved the problem with the non-numerix matrix thanks to the comment.

Next, increasing the amount of velocity data(row = 233, col = 154), the following error occurred.

Error: cannot allocate vector of size 152.6 Mb

I tried to check the amount of memory I used with gc().

 gc()
            used   (Mb) gc trigger   (Mb)  max used   (Mb)
Ncells   2765657   84.5    4718054  144.0   4718054  144.0
Vcells 311435640 2376.1  480298947 3664.4 439560179 3353.6

memory.limit is 4000(uplimit). Could I say it was caused by the PC memory?


Solution

  • The problem is that kee is a vector and not a matrix. So ncol and nrow return as NULL instead of an actual number. Here is a smaller reproducible example of why it is failing:

    v1 = 1:3
    v2 = 2:4
    
    mat = cbind(v1, v2)
    non_mat = as.numeric(unlist(mat))
    
    ## works!
    matrix(mat, ncol(mat), ncol(mat))
    #>      [,1] [,2]
    #> [1,]    1    3
    #> [2,]    2    2
    
    ## doesn't work!!
    matrix(non_mat, ncol = ncol(non_mat), nrow = nrow(non_mat))
    #> Error in matrix(non_mat, ncol = ncol(non_mat), nrow = nrow(non_mat)): non-numeric matrix extent
    
    ## it doesn't work because we return ncol = NULL and nrow = NULL
    ### the matrix needs an actual number!
    ncol(non_mat)
    #> NULL
    nrow(non_mat)
    #> NULL
    

    To fix, use ke instead of kee in the second wield() call.