@@ -100,3 +100,71 @@ test_that("logistic caps should be included in the correct order", {
100
100
dplyr :: arrange(time ) %> %
101
101
dplyr :: pull(cap )))))
102
102
})
103
+
104
+ test_that(" piecewise models fit and forecast without error" , {
105
+ skip_on_cran()
106
+ # Example of logistic growth with possible changepoints
107
+ # Simple logistic growth model
108
+ dNt = function (r , N , k ){
109
+ r * N * (k - N )
110
+ }
111
+
112
+ # Iterate growth through time
113
+ Nt = function (r , N , t , k ) {
114
+ for (i in 1 : (t - 1 )) {
115
+
116
+ # population at next time step is current population + growth,
117
+ # but we introduce several 'shocks' as changepoints
118
+ if (i %in% c(5 , 15 , 25 , 41 , 45 , 60 , 80 )){
119
+ N [i + 1 ] <- max(1 , N [i ] + dNt(r + runif(1 , - 0.1 , 0.1 ),
120
+ N [i ], k ))
121
+ } else {
122
+ N [i + 1 ] <- max(1 , N [i ] + dNt(r , N [i ], k ))
123
+ }
124
+ }
125
+ N
126
+ }
127
+
128
+ # Simulate expected values
129
+ set.seed(11 )
130
+ expected <- Nt(0.004 , 2 , 100 , 30 )
131
+ plot(expected , xlab = ' Time' )
132
+
133
+ # Take Poisson draws
134
+ y <- rpois(100 , expected )
135
+
136
+ # Assemble data into dataframe and model. We set a
137
+ # fixed carrying capacity of 35 for this example, but note that
138
+ # this value is not required to be fixed at each timepoint
139
+ mod_data <- data.frame (y = y ,
140
+ time = 1 : 100 ,
141
+ cap = 35 ,
142
+ series = as.factor(' series_1' ))
143
+ dat_train <- mod_data %> %
144
+ dplyr :: filter(time < = 90 )
145
+ dat_test <- mod_data %> %
146
+ dplyr :: filter(time > 90 )
147
+
148
+ # The intercept is nonidentifiable when using piecewise
149
+ # trends because the trend functions have their own offset
150
+ # parameters 'm'; it is recommended to always drop intercepts
151
+ # when using these trend models
152
+ mod <- mvgam(y ~ 0 ,
153
+ trend_model = PW(growth = ' logistic' ),
154
+ family = poisson(),
155
+ data = dat_train ,
156
+ chains = 2 )
157
+ # Compute and plot forecasts
158
+ fc <- forecast(mod , newdata = dat_test )
159
+ expect_no_error(capture_output(plot(fc )))
160
+
161
+ # Should also work for piecewise linear
162
+ mod <- mvgam(y ~ 0 ,
163
+ trend_model = PW(growth = ' linear' ),
164
+ family = poisson(),
165
+ data = dat_train ,
166
+ chains = 2 )
167
+ # Compute and plot forecasts
168
+ fc <- forecast(mod , newdata = dat_test )
169
+ expect_no_error(capture_output(plot(fc )))
170
+ })
0 commit comments