Spline_QMER.R 8.33 KB
Newer Older
1
2
library(scam)

luroth's avatar
luroth committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
`vcov.scam` <- function (object, freq = FALSE, dispersion = NULL,
                         parametrized = TRUE, ...)  {
    if (freq) {
        vc <- if (parametrized) {
            object$Ve.t
        } else {
            object$Ve
        }
    } else {
        vc <- if (parametrized) {
            object$Vp.t
        } else {
            object$Vp
        }
    }
    if (!is.null(dispersion)) {
        vc <- dispersion * vc/object$sig2
    }
    name <- names(object$edf)
    dimnames(vc) <- list(name, name)
    vc
}

`coef.scam` <- function(object, parametrized = TRUE, ...) {
    coefs <- if (parametrized) {
        object$coefficients.t
    } else {
        object$coefficients
    }
    coefs
}

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
fit_scam_spline <- function(x, y, k = NA, bs = "mpi", label = NULL, optimizer = "bfgs") {
  if (!is.null(label)) { print(label) }
  if (is.na(k)) k <- round(length(x) * 3 / 4)
  if (k > 20) k <- 20

  spline <- NULL
  try(
    system.time(spline <- scam(y ~ s(as.numeric(x), k = k, bs = bs), optimizer = optimizer))
  )
  if (is.null(spline)) {
    print("decreasing k")
    spline <- scam(y ~ s(as.numeric(x), k = k - 1, bs = bs))
  }
  return(spline)
}

luroth's avatar
luroth committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
fit_scam_spline_weights <- function(x, y, w, k = NA, bs = "mpi", label = NULL, optimizer = "bfgs") {
  w <- 1 / (w^2)
  if (!is.null(label)) { print(label) }
  if (is.na(k)) k <- round(length(x) * 3 / 4)
  if (k > 20) k <- 20

  spline <- NULL
  try(
    system.time(spline <- scam(y ~ s(as.numeric(x), k = k, bs = bs), optimizer = optimizer, weights=w))
  )
  if (is.null(spline)) {
    print("decreasing k")
    spline <- scam(y ~ s(as.numeric(x), k = k - 1, bs = bs), weights=w)
  }
  return(spline)
}

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
predict_scam_spline <- function(spline, x_, deriv = NULL, se = FALSE)
{

  if (!is.null(deriv)) {
    predicts <- predict.scam(spline, newdata = x_, se.fit = FALSE)
    for (i in 1:deriv) {
      predicts <- c(0, diff(predicts))
    }
  } else {
    predicts <- predict.scam(spline, newdata = x_, se.fit = se)
    if (se) {
      predicts <- predicts$se.fit
    } else {
      predicts <- predicts
    }

  }

  return(predicts)
}

luroth's avatar
luroth committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

predict_scam_spline_posteriors <- function(spline, x_)
{

  # Design matrix
  lp <- predict.scam(spline, newdata = x_, type = "lpmatrix")

  # Estimated coefficients
  coef <- coef.scam(spline)
  # install.packages("gratia")
  vc <- vcov.scam(spline)
  if (!all( eigen(vc)$values >0 )) {
    predicts <- predict.scam(spline, newdata = x_, se.fit = FALSE)
    return(list(predicts))
  }

  # Sample from the distrubitions of the coefficients
  set.seed(35)
  sim <- MASS::mvrnorm(1000, mu = c(coef), Sigma = unname(vc))

  # For each realisation, obtain the "fitted" curve
  predicts_ <- lp %*% t(sim)
  predicts <- lapply(seq_len(ncol(predicts_)), function(i) predicts_[,i])

  predicts_r <- sapply (predicts, function (x) {length (x) <- nrow(predicts_); return (x)})
  predicts_rr <- lapply(seq_len(nrow(predicts_r)), function(i) predicts_r[i,])

  return(predicts_rr)
}

119
120
121
# Finds start/stop of growth phase, final value and key percentiles
find_start_stop_growth_phase <- function(df, text = NA, threshold_start = 1 / 4, threshold_stop = 1 / 4, delta_days = 40, final_height_agg = 24) {
  if (!is.na(text)) print(text)
luroth's avatar
luroth committed
122

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
  # Extract maximum growth phase
  max_growth <- max(df$predict_deriv)
  if (max_growth == 0) {
    print("Spline has zero growth!")
    return(tibble(predict_start_growth = NA,
                  predict_start_growth_se = NA,
                  predict_stop_growth = NA,
                  predict_stop_growth_se = NA,
                  predict_final_value = NA,
                  predict_final_value_se = NA,
                  predict_p15 = NA,
                  predict_p15_se = NA,
                  predict_p95 = NA,
                  predict_p95_se = NA))
  }

  timepoint_max_growth <- (df %>% slice(which.max(predict_deriv)))$timestamp
  timepoint_max_growth <- ifelse(timepoint_max_growth < max(df$timestamp), timepoint_max_growth, min(df$timestamp))

  # Filter out datapoints which have growth rate higher than threshold * max, which corresponds to main growth phase
  df_ <- df %>%
    filter(predict_deriv > max_growth * threshold_start)
  # Earlieast value that is left indicates start of growth
  start <- (df_ %>% slice(1))$timestamp
  # First value after start that is at least 40 days later, after max. growth peak, and has growth rate smaller than threshold * max is stop of growth phase
  df__ <- df %>% filter(timestamp >= timepoint_max_growth &
                          timestamp > start + days(delta_days) &
                          predict_deriv <= (max_growth * threshold_stop))
  if (nrow(df__) > 0) {
    stop <- (df__ %>% slice(1))$timestamp
  }  else {
    stop <- max(df$timestamp)
  }

  # SEs
  start_se <- (df %>% filter(timestamp == start))$predict_se[[1]]
  stop_se <- (df %>% filter(timestamp == stop))$predict_se[[1]]

  # Correct start if out of measurement period
  start <- if_else(yday(start) != yday(min(df$timestamp)), start, as.POSIXct(NA))

  # Final value is median of measurement values after stop of growth phase
  final_value <- (df %>%
    filter(timestamp >= stop) %>%
    top_n(final_height_agg, predict) %>%
    summarize(final_height = median(predict, na.rm = T)))$final_height
  final_value_se <- (df %>%
     filter(timestamp >= stop) %>%
     top_n(final_height_agg, predict) %>%
     summarize(final_height = median(predict_se, na.rm = T)))$final_height

  # Timepoint where 15 and 95 percentile are reached are physiologically interesting (Kronenberg et al 2020)
  p15_final_value <- (df %>%
    filter(predict > final_value * 0.15) %>%
    slice(1))$timestamp
  if (length(p15_final_value) == 0) p15_final_value <- as.POSIXct(NA)
  p15_final_value <- if_else(yday(p15_final_value) != yday(min(df$timestamp)), p15_final_value, as.POSIXct(NA))
  p15_final_value <- if_else(length(p15_final_value) != 1, as.POSIXct(NA), p15_final_value)
  p15_final_value_se <- (df %>%
    filter(predict > final_value * 0.15) %>%
    slice(1))$predict_se
  if (length(p15_final_value_se) > 0) {
    p15_final_value_se <- p15_final_value_se[[1]]
  } else {
    p15_final_value_se <- NA
  }

  p95_final_value <- (df %>%
    filter(predict < final_value * 0.95) %>%
    slice(n()))$timestamp
  if (length(p95_final_value) == 0) p95_final_value <- as.POSIXct(NA)
  p95_final_value <- if_else(yday(p95_final_value) != yday(max(df$timestamp)), p95_final_value, as.POSIXct(NA))
  p95_final_value <- if_else(length(p95_final_value) != 1, as.POSIXct(NA), p95_final_value)
  p95_final_value_se <- (df %>%
    filter(predict < final_value * 0.95) %>%
    slice(n()))$predict_se
  if (length(p95_final_value_se) > 0) {
    p95_final_value_se <- p95_final_value_se[[1]]
  } else {
    p95_final_value_se <- NA
  }

  return(tibble(predict_start_growth = start,
                predict_start_growth_se = start_se,
                predict_stop_growth = stop,
                predict_stop_growth_se = stop_se,
                predict_final_value = final_value,
                predict_final_value_se = final_value_se,
                predict_p15 = p15_final_value,
                predict_p15_se = p15_final_value_se,
                predict_p95 = p95_final_value,
                predict_p95_se = p95_final_value_se))
}
luroth's avatar
luroth committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238


find_start_stop_growth_phase_posterior <- function(df, text = NA, threshold_start = 1 / 4, threshold_stop = 1 / 4, delta_days = 40, final_height_agg = 10) {

  f <- function(pred) {return(c(0, diff(pred)))}
  predict <- find_start_stop_growth_phase(df, text, threshold_start, threshold_stop, delta_days, final_height_agg)

  df_posterior_1 <- sapply (df$predict_posteriors, function (x) {length (x) <- length(df$predict_posteriors[[1]]); return (x)})
  df_posterior_1 <- lapply(seq_len(nrow(df_posterior_1)), function(i) df_posterior_1[i,])

  df_posterior_2 <- lapply(df_posterior_1, f)

  df_posterior <- mapply(function(X, Y) {tibble(predict = X, predict_deriv=Y, timestamp = df$timestamp, predict_se = df$predict_se)}, X=df_posterior_1, Y=df_posterior_2, SIMPLIFY = F)
  predict_posterior <- lapply(df_posterior, find_start_stop_growth_phase, NA, threshold_start, threshold_stop, delta_days, final_height_agg)
  df_predict_posterior <- bind_rows(predict_posterior)
  df_predict_posterior_se <- df_predict_posterior %>% dplyr::select(-ends_with("se")) %>%
    summarise_each(funs(mean,sd,sepost=sd(.)/sqrt(n()))) %>%
    dplyr::select(ends_with("sepost"))

  predict <- bind_cols(predict, df_predict_posterior_se)

  return(predict)
}