tests/testthat/test-standardize.R

context("Prediction")

#### simulate example dataset for testing ####

library(dplyr)

## set design elements
set.seed(1)
I = 100
p = 50

## coefficient functions
beta1 = function(t) { sin(2*t*pi) }
beta2 = function(t) { cos(2*t*pi) }
beta3 = function(t) { 1 }

## FPC basis functions
psi1 = function(t) { sin(2*t*pi) }
psi2 = function(t) { cos(2*t*pi) }

## generate subjects, observation times, and FPC scores
time.data = sapply(1:I, function(u) {
  ji = sample(10:15, 1)
  rbind(runif(ji, 0, 1) %>% sort, 
        rep(u, ji),
        rep(rnorm(1, 0, 3), ji),
        rep(rnorm(1, 0, 1), ji))
}) %>% unlist() %>% matrix(ncol = 4, byrow = TRUE)
colnames(time.data) = c("time", "subj", "c_i1", "c_i2")
time.data = as.data.frame(time.data)

## generate predictor data
predictor.data = matrix(rnorm(dim(time.data)[1] * p, sd = 4), dim(time.data)[1], p)
colnames(predictor.data) = paste0("Cov_", 1:p)

## combine and generate responses
concurrent.data = cbind(time.data, predictor.data)
concurrent.data = 
  mutate(concurrent.data,
         Y = Cov_1 * beta1(time) +            ## fixed effects
           Cov_2 * beta2(time) + 
           Cov_3 * beta3(time) + 
           c_i1 * psi1(time) +              ## pca effects
           c_i2 * psi2(time) + 
           rnorm(dim(concurrent.data)[1]))  ## measurement error

pred.list = paste("Cov", 1:p, sep = "_")
formula = as.formula( paste("Y ~", paste(pred.list, collapse = "+"), "| time") )


#### tests ####

test_that("the standardize function works", {
  
  fit.vbvs = vbvs_concurrent(formula, id.var = "subj", data = concurrent.data, standardized = FALSE,
                             t.min = 0, t.max = 1)
  fit.vb = vb_concurrent(formula, id.var = "subj", data = concurrent.data, standardized = FALSE,
                             t.min = 0, t.max = 1)
  
  expect_equal(var(concurrent.data$Cov_1), 16, tolerance = 1)
  expect_equal(var(fit.vbvs$data.model$Cov_1), 1, tolerance = 1e-1)
  expect_equal(var(fit.vb$data.model$Cov_1), 1, tolerance = 1e-1)
  expect_equal(fit.vb$data.model, fit.vbvs$data.model, tolerance = 1e-1)
  
  tf = terms.formula(fit.vb$formula.model, specials = NULL)
  trmstrings = attr(tf, "term.labels")
  
  data.stan.filtered = standardize_variables(data.original = concurrent.data, data.new = filter(concurrent.data, subj == 1),
                        trmstrings = trmstrings, time.var = fit.vb$time.var)
  
  expect_equal(data.stan.filtered$Cov_1, filter(fit.vb$data.model, subj == 1)$Cov_1)
  
})
jeff-goldsmith/vbvs.concurrent documentation built on Sept. 17, 2019, 2:26 p.m.