helske / KFAS

KFAS: R Package for Exponential Family State Space Models
64 stars 17 forks source link

ERROR: System matrices (excluding Z) contain NA or infinite values, covariance matrices contain values larger than 1e+07 #56

Closed LakeRainSound closed 3 years ago

LakeRainSound commented 3 years ago

I wrote the following source code and ran it, but an error occurred.

# read NDVI data
df <- read.csv("/Users/restartsugar/LSDATASET/NoCloud_csv_data_for_r/bari_cher_state_space_model.csv",header=T)

# Convert dataframe to ts
dat_t <- ts(df['ndvi'], start = c(1988,1),frequency = 12)
dat_t

build_kfas <- SSModel(dat_t ~ SSMtrend(degree=1, Q=matrix(NA)) 
                            + SSMseasonal(12, sea.type="trigonometric", Q=matrix(NA), n=n), 
                      H=matrix(NA))
# Step2:estimate parameter
fit_kfas <- fitSSM(build_kfas, inits = c(1, 3))

# Step3、4:filtering, smoothing
result_kfas <- KFS(
  fit_kfas$model, 
  filtering = c("state", "mean"),
  smoothing = c("state", "mean")
)

error (There's some Japanese in there.)

> # Step2:estimate parameter
> fit_kfas <- fitSSM(build_kfas, inits = c(1, 3))
 is.SSModel(do.call(updatefn, args = c(list(inits, model), update_args)),  でエラー: 
  System matrices (excluding Z) contain NA or infinite values, covariance matrices contain values larger than 1e+07

What is the cause of this error? How can I solve this problem?

helske commented 3 years ago

As the error states, you have NA values in your model matrices. Your model contains 3 variances parameters set to NA, but in your fitSSM call you are only supplying two initial values.

There is actually another related problem here: As said in the documentation of fitSSM: "Note that the default updatefn function cannot be used with trigonometric seasonal components as its covariance structure is of form σI, i.e. not all NA's correspond to unique value." So you should write your own updatefn for fitSSM. Easiest thing is to do it like this:

updatefn <- function(pars, model) {

  SSModel(dat_t ~ SSMtrend(degree=1, Q=matrix(exp(pars[1])))
    + SSMseasonal(12, sea.type="trigonometric", Q=matrix(exp(pars[2]))), 
    H=matrix(exp(pars[3])))
}
LakeRainSound commented 3 years ago

Thank you! I've solved it!