Title: | Time Series Methods Based on Growth Curves |
---|---|
Description: | The 'tsgc' package provides comprehensive tools for the analysis and forecasting of epidemic trajectories. It is designed to model the progression of an epidemic over time while accounting for the various uncertainties inherent in real-time data. Underpinned by a dynamic Gompertz model, the package adopts a state space approach, using the Kalman filter for flexible and robust estimation of the non-linear growth pattern commonly observed in epidemic data. The reinitialization feature enhances the model’s ability to adapt to the emergence of new waves. The forecasts generated by the package are of value to public health officials and researchers who need to understand and predict the course of an epidemic to inform decision-making. Beyond its application in public health, the package is also a useful resource for researchers and practitioners in fields where the trajectories of interest resemble those of epidemics, such as innovation diffusion. The package includes functionalities for data preprocessing, model fitting, and forecast visualization, as well as tools for evaluating forecast accuracy. The core methodologies implemented in 'tsgc' are based on well-established statistical techniques as described in Harvey and Kattuman (2020) <doi:10.1162/99608f92.828f40de>, Harvey and Kattuman (2021) <doi:10.1098/rsif.2021.0179>, and Ashby, Harvey, Kattuman, and Thamotheram (2024) <https://www.jbs.cam.ac.uk/wp-content/uploads/2024/03/cchle-tsgc-paper-2024.pdf>. |
Authors: | Craig Thamotheram [aut, cre] |
Maintainer: | Craig Thamotheram <[email protected]> |
License: | GPL (>= 3) |
Version: | 0.0 |
Built: | 2024-11-25 04:40:31 UTC |
Source: | https://github.com/craig-pt/tsgc |
Something similar to Python's argmax.
argmax(x, decreasing = TRUE)
argmax(x, decreasing = TRUE)
x |
Object to have its maximum found |
decreasing |
Logical value indicating whether |
The maximum value and its index.
library(tsgc) data(gauteng,package="tsgc") argmax(gauteng)
library(tsgc) data(gauteng,package="tsgc") argmax(gauteng)
Helper method to compute the log growth rates of cumulated variables. It will compute the log cumulative growth rate for each column in the data frame.
df2ldl(dt)
df2ldl(dt)
dt |
Cumulated data series. |
A data frame of log growth rates of the cumulated variable which has
been inputted via the parameter dt
.
library(tsgc) data(gauteng,package="tsgc") df2ldl(gauteng)
library(tsgc) data(gauteng,package="tsgc") df2ldl(gauteng)
Cumulative cases of Covid-19 in England.
data(england)
data(england)
An object of class "xts"
;
Cumulative cases of Covid-19
Downloaded from https://ukhsa-dashboard.data.gov.uk/topics/covid-19
data(england) # plot daily cases plot(diff(england))
data(england) # plot daily cases plot(diff(england))
Class for estimated Dynamic Gompertz Curve model and contains
methods to extract smoothed/filtered estimates of the states, the level of
the incidence variable , and forecasts of
.
get_growth_y(smoothed = FALSE, return.components = FALSE)
Returns the growth rate of the incidence () of the cumulated
variable (
). Computed as
smoothed
Logical value indicating whether to use the
smoothed estimates of and
to compute the
growth rate (
TRUE
), or the contemporaneous filtered estimates
(FALSE
). Default is FALSE
.
return.components
Logical value indicating whether to
return the estimates of and
as well as
the estimates of the growth rate, or just the growth rate. Default is
FALSE
.
xts
object containing
smoothed/filtered growth rates and components ( and
), where applicable.
get_gy_ci(smoothed = FALSE, confidence_level = 0.68)
Returns the growth rate of the incidence () of the cumulated
variable (
). Computed as
smoothed
Logical value indicating whether to use the
smoothed estimates of and
to compute the
growth rate (
TRUE
), or the contemporaneous filtered estimates
(FALSE
). Default is FALSE
.
confidence_level
Confidence level for the confidence
interval. Default is , which is one standard deviation for
a normally distributed random variable.
xts
object containing smoothed/filtered
growth rates and upper and lower bounds for the confidence intervals.
predict_all(n.ahead, sea.on = FALSE, return.all = FALSE)
Returns forecasts of the incidence variable , the state variables
and the conditional covariance matrix
for the states.
n.ahead
The number of forecasts you wish to create from
the end of your sample period.
sea.on
Logical value indicating whether seasonal
components should be included in the
state-space model or not. Default is TRUE
.
return.all
Logical value indicating whether to return
all filtered estimates and forecasts
(TRUE
) or only the forecasts (FALSE
). Default is
FALSE
.
xts
object containing the forecast
(and filtered, where applicable) level
of (
y.hat
), (
level.t.t
),
(
slope.t.t
), vector of states including the
seasonals where applicable (a.t.t
) and covariance matrix of all
states including seasonals where applicable (P.t.t
).
predict_level(
y.cum,
n.ahead,
confidence_level,
sea.on = FALSE,
return.diff = FALSE
)
Forecast the cumulated variable or the incidence of it. This function returns
the forecast of the cumulated variable , or the forecast of the incidence of the cumulated variable,
. For
example, in the case of an epidemic,
might be daily new cases of
the disease and
the cumulative number of recorded infections.
y.cum
The cumulated variable.
n.ahead
The number of periods ahead you wish to forecast from
the end of the estimation window.
confidence_level
The confidence level for the log growth
rate that should be used to compute
the forecast intervals of .
return.diff
Logical value indicating whether to return the cumulated variable,
, or the incidence of it,
(i.e., the first difference of the cumulated variable). Default is
FALSE
.
xts
object containing the point
forecasts and upper and lower bounds of
the forecast interval.
print_estimation_results()
Prints a table of estimated parameters in a format ready to paste into LaTeX.
Harvey, A. C. and Kattuman, P. (2021). A Farewell to R: Time Series Models for Tracking and Forecasting Epidemics, Journal of the Royal Society Interface, vol 18(182): 20210179
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Print estimation results res$print_estimation_results() # Forecast 7 days ahead from the end of the estimation window res$predict_level(y.cum = gauteng[idx.est], n.ahead = 7, confidence_level = 0.68) # Forecast 7 days ahead from the model and return filtered states res$predict_all(n.ahead = 7, return.all = TRUE) # Return the filtered growth rate and its components res$get_growth_y(return.components = TRUE) # Return smoothed growth rate of incidence variable and its confidence # interval res$get_gy_ci(smoothed = TRUE, confidence_level = 0.68)
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Print estimation results res$print_estimation_results() # Forecast 7 days ahead from the end of the estimation window res$predict_level(y.cum = gauteng[idx.est], n.ahead = 7, confidence_level = 0.68) # Forecast 7 days ahead from the model and return filtered states res$predict_all(n.ahead = 7, return.all = TRUE) # Return the filtered growth rate and its components res$get_growth_y(return.components = TRUE) # Return smoothed growth rate of incidence variable and its confidence # interval res$get_gy_ci(smoothed = TRUE, confidence_level = 0.68)
KFAS::KFS
output.Since Harvey and Kattuman (2021) show that
we can compute the
for which
and then will fall below zero. This
is given by
This is
predicated on , else there is super-exponential growth
and no peak in sight. Of course, it only makes sense to investigate an
upcoming peak for
(when cases are growing). The estimates
of
and
are extracted from the
KFS
object passed to the function.
forecast_peak(kfs_out)
forecast_peak(kfs_out)
kfs_out |
The |
Forecast of number of periods until peak.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") res <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005)$estimate() forecast_peak(res$output)
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") res <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005)$estimate() forecast_peak(res$output)
and
.Since Harvey and Kattuman (2021) show that
we can compute the for which
and then will fall
below zero. This
is given by
This is
predicated on , else there is super-exponential growth an
no peak in sight. Of course, it only makes sense to investigate an upcoming
peak for
(when cases are growing).
forecast.peak(delta, gamma)
forecast.peak(delta, gamma)
delta |
The estimate of |
gamma |
The estimate of |
Forecast of number of periods until peak.
# Forecasts the peak of an epidemic with gamma < 0 so that a peak is in # sight. forecast.peak(-2.87,-0.045) # Does not return a result (returns an error as gamma > 0) try(forecast.peak(-2.87,0.045), silent=TRUE)
# Forecasts the peak of an epidemic with gamma < 0 so that a peak is in # sight. forecast.peak(-2.87,-0.045) # Does not return a result (returns an error as gamma > 0) try(forecast.peak(-2.87,0.045), silent=TRUE)
Cumulative cases of Covid-19 in the South African province of Gauteng.
data(gauteng)
data(gauteng)
An object of class "xts"
;
Cumulative cases of Covid-19 from 10th March 2020
Downloaded from https://sacoronavirus.co.za/
data(gauteng) # plot daily cases plot(diff(gauteng))
data(gauteng) # plot daily cases plot(diff(gauteng))
Plots actual and filtered values of the log cumulative growth
rate () in the estimation sample and the forecast and realised
log cumulative growth rate out of the estimation sample.
plot_forecast( res, y.eval, n.ahead = 14, plt.start.date = NULL, title = "", caption = "" )
plot_forecast( res, y.eval, n.ahead = 14, plt.start.date = NULL, title = "", caption = "" )
res |
Results object estimated using the |
y.eval |
The out-of-sample realisation of the log growth rate of the cumulated variable (i.e. the actual values to which the forecasts should be compared). |
n.ahead |
The number of time periods ahead from the end of the sample to be forecast. The default is 14. |
plt.start.date |
Plot start date. Default is |
title |
Plot title. Enter as text string. |
caption |
Plot caption. Enter as text string. |
A ggplot2
plot.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") idx.eval <- (zoo::index(gauteng) >= as.Date("2020-07-20")) & zoo::index(gauteng) <= as.Date("2020-07-27") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot forecast and realised log growth rate of cumulative cases plot_forecast(res, y.eval = df2ldl(gauteng[idx.eval]), n.ahead = 7, title = "Forecast ln(g)", plt.start.date = as.Date("2020-07-13"))
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") idx.eval <- (zoo::index(gauteng) >= as.Date("2020-07-20")) & zoo::index(gauteng) <= as.Date("2020-07-27") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot forecast and realised log growth rate of cumulative cases plot_forecast(res, y.eval = df2ldl(gauteng[idx.eval]), n.ahead = 7, title = "Forecast ln(g)", plt.start.date = as.Date("2020-07-13"))
Plots the smoothed/filtered growth rate of the difference in the
cumulated variable () and the associated confidence intervals.
plot_gy_ci( res, plt.start.date = NULL, smoothed = FALSE, title = NULL, series.name = NULL, pad.right = NULL )
plot_gy_ci( res, plt.start.date = NULL, smoothed = FALSE, title = NULL, series.name = NULL, pad.right = NULL )
res |
Results object estimated using the |
plt.start.date |
Plot start date. Default is |
smoothed |
Logical value indicating whether to used the smoothed
estimates of |
title |
Title for plot. Enter as text string. |
series.name |
The name of the series the growth rate is being computed
for. E.g. |
pad.right |
Numerical value for the amount of time periods of blank space you wish to leave on the right of the graph. Extends the horizontal axis by the given number of time periods. |
A ggplot2
plot.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot filtered gy, g and gamma plot_gy_ci(res, plt.start.date = as.Date("2020-07-13"))
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot filtered gy, g and gamma plot_gy_ci(res, plt.start.date = as.Date("2020-07-13"))
Plots the smoothed/filtered growth rate of the difference in
the cumulated variable (), the smoothed/filtered growth rate of the
the cumulated variable (
), and the smoothed/filtered slope of
,
.
Following Harvey and Kattuman (2021), we compute
as
plot_gy_components(res, plt.start.date = NULL, smoothed = FALSE, title = NULL)
plot_gy_components(res, plt.start.date = NULL, smoothed = FALSE, title = NULL)
res |
Results object estimated using the |
plt.start.date |
Plot start date. Default is |
smoothed |
Logical value indicating whether to used the smoothed
estimates of |
title |
Title for plot. Enter as text string. |
A ggplot2
plot.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot filtered gy, g and gamma plot_gy_components(res, plt.start.date = as.Date("2020-07-06"))
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot filtered gy, g and gamma plot_gy_components(res, plt.start.date = as.Date("2020-07-06"))
Plots actual values of the difference in the cumulated variable,
the forecasts of the cumulated variable (both including and excluding the
seasonal component, where a seasonal is specified) and forecast intervals
around the forecasts, plus the actual outcomes from the holdout sample. The
forecast intervals are based on the prediction intervals for .
Also reports the mean absolute percentage prediction error over the holdout
sample.
plot_holdout( res, Y, Y.eval, confidence.level = 0.68, date_format = "%Y-%m-%d", series.name = NULL, title = NULL, caption = NULL )
plot_holdout( res, Y, Y.eval, confidence.level = 0.68, date_format = "%Y-%m-%d", series.name = NULL, title = NULL, caption = NULL )
res |
Results object estimated using the |
Y |
Values of the cumulated variable to be used in the estimation window. |
Y.eval |
Values of the cumulated variable to be used in the holdout sample (i.e. to which the forecasts should be compared to). |
confidence.level |
Width of prediction interval for |
date_format |
Date format, e.g. |
series.name |
Name of the variable you are forecasting for the purposes
of a $y$-axis label. E.g. if |
title |
Title for forecast plot. Enter as text string. |
caption |
Caption for forecast plot. Enter as text string. |
A ggplot2
plot.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") idx.eval <- (zoo::index(gauteng) >= as.Date("2020-07-20")) & zoo::index(gauteng) <= as.Date("2020-07-27") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot forecasts and outcomes over evaluation period plot_holdout(res = res, Y = gauteng[idx.est], Y.eval = gauteng[idx.eval])
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") idx.eval <- (zoo::index(gauteng) >= as.Date("2020-07-20")) & zoo::index(gauteng) <= as.Date("2020-07-27") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot forecasts and outcomes over evaluation period plot_holdout(res = res, Y = gauteng[idx.est], Y.eval = gauteng[idx.eval])
Plots actual values of the difference in the cumulated variable,
the forecasts of the cumulated variable (both including and excluding the
seasonal component, where a seasonal is specified) and forecast intervals
around the forecasts. The forecast intervals are based on the prediction
intervals for .
plot_new_cases( res, Y, n.ahead, confidence.level = 0.68, date_format = "%Y-%m-%d", title = NULL, plt.start.date = NULL )
plot_new_cases( res, Y, n.ahead, confidence.level = 0.68, date_format = "%Y-%m-%d", title = NULL, plt.start.date = NULL )
res |
Results object estimated using the |
Y |
Cumulated variable. |
n.ahead |
Number of forecasts (i.e. number of periods ahead to forecast from end of estimation window). |
confidence.level |
Width of prediction interval for |
date_format |
Date format. Default is |
title |
Title for forecast plot. Enter as text string. |
plt.start.date |
First date of actual data (from estimation sample) to
plot on graph. |
A ggplot2
plot.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot forecast of new cases 7 days ahead plot_new_cases(res, Y = gauteng[idx.est], n.ahead = 7, confidence.level = 0.68, date_format = "%Y-%m-%d", title = "Forecast new cases", plt.start.date = as.Date("2020-07-13"))
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-20") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate() # Plot forecast of new cases 7 days ahead plot_new_cases(res, Y = gauteng[idx.est], n.ahead = 7, confidence.level = 0.68, date_format = "%Y-%m-%d", title = "Forecast new cases", plt.start.date = as.Date("2020-07-13"))
reinit.date
row from
all columnsReinitialise a data frame by subtracting the reinit.date
row from
all columns
reinitialise_dataframe(dt, reinit.date)
reinitialise_dataframe(dt, reinit.date)
dt |
Cumulated data series. |
reinit.date |
Reinitialisation date. E.g. ‘'2021-05-12'’. |
The reinitialised data frame
library(tsgc) data(gauteng,package="tsgc") reinitialise_dataframe(gauteng,as.Date("2021-01-01"))
library(tsgc) data(gauteng,package="tsgc") reinitialise_dataframe(gauteng,as.Date("2021-01-01"))
SSModelDynamicGompertz
and SSModelDynGompertzReinit
refer back
to this base class.Base class for estimating time-series growth curve models. Classes
SSModelDynamicGompertz
and SSModelDynGompertzReinit
refer back
to this base class.
estimate(sea.type = "trigonometric", sea.period = 7)
Estimates the dynamic Gompertz curve model when applied to an object of
class SSModelDynamicGompertz
or SSModelDynGompertzReinit
.
sea.type
Seasonal type. Options are
'trigonometric'
and 'none'
. 'trigonometric'
will
yield a model with a trigonometric seasonal component and
'none'
will yield a model with no seasonal component.
sea.period
The period of seasonality. For a
day-of-the-week effect with daily data, this would be 7. Not required
if sea.type = 'none'
.
An object of class FilterResults
containing the result output for the estimated dynamic Gompertz curve
model.
get_dynamic_gompertz_model(
y,
q = NULL,
sea.type = "trigonometric",
sea.period = 7,
a1 = NULL,
P1 = NULL,
Q = NULL,
H = NULL
)
Returns dynamic Gompertz curve model.
y
The cumulated variable
q
The signal-to-noise ratio (ratio of slope to irregular
variance). Defaults to 'NULL'
, in which case no signal-to-noise
ratio will be imposed. Instead, it will be estimated.
sea.type
Seasonal type. Options are 'trigonometric'
and 'none'
. 'trigonometric'
will yield a model with a
trigonometric seasonal component and 'none'
will yield a model
with no seasonal component.
sea.period
The period of seasonality. For a day-of-the-week
effect with daily data, this would be 7. Not required if
sea.type = 'none'
.
a1
Optional parameter specifying the prior mean of the
states. Defaults to 'NULL'
. Leave as 'NULL'
for a diffuse
prior (no prior information). If a proper prior is to be specified, both
a1
and P1
must be given.
P1
Optional parameter specifying the prior mean of the
states. Defaults to 'NULL'
. Leave as 'NULL'
for a diffuse
prior (no prior information). If a proper prior is to be specified,
both a1
and P1
must be given.
Q
Optional parameter specifying the state error variances
where these are to be imposed rather than estimated. Defaults to
'NULL'
which will see the variances estimated.
H
Optional parameter specifying the irregular variance
where this is to be imposed rather than estimated. Defaults to
'NULL'
which will see the variance estimated.
The dynamic Gompertz with an integrated random walk (IRW) trend is
where is the cumulated variable,
,
and
where the observation disturbances and slope
disturbances
, are iid Normal and mutually independent.
Note that, the larger the signal-to-noise ratio,
,
the faster the slope changes in response to new observations. Conversely,
a lower signal-to-noise ratio induces smoothness.
For the model without seasonal terms (sea.type = 'none'
) the are
priors are
.
The diffuse prior has with
. Implementation of the diffuse prior is handled
by the package
KFAS
(Helske, 2017). Where the model has a seasonal
component (sea.type = 'trigonometric'
), the vector of prior means
and the prior covariance matrix
are extended
accordingly.
See the vignette for details of the variance matrix .
.
update(pars, model, q, sea.type)
Update method for Kalman filter to implement the dynamic Gompertz curve model. A maximum of 3 parameters are used to set the observation noise (1 parameter), the transition equation slope and seasonal noise. If q (signal to noise ratio) is not null then the slope noise is set using this ratio.
pars
Vector of parameters.
model
KFS
model object.
q
The signal-to-noise ratio (ratio of slope to irregular
variance).
sea.type
Seasonal type. Options are
'trigonometric'
and 'none'
.
KFS
model object.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate()
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate()
Class for dynamic Gompertz curve state space model object.
get_model(y, q = NULL, sea.type = 'trigonometric', sea.period = 7)
Retrieves the model object.
y
The cumulated variable.
q
The signal-to-noise ratio (ratio of slope to irregular
variance). Defaults to 'NULL'
, in which case no signal-to-noise ratio
will be imposed. Instead, it will be estimated.
sea.type
Seasonal type. Options are 'trigonometric'
and
'none'
. 'trigonometric'
will yield a model with a trigonometric
seasonal component and 'none'
will yield a model with no seasonal
component.
sea.period
The period of seasonality. For a day-of-the-week
effect with daily data, this would be 7. Not required if
sea.type = 'none'
.
KFS
model object.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate()
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") # Specify a model model <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005) # Estimate a specified model res <- model$estimate()
This class allows the implementation of the reinitialisation
procedure described in the vignette and summarised below.
Let denote the re-initialization date and
denote the
date at which the cumulative series is set to 0. As the growth rate of
cumulative cases is defined as
, we have:
where is the cumulative cases after re-initialization. We
choose to set the cumulative cases to zero at
,
such that the growth rate of cumulative cases is available from
onwards.
We reinitialise the model by specifying the prior distribution for the
initial states appropriately. See the vignette for details.
new(Y, q = NULL, reinit.date=NULL, original.results=NULL,
use.presample.info=TRUE)
Create an instance of the
SSModelDynGompertzReinit
class.
Y
The cumulated variable.
q
The signal-to-noise ratio (ratio of slope to irregular
variance). Defaults to 'NULL'
, in which case no signal-to-noise
ratio will be imposed. Instead, it will be estimated.
reinit.date
The reinitialisation date . Should be
specified as an object of class
"Date"
. Must be specified.
original.results
Rather than re-estimating the model up
to the reinit.date
, a FilterResults
class object can be
specified here and the parameters for the reinitialisation will be taken
from this object. Default is NULL
. This parameter is optional.
use.presample.info
Logical value denoting whether or
not to use information from before the reinitialisation date in the
reinitialisation procedure. Default is TRUE
. If FALSE
, the
model is estimated from scratch from the reinitialisation date and no
attempt to use information from before the reinitialisation date is made.
get_model(y, q=NULL, sea.type = NULL, sea.period)
Retrieves
the model object, which is a dynamic Gompertz curve model reinitialised at
self$reinit.date
.
y
The cumulated variable.
q
The signal-to-noise ratio (ratio of slope to irregular
variance). Defaults to 'NULL'
, in which case no signal-to-noise ratio
will be imposed. Instead, it will be estimated.
sea.type
Seasonal type. Options are 'trigonometric'
and
'none'
. 'trigonometric'
will yield a model with a
trigonometric seasonal component and 'none'
will yield a model with
no seasonal component.
sea.period
The period of seasonality. For a day-of-the-week
effect with daily data, this would be 7. Not required if
sea.type = 'none'
.
KFS
model object.
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2021-05-20") # Specify a model model.reinit <- SSModelDynGompertzReinit$new(Y = gauteng[idx.est], q = 0.005, reinit.date = as.Date("2021-04-29")) # Estimate a specified model res.reinit <- model.reinit$estimate() ## Alternatively, we could feed in a prior results object rather than a ## reinitialisation date. The results are identical to the above. # Specify initial model idx.orig <- zoo::index(gauteng) <= as.Date("2021-04-29") model.orig <- SSModelDynamicGompertz$new(Y = gauteng[idx.orig], q = 0.005) res.orig <- model.orig$estimate() # Estimate a specified model model.reinit2 <- SSModelDynGompertzReinit$new(Y = gauteng[idx.est], q = 0.005, reinit.date = as.Date("2021-04-29"), original.results = res.orig) res.reinit2 <- model.reinit2$estimate()
library(tsgc) data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2021-05-20") # Specify a model model.reinit <- SSModelDynGompertzReinit$new(Y = gauteng[idx.est], q = 0.005, reinit.date = as.Date("2021-04-29")) # Estimate a specified model res.reinit <- model.reinit$estimate() ## Alternatively, we could feed in a prior results object rather than a ## reinitialisation date. The results are identical to the above. # Specify initial model idx.orig <- zoo::index(gauteng) <= as.Date("2021-04-29") model.orig <- SSModelDynamicGompertz$new(Y = gauteng[idx.orig], q = 0.005) res.orig <- model.orig$estimate() # Estimate a specified model model.reinit2 <- SSModelDynGompertzReinit$new(Y = gauteng[idx.est], q = 0.005, reinit.date = as.Date("2021-04-29"), original.results = res.orig) res.reinit2 <- model.reinit2$estimate()
Function writes the following results to csv files which get
saved in the location specified in res.dir
: forecast new cases or
incidence variable, ; the filtered level and slope of
,
and
; filtered estimates of
and the
confidence intervals for these estimates.
write_results(res, res.dir, Y, n.ahead, confidence.level)
write_results(res, res.dir, Y, n.ahead, confidence.level)
res |
Results object estimated using the ‘estimate()’ method. |
res.dir |
File path to save the results to. |
Y |
Cumulated variable. |
n.ahead |
Number of periods ahead to forecast. |
confidence.level |
Confidence level to use for the confidence interval
on the forecasts |
A number of csv files saved in the directory specified in
res.dir
.
# Not run as do not wish to save to local disc when compiling documentation. # Below will run if copied and pasted into console. library(tsgc) library(here) res.dir <- tempdir() data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") res <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005)$estimate() tsgc::write_results( res=res, res.dir = res.dir, Y = gauteng[idx.est], n.ahead = 14, confidence.level = 0.68 )
# Not run as do not wish to save to local disc when compiling documentation. # Below will run if copied and pasted into console. library(tsgc) library(here) res.dir <- tempdir() data(gauteng,package="tsgc") idx.est <- zoo::index(gauteng) <= as.Date("2020-07-06") res <- SSModelDynamicGompertz$new(Y = gauteng[idx.est], q = 0.005)$estimate() tsgc::write_results( res=res, res.dir = res.dir, Y = gauteng[idx.est], n.ahead = 14, confidence.level = 0.68 )