diff --git a/.Rbuildignore b/.Rbuildignore index 72c2ccc3..675b9a69 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -4,6 +4,8 @@ .Rhistory .RData .gitignore +.git_diff_name-only +.git_ls-tree_r_name-only_HEAD ^\.github$ License.md diff --git a/DESCRIPTION b/DESCRIPTION index a3d2585e..b910dfa3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Package: MARSS Type: Package Title: Multivariate Autoregressive State-Space Modeling Version: 3.11.9 -Date: 2023-05-20 +Date: 2024-02-19 Depends: R (>= 3.5.0) Imports: generics (>= 0.1.2), graphics, grDevices, KFAS (>= 1.0.1), mvtnorm, nlme, stats, utils @@ -33,13 +33,13 @@ Description: The MARSS package provides maximum-likelihood parameter dynamic linear models, outlier and shock detection, and multivariate AR-p models. Online workshops (lectures, eBook, and computer labs) at . -License: GPL-3 + file LICENSE +License: GPL-2 LazyData: yes BuildVignettes: yes ByteCompile: TRUE URL: https://atsa-es.github.io/MARSS/ BugReports: https://github.com/atsa-es/MARSS/issues -RoxygenNote: 7.2.3 +RoxygenNote: 7.3.1 Roxygen: list(markdown = TRUE) Encoding: UTF-8 VignetteBuilder: knitr, utils diff --git a/LICENSE b/LICENSE deleted file mode 100644 index a47aa8d7..00000000 --- a/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -The MARSS package as a whole is distributed under GPL-3 (GNU GENERAL PUBLIC -LICENSE version 3). - -In addition this software has the following license addendum: - -Software code created by U.S. Government employees is not subject to -copyright in the United States (17 U.S.C. §105). The United State -s/Department of Commerce reserve all rights to seek and obtain copyright -protection in countries other than the United States for Software authored -in its entirety by the Department of Commerce. To this end, the Department -of Commerce hereby grants to Recipient a royalty-free, nonexclusive license -to use, copy, and create derivative works of the Software outside of the -United States. diff --git a/NEWS.md b/NEWS.md index acc52980..701919e4 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,12 +2,12 @@ output: html_document --- -# MARSS 3.11.9 (GitHub) +# MARSS 3.11.9 (CRAN 2024-02-19) -## ENHANCEMENT +Very minor cosmetic update. * Added the error message coming from a try-error to the message printed for the user. -* Updated to GPL-3 license. +* Fixed some Rd formatting errors that caused NOTEs on CRAN. # MARSS 3.11.8 (CRAN 2023-05-20) diff --git a/R/MARSS-methods.R b/R/MARSS-methods.R index fbaa1b1e..81fe7489 100644 --- a/R/MARSS-methods.R +++ b/R/MARSS-methods.R @@ -2,9 +2,9 @@ #' #' This is an internal function used by [MARSS()]. It is not #' intended for use by users but needs to be exported so -#' {marssTMB} can use it. Uses the method of a marssMLE class object. +#' the marssTMB package can use it. Uses the method of a marssMLE class object. #' Will call a function such as [MARSSkem()], [MARSSoptim()] in the -#' MARSS package or `MARSStmb()` in the {marssTMB} package. +#' MARSS package or `MARSStmb()` in the marssTMB package. #' @param x a [marssMLE] object. #' @param ... additional arguments for the fitting function MARSSfit <- function(x, ...) { diff --git a/R/MARSScv.R b/R/MARSScv.R index adac6f46..036e973c 100644 --- a/R/MARSScv.R +++ b/R/MARSScv.R @@ -11,7 +11,7 @@ #' that specifies initial values for the parameters. See also [MARSS.marxss()]. #' @param method Estimation method. MARSS provides an EM algorithm (`method="kem"`) #' (see [MARSSkem()]) and the BFGS algorithm (`method="BFGS"`) -#' (see [MARSSoptim()]). Fast TMB fitting provided by the companion package {marssTMB}. +#' (see [MARSSoptim()]). Fast TMB fitting provided by the companion package marssTMB. #' @param form The equation form used in the \code{MARSS()} call. The default is "marxss". #' See [MARSS.marxss()] or [MARSS.dfa()] #' @param silent Setting to TRUE(1) suppresses printing of full error messages, warnings, diff --git a/cran-comments.md b/cran-comments.md index 9a0ecc04..502848af 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -1,8 +1,10 @@ +This is a minor update to fix some formatting errors in Rd files. + ## Tested on OS -* `rhub::check_for_cran()` +* `rhub::check_for_cran()` on tar.gz * M1 MacBook -* R versions 4.3 and 4.2 +* R versions 4.3.2 ## R CMD check results @@ -21,20 +23,3 @@ This is correct. -─ checking CRAN incoming feasibility ... [20s] NOTE - Maintainer: 'Elizabeth Eli Holmes ' - -* New maintainer: - Elizabeth Eli Holmes - Old maintainer(s): - Elizabeth Holmes - NOAA Federal - -Correct. I changed to using Authors@R format - - -## revdepcheck results - -We checked 2 reverse dependencies, comparing R CMD check results across CRAN and dev versions of this package. - - * We saw 0 new problems - * We failed to check 0 packages diff --git a/inst/DEVELOPER_NOTES.md b/inst/DEVELOPER_NOTES.md index 6a642706..a8fe2ae9 100644 --- a/inst/DEVELOPER_NOTES.md +++ b/inst/DEVELOPER_NOTES.md @@ -4,7 +4,7 @@ The pkgdown webpage will be automatically updated whenever a push is made to the # Steps for a release -Once a release is ready, all tests done and documentation checked, the Makefile in `inst/doc` is run. I usually run one target at a time starting with `make movetovignettes`. Before doing this, I build the User Guide and run it through a few compressors: Adobe and then https://github.com/atsa-es/pdfsizeopt-readme. +Once a release is ready, all tests done and documentation checked, the Makefile in `inst/doc` is run. I usually run one target at a time starting with `make movetovignettes` then `make build` etc. This makefile will ensure that all the pieces of the tar.gz are in place. Before doing this, I build the User Guide and run it through a few compressors: Adobe and then https://github.com/atsa-es/pdfsizeopt-readme. ## Spellcheck the whole package diff --git a/inst/Makefile b/inst/Makefile index 27ef98d6..5b7e9af2 100644 --- a/inst/Makefile +++ b/inst/Makefile @@ -1,5 +1,5 @@ RM = rm -f -version = 3.11.8 +version = 3.11.9 GitHubdir = ~/Documents/GitHub tmpdir = ~/Dropbox diff --git a/inst/doc/Learning_MARSS.Rmd b/inst/doc/Learning_MARSS.Rmd new file mode 100644 index 00000000..286fca81 --- /dev/null +++ b/inst/doc/Learning_MARSS.Rmd @@ -0,0 +1,94 @@ +--- +title: "Learning MARSS" +link-citations: yes +pkgdown: + as_is: true +output: + rmarkdown::html_vignette: default + html_document: default +vignette: > + %\VignetteIndexEntry{Learning MARSS} + %\VignetteEncoding{UTF-8} + %\VignetteEngine{knitr::rmarkdown} +--- + +The MARSS R package: is part +of the [Applied Time Series Analysis](https://atsa-es.github.io/) for +Environmental Science suite of software and educational material for +time series analysis. See the GitHub repository for the [MARSS source +code](https://github.com/atsa-es/MARSS). For fast fitting to large datasets or DFA models, see our companion package, [marssTMB](https://atsa-es.github.io/marssTMB/). +
+
+ +# Documentation + +* [MARSS pkgdown site](https://atsa-es.github.io/MARSS/). + +# Tutorials + + + +* [Quick Start Guide](https://atsa-es.github.io/MARSS/articles/Quick_Start.html). +* [ATSA course website](https://atsa-es.github.io/atsa/) - We have + lectures and all material from our course on our course website. + Select the Lectures tab to find the lecture material and videos of + lectures. +* [ATSA lab book](https://atsa-es.github.io/atsa-labs/) - Many + applications are also covered in our Applied Time Series Analysis + book developed from the labs in our course. +* [2021 ATSA Lectures on + YouTube](https://www.youtube.com/playlist?list=PLA5yNsxyt7sC3B4qhj_sMgGWqWWaSerq-) +* The [User Guide on + CRAN](https://CRAN.R-project.org/package=MARSS/vignettes/UserGuide.pdf) included in the package has many examples of how to fit MARSS models to a variety of data sets. + +## For Statisticians + +For those who work on MARSS models. A good place to start might be the chapter at the end of the User Guide on the comparison of KFAS and MARSS outputs and terminology. Comparing the terminology between the two packages should help understanding the MARSS output. Similarly the chapter on StructTS will help understand the difference in notation and terminology. + +MARSS is designed to provide access to every possible conditional expectation of $\mathbf{X}$ and $\mathbf{Y}$. "Every possible" means all the temporal conditionings (time 1 to $t-1$, $t$ or $T$) and all the possible standardizations (none, marginal, Cholesky). It will return the standard errors for all of these combinations. The Residuals subsection in the KFAS chapter will compare the residual options in KFAS to the MARSS residuals. The KFAS terminology may be more familiar and a table in that chapter shows you what terminology is associated with what conditional expectation. Note, KFAS and MARSS give the same values. The difference is notation and terminology. + +The EM Derivation paper goes into the nitty-gritty of the underlying EM algorithm. The Residuals paper goes through the Residuals algorithms. All the help files for the functions that implement algorithms have the details for statisticians/developers. My notes on computing the Fisher Information matrix for MARSS are in a series of notes: [Notes on computing the Fisher Information matrix for MARSS models I-IV](https://eeholmes.github.io/posts/2016-5-18-FI-recursion-1/). + +# CITATION + +If you use MARSS results in publications, please cite the primary +citation: + +Holmes, E. E., Ward, E. J. and Wills, K. (2012) MARSS: Multivariate +Autoregressive State-space Models for Analyzing Time-series Data. The R +Journal. 4(1):11-19 + +You can also cite the package and user guide: + +Elizabeth E. Holmes, Eric J. Ward, Mark D. Scheuerell and Kellie Wills +(2023). MARSS: Multivariate Autoregressive State-Space Modeling. R +package version 3.11.7. + +Holmes, E. E., M. D. Scheuerell, and E. J. Ward (", year,") Analysis of +multivariate time-series using the MARSS package. Version ", +meta\$Version,". NOAA Fisheries, Northwest Fisheries Science Center, +2725 Montlake Blvd E., Seattle, WA 98112, DOI: 10.5281/zenodo.5781847 + +Type `citation("MARSS")` at the command line to get the most up to data +citations. + +### PUBLICATIONS {#pubs} + +To see our publications using MARSS models, see the [Applied Time Series +Analysis website](https://atsa-es.github.io/). + +### NOAA Disclaimer + +The MARSS R package is a scientific product and is not official +communication of the National Oceanic and Atmospheric Administration, or +the United States Department of Commerce. All NOAA code is provided on +an 'as is' basis and the user assumes responsibility for its use. Any +claims against the Department of Commerce or Department of Commerce +bureaus stemming from the use of this GitHub project will be governed by +all applicable Federal law. Any reference to specific commercial +products, processes, or services by service mark, trademark, +manufacturer, or otherwise, does not constitute or imply their +endorsement, recommendation or favoring by the Department of Commerce. +The Department of Commerce seal and logo, or the seal and logo of a DOC +bureau, shall not be used in any manner to imply endorsement of any +commercial product or activity by DOC or the United States Government. diff --git a/vignettes/Learning_MARSS.html b/inst/doc/Learning_MARSS.html similarity index 100% rename from vignettes/Learning_MARSS.html rename to inst/doc/Learning_MARSS.html diff --git a/vignettes/Quick_Start.R b/inst/doc/Quick_Start.R similarity index 100% rename from vignettes/Quick_Start.R rename to inst/doc/Quick_Start.R diff --git a/inst/doc/Quick_Start.Rmd b/inst/doc/Quick_Start.Rmd new file mode 100644 index 00000000..561d9f17 --- /dev/null +++ b/inst/doc/Quick_Start.Rmd @@ -0,0 +1,321 @@ +--- +title: "Quick Start Guide" +link-citations: yes +pkgdown: + as_is: true +output: + html_document: + toc: true + toc_float: true + number_sections: true + pdf_document: + citation_package: natbib + number_sections: true + extra_dependencies: + caption: ["labelfont={bf}"] + hyperref: ["unicode=true", "breaklinks=true"] + natbib: round + multirow: null + footmisc: bottom + amsmath: null + amsfonts: null + toc: true + toc_depth: 1 + rmarkdown::html_vignette: + toc: yes + toc_depth: 1 +vignette: > + %\VignetteIndexEntry{Quick Start Guide} + %\VignetteEncoding{UTF-8} + %\VignetteEngine{knitr::rmarkdown} +--- + +```{r, child='mathdefs.tex'} +``` + +# tldr; + +Put data (`y`) in a $n \times T$ matrix or ts/mts object. + +Specify each of the parameters in a list for the `model` argument. + +Fit with +``` +fit <- MARSS(y, model=list(...), method=c("kem", "BFGS", "TMB")) +``` +Choose one method from `c("kem", "BFGS", "TMB")`. + +*Specification of a properly constrained model with a unique solution is the responsibility of the user because the \{MARSS\} package has no way to tell if you have specified an insufficiently constrained model.* + +# The MARSS model + +The \{MARSS\} package fits multivariate autoregressive state-space (MARSS) models of the form: +\begin{equation} +\begin{gathered} +\xx_t = \BB_t\xx_{t-1} + \UU_t + \CC_t\cc_t + \GG_t\ww_t, \text{ where } \WW_t \sim \MVN(0,\QQ_t)\\ +\yy_t = \ZZ_t\xx_t + \AA_t + \DD_t\dd_t + \HH_t\vv_t, \text{ where } \VV_t \sim \MVN(0,\RR_t)\\ +\XX_1 \sim \MVN(\xixi,\LAM) \text{ or } \XX_0 \sim \MVN(\xixi,\LAM) +\end{gathered} +\end{equation} +$\cc$ and $\dd$ are inputs (aka, exogenous variables or covariates or indicator variables) and must have no missing values. The $\RR$, $\QQ$ and $\LAM$ variances can can have zeros on the diagonal to specify partially deterministic systems. This allows you to write MAR(p) models in MARSS form for example. See the User Guide. The \{MARSS\} package is designed to handle linear constraints within the parameter matrices. Linear constraint means you can write the elements of the matrix as a linear equation of all the other elements. See section below on linear constraints. + +Example: a mean-reverting random walk model with three observation time series: +\begin{gather} +\begin{bmatrix}x_1\\ x_2\end{bmatrix}_t += \begin{bmatrix}b&0\\ 0&b\end{bmatrix} +\begin{bmatrix}x_1\\ x_2\end{bmatrix}_{t-1} ++ \begin{bmatrix}w_1\\ w_2\end{bmatrix}_t, \quad +\begin{bmatrix}w_1\\ w_2\end{bmatrix}_t \sim \MVN\begin{pmatrix}\begin{bmatrix}0\\0\end{bmatrix},\begin{bmatrix}q_{11}&q_{12}\\ q_{12}&q_{22}\end{bmatrix} \end{pmatrix} +\\ +\begin{bmatrix}y_1\\y_2\\y_3\end{bmatrix}_t += \begin{bmatrix}1&1\\ 0&1\\ 1&0\end{bmatrix} +\begin{bmatrix}x_1\\x_2\end{bmatrix}_t ++ \begin{bmatrix}v_1\\ v_2\\ v_3\end{bmatrix}_t,\quad +\begin{bmatrix}v_1\\ v_2\\ v_3\end{bmatrix}_t \sim \MVN\begin{pmatrix}\begin{bmatrix}a_1\\ 0\\ 0\end{bmatrix}, + \begin{bmatrix}r_{11}&0&0\\ 0&r&0\\ 0&0&r\end{bmatrix} \end{pmatrix} +\\ +\begin{bmatrix}x_1\\ x_2\end{bmatrix}_0 \sim \MVN\begin{pmatrix}\begin{bmatrix}0\\ 0\end{bmatrix},\begin{bmatrix}1&0\\ 0&1\end{bmatrix} \end{pmatrix} +\end{gather} + +## Model specification + +Model specification is via a list with the structure of each of the model parameters: $\BB$, $\UU$, $\CC$, $\QQ$, +$\ZZ$, $\AA$, $\DD$, $\RR$, $\xixi$, and$\LAM$. There is a one-to-one correspondence between the model in \R and the math version of the model. The model written in matrix form is translated into equivalent matrices (or arrays if time-varying) in \R code. Matrices that combine fixed and estimated values are specified using a list matrix with numerical values for fixed values and character names for the estimated values. + +For the MARSS model above, this would be: +```{r} +B1 <- matrix(list("b",0,0,"b"),2,2) +U1 <- matrix(0,2,1) +Q1 <- matrix(c("q11","q12","q12","q22"),2,2) +Z1 <- matrix(c(1,0,1,1,1,0),3,2) +A1 <- matrix(list("a1",0,0),3,1) +R1 <- matrix(list("r11",0,0,0,"r",0,0,0,"r"),3,3) +pi1 <- matrix(0,2,1); V1=diag(1,2) +model.list <- list(B=B1,U=U1,Q=Q1,Z=Z1,A=A1,R=R1,x0=pi1,V0=V1,tinitx=0) +``` +The `tinitx` element tells MARSS whether the initial state for $x$ is at $t=1$ (`tinitx=1`) or $t=0$ (`tinitx=0`). + +MARSS has a number of text shortcuts for common parameter forms, such as `"diagonal and unequal"`; see below for the possible shortcuts. + +# Data and fitting + +## Data + +The data must be entered as a $n \times T$ matrix, or a `ts()` (or mts) object or vector (which will be converted to a $n \times T$ matrix). + +## Fit call + +The call to fit the model is. +```{r eval=FALSE} +fit <- MARSS(y, model=model.list) +``` +See `?MARSS` for all other arguments. The common ones are `method` to change the fitting method from default of EM (slow). See below. `control` is used to pass in a list to control fitting, e.g. `control=list(maxit=1000)` to increase maximum iterations if the fit does not converge. + +Example with simulated data: +```{r} +library(MARSS) +set.seed(1234) +x <- rbind(arima.sim(n=50,list(ar=0.95), sd=0.4), + arima.sim(n=50,list(ar=0.95), sd=.02)) +y <- Z1 %*% x + matrix(rnorm(3*50,0,0.1), 3, 50) +fit <- MARSS(y, model=model.list, silent=TRUE) +tidy(fit) +``` + +## Different fitting methods + +The EM algorithm in the \{MARSS\} package is in R and on top of that EM algorithms are famously slow. You can try `method="BFGS"` and see if that is faster. For some models, it will be much faster and for others slower. The companion package {[marssTMB](https://atsa-es.github.io/marssTMB/)} allows you to fit these models with TMB and will be the fastest, often much faster. Definitely if you are doing Dynamic Factor Analysis or working with large data sets, you will want to use {marssTMB}. +```{r eval=FALSE} +fit1 <- MARSS(y, model=model.list) +fit2 <- MARSS(y, model=model.list, method="BFGS") +fit3 <- MARSS(y, model=model.list, method="TMB") +``` +`method="BFGS"` and `method="TMB"` are both using quasi-Newton methods to optimize and these can be sensitive to initial conditions. You can run EM a few iterations use that as initial conditions for BFGS or TMB, and this will guard against poor initial conditions issues. + +```{r results="hide"} +fit1 <- MARSS(y, model=model.list, control = list(maxit=15)) +fit2 <- MARSS(y, model=model.list, method="BFGS", inits = fit1) +``` + +## Defaults for `model` list + +Form of the model list is `list(B=..., U=...)` etc. + +### `form="marxss"` + +For `form="marxss"` (the default), matrix names in the model list must be `B`, `U`, `C`, `c`, `Q`, +`Z`, `A`, `D`, `d`, `R`, `x0` ($\xixi$), and `V0` ($\LAM$), just like in the MARSS equation. There are defaults each parameter and you can leave off matrix names and the defaults will be used. Type `?MARSS.marxss` additional information. + +* `B="identity"` $m \times m$ identity matrix +* `U="unequal"` Each element in the $m \times 1$ matrix $\UU$ is estimated and allowed to be different. +* `Q="diagonal and unequal"` $\QQ$ is a diagonal matrix and each element on the diagonal is allowed to be different. +* `Z="identity"` $n \times n$ identity matrix thus in the default model each $y$ is associated with one $x$. +* `A="scaling"` If $\ZZ$ is identity, $\AA$ is zero. Otherwise, the first $y$ associated with a $x$ is set to 0 and the rest are estimated. +* `R="diagonal and equal"` $\RR$ is a diagonal matrix and each element on the diagonal is the same. +* `x0="unequal"` Each element in the $m \times 1$ matrix $\xixi$ is estimated and allowed to be different. +* `V0="zero"` $\LAM$ is set to zero thus $\xx_0$ is treated as an estimated parameter. +* `tinitx=0` The initial condition for $\xx$ is set at $t=0$. + +### `form="dfa"` + +Special form for fitting DFA models. Pass in `form="dfa"` to the `MARSS()` call. Typically only these would be in the model list: + +* `m=1` Number of factors. +* `R="diagonal and equal"` $\RR$ is a diagonal matrix and each element on the diagonal is the same. +* `d="zero"` If there are $p$ covariates, pass in as a $p \times T$ matrix. +* `D="unconstrained"` if covariates passed in. + +Defaults. + +* `Z` A special unconstrained matrix with the upper triangle (without the diagonal) set to zero. +* `Q="identity"` $\QQ$ is a diagonal matrix and each element on the diagonal is allowed to be different. +* `x0="zero"` Each element in the $m \times 1$ matrix $\xixi$ is estimated and allowed to be different. +* `V0=diag(5,n)` $\LAM$ is set to a diagonal matrix with 5 on the diagonal. +* `tinitx=0` The initial condition for $\xx$ is set at $t=0$. +* `B="identity"` $m \times m$ identity matrix +* `U="zero"` +* `A="zero"` + +# Showing the model fits and getting the parameters + +There are `plot.marssMLE()`, `autoplot.marssMLE()`, `print`, `summary`, `coef`, `fitted`, `residuals` and `predict` functions for marssMLE objects. `?print.MARSS` will show you how to get standard output from your fitted model objects and where that output is stored in the marssMLE object. See `coef.marssMLE()` for the different formats for displaying the estimated parameters. To see plots of your states and fits plus diagnostic plots, use `plot(fit)` or, better, `ggplot2::autoplot(fit)`. For summaries of the residuals (model and state), use the `residuals` function. See `?residuals.marssMLE`. To produce predictions and forecasts from a MARSS model, see `?predict.marssMLE`. + +# Tips and Troubleshooting + +## Tips + +Use `ggplot2::autoplot(fit)` (or `plot(fit)`) to see a series of standard plots and diagnostics for your model. Use `tidy(fit)` for parameter estimates or `coef(fit)`. Use `fitted(fit)` for model ($\yy$) estimates and `tsSmooth(fit)` for states ($\xx$) estimates. You can also use `fit$states` for the states. + +Let's say you specified your model with some text short-cuts, like `Q="unconstrained"`, but you want the list matrix for for a next step. `a <- summary(fit$model)` returns that list (invisibly). Because the model argument of `MARSS()` will understand a list of list matrices, you can pass in `model=a` to specify the model. `MARSSkfas(fit, return.kfas.model=TRUE)` will return your model in \{KFAS\} format (class SSModel), thus you can use all the functions available in the \{KFAS\} package on your model. + +## Troubleshooting + +Try `MARSSinfo()` if you get errors you don't understand or fitting is taking a long time to converge. When fitting a model with `MARSS()`, pass in `silent=2` to see what `MARSS()` is doing. This puts it in verbose mode. Use `fit=FALSE` to set up a model without fitting. Let's say you do `fit <- MARSS(..., fit=FALSE)`. Now you can do `summary(fit$model)` to see what `MARSS()` thinks you are trying to fit. + +You can also try `toLatex(fit$model)` to make a LaTeX file and pdf version of your model (saved in the working directory). This loads the \{Hmisc\} package (and all its dependencies) and requires that you are able to process LaTeX files. + +# More information and tutorials + +Many example analyses can be found in the MARSS User Guide ([pdf](https://CRAN.R-project.org/package=MARSS/vignettes/UserGuide.pdf)). In addition, recorded lectures and more examples on fitting multivariate models can be found at our course [website](https://atsa-es.github.io/atsa/) and in the ATSA course eBook [html](https://atsa-es.github.io/atsa-labs/). + +The MARSS User Guide starts with some tutorials on MARSS models and walks through many examples showing how to write multivariate time-series models in MARSS form. The User Guide also has vignettes: how to write AR(p) models in state-space form, dynamic linear models (regression models where the regression parameters are AR(p)), multivariate regression models with regression parameters that are time-varying and enter the non-AR part of your model or the AR part, detecting breakpoints using state-space models, and dynamic factor analysis. All of these can be written in MARSS form. It also has a series of vignettes on analysis of multivariate biological data. + +Background on the algorithms used in the \{MARSS\} package is included in the User Guide. + +# Shortcuts and all allowed model structures + +All parameters except `x0` and `V0` may be time-varying. If time-varying, then text shortcuts cannot be used. Enter as an array with the 3rd dimension being time. Time dimension must be 1 or equal to the number of time-steps in the data. + +The model list elements can have the following values: + +## `Z` + +Defaults to `"identity"`. Can be a text string, `"identity"`, `"unconstrained"`, `"diagonal and unequal"`, `"diagonal and equal"`, `"equalvarcov"`, or `"onestate"`, or a length $n$ vector of factors specifying which of the $m$ hidden state time series correspond to which of the n observation time series. May be specified as a $n \times m$ list matrix for general specification of both fixed and shared elements within the matrix. May also be specified as a numeric $n \times m$ matrix to use a custom fixed $\ZZ$. `"onestate"` gives a $n \times 1$ matrix of 1s. The text shortcuts all specify $n \times n$ matrices. + +## `B` + +Defaults to `"identity"`. Can be a text string, `"identity"`, `"unconstrained"`, `"diagonal and unequal"`, `"diagonal and equal"`, `"equalvarcov"`, `"zero"`. Can also be specified as a list matrix for general specification of both fixed and shared elements within the matrix. May also be specified as a numeric $m \times m$ matrix to use custom fixed $\BB$, but in this case all the eigenvalues of $\BB$ must fall in the unit circle. + +## `U` and `x0` + +Defaults to `"unequal"`. Can be a text string, `"unconstrained"`, `"equal"`, `"unequal"` or `"zero"`. May be specified as a $m \times 1$ list matrix for general specification of both fixed and shared elements within the matrix. May also be specified as a numeric $m \times 1$ matrix to use a custom fixed $\UU$ or $\xx_0$. + +## `A` + +Defaults to `"scaling"`. Can be a text string, `"scaling"` ,`"unconstrained"`, `"equal"`, "unequal" or "zero". May be specified as a n x 1 list matrix for general specification of both fixed and shared elements within the matrix. May also be specified as a numeric $n \times 1$ matrix to use a custom fixed $\AA$. Care must be taken so that the model is not under-constrained and unsolvable model. The default, `"scaling"`, only applies to $\ZZ$ matrices that are design matrices (only 1s and 0s and all rows sum to 1). When a column in $\ZZ$ has multiple 1s, the first row in the $\AA$ matrix associated with those $\ZZ$ rows is 0 and the other associated $\AA$ rows have an estimated value. This treats $\AA$ as an intercept where one intercept for each $\xx$ (hidden state) is fixed at 0 and any other intercepts associated with that $\xx$ have an estimated intercept. This ensures a solvable model when $\ZZ$ is a design matrix. + +## `Q`, `R` and `V0` + +Can be a text string, `"identity"`, `"unconstrained"`, `"diagonal and unequal"`, `"diagonal and equal"`, `"equalvarcov"`, "zero". May be specified as a list matrix for general specification of both fixed and shared elements within the matrix. May also be specified as a numeric matrix to use a custom fixed matrix. + +`V0` defaults to `"zero"`, which means that $\xx_0$ is treated as an estimated parameter. + +## `D` and `C` + +Defaults to `"zero"` or if no covariates, defaults to `"unconstrained"`. Can also be any of the options available for the variance matrices. + +## `d` and `c` + +Defaults to `"zero"`. Numeric matrix. No missing values allowed. Must have 1 column or the same number of columns as the data, The numbers of rows in must match the corresponding $\DD$ or $\CC$ matrix. + +## `G` and `H` + +Defaults to `"identity"`. Can be specified as a numeric matrix or array for time-varying cases. Size must match the corresponding $\QQ$ or $\RR$ matrix. + +# Covariates, Linear constraints and time-varying parameters + +## Covariates + +Inputs, aka covariates, are in $\cc$ and $\dd$. The are passed in via the model list and must be a numeric matrix (no missing values). $\CC$ and $\DD$ are the estimated parameters, aka covariate effects. + +Let's say you have temperature data and you want to include a linear effect of temperature that is different for each $\xx$ time series: +```{r} +temp <- matrix(rnorm(50, seq(0,1,1/50), 0.1),nrow=1) +C1 <- matrix(c("temp1","temp2"),2,1) +model.list$C <- C1 +model.list$c <- temp +``` +Fit as normal: +```{r results="hide"} +fit <- MARSS(y, model=model.list, method="BFGS") +``` + +A seasonal effect can be easily included via sine/cosine pairs. The `fourier()` function in the \{forecast\} package simplifies this. You will need to make your data into a ts/mts object. + +```{r} +yts <- ts(t(y), frequency = 12) # requires time down the rows +fcov <- forecast::fourier(yts,1) |> t() +``` + +If you want a factor effect, then you can use the `seasonaldummy()` function in \{forecast\} +```{r} +yts <- ts(t(y), frequency = 12) # monthly data +mcov <- forecast::seasonaldummy(yts) |> t() # month factor +``` + +## Linear constraints + +Your model can have simple linear constraints within all the parameters except $\QQ$, $\RR$ and $\LAM$. For example $1+2a-3b$ is a linear constraint. When entering this value for you matrix, you specify this as `"1+2*a+-3*b"`. NOTE: $+$'s join parts so `+-3*b` to specify $-3b$. Anything after `*` is a parameter. So `1*1` has a parameter called `"1"`. Example, let's change the $\BB$ and $\QQ$ matrices in the previous model to: +\begin{equation*} +\BB = \begin{bmatrix}b-0.1&0\\ 0&b+0.1\end{bmatrix}\quad +\QQ = \begin{bmatrix}1&0\\ 0&1\end{bmatrix}\quad +\ZZ = \begin{bmatrix}z_1-z_2&2 z_1\\ 0&z_1\\ z_2&0\end{bmatrix} +\end{equation*} +*$\QQ$ is fixed because $\ZZ$ is estimated and estimating both creates a statistically confounded model (both scale the variance of $\xx$).* + +This would be specified as (notice `"1*z1+-1*z2"` for `z1-z2`): +```{r} +B1 <- matrix(list("-0.1+1*b",0,0,"0.1+1*b"),2,2) +Q1 <- matrix(list(1,0,0,1),2,2) +Z1 <- matrix(list("1*z1+-1*z2",0,"z2","2*z1","z1",0),3,2) +model.list <- list(B=B1,U=U1,Q=Q1,Z=Z1,A=A1,R=R1,x0=pi1,V0=V1,tinitx=0) +``` + +Fit as usual: +```{r} +fit <- MARSS(y, model=model.list, silent = TRUE) +``` + +## Time-varying parameters + +The default model form allows you to pass in a 3-D array for a time-varying parameter ($T$ is the number of time-steps in your data and is the 3rd dimension in the array): +\begin{equation} +\begin{gathered} +\xx_t = \BB_t\xx_{t-1} + \UU_t + \CC_t\cc_t + \GG_t\ww_t, \quad +\WW_t \sim \MVN(0,\QQ_t)\\ +\yy_t = \ZZ_t\xx_t + \AA_t + \DD_t\dd_t + \HH_t\vv_t, \quad +\VV_t \sim \MVN(0,\RR_t)\\ +\xx_{t_0} \sim \MVN(\xixi,\LAM) +\end{gathered} +\end{equation} +Zeros are allowed on the diagonals of $\QQ$, $\RR$ and $\LAM$. NOTE(!!), the time indexing. Make sure you enter your arrays such that the correct parameter (or input) at time $t$ lines up with $\xx_t$; e.g., it is common for state equations to have $\BB_{t-1}$ lined up with $\xx_t$ so you might need to enter the $\BB$ array such that your $\BB_{t-1}$ is entered at `Bt[,,t]` in your \R code. + +The length of the 3rd dimension must be the same as your data. For example, say in your mean-reverting random walk model (the example on the first page) you wanted $\BB(2,2)$ to be one value before $t=20$ and another value after but $\BB(1,1)$ to be time constant. You can pass in the following: +```{r} +TT <- dim(y)[2] +B1 <- array(list(),dim=c(2,2,TT)) +B1[,,1:20] <- matrix(list("b",0,0,"b_1"),2,2) +B1[,,21:TT] <- matrix(list("b",0,0,"b_2"),2,2) +``` +Notice the specification is one-to-one to your $\BB_t$ matrices on paper. + diff --git a/vignettes/Quick_Start.html b/inst/doc/Quick_Start.html similarity index 73% rename from vignettes/Quick_Start.html rename to inst/doc/Quick_Start.html index 7ecf554e..9db9f3c1 100644 --- a/vignettes/Quick_Start.html +++ b/inst/doc/Quick_Start.html @@ -65,18 +65,12 @@ h6 {font-size: 12px;} code {color: inherit; background-color: rgba(0, 0, 0, 0.04);} pre:not([class]) { background-color: white } - +!function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)}(function(V){"use strict";V.ui=V.ui||{};V.ui.version="1.13.2";var n,i=0,a=Array.prototype.hasOwnProperty,r=Array.prototype.slice;V.cleanData=(n=V.cleanData,function(t){for(var e,i,s=0;null!=(i=t[s]);s++)(e=V._data(i,"events"))&&e.remove&&V(i).triggerHandler("remove");n(t)}),V.widget=function(t,i,e){var s,n,o,a={},r=t.split(".")[0],l=r+"-"+(t=t.split(".")[1]);return e||(e=i,i=V.Widget),Array.isArray(e)&&(e=V.extend.apply(null,[{}].concat(e))),V.expr.pseudos[l.toLowerCase()]=function(t){return!!V.data(t,l)},V[r]=V[r]||{},s=V[r][t],n=V[r][t]=function(t,e){if(!this||!this._createWidget)return new n(t,e);arguments.length&&this._createWidget(t,e)},V.extend(n,s,{version:e.version,_proto:V.extend({},e),_childConstructors:[]}),(o=new i).options=V.widget.extend({},o.options),V.each(e,function(e,s){function n(){return i.prototype[e].apply(this,arguments)}function o(t){return i.prototype[e].apply(this,t)}a[e]="function"==typeof s?function(){var t,e=this._super,i=this._superApply;return this._super=n,this._superApply=o,t=s.apply(this,arguments),this._super=e,this._superApply=i,t}:s}),n.prototype=V.widget.extend(o,{widgetEventPrefix:s&&o.widgetEventPrefix||t},a,{constructor:n,namespace:r,widgetName:t,widgetFullName:l}),s?(V.each(s._childConstructors,function(t,e){var i=e.prototype;V.widget(i.namespace+"."+i.widgetName,n,e._proto)}),delete s._childConstructors):i._childConstructors.push(n),V.widget.bridge(t,n),n},V.widget.extend=function(t){for(var e,i,s=r.call(arguments,1),n=0,o=s.length;n",options:{classes:{},disabled:!1,create:null},_createWidget:function(t,e){e=V(e||this.defaultElement||this)[0],this.element=V(e),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=V(),this.hoverable=V(),this.focusable=V(),this.classesElementLookup={},e!==this&&(V.data(e,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===e&&this.destroy()}}),this.document=V(e.style?e.ownerDocument:e.document||e),this.window=V(this.document[0].defaultView||this.document[0].parentWindow)),this.options=V.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:V.noop,_create:V.noop,_init:V.noop,destroy:function(){var i=this;this._destroy(),V.each(this.classesElementLookup,function(t,e){i._removeClass(e,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:V.noop,widget:function(){return this.element},option:function(t,e){var i,s,n,o=t;if(0===arguments.length)return V.widget.extend({},this.options);if("string"==typeof t)if(o={},t=(i=t.split(".")).shift(),i.length){for(s=o[t]=V.widget.extend({},this.options[t]),n=0;n
"),i=e.children()[0];return V("body").append(e),t=i.offsetWidth,e.css("overflow","scroll"),t===(i=i.offsetWidth)&&(i=e[0].clientWidth),e.remove(),s=t-i},getScrollInfo:function(t){var e=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),i=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),e="scroll"===e||"auto"===e&&t.widthx(k(s),k(n))?o.important="horizontal":o.important="vertical",u.using.call(this,t,o)}),a.offset(V.extend(h,{using:t}))})},V.ui.position={fit:{left:function(t,e){var i=e.within,s=i.isWindow?i.scrollLeft:i.offset.left,n=i.width,o=t.left-e.collisionPosition.marginLeft,a=s-o,r=o+e.collisionWidth-n-s;e.collisionWidth>n?0n?0")[0],w=d.each;function P(t){return null==t?t+"":"object"==typeof t?p[e.call(t)]||"object":typeof t}function M(t,e,i){var s=v[e.type]||{};return null==t?i||!e.def?null:e.def:(t=s.floor?~~t:parseFloat(t),isNaN(t)?e.def:s.mod?(t+s.mod)%s.mod:Math.min(s.max,Math.max(0,t)))}function S(s){var n=m(),o=n._rgba=[];return s=s.toLowerCase(),w(g,function(t,e){var i=e.re.exec(s),i=i&&e.parse(i),e=e.space||"rgba";if(i)return i=n[e](i),n[_[e].cache]=i[_[e].cache],o=n._rgba=i._rgba,!1}),o.length?("0,0,0,0"===o.join()&&d.extend(o,B.transparent),n):B[s]}function H(t,e,i){return 6*(i=(i+1)%1)<1?t+(e-t)*i*6:2*i<1?e:3*i<2?t+(e-t)*(2/3-i)*6:t}y.style.cssText="background-color:rgba(1,1,1,.5)",b.rgba=-1o.mod/2?s+=o.mod:s-n>o.mod/2&&(s-=o.mod)),l[i]=M((n-s)*a+s,e)))}),this[e](l)},blend:function(t){if(1===this._rgba[3])return this;var e=this._rgba.slice(),i=e.pop(),s=m(t)._rgba;return m(d.map(e,function(t,e){return(1-i)*s[e]+i*t}))},toRgbaString:function(){var t="rgba(",e=d.map(this._rgba,function(t,e){return null!=t?t:2").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e={width:i.width(),height:i.height()},n=document.activeElement;try{n.id}catch(t){n=document.body}return i.wrap(t),i[0]!==n&&!V.contains(i[0],n)||V(n).trigger("focus"),t=i.parent(),"static"===i.css("position")?(t.css({position:"relative"}),i.css({position:"relative"})):(V.extend(s,{position:i.css("position"),zIndex:i.css("z-index")}),V.each(["top","left","bottom","right"],function(t,e){s[e]=i.css(e),isNaN(parseInt(s[e],10))&&(s[e]="auto")}),i.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),i.css(e),t.css(s).show()},removeWrapper:function(t){var e=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),t[0]!==e&&!V.contains(t[0],e)||V(e).trigger("focus")),t}}),V.extend(V.effects,{version:"1.13.2",define:function(t,e,i){return i||(i=e,e="effect"),V.effects.effect[t]=i,V.effects.effect[t].mode=e,i},scaledDimensions:function(t,e,i){if(0===e)return{height:0,width:0,outerHeight:0,outerWidth:0};var s="horizontal"!==i?(e||100)/100:1,e="vertical"!==i?(e||100)/100:1;return{height:t.height()*e,width:t.width()*s,outerHeight:t.outerHeight()*e,outerWidth:t.outerWidth()*s}},clipToBox:function(t){return{width:t.clip.right-t.clip.left,height:t.clip.bottom-t.clip.top,left:t.clip.left,top:t.clip.top}},unshift:function(t,e,i){var s=t.queue();1").insertAfter(t).css({display:/^(inline|ruby)/.test(t.css("display"))?"inline-block":"block",visibility:"hidden",marginTop:t.css("marginTop"),marginBottom:t.css("marginBottom"),marginLeft:t.css("marginLeft"),marginRight:t.css("marginRight"),float:t.css("float")}).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).addClass("ui-effects-placeholder"),t.data(j+"placeholder",e)),t.css({position:i,left:s.left,top:s.top}),e},removePlaceholder:function(t){var e=j+"placeholder",i=t.data(e);i&&(i.remove(),t.removeData(e))},cleanUp:function(t){V.effects.restoreStyle(t),V.effects.removePlaceholder(t)},setTransition:function(s,t,n,o){return o=o||{},V.each(t,function(t,e){var i=s.cssUnit(e);0");l.appendTo("body").addClass(t.className).css({top:s.top-a,left:s.left-r,height:i.innerHeight(),width:i.innerWidth(),position:n?"fixed":"absolute"}).animate(o,t.duration,t.easing,function(){l.remove(),"function"==typeof e&&e()})}}),V.fx.step.clip=function(t){t.clipInit||(t.start=V(t.elem).cssClip(),"string"==typeof t.end&&(t.end=G(t.end,t.elem)),t.clipInit=!0),V(t.elem).cssClip({top:t.pos*(t.end.top-t.start.top)+t.start.top,right:t.pos*(t.end.right-t.start.right)+t.start.right,bottom:t.pos*(t.end.bottom-t.start.bottom)+t.start.bottom,left:t.pos*(t.end.left-t.start.left)+t.start.left})},Y={},V.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,t){Y[t]=function(t){return Math.pow(t,e+2)}}),V.extend(Y,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;t<((e=Math.pow(2,--i))-1)/11;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),V.each(Y,function(t,e){V.easing["easeIn"+t]=e,V.easing["easeOut"+t]=function(t){return 1-e(1-t)},V.easing["easeInOut"+t]=function(t){return t<.5?e(2*t)/2:1-e(-2*t+2)/2}});y=V.effects,V.effects.define("blind","hide",function(t,e){var i={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},s=V(this),n=t.direction||"up",o=s.cssClip(),a={clip:V.extend({},o)},r=V.effects.createPlaceholder(s);a.clip[i[n][0]]=a.clip[i[n][1]],"show"===t.mode&&(s.cssClip(a.clip),r&&r.css(V.effects.clipToBox(a)),a.clip=o),r&&r.animate(V.effects.clipToBox(a),t.duration,t.easing),s.animate(a,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("bounce",function(t,e){var i,s,n=V(this),o=t.mode,a="hide"===o,r="show"===o,l=t.direction||"up",h=t.distance,c=t.times||5,o=2*c+(r||a?1:0),u=t.duration/o,d=t.easing,p="up"===l||"down"===l?"top":"left",f="up"===l||"left"===l,g=0,t=n.queue().length;for(V.effects.createPlaceholder(n),l=n.css(p),h=h||n["top"==p?"outerHeight":"outerWidth"]()/3,r&&((s={opacity:1})[p]=l,n.css("opacity",0).css(p,f?2*-h:2*h).animate(s,u,d)),a&&(h/=Math.pow(2,c-1)),(s={})[p]=l;g").css({position:"absolute",visibility:"visible",left:-s*p,top:-i*f}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:p,height:f,left:n+(u?a*p:0),top:o+(u?r*f:0),opacity:u?0:1}).animate({left:n+(u?0:a*p),top:o+(u?0:r*f),opacity:u?1:0},t.duration||500,t.easing,m)}),V.effects.define("fade","toggle",function(t,e){var i="show"===t.mode;V(this).css("opacity",i?0:1).animate({opacity:i?1:0},{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("fold","hide",function(e,t){var i=V(this),s=e.mode,n="show"===s,o="hide"===s,a=e.size||15,r=/([0-9]+)%/.exec(a),l=!!e.horizFirst?["right","bottom"]:["bottom","right"],h=e.duration/2,c=V.effects.createPlaceholder(i),u=i.cssClip(),d={clip:V.extend({},u)},p={clip:V.extend({},u)},f=[u[l[0]],u[l[1]]],s=i.queue().length;r&&(a=parseInt(r[1],10)/100*f[o?0:1]),d.clip[l[0]]=a,p.clip[l[0]]=a,p.clip[l[1]]=0,n&&(i.cssClip(p.clip),c&&c.css(V.effects.clipToBox(p)),p.clip=u),i.queue(function(t){c&&c.animate(V.effects.clipToBox(d),h,e.easing).animate(V.effects.clipToBox(p),h,e.easing),t()}).animate(d,h,e.easing).animate(p,h,e.easing).queue(t),V.effects.unshift(i,s,4)}),V.effects.define("highlight","show",function(t,e){var i=V(this),s={backgroundColor:i.css("backgroundColor")};"hide"===t.mode&&(s.opacity=0),V.effects.saveStyle(i),i.css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(s,{queue:!1,duration:t.duration,easing:t.easing,complete:e})}),V.effects.define("size",function(s,e){var n,i=V(this),t=["fontSize"],o=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],a=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],r=s.mode,l="effect"!==r,h=s.scale||"both",c=s.origin||["middle","center"],u=i.css("position"),d=i.position(),p=V.effects.scaledDimensions(i),f=s.from||p,g=s.to||V.effects.scaledDimensions(i,0);V.effects.createPlaceholder(i),"show"===r&&(r=f,f=g,g=r),n={from:{y:f.height/p.height,x:f.width/p.width},to:{y:g.height/p.height,x:g.width/p.width}},"box"!==h&&"both"!==h||(n.from.y!==n.to.y&&(f=V.effects.setTransition(i,o,n.from.y,f),g=V.effects.setTransition(i,o,n.to.y,g)),n.from.x!==n.to.x&&(f=V.effects.setTransition(i,a,n.from.x,f),g=V.effects.setTransition(i,a,n.to.x,g))),"content"!==h&&"both"!==h||n.from.y!==n.to.y&&(f=V.effects.setTransition(i,t,n.from.y,f),g=V.effects.setTransition(i,t,n.to.y,g)),c&&(c=V.effects.getBaseline(c,p),f.top=(p.outerHeight-f.outerHeight)*c.y+d.top,f.left=(p.outerWidth-f.outerWidth)*c.x+d.left,g.top=(p.outerHeight-g.outerHeight)*c.y+d.top,g.left=(p.outerWidth-g.outerWidth)*c.x+d.left),delete f.outerHeight,delete f.outerWidth,i.css(f),"content"!==h&&"both"!==h||(o=o.concat(["marginTop","marginBottom"]).concat(t),a=a.concat(["marginLeft","marginRight"]),i.find("*[width]").each(function(){var t=V(this),e=V.effects.scaledDimensions(t),i={height:e.height*n.from.y,width:e.width*n.from.x,outerHeight:e.outerHeight*n.from.y,outerWidth:e.outerWidth*n.from.x},e={height:e.height*n.to.y,width:e.width*n.to.x,outerHeight:e.height*n.to.y,outerWidth:e.width*n.to.x};n.from.y!==n.to.y&&(i=V.effects.setTransition(t,o,n.from.y,i),e=V.effects.setTransition(t,o,n.to.y,e)),n.from.x!==n.to.x&&(i=V.effects.setTransition(t,a,n.from.x,i),e=V.effects.setTransition(t,a,n.to.x,e)),l&&V.effects.saveStyle(t),t.css(i),t.animate(e,s.duration,s.easing,function(){l&&V.effects.restoreStyle(t)})})),i.animate(g,{queue:!1,duration:s.duration,easing:s.easing,complete:function(){var t=i.offset();0===g.opacity&&i.css("opacity",f.opacity),l||(i.css("position","static"===u?"relative":u).offset(t),V.effects.saveStyle(i)),e()}})}),V.effects.define("scale",function(t,e){var i=V(this),s=t.mode,s=parseInt(t.percent,10)||(0===parseInt(t.percent,10)||"effect"!==s?0:100),s=V.extend(!0,{from:V.effects.scaledDimensions(i),to:V.effects.scaledDimensions(i,s,t.direction||"both"),origin:t.origin||["middle","center"]},t);t.fade&&(s.from.opacity=1,s.to.opacity=0),V.effects.effect.size.call(this,s,e)}),V.effects.define("puff","hide",function(t,e){t=V.extend(!0,{},t,{fade:!0,percent:parseInt(t.percent,10)||150});V.effects.effect.scale.call(this,t,e)}),V.effects.define("pulsate","show",function(t,e){var i=V(this),s=t.mode,n="show"===s,o=2*(t.times||5)+(n||"hide"===s?1:0),a=t.duration/o,r=0,l=1,s=i.queue().length;for(!n&&i.is(":visible")||(i.css("opacity",0).show(),r=1);l li > :first-child").add(t.find("> :not(li)").even())},heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},hideProps:{borderTopWidth:"hide",borderBottomWidth:"hide",paddingTop:"hide",paddingBottom:"hide",height:"hide"},showProps:{borderTopWidth:"show",borderBottomWidth:"show",paddingTop:"show",paddingBottom:"show",height:"show"},_create:function(){var t=this.options;this.prevShow=this.prevHide=V(),this._addClass("ui-accordion","ui-widget ui-helper-reset"),this.element.attr("role","tablist"),t.collapsible||!1!==t.active&&null!=t.active||(t.active=0),this._processPanels(),t.active<0&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():V()}},_createIcons:function(){var t,e=this.options.icons;e&&(t=V(""),this._addClass(t,"ui-accordion-header-icon","ui-icon "+e.header),t.prependTo(this.headers),t=this.active.children(".ui-accordion-header-icon"),this._removeClass(t,e.header)._addClass(t,null,e.activeHeader)._addClass(this.headers,"ui-accordion-icons"))},_destroyIcons:function(){this._removeClass(this.headers,"ui-accordion-icons"),this.headers.children(".ui-accordion-header-icon").remove()},_destroy:function(){var t;this.element.removeAttr("role"),this.headers.removeAttr("role aria-expanded aria-selected aria-controls tabIndex").removeUniqueId(),this._destroyIcons(),t=this.headers.next().css("display","").removeAttr("role aria-hidden aria-labelledby").removeUniqueId(),"content"!==this.options.heightStyle&&t.css("height","")},_setOption:function(t,e){"active"!==t?("event"===t&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(e)),this._super(t,e),"collapsible"!==t||e||!1!==this.options.active||this._activate(0),"icons"===t&&(this._destroyIcons(),e&&this._createIcons())):this._activate(e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",t),this._toggleClass(null,"ui-state-disabled",!!t),this._toggleClass(this.headers.add(this.headers.next()),null,"ui-state-disabled",!!t)},_keydown:function(t){if(!t.altKey&&!t.ctrlKey){var e=V.ui.keyCode,i=this.headers.length,s=this.headers.index(t.target),n=!1;switch(t.keyCode){case e.RIGHT:case e.DOWN:n=this.headers[(s+1)%i];break;case e.LEFT:case e.UP:n=this.headers[(s-1+i)%i];break;case e.SPACE:case e.ENTER:this._eventHandler(t);break;case e.HOME:n=this.headers[0];break;case e.END:n=this.headers[i-1]}n&&(V(t.target).attr("tabIndex",-1),V(n).attr("tabIndex",0),V(n).trigger("focus"),t.preventDefault())}},_panelKeyDown:function(t){t.keyCode===V.ui.keyCode.UP&&t.ctrlKey&&V(t.currentTarget).prev().trigger("focus")},refresh:function(){var t=this.options;this._processPanels(),!1===t.active&&!0===t.collapsible||!this.headers.length?(t.active=!1,this.active=V()):!1===t.active?this._activate(0):this.active.length&&!V.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=V()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var t=this.headers,e=this.panels;"function"==typeof this.options.header?this.headers=this.options.header(this.element):this.headers=this.element.find(this.options.header),this._addClass(this.headers,"ui-accordion-header ui-accordion-header-collapsed","ui-state-default"),this.panels=this.headers.next().filter(":not(.ui-accordion-content-active)").hide(),this._addClass(this.panels,"ui-accordion-content","ui-helper-reset ui-widget-content"),e&&(this._off(t.not(this.headers)),this._off(e.not(this.panels)))},_refresh:function(){var i,t=this.options,e=t.heightStyle,s=this.element.parent();this.active=this._findActive(t.active),this._addClass(this.active,"ui-accordion-header-active","ui-state-active")._removeClass(this.active,"ui-accordion-header-collapsed"),this._addClass(this.active.next(),"ui-accordion-content-active"),this.active.next().show(),this.headers.attr("role","tab").each(function(){var t=V(this),e=t.uniqueId().attr("id"),i=t.next(),s=i.uniqueId().attr("id");t.attr("aria-controls",s),i.attr("aria-labelledby",e)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(t.event),"fill"===e?(i=s.height(),this.element.siblings(":visible").each(function(){var t=V(this),e=t.css("position");"absolute"!==e&&"fixed"!==e&&(i-=t.outerHeight(!0))}),this.headers.each(function(){i-=V(this).outerHeight(!0)}),this.headers.next().each(function(){V(this).height(Math.max(0,i-V(this).innerHeight()+V(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.headers.next().each(function(){var t=V(this).is(":visible");t||V(this).show(),i=Math.max(i,V(this).css("height","").height()),t||V(this).hide()}).height(i))},_activate:function(t){t=this._findActive(t)[0];t!==this.active[0]&&(t=t||this.active[0],this._eventHandler({target:t,currentTarget:t,preventDefault:V.noop}))},_findActive:function(t){return"number"==typeof t?this.headers.eq(t):V()},_setupEvents:function(t){var i={keydown:"_keydown"};t&&V.each(t.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var e=this.options,i=this.active,s=V(t.currentTarget),n=s[0]===i[0],o=n&&e.collapsible,a=o?V():s.next(),r=i.next(),a={oldHeader:i,oldPanel:r,newHeader:o?V():s,newPanel:a};t.preventDefault(),n&&!e.collapsible||!1===this._trigger("beforeActivate",t,a)||(e.active=!o&&this.headers.index(s),this.active=n?V():s,this._toggle(a),this._removeClass(i,"ui-accordion-header-active","ui-state-active"),e.icons&&(i=i.children(".ui-accordion-header-icon"),this._removeClass(i,null,e.icons.activeHeader)._addClass(i,null,e.icons.header)),n||(this._removeClass(s,"ui-accordion-header-collapsed")._addClass(s,"ui-accordion-header-active","ui-state-active"),e.icons&&(n=s.children(".ui-accordion-header-icon"),this._removeClass(n,null,e.icons.header)._addClass(n,null,e.icons.activeHeader)),this._addClass(s.next(),"ui-accordion-content-active")))},_toggle:function(t){var e=t.newPanel,i=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=e,this.prevHide=i,this.options.animate?this._animate(e,i,t):(i.hide(),e.show(),this._toggleComplete(t)),i.attr({"aria-hidden":"true"}),i.prev().attr({"aria-selected":"false","aria-expanded":"false"}),e.length&&i.length?i.prev().attr({tabIndex:-1,"aria-expanded":"false"}):e.length&&this.headers.filter(function(){return 0===parseInt(V(this).attr("tabIndex"),10)}).attr("tabIndex",-1),e.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(t,i,e){var s,n,o,a=this,r=0,l=t.css("box-sizing"),h=t.length&&(!i.length||t.index()",delay:300,options:{icons:{submenu:"ui-icon-caret-1-e"},items:"> *",menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,this.lastMousePosition={x:null,y:null},this.element.uniqueId().attr({role:this.options.role,tabIndex:0}),this._addClass("ui-menu","ui-widget ui-widget-content"),this._on({"mousedown .ui-menu-item":function(t){t.preventDefault(),this._activateItem(t)},"click .ui-menu-item":function(t){var e=V(t.target),i=V(V.ui.safeActiveElement(this.document[0]));!this.mouseHandled&&e.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),e.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&i.closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":"_activateItem","mousemove .ui-menu-item":"_activateItem",mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(t,e){var i=this.active||this._menuItems().first();e||this.focus(t,i)},blur:function(t){this._delay(function(){V.contains(this.element[0],V.ui.safeActiveElement(this.document[0]))||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){this._closeOnDocumentClick(t)&&this.collapseAll(t,!0),this.mouseHandled=!1}})},_activateItem:function(t){var e,i;this.previousFilter||t.clientX===this.lastMousePosition.x&&t.clientY===this.lastMousePosition.y||(this.lastMousePosition={x:t.clientX,y:t.clientY},e=V(t.target).closest(".ui-menu-item"),i=V(t.currentTarget),e[0]===i[0]&&(i.is(".ui-state-active")||(this._removeClass(i.siblings().children(".ui-state-active"),null,"ui-state-active"),this.focus(t,i))))},_destroy:function(){var t=this.element.find(".ui-menu-item").removeAttr("role aria-disabled").children(".ui-menu-item-wrapper").removeUniqueId().removeAttr("tabIndex role aria-haspopup");this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeAttr("role aria-labelledby aria-expanded aria-hidden aria-disabled tabIndex").removeUniqueId().show(),t.children().each(function(){var t=V(this);t.data("ui-menu-submenu-caret")&&t.remove()})},_keydown:function(t){var e,i,s,n=!0;switch(t.keyCode){case V.ui.keyCode.PAGE_UP:this.previousPage(t);break;case V.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case V.ui.keyCode.HOME:this._move("first","first",t);break;case V.ui.keyCode.END:this._move("last","last",t);break;case V.ui.keyCode.UP:this.previous(t);break;case V.ui.keyCode.DOWN:this.next(t);break;case V.ui.keyCode.LEFT:this.collapse(t);break;case V.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case V.ui.keyCode.ENTER:case V.ui.keyCode.SPACE:this._activate(t);break;case V.ui.keyCode.ESCAPE:this.collapse(t);break;default:e=this.previousFilter||"",s=n=!1,i=96<=t.keyCode&&t.keyCode<=105?(t.keyCode-96).toString():String.fromCharCode(t.keyCode),clearTimeout(this.filterTimer),i===e?s=!0:i=e+i,e=this._filterMenuItems(i),(e=s&&-1!==e.index(this.active.next())?this.active.nextAll(".ui-menu-item"):e).length||(i=String.fromCharCode(t.keyCode),e=this._filterMenuItems(i)),e.length?(this.focus(t,e),this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}n&&t.preventDefault()},_activate:function(t){this.active&&!this.active.is(".ui-state-disabled")&&(this.active.children("[aria-haspopup='true']").length?this.expand(t):this.select(t))},refresh:function(){var t,e,s=this,n=this.options.icons.submenu,i=this.element.find(this.options.menus);this._toggleClass("ui-menu-icons",null,!!this.element.find(".ui-icon").length),e=i.filter(":not(.ui-menu)").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=V(this),e=t.prev(),i=V("").data("ui-menu-submenu-caret",!0);s._addClass(i,"ui-menu-icon","ui-icon "+n),e.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",e.attr("id"))}),this._addClass(e,"ui-menu","ui-widget ui-widget-content ui-front"),(t=i.add(this.element).find(this.options.items)).not(".ui-menu-item").each(function(){var t=V(this);s._isDivider(t)&&s._addClass(t,"ui-menu-divider","ui-widget-content")}),i=(e=t.not(".ui-menu-item, .ui-menu-divider")).children().not(".ui-menu").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),this._addClass(e,"ui-menu-item")._addClass(i,"ui-menu-item-wrapper"),t.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!V.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(t,e){var i;"icons"===t&&(i=this.element.find(".ui-menu-icon"),this._removeClass(i,null,this.options.icons.submenu)._addClass(i,null,e.submenu)),this._super(t,e)},_setOptionDisabled:function(t){this._super(t),this.element.attr("aria-disabled",String(t)),this._toggleClass(null,"ui-state-disabled",!!t)},focus:function(t,e){var i;this.blur(t,t&&"focus"===t.type),this._scrollIntoView(e),this.active=e.first(),i=this.active.children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",i.attr("id")),i=this.active.parent().closest(".ui-menu-item").children(".ui-menu-item-wrapper"),this._addClass(i,null,"ui-state-active"),t&&"keydown"===t.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),(i=e.children(".ui-menu")).length&&t&&/^mouse/.test(t.type)&&this._startOpening(i),this.activeMenu=e.parent(),this._trigger("focus",t,{item:e})},_scrollIntoView:function(t){var e,i,s;this._hasScroll()&&(i=parseFloat(V.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(V.css(this.activeMenu[0],"paddingTop"))||0,e=t.offset().top-this.activeMenu.offset().top-i-s,i=this.activeMenu.scrollTop(),s=this.activeMenu.height(),t=t.outerHeight(),e<0?this.activeMenu.scrollTop(i+e):s",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,liveRegionTimer:null,_create:function(){var i,s,n,t=this.element[0].nodeName.toLowerCase(),e="textarea"===t,t="input"===t;this.isMultiLine=e||!t&&this._isContentEditable(this.element),this.valueMethod=this.element[e||t?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(t){if(this.element.prop("readOnly"))s=n=i=!0;else{s=n=i=!1;var e=V.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:i=!0,this._move("previousPage",t);break;case e.PAGE_DOWN:i=!0,this._move("nextPage",t);break;case e.UP:i=!0,this._keyEvent("previous",t);break;case e.DOWN:i=!0,this._keyEvent("next",t);break;case e.ENTER:this.menu.active&&(i=!0,t.preventDefault(),this.menu.select(t));break;case e.TAB:this.menu.active&&this.menu.select(t);break;case e.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(t),t.preventDefault());break;default:s=!0,this._searchTimeout(t)}}},keypress:function(t){if(i)return i=!1,void(this.isMultiLine&&!this.menu.element.is(":visible")||t.preventDefault());if(!s){var e=V.ui.keyCode;switch(t.keyCode){case e.PAGE_UP:this._move("previousPage",t);break;case e.PAGE_DOWN:this._move("nextPage",t);break;case e.UP:this._keyEvent("previous",t);break;case e.DOWN:this._keyEvent("next",t)}}},input:function(t){if(n)return n=!1,void t.preventDefault();this._searchTimeout(t)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){clearTimeout(this.searching),this.close(t),this._change(t)}}),this._initSource(),this.menu=V("