Fit state space model using dlm - r

I am about to fit a state space model to at univariate time series (y_t). The model i try to fit is:
y_t=F x_t+\epsilon_t, \epsilon_t \sim N(0,V)
x_{t+1}=G x_t+w_t, w_t \sim N(0,W)
x_0 \sim N(m_0,C_0)
I use the following R-code:
# Create function of unknown parameters, which returns dlm object
Build <- function(theta) {dlm(FF=theta[1],
GG=theta[2],V=theta[3],W=theta[4],m0=theta[5],
C0=theta[6])}
# Fit model to data using MLE
f1 <- dlmMLE(y,parm=c(1,1,0.1,0.1,0,0.1),Build)
But I get the following error message (after running f1):
Error in dlm(FF = theta[1], GG = theta[2], V = theta[3], W = theta [4], :
V is not a valid variance matrix
My problem is that I don't understand why V is not a valid variance matrix..
Does anyone know what is wrong?
Thank you in advance
Regards fuente
EDIT:
I tried doing the same, but instead of my real data I used:
y <- rnorm(72,6.44,1.97)
This produced, however, an error involving W (and not V...):
Error in dlm(FF = theta[1], GG = theta[2], V = theta[3], W = theta[4], :
W is not a valid variance matrix
I'm confused. Does it have something to do with the starting values passed to parm=...?

Related

Non-linear least squares in R: Error in eval(predvars, data, env) : object not found

I am trying to fit a gnls function in R and throws me an error that says:
Error in eval(predvars, data, env) : object A not found Not sure where I am going wrong.
set.seed(111)
y.size <- rnorm(100,4,1)
p <- rnorm(100,5,1)
df <- data.frame(p, y.size)
# fit generalised nonlinear least squares
require(nlme)
mgnls <- gnls(y.size ~ ((A *((p*K/Ka)-1))-1)* log(p),
start = list(A = c(-1,-10),
K = c(800,3000),
Ka = c(35000,45000)),
data = df)
plot(mgnls) # more homogenous
For anyone needing more info: I'm trying to follow along this method
I see there are 2 issues. First I don't understand the convention list(A = c(-1,-10), K = c(800,3000),Ka = c(35000,4500)). Generally only 1 value is used to initialize the starting value.
Second, your equation defines K/Ka with both values as adjustable parameters. This will cause errors since there are an infinite number of values for K and Ka which will evaluate to the same value. It is better to set one value to a constant or define a new value equal to the ratio.
set.seed(111)
y.size <- rnorm(100,4,1)
p <- rnorm(100,5,1)
df <- data.frame(p, y.size)
# fit generalised nonlinear least squares
require(nlme)
mgnls <- gnls(y.size ~ ((A *((p*K_Ka)-1))-1)* log(p),
start = list(A = -5, K_Ka = 0.5),
data=df)
plot(mgnls) # more homogenous

How to solve "impacts()" neighbors length error after running spdep::lagsarlm (Spatial Autoregressive Regression model)?

I have 9,150 polygons in my dataset. I was trying to run a spatial autoregressive model (SAR) in spdep to test spatial dependence of my outcome variable. After running the model, I wanted to examine the direct/indirect impacts, but encountered an error that seems to have something to do with the length of neighbors in the weights matrix not being equal to n.
I tried running the very same equation as SLX model (Spatial Lag X), and impacts() worked fine, even though there were some polygons in my set that had no neighbors. I Googled and looked at spdep documentation, but couldn't find a clue on how to solve this error.
# Defining queen contiguity neighbors for polyset and storing the matrix as list
q.nbrs <- poly2nb(polyset)
listweights <- nb2listw(q.nbrs, zero.policy = TRUE)
# Defining the model
model.equation <- TIME ~ A + B + C
# Run SAR model
reg <- lagsarlm(model.equation, data = polyset, listw = listweights, zero.policy = TRUE)
# Run impacts() to show direct/indirect impacts
impacts(reg, listw = listweights, zero.policy = TRUE)
Error in intImpacts(rho = rho, beta = beta, P = P, n = n, mu = mu, Sigma = Sigma, :
length(listweights$neighbours) == n is not TRUE
I know that this is a question from 2019, but maybe it can help people dealing with the same problem. I found out that in my case the problem was the type of dataset, your data=polyset should be of type "SpatialPolygonsDataFrame". Which can be achieved by converting your data:
polyset_spatial_sf <- sf::as_Spatial(polyset, IDs = polyset$ID)
Then rerun your code.

Parameter estimates using FME ODE model fitting in R

I have a system of ODE equations that I am trying to fit to generated data, synthetic or lab. The final product I am interested in is the parameter and it's estimated error. We use the R package FME with modCost and modFit. As an example, a system of ODEs may be defined as such:
eqs <- function (time, y, parms, ...) {
with(as.list(c(parms, y)), {
dP <- k2*PA - k1*A*P # concentration of nucleic acid
dA <- dP # concentration of free protein
dPA <- -dP
list(c(dA,dP,dPA))
}
}
with parameters k1 and k2 and variables A,P and PA. I import the data (not shown) and define the cost function used in modFit
cost <- function(p, data, ...) {
yy <- p[c("A","P","PA")]
pp <- p[c("k1", "k2")]
out <- ode(yy, time, eqs, pp)
modCost(out, data, ...)
}
I set some initial conditions with a parms vector and then do the fitting with
fit <- modFit(f = cost, p = parms, data = dat, weight = "std",
lower = rep(0, 8), upper = c(600,100,600,0.01,0.01), method = "Marq")
I then do a final ode to get the generated fits with best parameters, Bob's your uncle, and boom, estimated parameters. The input numbers don't matter, I hope my process outline is legible for those who use this package.
My issue and question centers around two things: I'm a scientist, a physicist, and the error of the estimated parameters is important to report. Can I generate the estimated error from MFE somehow or is there a separate package for that kind of return?
I don't get your point. You can just use:
summary(fit)
to see the Std. Error.

predict value from a non parametric model in R

The target is to predict the values to the test set with the package monreg model, but this si not working with the predict function, because there isn't a model object to use the prediction function.
Giving an example:
require(monreg) # Package ‘monreg’
x <- rnorm(100)
y <- x + rnorm(100)
x_train=x[0:80]
y_train=y[0:80]
x_test=x[81:100]
y_test=y[81:100]
mon1 <- monreg(x, y, hd = .5, hr = .5)
# I was expecting to get the prediction over the test partion as R usualy works
predict(mon1,h=length(y_test))
But this is not working. In the case this package doesnt have any predict function, I would accept any advice to implement the Narayada Watson regression in R in order to predict values like this example I gave.

R dlm library: model definition

I am trying to build a state space model in R using the dlm library but keep getting the "incompatible dimensions of matrices" error.
The specifications of the model I am trying to produce are as per below:
Yt = At + beta*Ft + et
Ft = phi1Ft-1 + phi2Ft-2 + vt
At = At-1 + wt
where Yt is the observable variable, At is the time varying coefficient modelled as a random walk and Ft is a latent factor which follows an AR(2) process.
I have been trying to set up the FF, V, GG, W, m0 and C0 matrices required by dlm to specify the model, but have yet to get the program to work.
Please see below my latest attempt which returns an "incompatible dimensions of matrices" error.
I have traced the relative matrix sizes on paper and they look fine to me. Could anyone please advise where I am going wrong?
# the below code works now
model <- function(x) {
FF <- matrix(c(x[1],0,1), nr=1)
V <- matrix(exp(x[2]))
GG <- matrix(c(x[3],1,0,x[4],0,0,0,0,1), nr=3)
W <- diag(c(exp(x[5]),0,exp(x[6])))
m0 <- rep(0,3)
C0 <- 10*diag(3)
dlm(FF=FF, V=V, GG=GG, W=W, m0=m0,C0=C0)
}
# x[1:6] are beta, Var(et), phi1, phi2, Var(vt) and Var(wt)
fit <- dlmMLE(y1, parm = c(rep(0,6)), build = model)
dlmy1 <- model(fit$par)

Resources