Skip to content
Prev 22803 / 29559 Next

Fitting a basic structural model to a raster brick

Hi Srinivas, 

I do not think calc handles the z dimension by itself, you need to format the time-series within the function you're giving to calc().
I got an example below kind of working but it is so slow that I suspect something is not going right with it. I think the key is to figure the right formatting for the time-series you give to StructTS().

library(raster)
library(bfast)
library(zoo)
f <- system.file("extdata/modisraster.grd", package="bfast")
modisbrick<-brick(f)
modisbrick<-setZ(modisbrick,as.Date(strptime(paste(substr(names(modisbrick),start=2, stop=12)),"%Y.%m.%d")))


time <- getZ(modisbrick)

xStructTS <- function(x) {
  ts <- bfastts(x, time, type='16-day')
  fun <- function(ts) {
    StructTS(ts, type = 'BSM')$fitted[1]
  }
  fit <- sapply(ts, fun)
  return(fit)
}

r1.structs<- calc(modisbrick, fun=xStructTS) # Extremely slow

r1.structs



You can try to find the right formatting for the StructTS function by working on a single vector.

ts <- zoo(t(modisbrick[1]), time) 
StructTS(ts, type = 'BSM') # Returns an error about frequency of the data

ts  <- bfastts(t(modisbrick[1]), time, type='16-day')
StructTS(ts, type = 'BSM') # Works but really slowly


Hope it helps,
Lo?c