paul-buerkner / brms

brms R package for Bayesian generalized multivariate non-linear multilevel models using Stan
https://paul-buerkner.github.io/brms/
GNU General Public License v2.0
1.28k stars 183 forks source link

AR processes for binned time points #1695

Open wds15 opened 5 days ago

wds15 commented 5 days ago

I am working on a problem which requires to model binned time-points as a AR(1) process... but brms does not let me do that as I get the error Error: Time points within groups must be unique.. I don't quite see why it would not make sense to have an AR process defined on time points which are over binned time points? For example, let's say we have a process measured on days, but I want the AR process to work on weeks, for example:

# Load necessary library
set.seed(5678678) # For reproducibility

# Parameters
n <- 100 # Length of the time series
phi <- 0.7 # AR(1) coefficient
sigma <- 1 # Standard deviation of the primary white noise
sigma_eta <- 0.5 # Standard deviation of additional white noise

# Initialize the time series
X <- numeric(n)
X[1] <- rnorm(1, mean = 0, sd = sigma) # Initial value

# Simulate AR(1) process with additional white noise
for (t in 2:n) {
  e_t <- rnorm(1, mean = 0, sd = sigma) # Primary white noise
  eta_t <- rnorm(1, mean = 0, sd = sigma_eta) # Additional white noise
  X[t] <- phi * X[t-1] + e_t + eta_t
}

# Plot the time series
## plot(X, type = 'l', main = 'AR(1) Time Series with Additional White Noise', xlab = 'Time', ylab = 'X_t')

# Display the first few values
## head(X)

ar_example <- data.frame(y=X, time=1:length(X)) |> transform(week=as.integer((floor(time/7))))

library(brms)

## works ok:
day_ar <- brm(bf(y ~ ar(time, p=1)), data=ar_example)

## not possible to do?
week_ar <- brm(bf(y ~ ar(week,p=1)), data=ar_example)
wds15 commented 5 days ago

Basically, the AR process should be allowed to be defined to go over time bins rather than data rows.. or is that somehow possible with the gr argument?

paul-buerkner commented 4 days ago

Should be possible. Not sure how much effort it would be though. Can you tell me the math model these binned time points would imply?