prophet_linear_growth.stan 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. functions {
  2. matrix get_changepoint_matrix(vector t, vector t_change, int T, int S) {
  3. // Assumes t and t_change are sorted.
  4. matrix[T, S] A;
  5. row_vector[S] a_row;
  6. int cp_idx;
  7. // Start with an empty matrix.
  8. A = rep_matrix(0, T, S);
  9. a_row = rep_row_vector(0, S);
  10. cp_idx = 1;
  11. // Fill in each row of A.
  12. for (i in 1:T) {
  13. while ((cp_idx <= S) && (t[i] >= t_change[cp_idx])) {
  14. a_row[cp_idx] = 1;
  15. cp_idx += 1;
  16. }
  17. A[i] = a_row;
  18. }
  19. return A;
  20. }
  21. }
  22. data {
  23. int T; // Sample size
  24. int<lower=1> K; // Number of seasonal vectors
  25. vector[T] t; // Day
  26. vector[T] y; // Time-series
  27. int S; // Number of changepoints
  28. vector[S] t_change; // Index of changepoints
  29. matrix[T,K] X; // season vectors
  30. vector[K] sigmas; // scale on seasonality prior
  31. real<lower=0> tau; // scale on changepoints prior
  32. }
  33. transformed data {
  34. matrix[T, S] A;
  35. A = get_changepoint_matrix(t, t_change, T, S);
  36. }
  37. parameters {
  38. real k; // Base growth rate
  39. real m; // offset
  40. vector[S] delta; // Rate adjustments
  41. real<lower=0> sigma_obs; // Observation noise (incl. seasonal variation)
  42. vector[K] beta; // seasonal vector
  43. }
  44. transformed parameters {
  45. vector[S] gamma; // adjusted offsets, for piecewise continuity
  46. for (i in 1:S) {
  47. gamma[i] = -t_change[i] * delta[i];
  48. }
  49. }
  50. model {
  51. //priors
  52. k ~ normal(0, 5);
  53. m ~ normal(0, 5);
  54. delta ~ double_exponential(0, tau);
  55. sigma_obs ~ normal(0, 0.5);
  56. beta ~ normal(0, sigmas);
  57. // Likelihood
  58. y ~ normal((k + A * delta) .* t + (m + A * gamma) + X * beta, sigma_obs);
  59. }