diff --git a/.Rbuildignore b/.Rbuildignore index 683ff13..36b04dd 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -1,20 +1,18 @@ -^.*\.Rproj$ ^.*\.Rdata$ -^.*\.png$ +^.*\.Rproj$ +^.*tar.gz$ +^Makefile$ ^README.Rmd$ -^README_cache$ -^README/$ +^README/ ^\.DS_Store$ +^\.Rproj\.user$ ^\.travis\.yml$ -^packrat/ +^appveyor\.yml$ +^codecov\.yml$ +^cran-comments\.md$ ^data-ext/ ^docs/ -^wercker\.yml$ +^packrat/ +^readme-cache/ ^setup.r$ -^Makefile$ -^.*tar.gz$ -^\.Rproj\.user$ -^codecov\.yml$ -^appveyor\.yml$ -^cran-comments\.md$ - +^wercker\.yml$ diff --git a/.gitignore b/.gitignore index 00cf648..e641aed 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .Rproj.user -README_cache/ +dgo.Rcheck/ +*.tar.gz +readme-cache src/*.o src/*.so -src/include/models.hpp.bak diff --git a/DESCRIPTION b/DESCRIPTION index 85c2c07..91a2b1d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,11 +1,11 @@ Package: dgo Title: Dynamic Estimation of Group-Level Opinion -Version: 0.2.8 -Date: 2017-01-31 -Description: Fit dynamic group-level IRT models from individual or aggregated - item response data. This package handles common preprocessing tasks and extends - functions for inspecting results, poststratification, and quick iteration over - alternative models. Under active development. +Version: 0.2.9 +Date: 2017-05-21 +Description: Fit dynamic group-level IRT and MRP models from individual or + aggregated item response data. This package handles common preprocessing + tasks and extends functions for inspecting results, poststratification, and + quick iteration over alternative models. Maintainer: James Dunham Authors@R: c( person("James", "Dunham", email = "james@jdunham.io", role = c("aut", "cre")), @@ -18,29 +18,24 @@ BugReports: https://github.com/jamesdunham/dgo/issues Depends: dgodata, R (>= 3.2.2), - Rcpp (>= 0.11.0), - rstan (>= 2.8.1) + rstan (>= 2.15.1) LazyData: true Imports: assertthat, - concatenate, data.table, ggplot2, lubridate, methods, R6, + Rcpp (>= 0.12.10), survey Suggests: knitr, rmarkdown, testthat -LinkingTo: StanHeaders (>= 2.8.0), rstan (>= 2.8.1), BH (>= 1.58.0), Rcpp (>= - 0.11.0), RcppEigen -RcppModules: stan_fit42016_09_14_mod, stan_fit42016_04_20_mod, - stan_fit42015_12_16_mod, stan_fit42017_01_04_singleissue_mod, - stan_fit42017_01_04_mod +LinkingTo: Rcpp (>= 0.12.10) NeedsCompilation: yes -Collate: +Collate: 'RcppExports.R' 'aggregate_item_responses.r' 'assertions.r' @@ -51,14 +46,12 @@ Collate: 'class-dgirtin.r' 'class-dgmrp_fit.r' 'dgirt.r' - 'dgmrp.r' 'dichotomize_item_responses.r' 'expand_rownames.r' 'methods-control.r' 'methods-dgirtfit-plot.r' 'methods-dgirtfit-poststratify.r' 'methods-dgirtfit.r' - 'require_namespace.r' 'methods-dgirtin.r' 'name_helpers.r' 'package.R' @@ -66,10 +59,9 @@ Collate: 'restrict_input_data.r' 'reweight_item_responses.r' 'shape.r' - 'stanmodels.R' + 'shape_hierarchical.r' 'toy_dgirt_in.r' 'toy_dgirtfit.r' 'validate_dgirtIn.r' 'validate_input_data.r' - 'zzz.R' RoxygenNote: 6.0.1 diff --git a/Makefile b/Makefile index 05e4c1c..090293c 100644 --- a/Makefile +++ b/Makefile @@ -1,39 +1,53 @@ -# Makefile for development use - +PKG := $(shell head -1 DESCRIPTION | sed 's/Package: //' | cat) VERSION := $(shell sed -n 3p DESCRIPTION | sed 's/Version: //' | cat) -BINARY := dgo_$(VERSION).tar.gz +BINARY := $(PKG)_$(VERSION).tar.gz +MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST))) +CURRENT_DIR := $(notdir $(patsubst %/,%,$(dir $(MAKEFILE_PATH)))) +R_ARGS := --no-site-file --no-environ --no-save \ + --no-restore --no-resave-data --no-manual --quiet +ifneq (, $(findstring r-devel,$(CURRENT_DIR))) + R := R_devel.sh +else + R := R +endif + +all: clean build check install readme + +quick: clean -all: build check install readme doc +clean: + @rm -rf src/*.so src/*.o *tar.gz *Rcheck* build: - R --no-site-file --no-environ \ - --no-save --no-restore --quiet CMD build . \ - --no-resave-data --no-manual + $(R) $(R_ARGS) CMD build . +build-cran: + $(R) CMD build . --no-resave-data --no-manual + check: - R CMD check dgo_$(VERSION).tar.gz + $(R) CMD check $(PKG)_$(VERSION).tar.gz check-cran: - R CMD check --as-cran dgo_$(VERSION).tar.gz + $(R) CMD check --as-cran $(PKG)_$(VERSION).tar.gz -install: dgo_$(VERSION).tar.gz - R CMD INSTALL --no-multiarch --with-keep.source dgo_$(VERSION).tar.gz +check-quick $(PKG)_$(VERSION).tar.gz: + $(R) $(R_ARGS) CMD build . + $(R) CMD check $(PKG)_$(VERSION).tar.gz + +install: $(PKG)_$(VERSION).tar.gz + $(R) CMD INSTALL --no-multiarch --with-keep.source \ + $(PKG)_$(VERSION).tar.gz install-code: - R CMD INSTALL --no-multiarch --with-keep.source --no-docs . + $(R) CMD INSTALL --no-multiarch --with-keep.source --no-docs . -readme: dgo_$(VERSION).tar.gz - R --vanilla --slave -e "rmarkdown::render('README.Rmd')" +install-quick: + $(R) CMD INSTALL --no-multiarch --no-docs --no-html \ + --with-keep.source . -doc: dgo_$(VERSION).tar.gz - R CMD check --no-install --no-tests --no-examples dgo_$(VERSION).tar.gz +readme: $(PKG)_$(VERSION).tar.gz + $(R) --vanilla --slave -e "rmarkdown::render('README.Rmd')" -quick-install: - R CMD INSTALL --no-multiarch --no-docs --no-html \ - --with-keep.source . +docs: + $(R) --vanilla --slave -e "devtools::document()" -quick-check dgo_$(VERSION).tar.gz: - R --no-site-file --no-environ \ - --no-save --no-restore --quiet CMD build . \ - --no-resave-data --no-manual - R CMD check dgo_$(VERSION).tar.gz diff --git a/NAMESPACE b/NAMESPACE index 3311ded..ba5cc56 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -27,11 +27,6 @@ import(dgodata) import(ggplot2) import(methods) import(rstan) -importFrom(concatenate,cc) -importFrom(concatenate,cc_and) -importFrom(concatenate,cc_or) -importFrom(concatenate,cn) -importFrom(concatenate,cn_and) importFrom(lubridate,seconds_to_period) importFrom(stats,as.formula) importFrom(stats,formula) diff --git a/NEWS.md b/NEWS.md index d5f0c6d..51a2957 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,3 +1,16 @@ +# 0.2.9 + +* Switch from compiling Stan models at install time to compiling them at + runtime, avoiding an Rcpp module issue. +* Add `model` argument to `dgirt()` and `dgmrp()` taking for reuse a previously + compiled Stan model, as found in the `@stanmodel` slot of a `dgirt_fit`- or + `dgmrp_fit`-class object. +* The `version` argument to `dgirt()` and `dgmrp()` can be used to specify + arbitrary `.stan` files on the disk in addition to those included with the + package. +* Argument `by` to `get_n()` and `get_item_n()` methods properly accepts a + vector of variable names when combined with `aggregate` arguments. + # 0.2.8 * Improve Stan models for shorter run times diff --git a/R/class-dgirt_fit.r b/R/class-dgirt_fit.r index 84ac5a8..83931b0 100644 --- a/R/class-dgirt_fit.r +++ b/R/class-dgirt_fit.r @@ -26,9 +26,7 @@ #' apply(as.array(toy_dgirtfit, pars = 'xi'), 3, mean) #' #' # access the posterior samples -#' as.array(toy_dgirtfit, pars = 'theta_bar') -#' as.data.frame(toy_dgirtfit, pars = 'theta_bar') -#' extract(toy_dgirtfit, pars = 'theta_bar') +#' head(as.data.frame(toy_dgirtfit, pars = 'theta_bar')) dgirt_fit <- setClass("dgirt_fit", contains = c("dgo_fit")) #' Class \code{dgirtfit}: a class for fitted models diff --git a/R/class-dgirtin.r b/R/class-dgirtin.r index d979f05..c0ebfa6 100644 --- a/R/class-dgirtin.r +++ b/R/class-dgirtin.r @@ -9,6 +9,7 @@ #' @include constants.r #' @import R6 #' @examples +#' data(toy_dgirt_in) #' get_item_names(toy_dgirt_in) #' get_n(toy_dgirt_in) #' get_n(toy_dgirt_in, by = "year") @@ -54,4 +55,4 @@ dgirtIn <- R6::R6Class("dgirtIn", d_in_list }), private = list(model_objects = model_objects, - shape_objects = shape_objects)) \ No newline at end of file + shape_objects = shape_objects)) diff --git a/R/constants.r b/R/constants.r index 5ad5a37..f6011e8 100644 --- a/R/constants.r +++ b/R/constants.r @@ -4,8 +4,8 @@ model_objects <- c("NNl2", "SSl2", "XX", "ZZ", "ZZ_prior", "G", "Q", "T", "N", shape_objects <- c("gt_items", "group_grid", "group_grid_t", "group_counts", "item_data", "target_data", "aggregate_data", "modifier_data", - "control", "hier_names", "time_observed", "geo_observed", - "call", "mod_par_names", "unmod_par_names", "pkg_version") + "control", "hier_names", "call", "mod_par_names", + "unmod_par_names", "pkg_version") dgirt_pars <- c("separate_t", "delta_tbar_prior_mean", "delta_tbar_prior_sd", "innov_sd_delta_scale", "innov_sd_theta_scale", "version", diff --git a/R/dgirt.r b/R/dgirt.r index cfedd6f..1cbe6d5 100644 --- a/R/dgirt.r +++ b/R/dgirt.r @@ -1,21 +1,19 @@ -#' \code{dgirt}: fit a DGIRT model +#' \code{dgirt} and \code{dgmrp}: fit a DGIRT or single-issue MRP model #' -#' \code{dgirt} makes a call to \code{\link[rstan]{stan}} with the Stan code and -#' data for a DGIRT model. +#' \code{dgirt} and \code{dgmrp} make calls to \code{\link[rstan]{stan}} with +#' the Stan code and data for their respective models. #' #' The user will typically pass further arguments to \code{\link[rstan]{stan}} #' via the \code{...} argument, at a minimum \code{iter} and \code{cores}. #' -#' By default \code{dgirt} overrides the \code{\link[rstan]{stan}} default for -#' its \code{pars} argument to specify typical DGIRT parameters of interest. -#' \code{dgirt} also sets \code{iter_r} to \code{1L}. +#' By default \code{dgirt} and \code{dgmrp} override the +#' \code{\link[rstan]{stan}} default for its \code{pars} argument to specify +#' typical parameters of interest. They also set \code{iter_r} to \code{1L}. #' #' @param shaped_data Output from \code{\link{shape}}. +#' @param ... Further arguments, passed to \code{\link[rstan]{stan}}. #' @param separate_t Whether smoothing of estimates over time should be #' disabled. Default \code{FALSE}. -#' @param hierarchical_model Whether a hierarchical model should be used to -#' smooth the group IRT estimates. If set to FALSE, the model will return raw -#' group-IRT model estimates for each group. Default \code{TRUE}. #' @param delta_tbar_prior_mean Prior mean for \code{delta_tbar}, the normal #' weight on \code{theta_bar} in the previous period. Default \code{0.65}. #' @param delta_tbar_prior_sd Prior standard deviation for \code{delta_bar}. @@ -27,48 +25,136 @@ #' innovation standard deviation of \code{gamma}, \code{xi}, and if #' \code{constant_item} is \code{FALSE} the item difficulty \code{diff}. Default #' \code{2.5}. -#' @param version The version of the DGIRT model to use. -#' @param ... Further arguments passed to \code{\link[rstan]{stan}}. +#' @param version The name of the dgo model to estimate, or the path to a +#' \code{.stan} file. Valid names for dgo models are "2017_01_04", +#' "2017_01_04_singleissue". Ignored if argument \code{model} is used. +#' @param hierarchical_model Whether a hierarchical model should be used to +#' smooth the group IRT estimates. If set to FALSE, the model will return raw +#' group-IRT model estimates for each group. Default \code{TRUE}. +#' @param model A Stan model object of class `stanmodel` to be used in +#' estimation. Specifying this argument avoids repeated model compilation. Note +#' that the Stan model object for a model fitted with \code{dgirt()} or +#' \code{dgmrp()} can be found in the the \code{stanmodel} slot of the resulting +#' \code{dgirt_fit} or \code{dgmrp_fit} object. #' -#' @return A \code{\link{dgirtfit-class}} object that extends +#' @return A \code{\link{dgo_fit-class}} object that extends #' \code{\link[rstan]{stanfit-class}}. -#' @seealso \code{dgirt} expects \code{shaped_data} created by -#' \code{\link{shape}} and returns an object of class -#' \code{\link{dgirtfit-class}}. -#' \code{\link{dgirtfit-class}} \code{\link{shape}} #' +#' @aliases dgmrp #' @import rstan -#' @export #' @include constants.r -dgirt <- function(shaped_data, ..., separate_t = FALSE, delta_tbar_prior_mean = - 0.65, delta_tbar_prior_sd = 0.25, innov_sd_delta_scale = 2.5, - innov_sd_theta_scale = 2.5, version = "2017_01_04", - hierarchical_model = TRUE) { +#' @export +dgirt <- function(shaped_data, + ..., + separate_t = FALSE, + delta_tbar_prior_mean = 0.65, + delta_tbar_prior_sd = 0.25, + innov_sd_delta_scale = 2.5, + innov_sd_theta_scale = 2.5, + version = "2017_01_04", + hierarchical_model = TRUE, + model = NULL) { + + fit_dgo_model(model_output = "dgirt_fit", + shaped_data = shaped_data, + ..., + separate_t = separate_t, + delta_tbar_prior_mean = delta_tbar_prior_mean, + delta_tbar_prior_sd = delta_tbar_prior_sd, + innov_sd_delta_scale = delta_tbar_prior_sd, + innov_sd_theta_scale = innov_sd_theta_scale, + version = version, + hierarchical_model = hierarchical_model, + model = model) +} - dots <- list(..., object = stanmodels[[version]], data = - shaped_data$as_list(separate_t = separate_t, hierarchical_model = - hierarchical_model, delta_tbar_prior_mean = delta_tbar_prior_mean, - delta_tbar_prior_sd = delta_tbar_prior_sd, innov_sd_delta_scale = - innov_sd_delta_scale, innov_sd_theta_scale = innov_sd_theta_scale)) +#' @rdname dgirt +#' @export +dgmrp <- function(shaped_data, + ..., + separate_t = FALSE, + delta_tbar_prior_mean = 0.65, + delta_tbar_prior_sd = 0.25, + innov_sd_delta_scale = 2.5, + innov_sd_theta_scale = 2.5, + version = "2017_01_04_singleissue", + model = NULL) { - if (!length(dots$pars)) { - dots$pars <- default_pars + fit_dgo_model(model_output = "dgmrp_fit", + shaped_data = shaped_data, + ..., + separate_t = separate_t, + delta_tbar_prior_mean = delta_tbar_prior_mean, + delta_tbar_prior_sd = delta_tbar_prior_sd, + innov_sd_delta_scale = delta_tbar_prior_sd, + innov_sd_theta_scale = innov_sd_theta_scale, + version = version, + hierarchical_model = TRUE, + model = model) +} + +fit_dgo_model <- function(model_output, shaped_data, ..., separate_t, + delta_tbar_prior_mean, delta_tbar_prior_sd, innov_sd_delta_scale, + innov_sd_theta_scale, version, hierarchical_model, model) { + stopifnot(model_output %in% c("dgirt_fit", "dgmrp_fit")) + stopifnot(inherits(shaped_data, "dgirtIn")) + + dots <- list(..., data = + shaped_data$as_list(separate_t = separate_t, + hierarchical_model = hierarchical_model, + delta_tbar_prior_mean = delta_tbar_prior_mean, + delta_tbar_prior_sd = delta_tbar_prior_sd, + innov_sd_delta_scale = innov_sd_delta_scale, + innov_sd_theta_scale = innov_sd_theta_scale)) + + if (!length(model)) { + # No precompiled stanmodel object was given + model_file <- system.file(paste0("models/", version, ".stan"), package = "dgo") + if (model_file == "") { + # dgo model not found + if (file.exists(version)) { + model_file <- version + } else { + stop("'version' should give the name of a model included with dgo ", + "(see `?dgirt`) or the path to a .stan file") + } + } + stanc_ret = rstan::stanc(file = model_file) + message("Compiling model...") + model = rstan::stan_model(stanc_ret = stanc_ret) + message("Done.") + } else { + stopifnot(inherits(model, "stanmodel")) + } + dots$object = model + + if (model_output == "dgmrp_fit" && length(shaped_data$gt_items) > 1) { + stop("Multiple items in item data. Single-issue MRP models can only ", + "include one item.") } + if (!length(dots$init_r)) { dots$init_r <- 1L } - dots <- dots[!names(dots) %in% dgirt_pars] + + if (!length(dots$pars)) { + if (model_output == "dgmrp_fit") { + dots$pars <- default_pars_mrp + dots <- dots[!names(dots) %in% dgmrp_pars] + } else { + dots$pars <- default_pars + dots <- dots[!names(dots) %in% dgirt_pars] + } + } stanfit <- do.call(rstan::sampling, dots) - tryCatch(new("dgirt_fit", stanfit, dgirt_in = shaped_data, call = + tryCatch(new(model_output, stanfit, dgirt_in = shaped_data, call = match.call()), error = function(e) { - warning("Error constructing dgirt_fit; returning stanfit object instead") + warning("Error constructing dgo_fit; returning stanfit object instead: ", + e) stanfit - }) + }) } -models <- function() { - names(stanmodels) -} diff --git a/R/dgmrp.r b/R/dgmrp.r deleted file mode 100644 index 8ed8800..0000000 --- a/R/dgmrp.r +++ /dev/null @@ -1,68 +0,0 @@ -#' \code{dgmrp}: fit a single-issue MRP model, with hierarchical covariates -#' -#' \code{dgmrp} makes a call to \code{\link[rstan]{stan}} with the Stan code and -#' data for a dgmrp model. -#' -#' The user will typically pass further arguments to \code{\link[rstan]{stan}} -#' via the \code{...} argument, at a minimum \code{iter} and \code{cores}. -#' -#' By default \code{dgmrp} overrides the \code{\link[rstan]{stan}} default for -#' its \code{pars} argument to specify typical DGIRT parameters of interest. -#' \code{dgmrp} also sets \code{iter_r} to \code{1L}. -#' -#' @inheritParams dgirt -#' -#' @return A \code{\link{dgirtfit-class}} object that extends -#' \code{\link[rstan]{stanfit-class}}. -#' @seealso \code{dgmrp} expects \code{shaped_data} created by -#' \code{\link{shape}} and returns an object of class -#' \code{\link{dgirtfit-class}}. -#' \code{\link{dgirtfit-class}} \code{\link{shape}} -#' -#' @import rstan -#' @export -#' @include constants.r -dgmrp <- function(shaped_data, ..., separate_t = FALSE, delta_tbar_prior_mean = - 0.65, delta_tbar_prior_sd = 0.25, innov_sd_delta_scale = 2.5, - innov_sd_theta_scale = 2.5, version = "2017_01_04_singleissue") -{ - - dots <- list(..., - object = stanmodels[[version]], - data = shaped_data$as_list(separate_t = separate_t, - delta_tbar_prior_mean = - delta_tbar_prior_mean, - delta_tbar_prior_sd = - delta_tbar_prior_sd, - innov_sd_delta_scale = - innov_sd_delta_scale, - innov_sd_theta_scale = - innov_sd_theta_scale, - hierarchical_model=TRUE)) - - if (length(shaped_data$gt_items) > 1) { - stop("Multiple items in item data. Single-issue MRP models can only ", - "include one item.") - } - - if (!length(dots$pars)) { - dots$pars <- default_pars_mrp - } - if (!length(dots$init_r)) { - dots$init_r <- 1L - } - dots <- dots[!names(dots) %in% dgmrp_pars] - - stanfit <- do.call(rstan::sampling, dots) - - tryCatch(new("dgmrp_fit", stanfit, dgirt_in = shaped_data, call = - match.call()), - error = function(e) { - warning("Error constructing dgmrp_fit; returning stanfit object instead") - stanfit - }) -} - -models <- function() { - names(stanmodels) -} diff --git a/R/methods-dgirtfit-plot.r b/R/methods-dgirtfit-plot.r index dad6781..dd4665e 100644 --- a/R/methods-dgirtfit-plot.r +++ b/R/methods-dgirtfit-plot.r @@ -16,10 +16,13 @@ setGeneric("dgirt_plot", signature = "x", function(x, ...) #' @rdname plot-method #' @export #' @examples +#' \dontrun{ +#' data(toy_dgirtfit) #' dgirt_plot(toy_dgirtfit) #' dgirt_plot(toy_dgirtfit, y_min = NULL, y_max = NULL) #' p <- dgirt_plot(toy_dgirtfit) #' p %+% ylab("posterior median") +#' } setMethod("dgirt_plot", signature(x = "dgo_fit"), function(x, y_fun = "median", y_min = "q_025", y_max = "q_975", pars = "theta_bar") { assert(assertthat::is.string(pars)) @@ -45,9 +48,12 @@ setMethod("dgirt_plot", signature(x = "dgo_fit"), #' @rdname plot-method #' @export #' @examples +#' \dontrun{ +#' data(toy_dgirtfit) #' ps <- poststratify(toy_dgirtfit, annual_state_race_targets, strata_names = #' c("state", "year"), aggregated_names = "race3") #' dgirt_plot(ps, group_names = NULL, time_name = "year", geo_name = "state") +#' } setMethod("dgirt_plot", signature(x = "data.frame"), function(x, group_names, time_name, geo_name, y_fun = "median", y_min = "q_025", y_max = "q_975") { @@ -105,8 +111,10 @@ plot_internal <- function(samples, group_names, time_name, geo_name, y_fun, #' @rdname plot-method #' @export #' @examples -#' +#' \dontrun{ +#' data(toy_dgirtfit) #' plot(toy_dgirtfit) +#' } setMethod("plot", signature(x = "dgo_fit", y = "missing"), function(x, ...) { dgirt_plot(x, ...) @@ -128,9 +136,12 @@ setGeneric("plot_rhats", signature = "x", function(x, ...) #' @rdname plot-method #' @export #' @examples +#' \dontrun{ +#' data(toy_dgirtfit) #' plot_rhats(toy_dgirtfit) #' plot_rhats(toy_dgirtfit, facet_vars = "race3") + #' scale_x_continuous(breaks = seq.int(2006, 2008)) +#' } setMethod("plot_rhats", signature(x = "dgo_fit"), function(x, pars = "theta_bar", facet_vars = NULL, shape_var = NULL, color_var = NULL, x_var = NULL) { diff --git a/R/methods-dgirtfit-poststratify.r b/R/methods-dgirtfit-poststratify.r index 54ea2bf..c7ad422 100644 --- a/R/methods-dgirtfit-poststratify.r +++ b/R/methods-dgirtfit-poststratify.r @@ -65,26 +65,30 @@ setMethod("poststratify", "data.frame", assert(assertthat::is.string(proportion_name)) assert(all_strings(pars)) + if (anyDuplicated(c(strata_names, aggregated_names))) { + stop("Variable names cannot be used more than once across ", + "'strata_names' and 'aggregated_names'") + } + x <- data.table::setDT(data.table::copy(x)) if (!length(target_data)) stop("target_data is missing") targets <- data.table::setDT(data.table::copy(target_data)) missing_cols <- setdiff(strata_names, names(x)) - missing_msgs <- paste("%c", c("is", "are"), "in strata_names but", - c("isn't a name in", "aren't names in"), - c(rep(c("the table of estimates to be poststratified.", - "target_data"), each = 2L))) - if (length(missing_cols)) - stop(cn(missing_cols, missing_msgs[1], missing_msgs[2])) + if (length(missing_cols)) { + stop(paste(missing_cols, collapse = ", "), " in strata_names but ", + "not the table of estimates to be poststratified.") + } missing_cols <- setdiff(strata_names, names(target_data)) - if (length(missing_cols)) - stop(cn(missing_cols, missing_msgs[3], missing_msgs[4])) + if (length(missing_cols)) { + stop(paste(missing_cols, collapse = ", "), " in strata_names but ", + "not target_data.") + } targets_n <- nrow(unique(targets[, c(strata_names, aggregated_names), with = - FALSE])) + FALSE])) - # TODO: check more carefully than nrow() if (!identical(nrow(targets), targets_n)) { stop("Variables in aggregated_names should partition the strata ", "defined by the interaction of the variables in strata_names ", @@ -142,11 +146,10 @@ check_proportions <- function(tabular, strata_names) { prop_sums <- tabular[, lapply(.SD, sum), .SDcols = "scaled_prop", by = strata_names] if (!isTRUE(all.equal(rep(1L, nrow(prop_sums)), prop_sums$scaled_prop))) { - stop("Not all proportions sum to 1 within stratifying variables ", - cc_and(strata_names), " even though they should have been ", - "rescaled. (The mean sum is ", round(mean(prop_sums$scaled_prop), 2L), - "). This could indicate a problem in joining the estimates and ", - "targets or be a bug.") + stop("Not all proportions sum to 1 within stratifying variables even ", + " though they should have been rescaled. (The mean sum is ", + round(mean(prop_sums$scaled_prop), 2L), "). This could indicate a ", + "problem in joining the estimates and targets or be a bug.") } else TRUE } @@ -158,7 +161,7 @@ check_target_levels <- function(variable, x, targets) { } else if (!all(x[[variable]] %in% targets[[variable]])) { x_levels <- setdiff(x[[variable]], targets[[variable]]) stop("Not all levels of '", variable, "' in estimates are levels of '", - variable, "' in targets. ", cn_and(x_levels , "%c is ","%c are "), + variable, "' in targets. Missing: ", paste(x_levels , collapse = ", "), "missing. The target data should give the population proportion of each ", "group represented in the estimates.") } else TRUE diff --git a/R/methods-dgirtfit.r b/R/methods-dgirtfit.r index 8e30a94..8920ba4 100644 --- a/R/methods-dgirtfit.r +++ b/R/methods-dgirtfit.r @@ -43,8 +43,8 @@ print.dgo_fit <- function(x, ...) { cat(" Model version", x@model_name, "\n") cat(" ", nrow(ss), "parameters; ") cat(sum(grepl("^theta_bar", rownames(ss))), "theta_bars ") - cat("(", concatenate::cc_and(ctrl@time_name, ctrl@geo_name, - ctrl@group_names), ")", "\n", sep = "") + cat("(", paste(ctrl@time_name, ctrl@geo_name, + ctrl@group_names, collapse = ", "), ")", "\n", sep = "") cat(" ", x@dgirt_in$T, "periods", min(ctrl@time_filter), "to", max(ctrl@time_filter), "\n") @@ -112,6 +112,7 @@ setGeneric("summarize", signature = "x", #' @rdname dgo_fit-methods #' @export #' @examples +#' data(toy_dgirtfit) #' summarize(toy_dgirtfit) setMethod("summarize", "dgo_fit", function(x, pars = "theta_bar", @@ -137,6 +138,7 @@ do_funs <- function(value, funs) lapply(funs, function(f) do.call(f, value)) #' @export #' #' @examples +#' data(toy_dgirtfit) #' # access posterior samples #' as.data.frame(toy_dgirtfit, pars = 'theta_bar') as.data.frame.dgo_fit <- function(x, ..., pars = "theta_bar", @@ -192,6 +194,7 @@ setGeneric("rhats", signature = "x", function(x, ...) #' @export #' @rdname dgo_fit-methods #' @examples +#' data(toy_dgirtfit) #' rhats(toy_dgirtfit) setMethod("rhats", signature(x = "dgo_fit"), function(x, pars = "theta_bar") { diff --git a/R/methods-dgirtin.r b/R/methods-dgirtin.r index 053bb22..4f52381 100644 --- a/R/methods-dgirtin.r +++ b/R/methods-dgirtin.r @@ -9,7 +9,6 @@ setGeneric("summary") #' #' @rdname dgirtin-class #' @include class-dgirtin.r -#' @include require_namespace.r #' @export setMethod("summary", c(object = "dgirtIn"), function(object, ...) { @@ -53,6 +52,7 @@ setGeneric("get_item_names", signature = "x", #' #' @return A list of item names. #' @examples +#' data(toy_dgirt_in) #' get_item_names(toy_dgirt_in) #' @include class-dgirtin.r #' @rdname dgirtin-class @@ -78,17 +78,17 @@ setGeneric("get_n", signature = c("x", "by", "aggregate_name"), #' #' @examples #' # respondent count +#' data(toy_dgirt_in) #' get_n(toy_dgirt_in) #' #' # respondent count by year #' get_n(toy_dgirt_in, by = "year") #' -#' # respondent count by survey identifier -#' get_n(toy_dgirt_in, by = "source") +#' # respondent count by year and survey identifier +#' get_n(toy_dgirt_in, by = c("year", "source")) #' #' @seealso `\link{get_item_n}, \link{get_item_names}` #' @include class-dgirtin.r -#' @include require_namespace.r #' @aliases get_n #' @rdname dgirtin-class #' @export @@ -97,23 +97,22 @@ setMethod("get_n", c("x" = "dgirtIn"), if (!length(aggregate_name)) { n <- x$item_data[, list(n = .N), keyby = by] } else { - if (!length(x$aggregate_data)) - stop("Found no aggregate data") + stop_if_no_aggregates(x) if (!aggregate_name %chin% names(x$aggregate_data)) - stop(aggregate_name, "is not a name in aggregate data") + stop(aggregate_name, " is not a name in aggregate data") n <- x$aggregate_data[, list(n = sum(get("n_grp"), na.rm = TRUE)), keyby = c(aggregate_name, by)] - if (length(by)) { - f <- as.formula(paste(by, aggregate_name, sep = "~")) - n <- data.table::dcast(n, f, fun.aggregate = sum, value.var = "n") - } - # TODO: make sure that aggregate_data is restricted - n[, (setdiff(names(n), by)) := lapply(.SD, function(k) replace(k, is.na(k), 0L)), - .SDcols = setdiff(names(n), by)] + n <- cast_if_by(n, by) } - data.table::copy(n) + return(n) }) +stop_if_no_aggregates <- function(x) { + if (!length(x$aggregate_data)) { + stop("Found no aggregate data") + } +} + #' @rdname dgirtin-class setGeneric("get_item_n", signature = c("x", "by", "aggregate_data"), function(x, by = NULL, aggregate_data = FALSE) standardGeneric("get_item_n")) @@ -121,37 +120,45 @@ setGeneric("get_item_n", signature = c("x", "by", "aggregate_data"), #' Count Respondents for Items in DGIRT Data #' #' @include class-dgirtin.r -#' @include require_namespace.r #' @rdname dgirtin-class #' @examples +#' data(toy_dgirt_in) #' get_item_n(toy_dgirt_in) #' get_item_n(toy_dgirt_in, by = "year") #' @aliases get_item_n -#' @param aggregate_data If specified `get_n` will operate on the table passed +#' @param aggregate_data If specified `get_item_n` will operate on the table passed #' to `shape` as `aggregate_data` instead of on the individual data. #' @export setMethod("get_item_n", c("x" = "dgirtIn"), function(x, by = NULL, aggregate_data = FALSE) { if (!isTRUE(aggregate_data)) { n <- x$item_data[, lapply(.SD, function(z) sum(!is.na(z))), - .SDcols = x$control@item_names, keyby = by] + .SDcols = x$control@item_names, keyby = by] } else { - if (!length(x$aggregate_data)) - stop("Found no aggregate data") - n <- x$aggregate_data[, list(n = sum(get("n_grp"))), keyby = c("item", by)] - if (length(by)) { - f <- as.formula(paste(by, "item", sep = "~")) - n <- data.table::dcast(n, f, fun.aggregate = sum, value.var = "n") - } - n[, (setdiff(names(n), by)) := lapply(.SD, function(k) replace(k, is.na(k), 0L)), - .SDcols = setdiff(names(n), by)] + stop_if_no_aggregates(x) + n <- x$aggregate_data[, list(n = sum(get("n_grp"))), keyby = c("item", by)] + n <- cast_if_by(n, by) + n <- zero_nas(n, by) } - data.table::copy(n) + return(n) }) +cast_if_by <- function(n, by) { + if (length(by)) { + lhs <- paste(by, collapse = "+") + f <- as.formula(paste(lhs, "item", sep = "~")) + n <- data.table::dcast(n, f, fun.aggregate = sum, value.var = "n") + } + return(n) +} + +zero_nas <- function(n, by) { + n[, (setdiff(names(n), by)) := lapply(.SD, function(k) replace(k, is.na(k), 0L)), + .SDcols = setdiff(names(n), by)] +} + #' Show Summary of DGIRT Data #' @include class-dgirtin.r -#' @include require_namespace.r #' @rdname dgirtin-class #' @export -setMethod("show", c("dgirtIn"), function(object) summary(object)) \ No newline at end of file +setMethod("show", c("dgirtIn"), function(object) summary(object)) diff --git a/R/package.R b/R/package.R index cc0d442..9a4d521 100644 --- a/R/package.R +++ b/R/package.R @@ -1,6 +1,6 @@ #' dgo: Dynamic Estimation of Group-level Opinion #' -#' Fit dynamic group-level IRT models from individual or aggregated item +#' Fit dynamic group-level IRT and MRP models from individual or aggregated item #' response data. This package handles common preprocessing tasks and extends #' functions for inspecting results, poststratification, and quick iteration #' over alternative models. @@ -12,7 +12,6 @@ #' @import dgodata #' @import ggplot2 #' @import methods -#' @importFrom concatenate cc cc_and cc_or cn cn_and #' @importFrom lubridate seconds_to_period #' @importFrom stats as.formula formula model.frame model.matrix na.fail na.omit #' quantile sd setNames weighted.mean weights diff --git a/R/require_namespace.r b/R/require_namespace.r deleted file mode 100644 index 86b27a2..0000000 --- a/R/require_namespace.r +++ /dev/null @@ -1 +0,0 @@ -requireNamespace("data.table", quietly = TRUE) diff --git a/R/restrict_input_data.r b/R/restrict_input_data.r index be6b1f6..da2ab82 100644 --- a/R/restrict_input_data.r +++ b/R/restrict_input_data.r @@ -1,5 +1,4 @@ restrict_items <- function(item_data, ctrl) { - data.table::setDT(item_data) extra_colnames <- setdiff(names(item_data), c(ctrl@item_names, ctrl@survey_name, @@ -46,7 +45,6 @@ restrict_items <- function(item_data, ctrl) { restrict_modifier <- function(modifier_data, group_grid, ctrl) { if (length(modifier_data)) { - data.table::setDT(modifier_data) # apply as.character() to any factors varnames <- c(ctrl@modifier_names, ctrl@t1_modifier_names, ctrl@geo_name, @@ -76,15 +74,15 @@ restrict_modifier <- function(modifier_data, group_grid, ctrl) { stop("time and geo identifiers don't uniquely identify modifier data ", "observations") - # modifiers cannot have NA values - stop_if_any_na(modifier_data, varnames) - if (isTRUE(ctrl@standardize)) { # make modifiers zero-mean and unit-SD std_vars <- unique(c(ctrl@modifier_names, ctrl@t1_modifier_names)) modifier_data[, c(std_vars) := lapply(.SD, function(x) (x - mean(x)) / sd(x)), .SDcols = std_vars] } + + # modifiers cannot have NA values + stop_if_any_na(modifier_data, varnames) } invisible(modifier_data) } @@ -101,7 +99,6 @@ drop_extra_columns <- function(modifier_data, ctrl) { restrict_aggregates <- function(aggregate_data, ctrl) { if (length(aggregate_data)) { - data.table::setDT(aggregate_data) coerce_factors(aggregate_data, c(ctrl@group_names, ctrl@geo_name, ctrl@time_name)) diff --git a/R/shape.r b/R/shape.r index 3ae9617..4e18740 100644 --- a/R/shape.r +++ b/R/shape.r @@ -1,9 +1,9 @@ #' \code{shape}: prepare data for modeling with \code{dgirt} or \code{dgmrp} #' -#' This function shapes various kinds of data for use in a dgirt model. Most -#' arguments give the name or names of key variables in the data; they end in -#' \code{_name} or \code{_names} and should be character vectors. Some others -#' implement preprocessing and modeling choices. +#' This function shapes data for use in a dgirt or dgmrp model. Most +#' arguments give the name or names of key variables in the data. These +#' arguments end in \code{_name} or \code{_names} and should be character +#' vectors. #' #' @section Item Response Data: #' Individual-level data giving item responses is expected as argument @@ -27,7 +27,7 @@ #' The data given by \code{aggregate_data} must be in a long table of trial and #' success counts indexed by item, group, and time period. The variable names #' given by arguments \code{group_names}, \code{geo_name}, and\code{time_name} -#' should exist in \code{aggregate_data}. Three fixed variable names must also +#' should exist in \code{aggregate_data}. Three fixed variable names must also #' appear in \code{aggregate_data}: \code{item} giving item identifiers, #' \code{n_grp} giving counts of item-response trials, and \code{s_grp} giving #' counts of item-response successes. These counts should be adjusted @@ -138,9 +138,6 @@ #' # check sparseness of data to be modeled #' get_item_n(shaped_responses, by = "year") #' -#' @import data.table -#' @seealso \code{\link{dgirtin-class}} \code{\link{dgirtfit-class}} -#' @include require_namespace.r #' @export shape <- function(item_data, item_names, @@ -191,7 +188,11 @@ shape <- function(item_data, constant_item = constant_item, ...) - d_in <- dgirtIn$new(ctrl) + # setDT copies of *_data + item_data <- set_copy_dt(item_data) + aggregate_data <- set_copy_dt(aggregate_data) + modifier_data <- set_copy_dt(modifier_data) + target_data <- set_copy_dt(target_data) # validate inputs # check_targets(target_data, ctrl) @@ -203,11 +204,8 @@ shape <- function(item_data, item_data <- restrict_items(item_data, ctrl) ctrl@item_names <- intersect(ctrl@item_names, names(item_data)) aggregate_data <- restrict_aggregates(aggregate_data, ctrl) - ctrl@aggregate_item_names <- - ctrl@aggregate_item_names[ctrl@aggregate_item_names %chin% - aggregate_data$item] - d_in$time_observed <- get_observed(item_data, aggregate_data, ctrl@time_name) - d_in$geo_observed <- get_observed(item_data, aggregate_data, ctrl@geo_name) + ctrl@aggregate_item_names <- intersect(ctrl@aggregate_item_names, + aggregate_data$item) # rake survey weights # if (length(target_data)) { @@ -215,11 +213,33 @@ shape <- function(item_data, ctrl@weight_name <- "raked_weight" } + d_in <- init_dgirt_in(item_data, aggregate_data, modifier_data, target_data, + ctrl) + d_in$call <- match.call() + d_in$pkg_version <- packageVersion("dgo") + + # validate input to model # + check_dimensions(d_in) + check_values(d_in) + check_names(d_in) + + d_in +} + +set_copy_dt <- function(input_data) { + if (length(input_data)) { + return(data.table::setDT(data.table::copy(input_data))) + } else { + return(NULL) + } +} + +init_dgirt_in <- function(item_data, aggregate_data, modifier_data, target_data, + ctrl) { + d_in <- dgirtIn$new(ctrl) + # aggregate individual item response data to group level # item_data <- dichotomize(item_data, ctrl) - # this assignment should be redundant, but without it some variables created - # in dichotomize() weren't appearing in item_data - d_in$group_grid <- make_group_grid(item_data, aggregate_data, ctrl) d_in$group_grid_t <- make_group_grid_t(d_in$group_grid, ctrl) d_in$group_counts <- make_group_counts(item_data, aggregate_data, ctrl) @@ -235,23 +255,23 @@ shape <- function(item_data, d_in$s_vec <- setNames(d_in$group_counts$s_grp, d_in$group_counts$name) d_in$G <- nrow(unique(d_in$group_counts[, c(ctrl@geo_name, ctrl@group_names), - with = FALSE])) + with = FALSE])) d_in$G_hier <- ifelse(!length(modifier_data), nlevels(gl(1L, d_in$G)), - max(unlist(length(ctrl@modifier_names)), 1L)) + max(unlist(length(ctrl@modifier_names)), 1L)) d_in$T <- length(ctrl@time_filter) d_in$Q <- length(d_in$gt_items) + # not yet implemented d_in$WT <- array(1, dim = c(d_in$T, d_in$G_hier, d_in$G)) - d_in$l2_only <- matrix(0L, nrow = length(ctrl@time_filter), ncol = d_in$Q) d_in$NNl2 <- array(0L, dim = c(d_in$T, d_in$Q, d_in$G_hier)) d_in$SSl2 <- d_in$NNl2 d_in$XX <- make_design_matrix(d_in, ctrl) - d_in$ZZ <- shape_hierarchical_data(item_data, modifier_data, d_in, ctrl, - t1 = FALSE) - d_in$ZZ_prior <- shape_hierarchical_data(item_data, modifier_data, d_in, ctrl, - t1 = TRUE) + d_in$ZZ <- shape_hierarchical_data(modifier_data, ctrl@modifier_names, + d_in$group_grid_t, d_in$XX, ctrl) + d_in$ZZ_prior <- shape_hierarchical_data(modifier_data, + ctrl@t1_modifier_names, d_in$group_grid_t, d_in$XX, ctrl) d_in$hier_names <- dimnames(d_in$ZZ)[[2]] d_in$D <- ifelse(ctrl@constant_item, 1L, d_in$T) @@ -259,95 +279,15 @@ shape <- function(item_data, d_in$P <- ncol(d_in$ZZ) d_in$S <- length(unique(d_in$group_grid[[ctrl@geo_name]])) - 1 d_in$H <- dim(d_in$ZZ)[[3]] - #d_in$Hprior <- d_in$H d_in$Hprior <- dim(d_in$ZZ_prior)[[3]] - # include subset data and other objects that may be useful later # d_in$item_data <- item_data d_in$modifier_data <- modifier_data d_in$aggregate_data <- aggregate_data d_in$target_data <- target_data d_in$control <- ctrl - d_in$call <- match.call() - d_in$pkg_version <- packageVersion("dgo") - - # validate input to model # - check_dimensions(d_in) - check_values(d_in) - check_names(d_in) - - d_in -} - -shape_hierarchical_data <- function(item_data, modifier_data, d_in, ctrl, t1) { - - if (isTRUE(t1)) { - modifier_names <- ctrl@t1_modifier_names - } else { - modifier_names <- ctrl@modifier_names - } - if (!length(modifier_names)) { - modifier_names <- NA - } - - if (!length(modifier_data) | any(is.na(modifier_names))) { - zz.names <- list(ctrl@time_filter, dimnames(d_in$XX)[[2]], "") - zz <- array(data = 0, dim = lapply(zz.names, length), dimnames = zz.names) - } else { - # the array of hierarchical data ZZ should be T x P x H, where T is the - # number of time periods, P is the number of hierarchical parameters - # (including the geographic), and H is the number of predictors for - # geographic unit effects - - hier_frame <- data.table::copy(modifier_data) - - extra_colnames <- setdiff(names(hier_frame), - c(ctrl@geo_name, ctrl@time_name, modifier_names)) - if (length(extra_colnames)) { - hier_frame[, c(extra_colnames) := NULL] - } - - # NOTE: We create param by renaming geo_name. Thus the requirement to model - # geographic predictors. - hier_frame[, c("param", ctrl@geo_name) := list(hier_frame[[ctrl@geo_name]], - NULL)] - data.table::setkeyv(hier_frame, c("param", ctrl@time_name)) - all(ctrl@time_filter %in% hier_frame$D_year) - - # "param" is just the unique values of the geo var at the moment - modeled_param_names <- unique(hier_frame[, get("param")]) - - # unmodeled param levels will be those of groups - unmodeled_param_levels = unlist(lapply(d_in$unmod_par_names, function(x) { - paste0(x, unique(d_in$group_grid_t[[x]]))[-1] - })) - param_levels <- c(modeled_param_names, unmodeled_param_levels) - - # make a zeroed table for unmodeled parameters by time period - unmodeled_frame <- expand.grid(c(list(unmodeled_param_levels, - ctrl@time_filter), rep(list(0L), - length(modifier_names)))) - unmodeled_frame <- setNames(unmodeled_frame, c("param", ctrl@time_name, - modifier_names)) - data.table::setDT(unmodeled_frame, key = c("param", ctrl@time_name)) - - hier_frame <- rbind(hier_frame, unmodeled_frame) - - zz <- sapply(modifier_names, function(x) { - matrix(hier_frame[[x]], - # We have T rows, so filling by column is correct SO - # LONG AS time varies fastest then param in - # hier_frame - nrow = length(unique(hier_frame[[ctrl@time_name]])), - ncol = length(unique(hier_frame$param)), - dimnames = list(unique(hier_frame[[ctrl@time_name]]), - unique(hier_frame$param))) - }, simplify = 'array') - # omit first geo parameter - zz <- zz[, -1, , drop = FALSE] - } - zz + return(d_in) } make_design_matrix <- function(d_in, ctrl) { @@ -368,8 +308,6 @@ make_design_matrix <- function(d_in, ctrl) { colnames(design_matrix)) design_matrix <- subset(design_matrix, select = -1) - - # TODO: move to S4 validate invalid_values <- setdiff(as.vector(design_matrix), c(0, 1)) if (length(invalid_values)) { stop("design matrix values should be in (0, 1); found ", diff --git a/R/shape_hierarchical.r b/R/shape_hierarchical.r new file mode 100644 index 0000000..eb2b084 --- /dev/null +++ b/R/shape_hierarchical.r @@ -0,0 +1,64 @@ +shape_hierarchical_data <- function(modifier_data, modifier_names, group_grid_t, + XX, ctrl) { + # The array of hierarchical data ZZ should be T x P x H, where T is the + # number of time periods, P is the number of hierarchical parameters + # (including the geographic), and H is the number of predictors for + # geographic unit effects. + if (!length(modifier_names)) { + return(zero_zz(XX, ctrl)) + } + hierarchical <- data.table::copy(modifier_data) + hierarchical <- drop_extra_cols(hierarchical, modifier_names, ctrl) + data.table::setkeyv(hierarchical, c(ctrl@geo_name, ctrl@time_name)) + unmodeled <- zero_unmodeled(hierarchical, modifier_names, group_grid_t, ctrl) + hierarchical <- rbind(hierarchical, unmodeled) + zz <- create_zz(hierarchical, modifier_names, ctrl) + return(zz) +} + +zero_zz <- function(XX, ctrl) { + zz_dimnames <- list(ctrl@time_filter, dimnames(XX)[[2]], "") + zz <- array(data = 0, dim = lapply(zz_dimnames, length), dimnames = + zz_dimnames) + zz +} + +drop_extra_cols <- function(hierarchical, modifier_names, ctrl) { + extra_colnames <- setdiff(names(hierarchical), c(ctrl@geo_name, + ctrl@time_name, modifier_names)) + if (length(extra_colnames)) { + hierarchical[, c(extra_colnames) := NULL] + } + hierarchical +} + +zero_unmodeled <- function(hierarchical, modifier_names, group_grid_t, ctrl) { + # make a zeroed table for unmodeled parameters by time period + modeled_param_names <- unique(hierarchical[[ctrl@geo_name]]) + # unmodeled param levels will be those of groups + unmodeled_param_levels = unlist(lapply(ctrl@group_names, function(x) { + paste0(x, unique(group_grid_t[[x]]))[-1] + })) + unmodeled_frame <- expand.grid(c(list(unmodeled_param_levels, + ctrl@time_filter), rep(list(0L), length(modifier_names)))) + unmodeled_frame <- setNames(unmodeled_frame, c(ctrl@geo_name, ctrl@time_name, + modifier_names)) + data.table::setDT(unmodeled_frame, key = c(ctrl@geo_name, ctrl@time_name)) + unmodeled_frame +} + +create_zz <- function(hierarchical, modifier_names, ctrl) { + unique_time <- unique(hierarchical[[ctrl@time_name]]) + unique_geo <- unique(hierarchical[[ctrl@geo_name]]) + zz <- sapply(modifier_names, function(x) { + matrix(hierarchical[[x]], + # We have T rows, so filling by column is correct SO LONG AS time varies + # fastest then geo in hierarchical + nrow = length(unique_time), ncol = length(unique_geo), + dimnames = list(unique_time, unique_geo)) + }, simplify = 'array') + # omit first geo parameter + zz <- zz[, -1, , drop = FALSE] + zz +} + diff --git a/R/stanmodels.R b/R/stanmodels.R deleted file mode 100644 index 4cd7769..0000000 --- a/R/stanmodels.R +++ /dev/null @@ -1,40 +0,0 @@ -# Part of the rstanarm package for estimating model parameters -# Copyright (C) 2015, 2016 Trustees of Columbia University -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 3 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - -# This file is only intended to be used during the installation process -# nocov start -MODELS_HOME <- "exec" -if (!file.exists(MODELS_HOME)) MODELS_HOME <- sub("R$", "exec", getwd()) - -stan_files <- dir(MODELS_HOME, pattern = "stan$", full.names = TRUE) -stanmodels <- sapply(stan_files, function(f) { - model_cppname <- sub("\\.stan$", "", basename(f)) - isystem <- system.file("chunks", package = methods::getPackageName(environment(), FALSE)) - if (!file.exists(file.path(isystem, "common_functions.stan"))) - isystem <- file.path("inst", "chunks") - if (!file.exists(file.path(isystem, "common_functions.stan"))) - isystem <- file.path("..", "inst", "chunks") - stanfit <- rstan::stanc_builder(f, isystem) - stanfit$model_cpp <- list(model_cppname = stanfit$model_name, - model_cppcode = stanfit$cppcode) - return(do.call(methods::new, args = c(stanfit[-(1:3)], Class = "stanmodel", - mk_cppmodule = function(x) get(paste0("model_", model_cppname))))) - } -) -names(stanmodels) <- sub("\\.stan$", "", basename(names(stanmodels))) -rm(MODELS_HOME) -# nocov end diff --git a/R/sysdata.rda b/R/sysdata.rda deleted file mode 100644 index 5541df4..0000000 Binary files a/R/sysdata.rda and /dev/null differ diff --git a/R/toy_dgirt_in.r b/R/toy_dgirt_in.r index 3635bac..670a88c 100644 --- a/R/toy_dgirt_in.r +++ b/R/toy_dgirt_in.r @@ -8,6 +8,4 @@ #' @name toy_dgirt_in #' @usage toy_dgirt_in #' @format A \code{\link[dgo]{dgirtin-class}} object. -#' @examples -#' toy_dgirt_in NULL diff --git a/R/toy_dgirtfit.r b/R/toy_dgirtfit.r index ba1b16f..8a07ea9 100644 --- a/R/toy_dgirtfit.r +++ b/R/toy_dgirtfit.r @@ -8,6 +8,4 @@ #' @name toy_dgirtfit #' @usage toy_dgirtfit #' @format A \code{\link[dgo]{dgirtfit-class}} object. -#' @examples -#' toy_dgirtfit NULL diff --git a/R/validate_input_data.r b/R/validate_input_data.r index 0296a4a..1682334 100644 --- a/R/validate_input_data.r +++ b/R/validate_input_data.r @@ -104,7 +104,7 @@ has_type <- function(slots, where, ctrl, valid_types = var_types) { v_class <- class(where[[v]]) if (!any(v_valid_types %in% v_class)) { stop(slot_name, " \"", v, "\"", " is ", v_class, " in ", tab_name, - " but should be ", cc_or(v_valid_types)) + " but should be one of: ", paste(v_valid_types, collapse = ", ")) } } diff --git a/R/zzz.R b/R/zzz.R deleted file mode 100644 index 6ece088..0000000 --- a/R/zzz.R +++ /dev/null @@ -1,5 +0,0 @@ -.onLoad <- function(libname, pkgname) { - assertthat::assert_that(assertthat::not_empty(stanmodels)) - modules <- paste0("stan_fit4", names(stanmodels), "_mod") - for (m in modules) Rcpp::loadModule(m, what = TRUE) -} diff --git a/README.Rmd b/README.Rmd index 4e87316..38aad08 100644 --- a/README.Rmd +++ b/README.Rmd @@ -5,6 +5,7 @@ output: --- [![Build Status](https://travis-ci.org/jamesdunham/dgo.svg?branch=master)](https://travis-ci.org/jamesdunham/dgo) [![Build status](https://ci.appveyor.com/api/projects/status/1ta36kmoqen98k87?svg=true)](https://ci.appveyor.com/project/jamesdunham/dgo) +[![codecov](https://codecov.io/gh/jamesdunham/dgo/branch/master/graph/badge.svg)](https://codecov.io/gh/jamesdunham/dgo) dgo is an R package for the dynamic estimation of group-level opinion. The package can be used to estimate subpopulation groups' average latent @@ -36,25 +37,24 @@ knitr::opts_chunk$set( echo = TRUE, collapse = TRUE, comment = "#>", - fig.path = "README/", - cache = FALSE) + cache = TRUE, + cache.path = 'readme-cache/', + fig.path = "README/") ``` -# Prerequisites - -Installation requires [RStan](http://mc-stan.org/interfaces/rstan.html) and its -prerequisites, in particular a C++ toolchain. If you don't have RStan, follow -its "[Getting -Started](https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started)" guide -before continuing. - # Installation +dgo requires a working installation of [RStan](http://mc-stan.org/interfaces/rstan.html). +If you don't have already have RStan, follow its +"[Getting Started](https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started)" +guide before continuing. + dgo can be installed from [GitHub](https://github.com/jamesdunham/dgo) using [devtools](https://github.com/hadley/devtools/): ```{r, eval = FALSE} -devtools::install_github("jamesdunham/dgo", dependencies = TRUE) +if (!require(devtools, quietly = TRUE)) install.packages("devtools") +devtools::install_github("jamesdunham/dgo") ``` # Getting started @@ -137,8 +137,8 @@ be passed to RStan's `stan` via the `...` argument of `dgirt` and `dgmrp`. This will almost always be desirable, at a minimum to specify the number of sampler iterations, chains, and cores. -```{r, warning = FALSE} -dgirt_out_abortion <- dgmrp(dgirt_in_abortion, iter = 1500, chains = 4, cores = +```{r, warning = FALSE, message = FALSE, results = 'hide'} +dgmrp_out_abortion <- dgmrp(dgirt_in_abortion, iter = 1500, chains = 4, cores = 4, seed = 42) ``` @@ -151,7 +151,7 @@ But dgo provides its own methods for typical post-estimation tasks. For a high-level summary of the result, use `summary`. ```{r} -summary(dgirt_out_abortion) +summary(dgmrp_out_abortion) ``` To summarize posterior samples, use `summarize`. The default output gives @@ -160,7 +160,7 @@ the latent outcome for the groups defined by time, local geographic area, and the demographic characteristics specified in the earlier call to `shape`. ```{r} -head(summarize(dgirt_out_abortion)) +head(summarize(dgmrp_out_abortion)) ``` Alternatively, `summarize` can apply arbitrary functions to posterior samples @@ -169,7 +169,7 @@ with quotes. For convenience, `"q_025"` and `"q_975"` give the 2.5th and 97.5th posterior quantiles. ```{r} -summarize(dgirt_out_abortion, pars = "xi", funs = "var") +summarize(dgmrp_out_abortion, pars = "xi", funs = "var") ``` To access posterior samples in tabular form use `as.data.frame`. By default, @@ -177,7 +177,7 @@ this method returns post-warmup samples for the `theta_bar` parameters, but like other methods takes a `pars` argument. ```{r} -head(as.data.frame(dgirt_out_abortion)) +head(as.data.frame(dgmrp_out_abortion)) ``` To poststratify the results use `poststratify`. The following example uses the @@ -187,7 +187,7 @@ and aggregate estimates to strata defined by state-years. Read `help("poststratify")` for more details. ```{r} -poststratify(dgirt_out_abortion, annual_state_race_targets, strata_names = +poststratify(dgmrp_out_abortion, annual_state_race_targets, strata_names = c("state", "year"), aggregated_names = "race3") ``` @@ -196,17 +196,21 @@ samples by time period. By default, it shows a 95% credible interval around posterior medians for the `theta_bar` parameters, for each local geographic area. For this (unconverged) toy example we omit the CIs. -```{r} -dgirt_plot(dgirt_out_abortion, y_min = NULL, y_max = NULL) +```{r dgmrp_plot, fig.show = 'hide'} +dgirt_plot(dgmrp_out_abortion, y_min = NULL, y_max = NULL) ``` +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgmrp_plot-1.png) + Output from `dgirt_plot` can be customized to some extent using objects from the ggplot2 package. -```{r} -dgirt_plot(dgirt_out_abortion, y_min = NULL, y_max = NULL) + theme_classic() +```{r dgmrp_plot_plus, fig.show = 'hide'} +dgirt_plot(dgmrp_out_abortion, y_min = NULL, y_max = NULL) + theme_classic() ``` +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgmrp_plot_plus-1.png) + `dgirt_plot` can also plot the `data.frame` output from `poststratify`. This requires arguments that identify the relevant variables in the `data.frame`. Below, `poststratify` aggregates over the demographic grouping variable `race3`, @@ -215,13 +219,15 @@ call to `dgirt_plot`, we pass the names of the state and year variables. The `group_names` argument is `NULL` because there are no grouping variables left after aggregating over `race3`. -```{r} -ps <- poststratify(dgirt_out_abortion, annual_state_race_targets, strata_names = +```{r dgmrp_plot_ps, fig.show = 'hide'} +ps <- poststratify(dgmrp_out_abortion, annual_state_race_targets, strata_names = c("state", "year"), aggregated_names = "race3") head(ps) dgirt_plot(ps, group_names = NULL, time_name = "year", geo_name = "state") ``` +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgmrp_plot_ps-1.png) + ## Policy Liberalism ### Prepare input data with `shape` @@ -259,7 +265,7 @@ be passed to RStan's `stan` via the `...` argument of `dgirt` and `dgmrp`. This will almost always be desirable, at a minimum to specify the number of sampler iterations, chains, and cores. -```{r, warning = FALSE} +```{r, warning = FALSE, message = FALSE, results = 'hide'} dgirt_out_liberalism <- dgirt(dgirt_in_liberalism, iter = 3000, chains = 4, cores = 4, seed = 42) ``` @@ -317,10 +323,12 @@ samples by time period. By default, it shows a 95% credible interval around posterior medians for the `theta_bar` parameters, for each local geographic area. For this (unconverged) toy example we omit the CIs. -```{r} +```{r dgirt_plot, fig.show = 'hide'} dgirt_plot(dgirt_out_liberalism, y_min = NULL, y_max = NULL) ``` +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgirt_plot-1.png) + `dgirt_plot` can also plot the `data.frame` output from `poststratify`. This requires arguments that identify the relevant variables in the `data.frame`. Below, `poststratify` aggregates over the demographic grouping variable `race3`, @@ -329,13 +337,15 @@ call to `dgirt_plot`, we pass the names of the state and year variables. The `group_names` argument is `NULL` because there are no grouping variables left after aggregating over `race3`. -```{r} +```{r dgirt_plot_ps, fig.show = 'hide'} ps <- poststratify(dgirt_out_liberalism, annual_state_race_targets, strata_names = c("state", "year"), aggregated_names = "race3") head(ps) dgirt_plot(ps, group_names = NULL, time_name = "year", geo_name = "state") ``` +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgirt_plot_ps-1.png) + ## Troubleshooting Please [report issues](https://github.com/jamesdunham/dgo/issues) that you @@ -362,6 +372,13 @@ tempdir() #> [1] "/var/folders/2p/_d3c95qd6ljg28j1f5l2jqxm0000gn/T//Rtmp38a10A" ``` +Models fitted before October 2016 (specifically < +[#8e6a2cf](https://github.com/jamesdunham/dgo/commit/8e6a2cfbe00b2cd4a908b3067241e06124d143cd)) +using dgirtfit are not fully compatible with dgo. Their contents can be +extracted without using dgo, however, with the `$` indexing operator. For +example: `as.data.frame(dgirtfit_object$stan.cmb)`. + + ## Contributing and citing dgo is under development and we welcome diff --git a/README.md b/README.md index 7207b55..e534514 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![Build Status](https://travis-ci.org/jamesdunham/dgo.svg?branch=master)](https://travis-ci.org/jamesdunham/dgo) [![Build status](https://ci.appveyor.com/api/projects/status/1ta36kmoqen98k87?svg=true)](https://ci.appveyor.com/project/jamesdunham/dgo) +[![Build Status](https://travis-ci.org/jamesdunham/dgo.svg?branch=master)](https://travis-ci.org/jamesdunham/dgo) [![Build status](https://ci.appveyor.com/api/projects/status/1ta36kmoqen98k87?svg=true)](https://ci.appveyor.com/project/jamesdunham/dgo) [![codecov](https://codecov.io/gh/jamesdunham/dgo/branch/master/graph/badge.svg)](https://codecov.io/gh/jamesdunham/dgo) dgo is an R package for the dynamic estimation of group-level opinion. The package can be used to estimate subpopulation groups' average latent conservatism (or other latent trait) from individuals' responses to dichotomous questions using a Bayesian group-level IRT approach developed by [Caughey and Warshaw 2015](http://pan.oxfordjournals.org/content/early/2015/02/04/pan.mpu021.full.pdf+html) that models latent traits at the level of demographic and/or geographic groups rather than individuals. This approach uses a hierarchical model to borrow strength cross-sectionally and dynamic linear models to do so across time. The group-level estimates can be weighted to generate estimates for geographic units, such as states. @@ -6,18 +6,16 @@ dgo can also be used to estimate smoothed estimates of subpopulation groups' ave This model opens up new areas of research on historical public opinion in the United States at the subnational level. It also enables scholars of comparative politics to estimate dynamic models of public opinion opinion at the country or subnational level. -Prerequisites -============= - -Installation requires [RStan](http://mc-stan.org/interfaces/rstan.html) and its prerequisites, in particular a C++ toolchain. If you don't have RStan, follow its "[Getting Started](https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started)" guide before continuing. - Installation ============ +dgo requires a working installation of [RStan](http://mc-stan.org/interfaces/rstan.html). If you don't have already have RStan, follow its "[Getting Started](https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started)" guide before continuing. + dgo can be installed from [GitHub](https://github.com/jamesdunham/dgo) using [devtools](https://github.com/hadley/devtools/): ``` r -devtools::install_github("jamesdunham/dgo", dependencies = TRUE) +if (!require(devtools, quietly = TRUE)) install.packages("devtools") +devtools::install_github("jamesdunham/dgo") ``` Getting started @@ -25,15 +23,6 @@ Getting started ``` r library(dgo) -#> Loading required package: dgodata -#> Loading required package: Rcpp -#> Loading required package: rstan -#> Loading required package: ggplot2 -#> Loading required package: StanHeaders -#> rstan (Version 2.14.1, packaged: 2016-12-28 14:55:41 UTC, GitRev: 5fa1e80eb817) -#> For execution on a local, multicore CPU with excess RAM we recommend calling -#> rstan_options(auto_write = TRUE) -#> options(mc.cores = parallel::detectCores()) ``` The minimal workflow from raw data to estimation is: @@ -127,7 +116,7 @@ get_item_n(dgirt_in_abortion, by = "year") Under the hood, these functions use RStan for MCMC sampling, and arguments can be passed to RStan's `stan` via the `...` argument of `dgirt` and `dgmrp`. This will almost always be desirable, at a minimum to specify the number of sampler iterations, chains, and cores. ``` r -dgirt_out_abortion <- dgmrp(dgirt_in_abortion, iter = 1500, chains = 4, cores = +dgmrp_out_abortion <- dgmrp(dgirt_in_abortion, iter = 1500, chains = 4, cores = 4, seed = 42) ``` @@ -138,73 +127,73 @@ The model results are held in a `dgirtfit` object. Methods from RStan like `extr For a high-level summary of the result, use `summary`. ``` r -summary(dgirt_out_abortion) +summary(dgmrp_out_abortion) #> dgirt samples from 4 chains of 1500 iterations, 750 warmup, thinned every 1 -#> Drawn Wed Feb 8 12:24:24 2017 -#> Package version 0.2.8 +#> Drawn Mon May 22 10:57:03 2017 +#> Package version 0.2.9 #> Model version 2017_01_04_singleissue -#> 117 parameters; 60 theta_bars (year, state and race3) +#> 117 parameters; 60 theta_bars (year state race3) #> 5 periods 2006 to 2010 #> #> n_eff #> Min. 1st Qu. Median Mean 3rd Qu. Max. -#> 15.80 89.68 264.50 483.90 597.70 3000.00 +#> 95.68 242.50 451.87 685.85 927.30 3000.00 #> #> Rhat #> Min. 1st Qu. Median Mean 3rd Qu. Max. -#> 0.9992 1.0050 1.0150 1.0250 1.0430 1.1090 +#> 0.9993 1.0028 1.0068 1.0081 1.0126 1.0406 #> #> Elapsed time #> chain warmup sample total -#> 1: 1 10S 20S 30S -#> 2: 2 10S 22S 32S -#> 3: 3 10S 19S 29S -#> 4: 4 13S 20S 33S +#> 1: 1 15S 17S 32S +#> 2: 2 15S 12S 27S +#> 3: 3 14S 20S 34S +#> 4: 4 16S 12S 28S ``` To summarize posterior samples, use `summarize`. The default output gives summary statistics for the `theta_bar` parameters, which represent the mean of the latent outcome for the groups defined by time, local geographic area, and the demographic characteristics specified in the earlier call to `shape`. ``` r -head(summarize(dgirt_out_abortion)) +head(summarize(dgmrp_out_abortion)) #> param state race3 year mean sd median q_025 -#> 1: theta_bar CA black 2006 0.7754603 0.02155152 0.7760716 0.7316139 -#> 2: theta_bar CA black 2007 0.7988475 0.03076377 0.7971067 0.7442743 -#> 3: theta_bar CA black 2008 0.7225603 0.02428735 0.7222470 0.6753476 -#> 4: theta_bar CA black 2009 0.6846860 0.02226090 0.6847197 0.6395305 -#> 5: theta_bar CA black 2010 0.7394164 0.01584579 0.7399492 0.7078935 -#> 6: theta_bar CA other 2006 0.7319499 0.02315218 0.7322472 0.6878444 +#> 1: theta_bar CA black 2006 0.7739283 0.02098019 0.7749083 0.7307567 +#> 2: theta_bar CA black 2007 0.7980027 0.02771553 0.7979378 0.7439328 +#> 3: theta_bar CA black 2008 0.7232980 0.02362116 0.7231930 0.6786121 +#> 4: theta_bar CA black 2009 0.6863666 0.02128237 0.6863458 0.6463628 +#> 5: theta_bar CA black 2010 0.7407779 0.01682742 0.7414667 0.7058706 +#> 6: theta_bar CA other 2006 0.7347199 0.02322850 0.7354365 0.6872140 #> q_975 -#> 1: 0.8136820 -#> 2: 0.8701612 -#> 3: 0.7691617 -#> 4: 0.7271336 -#> 5: 0.7685217 -#> 6: 0.7775199 +#> 1: 0.8144084 +#> 2: 0.8517811 +#> 3: 0.7693334 +#> 4: 0.7279652 +#> 5: 0.7717651 +#> 6: 0.7790182 ``` Alternatively, `summarize` can apply arbitrary functions to posterior samples for whatever parameter is given by its `pars` argument. Enclose function names with quotes. For convenience, `"q_025"` and `"q_975"` give the 2.5th and 97.5th posterior quantiles. ``` r -summarize(dgirt_out_abortion, pars = "xi", funs = "var") +summarize(dgmrp_out_abortion, pars = "xi", funs = "var") #> param year var -#> 1: xi 2006 0.01946319 -#> 2: xi 2007 0.03932934 -#> 3: xi 2008 0.04135631 -#> 4: xi 2009 0.03546163 -#> 5: xi 2010 0.03086187 +#> 1: xi 2006 0.01814362 +#> 2: xi 2007 0.05026942 +#> 3: xi 2008 0.05606188 +#> 4: xi 2009 0.04857038 +#> 5: xi 2010 0.04149793 ``` To access posterior samples in tabular form use `as.data.frame`. By default, this method returns post-warmup samples for the `theta_bar` parameters, but like other methods takes a `pars` argument. ``` r -head(as.data.frame(dgirt_out_abortion)) +head(as.data.frame(dgmrp_out_abortion)) #> param state race3 year iteration value -#> 1: theta_bar CA black 2006 1 0.7614693 -#> 2: theta_bar CA black 2006 2 0.7505157 -#> 3: theta_bar CA black 2006 3 0.7915333 -#> 4: theta_bar CA black 2006 4 0.7742232 -#> 5: theta_bar CA black 2006 5 0.7778495 -#> 6: theta_bar CA black 2006 6 0.7457225 +#> 1: theta_bar CA black 2006 1 0.7661626 +#> 2: theta_bar CA black 2006 2 0.7690362 +#> 3: theta_bar CA black 2006 3 0.7656257 +#> 4: theta_bar CA black 2006 4 0.7935372 +#> 5: theta_bar CA black 2006 5 0.7544080 +#> 6: theta_bar CA black 2006 6 0.7819740 ``` To poststratify the results use `poststratify`. The following example uses the group population proportions bundled as `annual_state_race_targets` to reweight and aggregate estimates to strata defined by state-years. @@ -212,64 +201,64 @@ To poststratify the results use `poststratify`. The following example uses the g Read `help("poststratify")` for more details. ``` r -poststratify(dgirt_out_abortion, annual_state_race_targets, strata_names = +poststratify(dgmrp_out_abortion, annual_state_race_targets, strata_names = c("state", "year"), aggregated_names = "race3") #> state year value -#> 1: CA 2006 0.7188081 -#> 2: CA 2007 0.7470397 -#> 3: CA 2008 0.6566884 -#> 4: CA 2009 0.6267420 -#> 5: CA 2010 0.6756431 -#> 6: GA 2006 0.6333206 -#> 7: GA 2007 0.6223014 -#> 8: GA 2008 0.5243312 -#> 9: GA 2009 0.5105648 -#> 10: GA 2010 0.5704081 -#> 11: LA 2006 0.5258743 -#> 12: LA 2007 0.4770990 -#> 13: LA 2008 0.4151797 -#> 14: LA 2009 0.4024384 -#> 15: LA 2010 0.4246879 -#> 16: MA 2006 0.7629225 -#> 17: MA 2007 0.8101844 -#> 18: MA 2008 0.7056092 -#> 19: MA 2009 0.6600767 -#> 20: MA 2010 0.7082504 +#> 1: CA 2006 0.7187353 +#> 2: CA 2007 0.7469064 +#> 3: CA 2008 0.6562966 +#> 4: CA 2009 0.6272075 +#> 5: CA 2010 0.6754691 +#> 6: GA 2006 0.6339750 +#> 7: GA 2007 0.6225482 +#> 8: GA 2008 0.5232615 +#> 9: GA 2009 0.5095145 +#> 10: GA 2010 0.5705449 +#> 11: LA 2006 0.5266416 +#> 12: LA 2007 0.4769044 +#> 13: LA 2008 0.4142786 +#> 14: LA 2009 0.3985367 +#> 15: LA 2010 0.4229707 +#> 16: MA 2006 0.7629194 +#> 17: MA 2007 0.8099707 +#> 18: MA 2008 0.7058450 +#> 19: MA 2009 0.6624888 +#> 20: MA 2010 0.7078342 ``` To plot the results use `dgirt_plot`. This method plots summaries of posterior samples by time period. By default, it shows a 95% credible interval around posterior medians for the `theta_bar` parameters, for each local geographic area. For this (unconverged) toy example we omit the CIs. ``` r -dgirt_plot(dgirt_out_abortion, y_min = NULL, y_max = NULL) +dgirt_plot(dgmrp_out_abortion, y_min = NULL, y_max = NULL) ``` -![](README/unnamed-chunk-14-1.png) +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgmrp_plot-1.png) Output from `dgirt_plot` can be customized to some extent using objects from the ggplot2 package. ``` r -dgirt_plot(dgirt_out_abortion, y_min = NULL, y_max = NULL) + theme_classic() +dgirt_plot(dgmrp_out_abortion, y_min = NULL, y_max = NULL) + theme_classic() ``` -![](README/unnamed-chunk-15-1.png) +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgmrp_plot_plus-1.png) `dgirt_plot` can also plot the `data.frame` output from `poststratify`. This requires arguments that identify the relevant variables in the `data.frame`. Below, `poststratify` aggregates over the demographic grouping variable `race3`, resulting in a `data.frame` of estimates by state-year. So, in the subsequent call to `dgirt_plot`, we pass the names of the state and year variables. The `group_names` argument is `NULL` because there are no grouping variables left after aggregating over `race3`. ``` r -ps <- poststratify(dgirt_out_abortion, annual_state_race_targets, strata_names = +ps <- poststratify(dgmrp_out_abortion, annual_state_race_targets, strata_names = c("state", "year"), aggregated_names = "race3") head(ps) #> state year value -#> 1: CA 2006 0.7188081 -#> 2: CA 2007 0.7470397 -#> 3: CA 2008 0.6566884 -#> 4: CA 2009 0.6267420 -#> 5: CA 2010 0.6756431 -#> 6: GA 2006 0.6333206 +#> 1: CA 2006 0.7187353 +#> 2: CA 2007 0.7469064 +#> 3: CA 2008 0.6562966 +#> 4: CA 2009 0.6272075 +#> 5: CA 2010 0.6754691 +#> 6: GA 2006 0.6339750 dgirt_plot(ps, group_names = NULL, time_name = "year", geo_name = "state") ``` -![](README/unnamed-chunk-16-1.png) +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgmrp_plot_ps-1.png) Policy Liberalism ----------------- @@ -350,26 +339,26 @@ For a high-level summary of the result, use `summary`. ``` r summary(dgirt_out_liberalism) #> dgirt samples from 4 chains of 3000 iterations, 1500 warmup, thinned every 1 -#> Drawn Wed Feb 8 12:29:09 2017 -#> Package version 0.2.8 +#> Drawn Mon May 22 11:08:37 2017 +#> Package version 0.2.9 #> Model version 2017_01_04 -#> 137 parameters; 60 theta_bars (year, state and race3) +#> 137 parameters; 60 theta_bars (year state race3) #> 5 periods 2006 to 2010 #> #> n_eff #> Min. 1st Qu. Median Mean 3rd Qu. Max. -#> 229.7 686.5 1026.0 1540.0 1563.0 6000.0 +#> 65.07 388.19 585.84 1083.11 1245.79 6000.00 #> #> Rhat #> Min. 1st Qu. Median Mean 3rd Qu. Max. -#> 0.9997 1.0000 1.0010 1.0020 1.0020 1.0150 +#> 0.9997 1.0020 1.0059 1.0084 1.0119 1.0553 #> #> Elapsed time -#> chain warmup sample total -#> 1: 1 1M 44S 1M 50S 2M 94S -#> 2: 2 1M 42S 2M 54S 3M 96S -#> 3: 3 1M 54S 1M 48S 2M 102S -#> 4: 4 1M 47S 1M 50S 2M 97S +#> chain warmup sample total +#> 1: 1 2M 14S 2M 2S 4M 16S +#> 2: 2 2M 3S 4M 11S 6M 14S +#> 3: 3 2M 29S 4M 7S 6M 36S +#> 4: 4 2M 27S 4M 15S 6M 42S ``` To summarize posterior samples, use `summarize`. The default output gives summary statistics for the `theta_bar` parameters, which represent the mean of the latent outcome for the groups defined by time, local geographic area, and the demographic characteristics specified in the earlier call to `shape`. @@ -377,19 +366,19 @@ To summarize posterior samples, use `summarize`. The default output gives summar ``` r head(summarize(dgirt_out_liberalism)) #> param state race3 year mean sd median q_025 -#> 1: theta_bar CA black 2006 0.5181310 0.06903540 0.5155607 0.38979007 -#> 2: theta_bar CA black 2007 0.6132564 0.09604204 0.6052594 0.44996480 -#> 3: theta_bar CA black 2008 0.6091027 0.10859095 0.5952582 0.43748868 -#> 4: theta_bar CA black 2009 0.5204638 0.08900999 0.5085677 0.38176128 -#> 5: theta_bar CA black 2010 0.4992275 0.06126724 0.4930813 0.39782512 -#> 6: theta_bar CA other 2006 0.1508179 0.06059458 0.1573339 0.01016673 +#> 1: theta_bar CA black 2006 0.5247367 0.06827003 0.5194593 0.40423566 +#> 2: theta_bar CA black 2007 0.5944296 0.08813494 0.5853362 0.44776239 +#> 3: theta_bar CA black 2008 0.5823158 0.10139495 0.5667726 0.43013247 +#> 4: theta_bar CA black 2009 0.5132426 0.08060875 0.5021405 0.38781331 +#> 5: theta_bar CA black 2010 0.4977903 0.05987256 0.4922105 0.39645056 +#> 6: theta_bar CA other 2006 0.1593904 0.05938098 0.1664194 0.02339847 #> q_975 -#> 1: 0.6657002 -#> 2: 0.8279937 -#> 3: 0.8639421 -#> 4: 0.7290341 -#> 5: 0.6363504 -#> 6: 0.2529650 +#> 1: 0.6754660 +#> 2: 0.7932721 +#> 3: 0.8190219 +#> 4: 0.7062299 +#> 5: 0.6332728 +#> 6: 0.2583196 ``` Alternatively, `summarize` can apply arbitrary functions to posterior samples for whatever parameter is given by its `pars` argument. Enclose function names with quotes. For convenience, `"q_025"` and `"q_975"` give the 2.5th and 97.5th posterior quantiles. @@ -397,11 +386,11 @@ Alternatively, `summarize` can apply arbitrary functions to posterior samples fo ``` r summarize(dgirt_out_liberalism, pars = "xi", funs = "var") #> param year var -#> 1: xi 2006 0.011302809 -#> 2: xi 2007 0.007723304 -#> 3: xi 2008 0.006361194 -#> 4: xi 2009 0.005262130 -#> 5: xi 2010 0.005754282 +#> 1: xi 2006 0.013076032 +#> 2: xi 2007 0.008053516 +#> 3: xi 2008 0.006789127 +#> 4: xi 2009 0.006144990 +#> 5: xi 2010 0.005945176 ``` To access posterior samples in tabular form use `as.data.frame`. By default, this method returns post-warmup samples for the `theta_bar` parameters, but like other methods takes a `pars` argument. @@ -409,12 +398,12 @@ To access posterior samples in tabular form use `as.data.frame`. By default, thi ``` r head(as.data.frame(dgirt_out_liberalism)) #> param state race3 year iteration value -#> 1: theta_bar CA black 2006 1 0.5326097 -#> 2: theta_bar CA black 2006 2 0.5249095 -#> 3: theta_bar CA black 2006 3 0.4810473 -#> 4: theta_bar CA black 2006 4 0.5842495 -#> 5: theta_bar CA black 2006 5 0.6794800 -#> 6: theta_bar CA black 2006 6 0.5321501 +#> 1: theta_bar CA black 2006 1 0.6107959 +#> 2: theta_bar CA black 2006 2 0.4745799 +#> 3: theta_bar CA black 2006 3 0.4980549 +#> 4: theta_bar CA black 2006 4 0.4898826 +#> 5: theta_bar CA black 2006 5 0.4939210 +#> 6: theta_bar CA black 2006 6 0.4746524 ``` To poststratify the results use `poststratify`. The following example uses the group population proportions bundled as `annual_state_race_targets` to reweight and aggregate estimates to strata defined by state-years. Read `help("poststratify")` for more details. @@ -422,27 +411,27 @@ To poststratify the results use `poststratify`. The following example uses the g ``` r poststratify(dgirt_out_liberalism, annual_state_race_targets, strata_names = c("state", "year"), aggregated_names = "race3") -#> state year value -#> 1: CA 2006 0.1355272858 -#> 2: CA 2007 0.1848865835 -#> 3: CA 2008 0.1043107399 -#> 4: CA 2009 0.0459467646 -#> 5: CA 2010 0.0839898062 -#> 6: GA 2006 0.0964239685 -#> 7: GA 2007 0.0744225784 -#> 8: GA 2008 -0.0300159778 -#> 9: GA 2009 -0.0309101191 -#> 10: GA 2010 0.0003758105 -#> 11: LA 2006 0.0138033941 -#> 12: LA 2007 -0.0171435561 -#> 13: LA 2008 -0.1198432366 -#> 14: LA 2009 -0.1459680343 -#> 15: LA 2010 -0.1016888955 -#> 16: MA 2006 0.1398600252 -#> 17: MA 2007 0.2725613449 -#> 18: MA 2008 0.1556987370 -#> 19: MA 2009 0.0713680458 -#> 20: MA 2010 0.1154100785 +#> state year value +#> 1: CA 2006 0.143321712 +#> 2: CA 2007 0.188969603 +#> 3: CA 2008 0.112907172 +#> 4: CA 2009 0.058219329 +#> 5: CA 2010 0.092557709 +#> 6: GA 2006 0.103355439 +#> 7: GA 2007 0.084458691 +#> 8: GA 2008 -0.011351441 +#> 9: GA 2009 -0.015584764 +#> 10: GA 2010 0.010578655 +#> 11: LA 2006 0.021248643 +#> 12: LA 2007 -0.003170117 +#> 13: LA 2008 -0.095756506 +#> 14: LA 2009 -0.124279123 +#> 15: LA 2010 -0.088613763 +#> 16: MA 2006 0.147235550 +#> 17: MA 2007 0.269984992 +#> 18: MA 2008 0.159194876 +#> 19: MA 2009 0.082495757 +#> 20: MA 2010 0.122864118 ``` To plot the results use `dgirt_plot`. This method plots summaries of posterior samples by time period. By default, it shows a 95% credible interval around posterior medians for the `theta_bar` parameters, for each local geographic area. For this (unconverged) toy example we omit the CIs. @@ -451,7 +440,7 @@ To plot the results use `dgirt_plot`. This method plots summaries of posterior s dgirt_plot(dgirt_out_liberalism, y_min = NULL, y_max = NULL) ``` -![](README/unnamed-chunk-26-1.png) +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgirt_plot-1.png) `dgirt_plot` can also plot the `data.frame` output from `poststratify`. This requires arguments that identify the relevant variables in the `data.frame`. Below, `poststratify` aggregates over the demographic grouping variable `race3`, resulting in a `data.frame` of estimates by state-year. So, in the subsequent call to `dgirt_plot`, we pass the names of the state and year variables. The `group_names` argument is `NULL` because there are no grouping variables left after aggregating over `race3`. @@ -460,16 +449,16 @@ ps <- poststratify(dgirt_out_liberalism, annual_state_race_targets, strata_names "year"), aggregated_names = "race3") head(ps) #> state year value -#> 1: CA 2006 0.13552729 -#> 2: CA 2007 0.18488658 -#> 3: CA 2008 0.10431074 -#> 4: CA 2009 0.04594676 -#> 5: CA 2010 0.08398981 -#> 6: GA 2006 0.09642397 +#> 1: CA 2006 0.14332171 +#> 2: CA 2007 0.18896960 +#> 3: CA 2008 0.11290717 +#> 4: CA 2009 0.05821933 +#> 5: CA 2010 0.09255771 +#> 6: GA 2006 0.10335544 dgirt_plot(ps, group_names = NULL, time_name = "year", geo_name = "state") ``` -![](README/unnamed-chunk-27-1.png) +![](https://raw.githubusercontent.com/jamesdunham/dgo/master/README/dgirt_plot_ps-1.png) Troubleshooting --------------- @@ -488,6 +477,8 @@ tempdir() #> [1] "/var/folders/2p/_d3c95qd6ljg28j1f5l2jqxm0000gn/T//Rtmp38a10A" ``` +Models fitted before October 2016 (specifically < [\#8e6a2cf](https://github.com/jamesdunham/dgo/commit/8e6a2cfbe00b2cd4a908b3067241e06124d143cd)) using dgirtfit are not fully compatible with dgo. Their contents can be extracted without using dgo, however, with the `$` indexing operator. For example: `as.data.frame(dgirtfit_object$stan.cmb)`. + Contributing and citing ----------------------- diff --git a/README/dgirt_plot-1.png b/README/dgirt_plot-1.png new file mode 100644 index 0000000..a233a89 Binary files /dev/null and b/README/dgirt_plot-1.png differ diff --git a/README/dgirt_plot_ps-1.png b/README/dgirt_plot_ps-1.png new file mode 100644 index 0000000..8cbba0e Binary files /dev/null and b/README/dgirt_plot_ps-1.png differ diff --git a/README/dgmrp_plot-1.png b/README/dgmrp_plot-1.png new file mode 100644 index 0000000..6506da0 Binary files /dev/null and b/README/dgmrp_plot-1.png differ diff --git a/README/dgmrp_plot_plus-1.png b/README/dgmrp_plot_plus-1.png new file mode 100644 index 0000000..9a3ef8a Binary files /dev/null and b/README/dgmrp_plot_plus-1.png differ diff --git a/README/dgmrp_plot_ps-1.png b/README/dgmrp_plot_ps-1.png new file mode 100644 index 0000000..baa1082 Binary files /dev/null and b/README/dgmrp_plot_ps-1.png differ diff --git a/README/unnamed-chunk-14-1.png b/README/unnamed-chunk-14-1.png deleted file mode 100644 index 37b6c02..0000000 Binary files a/README/unnamed-chunk-14-1.png and /dev/null differ diff --git a/README/unnamed-chunk-15-1.png b/README/unnamed-chunk-15-1.png deleted file mode 100644 index 266ffdf..0000000 Binary files a/README/unnamed-chunk-15-1.png and /dev/null differ diff --git a/README/unnamed-chunk-16-1.png b/README/unnamed-chunk-16-1.png deleted file mode 100644 index 07da570..0000000 Binary files a/README/unnamed-chunk-16-1.png and /dev/null differ diff --git a/README/unnamed-chunk-26-1.png b/README/unnamed-chunk-26-1.png deleted file mode 100644 index c48b3f0..0000000 Binary files a/README/unnamed-chunk-26-1.png and /dev/null differ diff --git a/README/unnamed-chunk-27-1.png b/README/unnamed-chunk-27-1.png deleted file mode 100644 index 0db32d0..0000000 Binary files a/README/unnamed-chunk-27-1.png and /dev/null differ diff --git a/README_cache/markdown_github/__packages b/README_cache/markdown_github/__packages deleted file mode 100644 index fe3922a..0000000 --- a/README_cache/markdown_github/__packages +++ /dev/null @@ -1,8 +0,0 @@ -base -setwidth -nvimcom -ggplot2 -rstan -Rcpp -dgirt -StanHeaders diff --git a/README_cache/markdown_github/unnamed-chunk-4_d06a505b50cbd030494e5ccd551db7ee.rdb b/README_cache/markdown_github/unnamed-chunk-4_d06a505b50cbd030494e5ccd551db7ee.rdb deleted file mode 100644 index 803b5d0..0000000 Binary files a/README_cache/markdown_github/unnamed-chunk-4_d06a505b50cbd030494e5ccd551db7ee.rdb and /dev/null differ diff --git a/README_cache/markdown_github/unnamed-chunk-4_d06a505b50cbd030494e5ccd551db7ee.rdx b/README_cache/markdown_github/unnamed-chunk-4_d06a505b50cbd030494e5ccd551db7ee.rdx deleted file mode 100644 index 55da12c..0000000 Binary files a/README_cache/markdown_github/unnamed-chunk-4_d06a505b50cbd030494e5ccd551db7ee.rdx and /dev/null differ diff --git a/README_cache/markdown_github/unnamed-chunk-5_1167472bee5196bdeb75c55a33f83bc8.rdb b/README_cache/markdown_github/unnamed-chunk-5_1167472bee5196bdeb75c55a33f83bc8.rdb deleted file mode 100644 index 3aed5ca..0000000 Binary files a/README_cache/markdown_github/unnamed-chunk-5_1167472bee5196bdeb75c55a33f83bc8.rdb and /dev/null differ diff --git a/README_cache/markdown_github/unnamed-chunk-5_1167472bee5196bdeb75c55a33f83bc8.rdx b/README_cache/markdown_github/unnamed-chunk-5_1167472bee5196bdeb75c55a33f83bc8.rdx deleted file mode 100644 index 99c7669..0000000 Binary files a/README_cache/markdown_github/unnamed-chunk-5_1167472bee5196bdeb75c55a33f83bc8.rdx and /dev/null differ diff --git a/README_cache/markdown_github/unnamed-chunk-7_51d725ceb8e6054da754dfee50233a06.rdb b/README_cache/markdown_github/unnamed-chunk-7_51d725ceb8e6054da754dfee50233a06.rdb deleted file mode 100644 index 1509429..0000000 Binary files a/README_cache/markdown_github/unnamed-chunk-7_51d725ceb8e6054da754dfee50233a06.rdb and /dev/null differ diff --git a/README_cache/markdown_github/unnamed-chunk-7_51d725ceb8e6054da754dfee50233a06.rdx b/README_cache/markdown_github/unnamed-chunk-7_51d725ceb8e6054da754dfee50233a06.rdx deleted file mode 100644 index 6f235be..0000000 Binary files a/README_cache/markdown_github/unnamed-chunk-7_51d725ceb8e6054da754dfee50233a06.rdx and /dev/null differ diff --git a/cleanup b/cleanup deleted file mode 100755 index bf4430d..0000000 --- a/cleanup +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh - -# Note to Windows users: This is not actually platform specific. -mkdir -p src/include -"${R_HOME}/bin/R" --vanilla --slave --file=tools/make_cpp.R -sed -i.bak '/current_statement_begin__ = [0-9]/d' src/include/models.hpp -cat src/*.cc > src/Modules.cpp -rm src/*.cc -"${R_HOME}/bin/R" --vanilla --slave -e 'roxygen2::roxygenize(clean = TRUE)' -exit $? - - - diff --git a/cleanup.win b/cleanup.win deleted file mode 100755 index bf4430d..0000000 --- a/cleanup.win +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh - -# Note to Windows users: This is not actually platform specific. -mkdir -p src/include -"${R_HOME}/bin/R" --vanilla --slave --file=tools/make_cpp.R -sed -i.bak '/current_statement_begin__ = [0-9]/d' src/include/models.hpp -cat src/*.cc > src/Modules.cpp -rm src/*.cc -"${R_HOME}/bin/R" --vanilla --slave -e 'roxygen2::roxygenize(clean = TRUE)' -exit $? - - - diff --git a/cran-comments.md b/cran-comments.md index 66a599c..06e7484 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -1,23 +1,15 @@ ## Test environments -* local Ubuntu 16.04, R 3.3.2 (devel and release) -* Ubuntu 12.04 (on travis-ci), R 3.3.2 -* Windows Server 2012 R2 x64 (on appveyor), R 3.3.2 +* local Ubuntu 16.04, R 3.4.0 +* Ubuntu 12.04 (on travis-ci), R 3.4.0 (devel and release) +* Windows Server 2012 R2 x64 (on appveyor), R 3.4.0 (devel and release) + ## R CMD check results There were no ERRORs or WARNINGs. -There were a few NOTEs: - -* "Strong dependencies not in mainstream repositories: dgodata": The dgodata - package contains datasets that appear in dgo examples and will be useful to - dgo users. We've submitted it to CRAN along with dgo. It's meanwhile available - at . - -* "installed size is 5.8Mb / sub-directories of 1Mb or more: libs 3.8Mb": The - file in the 'libs' directory provides Stan models compiled during package - installation. This follows the practice of existing CRAN package 'rstanarm'. +There was one NOTE: * "New submission": This is the first submission with this maintainer email. diff --git a/data/toy_dgirt_in.rda b/data/toy_dgirt_in.rda index 6420262..7fb8b4a 100644 Binary files a/data/toy_dgirt_in.rda and b/data/toy_dgirt_in.rda differ diff --git a/data/toy_dgirtfit.rda b/data/toy_dgirtfit.rda index d5b8d81..a29592b 100644 Binary files a/data/toy_dgirtfit.rda and b/data/toy_dgirtfit.rda differ diff --git a/exec/2015_12_16.stan b/exec/2015_12_16.stan deleted file mode 100644 index fc68136..0000000 --- a/exec/2015_12_16.stan +++ /dev/null @@ -1,227 +0,0 @@ -data { - int G; ## number of covariate groups - int G_hier; ## number of level-two demographic groups - int Q; ## number of items/questions - int T; ## number of years - int N; ## number of observed cells - int S; ## number of geographic units (e.g., states) - int P; ## number of hierarchical parameters, including geographic - int H; ## number of predictors for geographic unit effects - int Hprior; ## number of predictors for geographic unit effects (t=1) - int D; ## number of difficulty parameters per question - int constant_item; ## indicator for constant item parameters - int separate_t; ## indicator for no over-time smoothing - real delta_tbar_prior_mean; - real delta_tbar_prior_sd; - real innov_sd_delta_scale; - real innov_sd_theta_scale; - int n_vec[N]; ## long vector of trials - int s_vec[N]; ## long vector of successes - int NNl2[T, Q, G_hier]; ## trials - int SSl2[T, Q, G_hier]; ## successes - int MMM[T, Q, G]; ## missingness array - matrix[G, P] XX; ## indicator matrix for hierarchical vars. - matrix[G_hier, G] WT[T]; ## weight array - matrix[P, H] ZZ[T]; ## data for geographic model - matrix[P, Hprior] ZZ_prior[T]; ## data for geographic model (prior) - matrix[T, Q] l2_only; -} -transformed data { -} -parameters { - vector[Q] diff_raw[D]; ## raw difficulty - vector[Q] disc_raw; ## discrimination - vector[T] xi; ## common intercept - vector[P] gamma_raw[T]; ## hierarchical parameters (raw) - vector[T] delta_gamma; ## weight placed on gamma from prev. period - vector[H] nu_geo[T]; ## weight on geographic predictors - vector[Hprior] nu_geo_prior; ## weight on geographic predictors (t=1) - vector[T] delta_tbar; ## - vector[G] theta_bar_raw[T]; ## group mean ability (raw) #!# - #!# vector[G] theta_bar[T]; ## group means - vector[T] sd_theta_bar; ## residual sd of group ability means - vector[T] sd_theta; ## sd of abilities (by period) - real sd_gamma; ## prior sd of geographic effects - real sd_innov_delta; ## innovation sd of nu_geo and delta_gamma - real sd_innov_logsd; ## innovation sd of sd_theta - real sd_innov_gamma; ## innovation sd of gamma, xi, and (opt.) diff -} -transformed parameters { - vector[G] theta_bar[T]; ## group means (transformed) #!# - vector[Q] diff[D]; ## adjusted difficulty - vector[Q] kappa[D]; ## threshold - vector[Q] disc; ## normalized discrimination - vector[Q] sd_item; ## item standard deviation - vector[Q] var_item; ## item variance - vector[T] var_theta; ## within-group variance of theta - ## var. of theta_bar w/in each level-two group **NOT CONSTRAINED TO BE POSITIVE** - vector[G_hier] var_theta_bar_l2[T]; - vector[P] gamma[T]; ## hierarchical parameters (adjusted) - vector[G] mu_theta_bar[T]; ## linear predictor for group means - vector[P] mu_gamma[T]; - vector[G] z[T, Q]; ## array of vectors of group deviates - vector[G_hier] z_l2[T, Q]; ## - real prob[T, Q, G]; ## array of probabilities - vector[G_hier] prob_l2[T, Q]; ## array of probabilities - vector[G_hier] theta_l2[T]; ## second-level group abililities - ## scale (product = 1) - disc = disc_raw * pow(exp(sum(log(disc_raw))), (-inv(Q))); - for (q in 1:Q) { - sd_item[q] = inv(disc[q]); ## item standard deviations - } - for (d in 1:D) { - ## location (mean in first year = 0) - diff[d] = diff_raw[d] - mean(diff_raw[1]); - kappa[d] = diff[d] ./ disc; ## item thresholds - } - var_item = sd_item .* sd_item; - var_theta = sd_theta .* sd_theta; - for (t in 1:T) { ## loop over years - if (t == 1 || separate_t == 1) { - mu_gamma[t] = ZZ_prior[t] * nu_geo_prior; - gamma[t] = mu_gamma[t] + sd_gamma * gamma_raw[t]; - mu_theta_bar[t] = xi[t] + XX * gamma[t]; - ##mu_theta_bar[t] = XX * gamma[t]; - } - if (t > 1 && separate_t == 0) { - if (t == 2) { - ## 2016-02-05: need to think more about nu_geo_prior; make it different for geographic and demographic - ## parameters - ## - ## In the second year, agian use uniformative prior for gamma, rather - ## than one centered on its lagged value, because gamma is likely to be - ## very different in periods 1 and 2 because only in 2 is - ## theta_bar[t - 1] used to inform theta_bar[t]. - mu_gamma[t] = ZZ_prior[t] * nu_geo_prior; - gamma[t] = mu_gamma[t] + sd_gamma * gamma_raw[t]; - } else { - ## 2016-02-05: maybe delta_gamma should differ for geographic and demographic parameters ; - ## could do random walk DLM for demographic parameters - mu_gamma[t] = gamma[t - 1] * delta_gamma[t] + ZZ[t] * nu_geo[t]; - gamma[t] = mu_gamma[t] + sd_innov_gamma * gamma_raw[t]; - } - mu_theta_bar[t] = xi[t] + XX * gamma[t] + theta_bar[t - 1] * delta_tbar[t]; - ##mu_theta_bar[t] = theta_bar[t - 1] * delta_tbar[t] + XX * gamma[t]; - } - ## Matt trick for group means - theta_bar[t] = mu_theta_bar[t] + sd_theta_bar[t] * theta_bar_raw[t]; #!# - ## Weighted average of group means (weights must sum to 1) - theta_l2[t] = WT[t] * theta_bar[t]; ## G_hierx1 = G_hierxG * Gx1 - for (n in 1:G_hier) { - matrix[G, G] WTdiag; - for (g in 1:G) { - for (h in 1:G) { - if (g == h) { - WTdiag[g, h] = WT[t][n][g]; - } - if (g != h) { - WTdiag[g, h] = 0; - } - } - } - ## (y - w'y)' W (y - w'y) = weighted variance - var_theta_bar_l2[t][n] = (theta_bar[t] - theta_l2[t, n])' * WTdiag * - (theta_bar[t] - theta_l2[t, n]); - } - for (q in 1:Q) { ## loop over questions - real sd_tq; - real sd_l2_tq[G_hier]; - sd_tq = sqrt(var_theta[t] + var_item[q]); - for (n in 1:G_hier) { - sd_l2_tq[n] = sqrt(square(sd_tq) + var_theta_bar_l2[t, n]); - } - ## Group-level IRT model - if (constant_item == 0) { - z[t, q] = (theta_bar[t] - kappa[t][q]) / sd_tq; - for (n in 1:G_hier) { - z_l2[t, q, n] = - (theta_l2[t, n] - kappa[t][q]) / sd_l2_tq[n]; - prob_l2[t, q, n] = Phi_approx(z_l2[t, q, n]); - } - } - if (constant_item == 1) { - z[t, q] = (theta_bar[t] - kappa[1][q]) / sd_tq; - for (n in 1:G_hier) { - z_l2[t, q, n] = - (theta_l2[t, n] - kappa[1][q]) / sd_l2_tq[n]; - prob_l2[t, q, n] = Phi_approx(z_l2[t, q, n]); - } - } - for (g in 1:G) { ## loop over groups - prob[t, q, g] = Phi_approx(z[t, q, g]); ## fast normal CDF - } - } ## end question loop - } ## end year loop -} -model { - ## TEMPORARY VARIABLES - real prob_vec[N]; ## long vector of probabilities (empty cells omitted) - int pos; - pos = 0; - ## PRIORS - if (constant_item == 1) { - diff_raw[1] ~ normal(0, 1); ## item difficulty (constant) - } - disc_raw ~ lognormal(0, 1); ## item discrimination - sd_gamma ~ cauchy(0, 2.5); ## sd of geographic effects - sd_innov_delta ~ cauchy(0, innov_sd_delta_scale); ## innovation sd of nu_geo, delta_gamma - sd_innov_gamma ~ cauchy(0, 2.5); ## innovation sd. of gamma, xi, and diff - sd_innov_logsd ~ cauchy(0, innov_sd_theta_scale); ## innovation sd of theta_sd - for (t in 1:T) { ## loop over years - gamma_raw[t] ~ normal(0, 1); - theta_bar_raw[t] ~ normal(0, 1); ## Matt trick done above #!# - #!# theta_bar[t] ~ normal(mu_theta_bar[t], sd_theta_bar[t]); ## group means - if (t == 1) { - if (constant_item == 0) { - diff_raw[t] ~ normal(0, 1); ## item difficulty - } - ## Priors for first period - sd_theta_bar[t] ~ cauchy(0, 2.5); - sd_theta[t] ~ cauchy(0, 2.5); - nu_geo[t] ~ normal(0, 10); - nu_geo_prior ~ normal(0, 10); - delta_gamma[t] ~ normal(0.5, 0.5); ## 68% of prior mass btwn 0 and 1 - delta_tbar[t] ~ normal(delta_tbar_prior_mean, delta_tbar_prior_sd); - xi[t] ~ normal(0, 10); ## intercept - } - if (t > 1) { - ## TRANSITION MODEL - ## Difficulty parameters (if not constant) - if (constant_item == 0) { - diff_raw[t] ~ normal(diff_raw[t - 1], sd_innov_gamma); - } - ## predictors in geographic models (random walk) - delta_gamma[t] ~ normal(delta_gamma[t - 1], sd_innov_delta); - nu_geo[t] ~ normal(nu_geo[t - 1], sd_innov_delta); - delta_tbar[t] ~ normal(delta_tbar[t - 1], sd_innov_delta); - sd_theta_bar[t] ~ lognormal(log(sd_theta_bar[t - 1]), sd_innov_logsd); - sd_theta[t] ~ lognormal(log(sd_theta[t - 1]), sd_innov_logsd); - if (separate_t == 0 && t > 2) { - xi[t] ~ normal(xi[t - 1], sd_innov_gamma); - } - if (separate_t == 1 || t == 2) { ## Estimate model anew each period - xi[t] ~ normal(0, 10); - } - } - for (q in 1:Q) { ## loop over questions - if (l2_only[t, q] == 1) { - ## Second-level mean - SSl2[t, q] ~ binomial(NNl2[t, q], prob_l2[t, q]); - } - for (g in 1:G) { ## loop over groups - if (MMM[t, q, g] == 0) { ## Use only if not missing - pos = pos + 1; - prob_vec[pos] = prob[t, q, g]; - } - } ## end group loop - } ## end question loop - } ## end time loop - ## Sampling model for group responses - s_vec ~ binomial(n_vec, prob_vec); -} -generated quantities { - vector[T] sd_total; - for (t in 1:T) { - sd_total[t] = sqrt(variance(theta_bar[t]) + square(sd_theta[t])); - } -} diff --git a/exec/2016_04_20.stan b/exec/2016_04_20.stan deleted file mode 100644 index 8c820c2..0000000 --- a/exec/2016_04_20.stan +++ /dev/null @@ -1,238 +0,0 @@ -data { - int G; ## number of covariate groups - int G_hier; ## number of level-two demographic groups - int Q; ## number of items/questions - int T; ## number of years - int N; ## number of cells - int N_observed; ## number of observed cells - int S; ## number of geographic units (e.g., states) - int P; ## number of hierarchical parameters, including geographic - int H; ## number of predictors for geographic unit effects - int Hprior; ## number of predictors for geographic unit effects (t=1) - int D; ## number of difficulty parameters per question - int constant_item; ## indicator for constant item parameters - int separate_t; ## indicator for no over-time smoothing - real delta_tbar_prior_mean; - real delta_tbar_prior_sd; - real innov_sd_delta_scale; - real innov_sd_theta_scale; - int n_vec[N]; - int s_vec[N]; - int observed[N_observed]; ## non-missing indexes for n_vec and s_vec - int NNl2[T, Q, G_hier]; ## trials - int SSl2[T, Q, G_hier]; ## successes - matrix[G, P] XX; ## indicator matrix for hierarchical vars. - matrix[G_hier, G] WT[T]; ## weight array - matrix[P, H] ZZ[T]; ## data for geographic model - matrix[P, Hprior] ZZ_prior[T]; ## data for geographic model (prior) - matrix[T, Q] l2_only; -} - -transformed data { -} - -parameters { - vector[Q] diff_raw[D]; ## raw difficulty - vector[Q] disc_raw; ## discrimination - vector[T] xi; ## common intercept - vector[P] gamma_raw[T]; ## hierarchical parameters (raw) - vector[T] delta_gamma; ## weight placed on gamma from prev. period - vector[H] nu_geo[T]; ## weight on geographic predictors - vector[Hprior] nu_geo_prior; ## weight on geographic predictors (t=1) - vector[T] delta_tbar; ## - vector[G] theta_bar_raw[T]; ## group mean ability (raw) #!# - #!# vector[G] theta_bar[T]; ## group means - vector[T] sd_theta_bar; ## residual sd of group ability means - vector[T] sd_theta; ## sd of abilities (by period) - real sd_gamma; ## prior sd of geographic effects - real sd_innov_delta; ## innovation sd of nu_geo and delta_gamma - real sd_innov_logsd; ## innovation sd of sd_theta - real sd_innov_gamma; ## innovation sd of gamma, xi, and (opt.) diff -} - -transformed parameters { - vector[G] theta_bar[T]; ## group means (transformed) #!# - vector[Q] diff[D]; ## adjusted difficulty - vector[Q] kappa[D]; ## threshold - vector[Q] disc; ## normalized discrimination - vector[Q] sd_item; ## item standard deviation - vector[Q] var_item; ## item variance - vector[T] var_theta; ## within-group variance of theta - ## var. of theta_bar w/in each level-two group **NOT CONSTRAINED TO BE POSITIVE** - vector[G_hier] var_theta_bar_l2[T]; - vector[P] gamma[T]; ## hierarchical parameters (adjusted) - vector[G] mu_theta_bar[T]; ## linear predictor for group means - vector[P] mu_gamma[T]; - vector[G] z[T, Q]; ## array of vectors of group deviates - vector[G_hier] z_l2[T, Q]; ## - real prob[T, Q, G]; ## array of probabilities - vector[G_hier] prob_l2[T, Q]; ## array of probabilities - vector[G_hier] theta_l2[T]; ## second-level group abililities - ## scale (product = 1) - disc = disc_raw * pow(exp(sum(log(disc_raw))), (-inv(Q))); - for (q in 1:Q) { - sd_item[q] = inv(disc[q]); ## item standard deviations - } - for (d in 1:D) { - ## location (mean in first year = 0) - diff[d] = diff_raw[d] - mean(diff_raw[1]); - kappa[d] = diff[d] ./ disc; ## item thresholds - } - var_item = sd_item .* sd_item; - var_theta = sd_theta .* sd_theta; - for (t in 1:T) { ## loop over years - if (t == 1 || separate_t == 1) { - mu_gamma[t] = ZZ_prior[t] * nu_geo_prior; - gamma[t] = mu_gamma[t] + sd_gamma * gamma_raw[t]; - mu_theta_bar[t] = xi[t] + XX * gamma[t]; - ##mu_theta_bar[t] = XX * gamma[t]; - } - if (t > 1 && separate_t == 0) { - if (t == 2) { - ## 2016-02-05: need to think more about nu_geo_prior; make it different for geographic and demographic - ## parameters - ## - ## In the second year, agian use uniformative prior for gamma, rather - ## than one centered on its lagged value, because gamma is likely to be - ## very different in periods 1 and 2 because only in 2 is - ## theta_bar[t - 1] used to inform theta_bar[t]. - mu_gamma[t] = ZZ_prior[t] * nu_geo_prior; - gamma[t] = mu_gamma[t] + sd_gamma * gamma_raw[t]; - } else { - ## 2016-02-05: maybe delta_gamma should differ for geographic and demographic parameters ; - ## could do random walk DLM for demographic parameters - mu_gamma[t] = gamma[t - 1] * delta_gamma[t] + ZZ[t] * nu_geo[t]; - gamma[t] = mu_gamma[t] + sd_innov_gamma * gamma_raw[t]; - } - mu_theta_bar[t] = xi[t] + XX * gamma[t] + theta_bar[t - 1] * delta_tbar[t]; - ##mu_theta_bar[t] = theta_bar[t - 1] * delta_tbar[t] + XX * gamma[t]; - } - ## Matt trick for group means - theta_bar[t] = mu_theta_bar[t] + sd_theta_bar[t] * theta_bar_raw[t]; #!# - ## Weighted average of group means (weights must sum to 1) - theta_l2[t] = WT[t] * theta_bar[t]; ## G_hierx1 = G_hierxG * Gx1 - for (n in 1:G_hier) { - matrix[G, G] WTdiag; - for (g in 1:G) { - for (h in 1:G) { - if (g == h) { - WTdiag[g, h] = WT[t][n][g]; - } - if (g != h) { - WTdiag[g, h] = 0; - } - } - } - ## (y - w'y)' W (y - w'y) = weighted variance - var_theta_bar_l2[t][n] = (theta_bar[t] - theta_l2[t, n])' * WTdiag * - (theta_bar[t] - theta_l2[t, n]); - } - for (q in 1:Q) { ## loop over questions - real sd_tq; - real sd_l2_tq[G_hier]; - sd_tq = sqrt(var_theta[t] + var_item[q]); - for (n in 1:G_hier) { - sd_l2_tq[n] = sqrt(square(sd_tq) + var_theta_bar_l2[t, n]); - } - ## Group-level IRT model - if (constant_item == 0) { - z[t, q] = (theta_bar[t] - kappa[t][q]) / sd_tq; - for (n in 1:G_hier) { - z_l2[t, q, n] = - (theta_l2[t, n] - kappa[t][q]) / sd_l2_tq[n]; - prob_l2[t, q, n] = Phi_approx(z_l2[t, q, n]); - } - } - if (constant_item == 1) { - z[t, q] = (theta_bar[t] - kappa[1][q]) / sd_tq; - for (n in 1:G_hier) { - z_l2[t, q, n] = - (theta_l2[t, n] - kappa[1][q]) / sd_l2_tq[n]; - prob_l2[t, q, n] = Phi_approx(z_l2[t, q, n]); - } - } - for (g in 1:G) { ## loop over groups - prob[t, q, g] = Phi_approx(z[t, q, g]); ## fast normal CDF - } - } ## end question loop - } ## end year loop -} - -model { - ## TEMPORARY VARIABLES - real prob_vec[N]; ## long vector of probabilities - int pos; - pos = 0; - - ## PRIORS - if (constant_item == 1) { - diff_raw[1] ~ normal(0, 1); ## item difficulty (constant) - } - disc_raw ~ lognormal(0, 1); ## item discrimination - sd_gamma ~ cauchy(0, 2.5); ## sd of geographic effects - sd_innov_delta ~ cauchy(0, innov_sd_delta_scale); ## innovation sd of nu_geo, delta_gamma - sd_innov_gamma ~ cauchy(0, 2.5); ## innovation sd. of gamma, xi, and diff - sd_innov_logsd ~ cauchy(0, innov_sd_theta_scale); ## innovation sd of theta_sd - - for (t in 1:T) { ## loop over years - gamma_raw[t] ~ normal(0, 1); - theta_bar_raw[t] ~ normal(0, 1); ## Matt trick done above #!# - if (t == 1) { - if (constant_item == 0) { - diff_raw[t] ~ normal(0, 1); ## item difficulty - } - ## Priors for first period - sd_theta_bar[t] ~ cauchy(0, 2.5); - sd_theta[t] ~ cauchy(0, 2.5); - nu_geo[t] ~ normal(0, 10); - nu_geo_prior ~ normal(0, 10); - delta_gamma[t] ~ normal(0.5, 0.5); ## 68% of prior mass btwn 0 and 1 - delta_tbar[t] ~ normal(delta_tbar_prior_mean, delta_tbar_prior_sd); - xi[t] ~ normal(0, 10); ## intercept - } - if (t > 1) { - ## TRANSITION MODEL - - ## Difficulty parameters (if not constant) - if (constant_item == 0) { - diff_raw[t] ~ normal(diff_raw[t - 1], sd_innov_gamma); - } - - ## predictors in geographic models (random walk) - delta_gamma[t] ~ normal(delta_gamma[t - 1], sd_innov_delta); - nu_geo[t] ~ normal(nu_geo[t - 1], sd_innov_delta); - delta_tbar[t] ~ normal(delta_tbar[t - 1], sd_innov_delta); - sd_theta_bar[t] ~ lognormal(log(sd_theta_bar[t - 1]), sd_innov_logsd); - sd_theta[t] ~ lognormal(log(sd_theta[t - 1]), sd_innov_logsd); - if (separate_t == 0 && t > 2) { - xi[t] ~ normal(xi[t - 1], sd_innov_gamma); - } - if (separate_t == 1 || t == 2) { ## Estimate model anew each period - xi[t] ~ normal(0, 10); - } - } - - for (q in 1:Q) { ## loop over questions - # skip until implemented - # if (l2_only[t, q] == 1) { - # ## Second-level mean - # SSl2[t, q] ~ binomial(NNl2[t, q], prob_l2[t, q]); - # } - for (g in 1:G) { ## loop over groups - pos = pos + 1; - prob_vec[pos] = prob[t, q, g]; - } ## end group loop - } ## end question loop - - } ## end time loop - - ## Sampling model for group responses - s_vec[observed] ~ binomial(n_vec[observed], prob_vec[observed]); -} - -generated quantities { - vector[T] sd_total; - for (t in 1:T) { - sd_total[t] = sqrt(variance(theta_bar[t]) + square(sd_theta[t])); - } -} diff --git a/inst/chunks/common_functions.txt b/inst/chunks/common_functions.txt deleted file mode 100644 index e69de29..0000000 diff --git a/exec/2017_01_04.stan b/inst/models/2017_01_04.stan similarity index 100% rename from exec/2017_01_04.stan rename to inst/models/2017_01_04.stan diff --git a/exec/2017_01_04_singleissue.stan b/inst/models/2017_01_04_singleissue.stan similarity index 100% rename from exec/2017_01_04_singleissue.stan rename to inst/models/2017_01_04_singleissue.stan diff --git a/man/dgirt.Rd b/man/dgirt.Rd index 6896ad4..109e001 100644 --- a/man/dgirt.Rd +++ b/man/dgirt.Rd @@ -2,17 +2,24 @@ % Please edit documentation in R/dgirt.r \name{dgirt} \alias{dgirt} -\title{\code{dgirt}: fit a DGIRT model} +\alias{dgmrp} +\alias{dgmrp} +\title{\code{dgirt} and \code{dgmrp}: fit a DGIRT or single-issue MRP model} \usage{ dgirt(shaped_data, ..., separate_t = FALSE, delta_tbar_prior_mean = 0.65, delta_tbar_prior_sd = 0.25, innov_sd_delta_scale = 2.5, innov_sd_theta_scale = 2.5, version = "2017_01_04", - hierarchical_model = TRUE) + hierarchical_model = TRUE, model = NULL) + +dgmrp(shaped_data, ..., separate_t = FALSE, delta_tbar_prior_mean = 0.65, + delta_tbar_prior_sd = 0.25, innov_sd_delta_scale = 2.5, + innov_sd_theta_scale = 2.5, version = "2017_01_04_singleissue", + model = NULL) } \arguments{ \item{shaped_data}{Output from \code{\link{shape}}.} -\item{...}{Further arguments passed to \code{\link[rstan]{stan}}.} +\item{...}{Further arguments, passed to \code{\link[rstan]{stan}}.} \item{separate_t}{Whether smoothing of estimates over time should be disabled. Default \code{FALSE}.} @@ -32,31 +39,33 @@ innovation standard deviation of \code{gamma}, \code{xi}, and if \code{constant_item} is \code{FALSE} the item difficulty \code{diff}. Default \code{2.5}.} -\item{version}{The version of the DGIRT model to use.} +\item{version}{The name of the dgo model to estimate, or the path to a +\code{.stan} file. Valid names for dgo models are "2017_01_04", +"2017_01_04_singleissue". Ignored if argument \code{model} is used.} \item{hierarchical_model}{Whether a hierarchical model should be used to smooth the group IRT estimates. If set to FALSE, the model will return raw group-IRT model estimates for each group. Default \code{TRUE}.} + +\item{model}{A Stan model object of class `stanmodel` to be used in +estimation. Specifying this argument avoids repeated model compilation. Note +that the Stan model object for a model fitted with \code{dgirt()} or +\code{dgmrp()} can be found in the the \code{stanmodel} slot of the resulting +\code{dgirt_fit} or \code{dgmrp_fit} object.} } \value{ -A \code{\link{dgirtfit-class}} object that extends +A \code{\link{dgo_fit-class}} object that extends \code{\link[rstan]{stanfit-class}}. } \description{ -\code{dgirt} makes a call to \code{\link[rstan]{stan}} with the Stan code and -data for a DGIRT model. +\code{dgirt} and \code{dgmrp} make calls to \code{\link[rstan]{stan}} with +the Stan code and data for their respective models. } \details{ The user will typically pass further arguments to \code{\link[rstan]{stan}} via the \code{...} argument, at a minimum \code{iter} and \code{cores}. -By default \code{dgirt} overrides the \code{\link[rstan]{stan}} default for -its \code{pars} argument to specify typical DGIRT parameters of interest. -\code{dgirt} also sets \code{iter_r} to \code{1L}. -} -\seealso{ -\code{dgirt} expects \code{shaped_data} created by - \code{\link{shape}} and returns an object of class - \code{\link{dgirtfit-class}}. -\code{\link{dgirtfit-class}} \code{\link{shape}} +By default \code{dgirt} and \code{dgmrp} override the +\code{\link[rstan]{stan}} default for its \code{pars} argument to specify +typical parameters of interest. They also set \code{iter_r} to \code{1L}. } diff --git a/man/dgirt_fit-class.Rd b/man/dgirt_fit-class.Rd index dd6604f..4ccc180 100644 --- a/man/dgirt_fit-class.Rd +++ b/man/dgirt_fit-class.Rd @@ -33,9 +33,7 @@ get_posterior_mean(toy_dgirtfit, pars = 'theta_bar') apply(as.array(toy_dgirtfit, pars = 'xi'), 3, mean) # access the posterior samples -as.array(toy_dgirtfit, pars = 'theta_bar') -as.data.frame(toy_dgirtfit, pars = 'theta_bar') -extract(toy_dgirtfit, pars = 'theta_bar') +head(as.data.frame(toy_dgirtfit, pars = 'theta_bar')) } \seealso{ \code{\link{dgmrp_fit}} \code{\link{dgo_fit}} diff --git a/man/dgirtin-class.Rd b/man/dgirtin-class.Rd index 8630aad..ce0e64f 100644 --- a/man/dgirtin-class.Rd +++ b/man/dgirtin-class.Rd @@ -60,7 +60,7 @@ get_item_n(x, by = NULL, aggregate_data = FALSE) to `shape` as `aggregate_data` instead of on the individual data and count nonmissingness in the given variable.} -\item{aggregate_data}{If specified `get_n` will operate on the table passed +\item{aggregate_data}{If specified `get_item_n` will operate on the table passed to `shape` as `aggregate_data` instead of on the individual data.} } \value{ @@ -81,22 +81,26 @@ Count Respondents for Items in DGIRT Data Show Summary of DGIRT Data } \examples{ +data(toy_dgirt_in) get_item_names(toy_dgirt_in) get_n(toy_dgirt_in) get_n(toy_dgirt_in, by = "year") get_n(toy_dgirt_in, by = "source") get_item_n(toy_dgirt_in) get_item_n(toy_dgirt_in, by = "year") +data(toy_dgirt_in) get_item_names(toy_dgirt_in) # respondent count +data(toy_dgirt_in) get_n(toy_dgirt_in) # respondent count by year get_n(toy_dgirt_in, by = "year") -# respondent count by survey identifier -get_n(toy_dgirt_in, by = "source") +# respondent count by year and survey identifier +get_n(toy_dgirt_in, by = c("year", "source")) +data(toy_dgirt_in) get_item_n(toy_dgirt_in) get_item_n(toy_dgirt_in, by = "year") } diff --git a/man/dgmrp.Rd b/man/dgmrp.Rd deleted file mode 100644 index ea398d3..0000000 --- a/man/dgmrp.Rd +++ /dev/null @@ -1,57 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/dgmrp.r -\name{dgmrp} -\alias{dgmrp} -\title{\code{dgmrp}: fit a single-issue MRP model, with hierarchical covariates} -\usage{ -dgmrp(shaped_data, ..., separate_t = FALSE, delta_tbar_prior_mean = 0.65, - delta_tbar_prior_sd = 0.25, innov_sd_delta_scale = 2.5, - innov_sd_theta_scale = 2.5, version = "2017_01_04_singleissue") -} -\arguments{ -\item{shaped_data}{Output from \code{\link{shape}}.} - -\item{...}{Further arguments passed to \code{\link[rstan]{stan}}.} - -\item{separate_t}{Whether smoothing of estimates over time should be -disabled. Default \code{FALSE}.} - -\item{delta_tbar_prior_mean}{Prior mean for \code{delta_tbar}, the normal -weight on \code{theta_bar} in the previous period. Default \code{0.65}.} - -\item{delta_tbar_prior_sd}{Prior standard deviation for \code{delta_bar}. -Default \code{0.25}.} - -\item{innov_sd_delta_scale}{Prior scale for \code{sd_innov_delta}, the Cauchy -innovation standard deviation of \code{nu_geo} and \code{delta_gamma}. -Default \code{2.5}.} - -\item{innov_sd_theta_scale}{Prior scale for \code{sd_innov_theta}, the Cauchy -innovation standard deviation of \code{gamma}, \code{xi}, and if -\code{constant_item} is \code{FALSE} the item difficulty \code{diff}. Default -\code{2.5}.} - -\item{version}{The version of the DGIRT model to use.} -} -\value{ -A \code{\link{dgirtfit-class}} object that extends -\code{\link[rstan]{stanfit-class}}. -} -\description{ -\code{dgmrp} makes a call to \code{\link[rstan]{stan}} with the Stan code and -data for a dgmrp model. -} -\details{ -The user will typically pass further arguments to \code{\link[rstan]{stan}} -via the \code{...} argument, at a minimum \code{iter} and \code{cores}. - -By default \code{dgmrp} overrides the \code{\link[rstan]{stan}} default for -its \code{pars} argument to specify typical DGIRT parameters of interest. -\code{dgmrp} also sets \code{iter_r} to \code{1L}. -} -\seealso{ -\code{dgmrp} expects \code{shaped_data} created by - \code{\link{shape}} and returns an object of class - \code{\link{dgirtfit-class}}. -\code{\link{dgirtfit-class}} \code{\link{shape}} -} diff --git a/man/dgo.Rd b/man/dgo.Rd index f1843f1..dc2f5c5 100644 --- a/man/dgo.Rd +++ b/man/dgo.Rd @@ -6,7 +6,7 @@ \alias{dgo-package} \title{dgo: Dynamic Estimation of Group-level Opinion} \description{ -Fit dynamic group-level IRT models from individual or aggregated item +Fit dynamic group-level IRT and MRP models from individual or aggregated item response data. This package handles common preprocessing tasks and extends functions for inspecting results, poststratification, and quick iteration over alternative models. diff --git a/man/dgo_fit-methods.Rd b/man/dgo_fit-methods.Rd index 98f20ba..c20d773 100644 --- a/man/dgo_fit-methods.Rd +++ b/man/dgo_fit-methods.Rd @@ -74,8 +74,11 @@ objects \code{rhats}: extract split R-hats from \code{dgo_fit}-class objects } \examples{ +data(toy_dgirtfit) summarize(toy_dgirtfit) +data(toy_dgirtfit) # access posterior samples as.data.frame(toy_dgirtfit, pars = 'theta_bar') +data(toy_dgirtfit) rhats(toy_dgirtfit) } diff --git a/man/plot-method.Rd b/man/plot-method.Rd index 669986e..01f6d7f 100644 --- a/man/plot-method.Rd +++ b/man/plot-method.Rd @@ -67,16 +67,27 @@ respectively.} This function plots R-hats from a dgirt model. } \examples{ +\dontrun{ +data(toy_dgirtfit) dgirt_plot(toy_dgirtfit) dgirt_plot(toy_dgirtfit, y_min = NULL, y_max = NULL) p <- dgirt_plot(toy_dgirtfit) p \%+\% ylab("posterior median") +} +\dontrun{ +data(toy_dgirtfit) ps <- poststratify(toy_dgirtfit, annual_state_race_targets, strata_names = c("state", "year"), aggregated_names = "race3") dgirt_plot(ps, group_names = NULL, time_name = "year", geo_name = "state") - +} +\dontrun{ +data(toy_dgirtfit) plot(toy_dgirtfit) +} +\dontrun{ +data(toy_dgirtfit) plot_rhats(toy_dgirtfit) plot_rhats(toy_dgirtfit, facet_vars = "race3") + scale_x_continuous(breaks = seq.int(2006, 2008)) } +} diff --git a/man/shape.Rd b/man/shape.Rd index be3ead7..3486111 100644 --- a/man/shape.Rd +++ b/man/shape.Rd @@ -86,10 +86,10 @@ An object of class \code{dgirtIn} expected by \code{\link{dgirt}} and \code{\link{dgmrp}}. } \description{ -This function shapes various kinds of data for use in a dgirt model. Most -arguments give the name or names of key variables in the data; they end in -\code{_name} or \code{_names} and should be character vectors. Some others -implement preprocessing and modeling choices. +This function shapes data for use in a dgirt or dgmrp model. Most +arguments give the name or names of key variables in the data. These +arguments end in \code{_name} or \code{_names} and should be character +vectors. } \section{Item Response Data}{ @@ -118,7 +118,7 @@ be provided with argument \code{aggregate_data}. The data given by \code{aggregate_data} must be in a long table of trial and success counts indexed by item, group, and time period. The variable names given by arguments \code{group_names}, \code{geo_name}, and\code{time_name} -should exist in \code{aggregate_data}. Three fixed variable names must also +should exist in \code{aggregate_data}. Three fixed variable names must also appear in \code{aggregate_data}: \code{item} giving item identifiers, \code{n_grp} giving counts of item-response trials, and \code{s_grp} giving counts of item-response successes. These counts should be adjusted @@ -165,6 +165,3 @@ summary(shaped_responses) get_item_n(shaped_responses, by = "year") } -\seealso{ -\code{\link{dgirtin-class}} \code{\link{dgirtfit-class}} -} diff --git a/man/toy_dgirt_in.Rd b/man/toy_dgirt_in.Rd index ac80e46..78d1ef3 100644 --- a/man/toy_dgirt_in.Rd +++ b/man/toy_dgirt_in.Rd @@ -13,6 +13,3 @@ toy_dgirt_in used with \code{\link[dgo]{dgirt}} for DGIRT modeling. \code{toy_dgirt_in} is a minimal \code{\link[dgo]{dgirtin-class}} object for use in examples. } -\examples{ -toy_dgirt_in -} diff --git a/man/toy_dgirtfit.Rd b/man/toy_dgirtfit.Rd index 624f313..a436c7b 100644 --- a/man/toy_dgirtfit.Rd +++ b/man/toy_dgirtfit.Rd @@ -13,6 +13,3 @@ toy_dgirtfit that extends \code{\link[rstan]{stanfit-class}}. \code{toy_dgirtfit} is a minimal \code{\link[dgo]{dgirtfit}} object for use in examples. } -\examples{ -toy_dgirtfit -} diff --git a/src/Makevars b/src/Makevars deleted file mode 100644 index 6371e2f..0000000 --- a/src/Makevars +++ /dev/null @@ -1,2 +0,0 @@ -STANHEADERS_SRC = `"$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" --vanilla -e "cat(system.file('include', 'src', package = 'StanHeaders'))"` -PKG_CPPFLAGS = -I"$(STANHEADERS_SRC)" -DBOOST_RESULT_OF_USE_TR1 -DBOOST_NO_DECLTYPE -DBOOST_DISABLE_ASSERTS diff --git a/src/Modules.cpp b/src/Modules.cpp deleted file mode 100644 index d3cd58c..0000000 --- a/src/Modules.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include -using namespace Rcpp ; -#include "include/models.hpp" - -RCPP_MODULE(stan_fit42015_12_16_mod) { - - - class_ >("model_2015_12_16") - - .constructor() - - - .method("call_sampler", &rstan::stan_fit ::call_sampler) - .method("param_names", &rstan::stan_fit ::param_names) - .method("param_names_oi", &rstan::stan_fit ::param_names_oi) - .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) - .method("param_dims", &rstan::stan_fit ::param_dims) - .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) - .method("update_param_oi", &rstan::stan_fit ::update_param_oi) - .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) - .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) - .method("log_prob", &rstan::stan_fit ::log_prob) - .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) - .method("constrain_pars", &rstan::stan_fit ::constrain_pars) - .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) - .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) - .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) - ; -} -#include -using namespace Rcpp ; -#include "include/models.hpp" - -RCPP_MODULE(stan_fit42016_04_20_mod) { - - - class_ >("model_2016_04_20") - - .constructor() - - - .method("call_sampler", &rstan::stan_fit ::call_sampler) - .method("param_names", &rstan::stan_fit ::param_names) - .method("param_names_oi", &rstan::stan_fit ::param_names_oi) - .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) - .method("param_dims", &rstan::stan_fit ::param_dims) - .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) - .method("update_param_oi", &rstan::stan_fit ::update_param_oi) - .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) - .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) - .method("log_prob", &rstan::stan_fit ::log_prob) - .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) - .method("constrain_pars", &rstan::stan_fit ::constrain_pars) - .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) - .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) - .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) - ; -} -#include -using namespace Rcpp ; -#include "include/models.hpp" - -RCPP_MODULE(stan_fit42016_09_14_mod) { - - - class_ >("model_2016_09_14") - - .constructor() - - - .method("call_sampler", &rstan::stan_fit ::call_sampler) - .method("param_names", &rstan::stan_fit ::param_names) - .method("param_names_oi", &rstan::stan_fit ::param_names_oi) - .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) - .method("param_dims", &rstan::stan_fit ::param_dims) - .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) - .method("update_param_oi", &rstan::stan_fit ::update_param_oi) - .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) - .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) - .method("log_prob", &rstan::stan_fit ::log_prob) - .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) - .method("constrain_pars", &rstan::stan_fit ::constrain_pars) - .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) - .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) - .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) - ; -} -#include -using namespace Rcpp ; -#include "include/models.hpp" - -RCPP_MODULE(stan_fit42017_01_04_mod) { - - - class_ >("model_2017_01_04") - - .constructor() - - - .method("call_sampler", &rstan::stan_fit ::call_sampler) - .method("param_names", &rstan::stan_fit ::param_names) - .method("param_names_oi", &rstan::stan_fit ::param_names_oi) - .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) - .method("param_dims", &rstan::stan_fit ::param_dims) - .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) - .method("update_param_oi", &rstan::stan_fit ::update_param_oi) - .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) - .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) - .method("log_prob", &rstan::stan_fit ::log_prob) - .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) - .method("constrain_pars", &rstan::stan_fit ::constrain_pars) - .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) - .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) - .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) - ; -} -#include -using namespace Rcpp ; -#include "include/models.hpp" - -RCPP_MODULE(stan_fit42017_01_04_singleissue_mod) { - - - class_ >("model_2017_01_04_singleissue") - - .constructor() - - - .method("call_sampler", &rstan::stan_fit ::call_sampler) - .method("param_names", &rstan::stan_fit ::param_names) - .method("param_names_oi", &rstan::stan_fit ::param_names_oi) - .method("param_fnames_oi", &rstan::stan_fit ::param_fnames_oi) - .method("param_dims", &rstan::stan_fit ::param_dims) - .method("param_dims_oi", &rstan::stan_fit ::param_dims_oi) - .method("update_param_oi", &rstan::stan_fit ::update_param_oi) - .method("param_oi_tidx", &rstan::stan_fit ::param_oi_tidx) - .method("grad_log_prob", &rstan::stan_fit ::grad_log_prob) - .method("log_prob", &rstan::stan_fit ::log_prob) - .method("unconstrain_pars", &rstan::stan_fit ::unconstrain_pars) - .method("constrain_pars", &rstan::stan_fit ::constrain_pars) - .method("num_pars_unconstrained", &rstan::stan_fit ::num_pars_unconstrained) - .method("unconstrained_param_names", &rstan::stan_fit ::unconstrained_param_names) - .method("constrained_param_names", &rstan::stan_fit ::constrained_param_names) - ; -} diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp index ed10878..1637225 100644 --- a/src/RcppExports.cpp +++ b/src/RcppExports.cpp @@ -1,7 +1,6 @@ // Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 -#include #include using namespace Rcpp; diff --git a/src/dgo_init.c b/src/dgo_init.c new file mode 100644 index 0000000..3ec91e6 --- /dev/null +++ b/src/dgo_init.c @@ -0,0 +1,18 @@ +#include +#include +#include // for NULL +#include + +/* .Call calls */ +extern SEXP dgo_dichotomize_cpp(SEXP); + +static const R_CallMethodDef CallEntries[] = { + {"dgo_dichotomize_cpp", (DL_FUNC) &dgo_dichotomize_cpp, 1}, + {NULL, NULL, 0} +}; + +void R_init_dgo(DllInfo *dll) +{ + R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); + R_useDynamicSymbols(dll, FALSE); +} diff --git a/src/include/models.hpp b/src/include/models.hpp deleted file mode 100644 index a2a32fa..0000000 --- a/src/include/models.hpp +++ /dev/null @@ -1,10142 +0,0 @@ -#ifndef MODELS_HPP -#define MODELS_HPP -#define STAN__SERVICES__COMMAND_HPP -#include -// Code generated by Stan version 2.14 - -#include - -namespace model_2015_12_16_namespace { - -using std::istream; -using std::string; -using std::stringstream; -using std::vector; -using stan::io::dump; -using stan::math::lgamma; -using stan::model::prob_grad; -using namespace stan::math; - -typedef Eigen::Matrix vector_d; -typedef Eigen::Matrix row_vector_d; -typedef Eigen::Matrix matrix_d; - -static int current_statement_begin__; - -class model_2015_12_16 : public prob_grad { -private: - int G; - int G_hier; - int Q; - int T; - int N; - int S; - int P; - int H; - int Hprior; - int D; - int constant_item; - int separate_t; - double delta_tbar_prior_mean; - double delta_tbar_prior_sd; - double innov_sd_delta_scale; - double innov_sd_theta_scale; - vector n_vec; - vector s_vec; - vector > > NNl2; - vector > > SSl2; - vector > > MMM; - matrix_d XX; - vector WT; - vector ZZ; - vector ZZ_prior; - matrix_d l2_only; -public: - model_2015_12_16(stan::io::var_context& context__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - typedef boost::ecuyer1988 rng_t; - rng_t base_rng(0); // 0 seed default - ctor_body(context__, base_rng, pstream__); - } - - template - model_2015_12_16(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - ctor_body(context__, base_rng__, pstream__); - } - - template - void ctor_body(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__) { - current_statement_begin__ = -1; - - static const char* function__ = "model_2015_12_16_namespace::model_2015_12_16"; - (void) function__; // dummy call to supress warning - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_i__; - std::vector vals_r__; - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - // initialize member variables - context__.validate_dims("data initialization", "G", "int", context__.to_vec()); - G = int(0); - vals_i__ = context__.vals_i("G"); - pos__ = 0; - G = vals_i__[pos__++]; - context__.validate_dims("data initialization", "G_hier", "int", context__.to_vec()); - G_hier = int(0); - vals_i__ = context__.vals_i("G_hier"); - pos__ = 0; - G_hier = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Q", "int", context__.to_vec()); - Q = int(0); - vals_i__ = context__.vals_i("Q"); - pos__ = 0; - Q = vals_i__[pos__++]; - context__.validate_dims("data initialization", "T", "int", context__.to_vec()); - T = int(0); - vals_i__ = context__.vals_i("T"); - pos__ = 0; - T = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N", "int", context__.to_vec()); - N = int(0); - vals_i__ = context__.vals_i("N"); - pos__ = 0; - N = vals_i__[pos__++]; - context__.validate_dims("data initialization", "S", "int", context__.to_vec()); - S = int(0); - vals_i__ = context__.vals_i("S"); - pos__ = 0; - S = vals_i__[pos__++]; - context__.validate_dims("data initialization", "P", "int", context__.to_vec()); - P = int(0); - vals_i__ = context__.vals_i("P"); - pos__ = 0; - P = vals_i__[pos__++]; - context__.validate_dims("data initialization", "H", "int", context__.to_vec()); - H = int(0); - vals_i__ = context__.vals_i("H"); - pos__ = 0; - H = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Hprior", "int", context__.to_vec()); - Hprior = int(0); - vals_i__ = context__.vals_i("Hprior"); - pos__ = 0; - Hprior = vals_i__[pos__++]; - context__.validate_dims("data initialization", "D", "int", context__.to_vec()); - D = int(0); - vals_i__ = context__.vals_i("D"); - pos__ = 0; - D = vals_i__[pos__++]; - context__.validate_dims("data initialization", "constant_item", "int", context__.to_vec()); - constant_item = int(0); - vals_i__ = context__.vals_i("constant_item"); - pos__ = 0; - constant_item = vals_i__[pos__++]; - context__.validate_dims("data initialization", "separate_t", "int", context__.to_vec()); - separate_t = int(0); - vals_i__ = context__.vals_i("separate_t"); - pos__ = 0; - separate_t = vals_i__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_mean", "double", context__.to_vec()); - delta_tbar_prior_mean = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_mean"); - pos__ = 0; - delta_tbar_prior_mean = vals_r__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_sd", "double", context__.to_vec()); - delta_tbar_prior_sd = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_sd"); - pos__ = 0; - delta_tbar_prior_sd = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_delta_scale", "double", context__.to_vec()); - innov_sd_delta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_delta_scale"); - pos__ = 0; - innov_sd_delta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_theta_scale", "double", context__.to_vec()); - innov_sd_theta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_theta_scale"); - pos__ = 0; - innov_sd_theta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "n_vec", "int", context__.to_vec(N)); - validate_non_negative_index("n_vec", "N", N); - n_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("n_vec"); - pos__ = 0; - size_t n_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < n_vec_limit_0__; ++i_0__) { - n_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "s_vec", "int", context__.to_vec(N)); - validate_non_negative_index("s_vec", "N", N); - s_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("s_vec"); - pos__ = 0; - size_t s_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < s_vec_limit_0__; ++i_0__) { - s_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "NNl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("NNl2", "T", T); - validate_non_negative_index("NNl2", "Q", Q); - validate_non_negative_index("NNl2", "G_hier", G_hier); - NNl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("NNl2"); - pos__ = 0; - size_t NNl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < NNl2_limit_2__; ++i_2__) { - size_t NNl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < NNl2_limit_1__; ++i_1__) { - size_t NNl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < NNl2_limit_0__; ++i_0__) { - NNl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "SSl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("SSl2", "T", T); - validate_non_negative_index("SSl2", "Q", Q); - validate_non_negative_index("SSl2", "G_hier", G_hier); - SSl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("SSl2"); - pos__ = 0; - size_t SSl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < SSl2_limit_2__; ++i_2__) { - size_t SSl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < SSl2_limit_1__; ++i_1__) { - size_t SSl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < SSl2_limit_0__; ++i_0__) { - SSl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "MMM", "int", context__.to_vec(T,Q,G)); - validate_non_negative_index("MMM", "T", T); - validate_non_negative_index("MMM", "Q", Q); - validate_non_negative_index("MMM", "G", G); - MMM = std::vector > >(T,std::vector >(Q,std::vector(G,int(0)))); - vals_i__ = context__.vals_i("MMM"); - pos__ = 0; - size_t MMM_limit_2__ = G; - for (size_t i_2__ = 0; i_2__ < MMM_limit_2__; ++i_2__) { - size_t MMM_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < MMM_limit_1__; ++i_1__) { - size_t MMM_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < MMM_limit_0__; ++i_0__) { - MMM[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "XX", "matrix_d", context__.to_vec(G,P)); - validate_non_negative_index("XX", "G", G); - validate_non_negative_index("XX", "P", P); - XX = matrix_d(static_cast(G),static_cast(P)); - vals_r__ = context__.vals_r("XX"); - pos__ = 0; - size_t XX_m_mat_lim__ = G; - size_t XX_n_mat_lim__ = P; - for (size_t n_mat__ = 0; n_mat__ < XX_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < XX_m_mat_lim__; ++m_mat__) { - XX(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - context__.validate_dims("data initialization", "WT", "matrix_d", context__.to_vec(T,G_hier,G)); - validate_non_negative_index("WT", "T", T); - validate_non_negative_index("WT", "G_hier", G_hier); - validate_non_negative_index("WT", "G", G); - WT = std::vector(T,matrix_d(static_cast(G_hier),static_cast(G))); - vals_r__ = context__.vals_r("WT"); - pos__ = 0; - size_t WT_m_mat_lim__ = G_hier; - size_t WT_n_mat_lim__ = G; - for (size_t n_mat__ = 0; n_mat__ < WT_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < WT_m_mat_lim__; ++m_mat__) { - size_t WT_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < WT_limit_0__; ++i_0__) { - WT[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ", "matrix_d", context__.to_vec(T,P,H)); - validate_non_negative_index("ZZ", "T", T); - validate_non_negative_index("ZZ", "P", P); - validate_non_negative_index("ZZ", "H", H); - ZZ = std::vector(T,matrix_d(static_cast(P),static_cast(H))); - vals_r__ = context__.vals_r("ZZ"); - pos__ = 0; - size_t ZZ_m_mat_lim__ = P; - size_t ZZ_n_mat_lim__ = H; - for (size_t n_mat__ = 0; n_mat__ < ZZ_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_m_mat_lim__; ++m_mat__) { - size_t ZZ_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_limit_0__; ++i_0__) { - ZZ[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ_prior", "matrix_d", context__.to_vec(T,P,Hprior)); - validate_non_negative_index("ZZ_prior", "T", T); - validate_non_negative_index("ZZ_prior", "P", P); - validate_non_negative_index("ZZ_prior", "Hprior", Hprior); - ZZ_prior = std::vector(T,matrix_d(static_cast(P),static_cast(Hprior))); - vals_r__ = context__.vals_r("ZZ_prior"); - pos__ = 0; - size_t ZZ_prior_m_mat_lim__ = P; - size_t ZZ_prior_n_mat_lim__ = Hprior; - for (size_t n_mat__ = 0; n_mat__ < ZZ_prior_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_prior_m_mat_lim__; ++m_mat__) { - size_t ZZ_prior_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_prior_limit_0__; ++i_0__) { - ZZ_prior[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "l2_only", "matrix_d", context__.to_vec(T,Q)); - validate_non_negative_index("l2_only", "T", T); - validate_non_negative_index("l2_only", "Q", Q); - l2_only = matrix_d(static_cast(T),static_cast(Q)); - vals_r__ = context__.vals_r("l2_only"); - pos__ = 0; - size_t l2_only_m_mat_lim__ = T; - size_t l2_only_n_mat_lim__ = Q; - for (size_t n_mat__ = 0; n_mat__ < l2_only_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < l2_only_m_mat_lim__; ++m_mat__) { - l2_only(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - - // validate, data variables - check_greater_or_equal(function__,"G",G,1); - check_greater_or_equal(function__,"G_hier",G_hier,1); - check_greater_or_equal(function__,"Q",Q,1); - check_greater_or_equal(function__,"T",T,1); - check_greater_or_equal(function__,"N",N,1); - check_greater_or_equal(function__,"S",S,1); - check_greater_or_equal(function__,"P",P,1); - check_greater_or_equal(function__,"H",H,1); - check_greater_or_equal(function__,"Hprior",Hprior,1); - check_greater_or_equal(function__,"D",D,1); - check_greater_or_equal(function__,"constant_item",constant_item,0); - check_less_or_equal(function__,"constant_item",constant_item,1); - check_greater_or_equal(function__,"separate_t",separate_t,0); - check_less_or_equal(function__,"separate_t",separate_t,1); - check_greater_or_equal(function__,"delta_tbar_prior_sd",delta_tbar_prior_sd,0); - check_greater_or_equal(function__,"innov_sd_delta_scale",innov_sd_delta_scale,0); - check_greater_or_equal(function__,"innov_sd_theta_scale",innov_sd_theta_scale,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"MMM[k0__][k1__][k2__]",MMM[k0__][k1__][k2__],0); - } - } - } - check_greater_or_equal(function__,"XX",XX,0); - check_less_or_equal(function__,"XX",XX,1); - for (int k0__ = 0; k0__ < T; ++k0__) { - check_greater_or_equal(function__,"WT[k0__]",WT[k0__],0); - check_less_or_equal(function__,"WT[k0__]",WT[k0__],1); - } - check_greater_or_equal(function__,"l2_only",l2_only,0); - check_less_or_equal(function__,"l2_only",l2_only,1); - // initialize data variables - - try { - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed data - - // set parameter ranges - num_params_r__ = 0U; - param_ranges_i__.clear(); - num_params_r__ += Q * D; - num_params_r__ += Q; - num_params_r__ += T; - num_params_r__ += P * T; - num_params_r__ += T; - num_params_r__ += H * T; - num_params_r__ += Hprior; - num_params_r__ += T; - num_params_r__ += G * T; - num_params_r__ += T; - num_params_r__ += T; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - } - - ~model_2015_12_16() { } - - - void transform_inits(const stan::io::var_context& context__, - std::vector& params_i__, - std::vector& params_r__, - std::ostream* pstream__) const { - stan::io::writer writer__(params_r__,params_i__); - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_r__; - std::vector vals_i__; - - if (!(context__.contains_r("diff_raw"))) - throw std::runtime_error("variable diff_raw missing"); - vals_r__ = context__.vals_r("diff_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "diff_raw", "vector_d", context__.to_vec(D,Q)); - // generate_declaration diff_raw - std::vector diff_raw(D,vector_d(static_cast(Q))); - for (int j1__ = 0U; j1__ < Q; ++j1__) - for (int i0__ = 0U; i0__ < D; ++i0__) - diff_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < D; ++i0__) - try { - writer__.vector_unconstrain(diff_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable diff_raw: ") + e.what()); - } - - if (!(context__.contains_r("disc_raw"))) - throw std::runtime_error("variable disc_raw missing"); - vals_r__ = context__.vals_r("disc_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "disc_raw", "vector_d", context__.to_vec(Q)); - // generate_declaration disc_raw - vector_d disc_raw(static_cast(Q)); - for (int j1__ = 0U; j1__ < Q; ++j1__) - disc_raw(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,disc_raw); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable disc_raw: ") + e.what()); - } - - if (!(context__.contains_r("xi"))) - throw std::runtime_error("variable xi missing"); - vals_r__ = context__.vals_r("xi"); - pos__ = 0U; - context__.validate_dims("initialization", "xi", "vector_d", context__.to_vec(T)); - // generate_declaration xi - vector_d xi(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - xi(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(xi); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable xi: ") + e.what()); - } - - if (!(context__.contains_r("gamma_raw"))) - throw std::runtime_error("variable gamma_raw missing"); - vals_r__ = context__.vals_r("gamma_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "gamma_raw", "vector_d", context__.to_vec(T,P)); - // generate_declaration gamma_raw - std::vector gamma_raw(T,vector_d(static_cast(P))); - for (int j1__ = 0U; j1__ < P; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - gamma_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(gamma_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable gamma_raw: ") + e.what()); - } - - if (!(context__.contains_r("delta_gamma"))) - throw std::runtime_error("variable delta_gamma missing"); - vals_r__ = context__.vals_r("delta_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_gamma", "vector_d", context__.to_vec(T)); - // generate_declaration delta_gamma - vector_d delta_gamma(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_gamma(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_gamma: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo"))) - throw std::runtime_error("variable nu_geo missing"); - vals_r__ = context__.vals_r("nu_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo", "vector_d", context__.to_vec(T,H)); - // generate_declaration nu_geo - std::vector nu_geo(T,vector_d(static_cast(H))); - for (int j1__ = 0U; j1__ < H; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - nu_geo[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(nu_geo[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo_prior"))) - throw std::runtime_error("variable nu_geo_prior missing"); - vals_r__ = context__.vals_r("nu_geo_prior"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo_prior", "vector_d", context__.to_vec(Hprior)); - // generate_declaration nu_geo_prior - vector_d nu_geo_prior(static_cast(Hprior)); - for (int j1__ = 0U; j1__ < Hprior; ++j1__) - nu_geo_prior(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(nu_geo_prior); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo_prior: ") + e.what()); - } - - if (!(context__.contains_r("delta_tbar"))) - throw std::runtime_error("variable delta_tbar missing"); - vals_r__ = context__.vals_r("delta_tbar"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_tbar", "vector_d", context__.to_vec(T)); - // generate_declaration delta_tbar - vector_d delta_tbar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_tbar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_tbar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_tbar: ") + e.what()); - } - - if (!(context__.contains_r("theta_bar_raw"))) - throw std::runtime_error("variable theta_bar_raw missing"); - vals_r__ = context__.vals_r("theta_bar_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "theta_bar_raw", "vector_d", context__.to_vec(T,G)); - // generate_declaration theta_bar_raw - std::vector theta_bar_raw(T,vector_d(static_cast(G))); - for (int j1__ = 0U; j1__ < G; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - theta_bar_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(theta_bar_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable theta_bar_raw: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta_bar"))) - throw std::runtime_error("variable sd_theta_bar missing"); - vals_r__ = context__.vals_r("sd_theta_bar"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta_bar", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta_bar - vector_d sd_theta_bar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta_bar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta_bar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta_bar: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta"))) - throw std::runtime_error("variable sd_theta missing"); - vals_r__ = context__.vals_r("sd_theta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta - vector_d sd_theta(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma"))) - throw std::runtime_error("variable sd_gamma missing"); - vals_r__ = context__.vals_r("sd_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma", "double", context__.to_vec()); - // generate_declaration sd_gamma - double sd_gamma(0); - sd_gamma = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_delta"))) - throw std::runtime_error("variable sd_innov_delta missing"); - vals_r__ = context__.vals_r("sd_innov_delta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_delta", "double", context__.to_vec()); - // generate_declaration sd_innov_delta - double sd_innov_delta(0); - sd_innov_delta = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_delta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_delta: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_logsd"))) - throw std::runtime_error("variable sd_innov_logsd missing"); - vals_r__ = context__.vals_r("sd_innov_logsd"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_logsd", "double", context__.to_vec()); - // generate_declaration sd_innov_logsd - double sd_innov_logsd(0); - sd_innov_logsd = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_logsd); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_logsd: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_gamma"))) - throw std::runtime_error("variable sd_innov_gamma missing"); - vals_r__ = context__.vals_r("sd_innov_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_gamma", "double", context__.to_vec()); - // generate_declaration sd_innov_gamma - double sd_innov_gamma(0); - sd_innov_gamma = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_gamma: ") + e.what()); - } - - params_r__ = writer__.data_r(); - params_i__ = writer__.data_i(); - } - - void transform_inits(const stan::io::var_context& context, - Eigen::Matrix& params_r, - std::ostream* pstream__) const { - std::vector params_r_vec; - std::vector params_i_vec; - transform_inits(context, params_i_vec, params_r_vec, pstream__); - params_r.resize(params_r_vec.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r(i) = params_r_vec[i]; - } - - - template - T__ log_prob(vector& params_r__, - vector& params_i__, - std::ostream* pstream__ = 0) const { - - T__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - T__ lp__(0.0); - stan::math::accumulator lp_accum__; - - // model parameters - stan::io::reader in__(params_r__,params_i__); - - vector > diff_raw; - size_t dim_diff_raw_0__ = D; - diff_raw.reserve(dim_diff_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - if (jacobian__) - diff_raw.push_back(in__.vector_constrain(Q,lp__)); - else - diff_raw.push_back(in__.vector_constrain(Q)); - } - - Eigen::Matrix disc_raw; - (void) disc_raw; // dummy to suppress unused var warning - if (jacobian__) - disc_raw = in__.vector_lb_constrain(0,Q,lp__); - else - disc_raw = in__.vector_lb_constrain(0,Q); - - Eigen::Matrix xi; - (void) xi; // dummy to suppress unused var warning - if (jacobian__) - xi = in__.vector_constrain(T,lp__); - else - xi = in__.vector_constrain(T); - - vector > gamma_raw; - size_t dim_gamma_raw_0__ = T; - gamma_raw.reserve(dim_gamma_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - if (jacobian__) - gamma_raw.push_back(in__.vector_constrain(P,lp__)); - else - gamma_raw.push_back(in__.vector_constrain(P)); - } - - Eigen::Matrix delta_gamma; - (void) delta_gamma; // dummy to suppress unused var warning - if (jacobian__) - delta_gamma = in__.vector_constrain(T,lp__); - else - delta_gamma = in__.vector_constrain(T); - - vector > nu_geo; - size_t dim_nu_geo_0__ = T; - nu_geo.reserve(dim_nu_geo_0__); - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - if (jacobian__) - nu_geo.push_back(in__.vector_constrain(H,lp__)); - else - nu_geo.push_back(in__.vector_constrain(H)); - } - - Eigen::Matrix nu_geo_prior; - (void) nu_geo_prior; // dummy to suppress unused var warning - if (jacobian__) - nu_geo_prior = in__.vector_constrain(Hprior,lp__); - else - nu_geo_prior = in__.vector_constrain(Hprior); - - Eigen::Matrix delta_tbar; - (void) delta_tbar; // dummy to suppress unused var warning - if (jacobian__) - delta_tbar = in__.vector_constrain(T,lp__); - else - delta_tbar = in__.vector_constrain(T); - - vector > theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - theta_bar_raw.reserve(dim_theta_bar_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - if (jacobian__) - theta_bar_raw.push_back(in__.vector_constrain(G,lp__)); - else - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - - Eigen::Matrix sd_theta_bar; - (void) sd_theta_bar; // dummy to suppress unused var warning - if (jacobian__) - sd_theta_bar = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta_bar = in__.vector_lb_constrain(0,T); - - Eigen::Matrix sd_theta; - (void) sd_theta; // dummy to suppress unused var warning - if (jacobian__) - sd_theta = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta = in__.vector_lb_constrain(0,T); - - T__ sd_gamma; - (void) sd_gamma; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma = in__.scalar_lb_constrain(0); - - T__ sd_innov_delta; - (void) sd_innov_delta; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_delta = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_delta = in__.scalar_lb_constrain(0); - - T__ sd_innov_logsd; - (void) sd_innov_logsd; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_logsd = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_logsd = in__.scalar_lb_constrain(0); - - T__ sd_innov_gamma; - (void) sd_innov_gamma; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_gamma = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_gamma = in__.scalar_lb_constrain(0); - - - // transformed parameters - vector > theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(theta_bar, DUMMY_VAR__); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector > diff(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(diff, DUMMY_VAR__); - stan::math::fill(diff,DUMMY_VAR__); - vector > kappa(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(kappa, DUMMY_VAR__); - stan::math::fill(kappa,DUMMY_VAR__); - Eigen::Matrix disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, DUMMY_VAR__); - stan::math::fill(disc,DUMMY_VAR__); - Eigen::Matrix sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, DUMMY_VAR__); - stan::math::fill(sd_item,DUMMY_VAR__); - Eigen::Matrix var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, DUMMY_VAR__); - stan::math::fill(var_item,DUMMY_VAR__); - Eigen::Matrix var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, DUMMY_VAR__); - stan::math::fill(var_theta,DUMMY_VAR__); - vector > var_theta_bar_l2(T, (Eigen::Matrix (static_cast(G_hier)))); - stan::math::initialize(var_theta_bar_l2, DUMMY_VAR__); - stan::math::fill(var_theta_bar_l2,DUMMY_VAR__); - vector > gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(gamma, DUMMY_VAR__); - stan::math::fill(gamma,DUMMY_VAR__); - vector > mu_theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(mu_theta_bar, DUMMY_VAR__); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector > mu_gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(mu_gamma, DUMMY_VAR__); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > > z(T, (vector >(Q, (Eigen::Matrix (static_cast(G)))))); - stan::math::initialize(z, DUMMY_VAR__); - stan::math::fill(z,DUMMY_VAR__); - vector > > z_l2(T, (vector >(Q, (Eigen::Matrix (static_cast(G_hier)))))); - stan::math::initialize(z_l2, DUMMY_VAR__); - stan::math::fill(z_l2,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G))))); - stan::math::initialize(prob, DUMMY_VAR__); - stan::math::fill(prob,DUMMY_VAR__); - vector > > prob_l2(T, (vector >(Q, (Eigen::Matrix (static_cast(G_hier)))))); - stan::math::initialize(prob_l2, DUMMY_VAR__); - stan::math::fill(prob_l2,DUMMY_VAR__); - vector > theta_l2(T, (Eigen::Matrix (static_cast(G_hier)))); - stan::math::initialize(theta_l2, DUMMY_VAR__); - stan::math::fill(theta_l2,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } else { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), add(multiply(get_base1(gamma,(t - 1),"gamma",1),get_base1(delta_gamma,t,"delta_gamma",1)),multiply(get_base1(ZZ,t,"ZZ",1),get_base1(nu_geo,t,"nu_geo",1)))); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - stan::math::assign(get_base1_lhs(theta_l2,t,"theta_l2",1), multiply(get_base1(WT,t,"WT",1),get_base1(theta_bar,t,"theta_bar",1))); - for (int n = 1; n <= G_hier; ++n) { - { - Eigen::Matrix WTdiag(static_cast(G),static_cast(G)); - (void) WTdiag; // dummy to suppress unused var warning - stan::math::initialize(WTdiag, DUMMY_VAR__); - stan::math::fill(WTdiag,DUMMY_VAR__); - - - for (int g = 1; g <= G; ++g) { - - for (int h = 1; h <= G; ++h) { - - if (as_bool(logical_eq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), get_base1(get_base1(WT,t,"WT",1),n,g,"WT",2)); - } - if (as_bool(logical_neq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), 0); - } - } - } - stan::math::assign(get_base1_lhs(get_base1_lhs(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2), multiply(multiply(transpose(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2))),WTdiag),subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2)))); - } - } - for (int q = 1; q <= Q; ++q) { - { - T__ sd_tq; - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, DUMMY_VAR__); - stan::math::fill(sd_tq,DUMMY_VAR__); - vector sd_l2_tq(G_hier); - stan::math::initialize(sd_l2_tq, DUMMY_VAR__); - stan::math::fill(sd_l2_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(sd_l2_tq,n,"sd_l2_tq",1), sqrt((square(sd_tq) + get_base1(get_base1(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2)))); - } - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - for (int g = 1; g <= G; ++g) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(diff[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: diff" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(kappa[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: kappa" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(disc(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: disc" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(sd_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: sd_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(var_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - if (stan::math::is_uninitialized(var_theta(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_theta" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G_hier; ++i1__) { - if (stan::math::is_uninitialized(var_theta_bar_l2[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_theta_bar_l2" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(mu_theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(mu_gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(z[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G_hier; ++i2__) { - if (stan::math::is_uninitialized(z_l2[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z_l2" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(prob[i0__][i1__][i2__])) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G_hier; ++i2__) { - if (stan::math::is_uninitialized(prob_l2[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob_l2" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G_hier; ++i1__) { - if (stan::math::is_uninitialized(theta_l2[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_l2" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - - const char* function__ = "validate transformed params"; - (void) function__; // dummy to suppress unused var warning - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // model body - try { - { - vector prob_vec(N); - stan::math::initialize(prob_vec, DUMMY_VAR__); - stan::math::fill(prob_vec,DUMMY_VAR__); - int pos(0); - (void) pos; // dummy to suppress unused var warning - stan::math::fill(pos, std::numeric_limits::min()); - - - stan::math::assign(pos, 0); - if (as_bool(logical_eq(constant_item,1))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,1,"diff_raw",1), 0, 1)); - } - lp_accum__.add(lognormal_log(disc_raw, 0, 1)); - lp_accum__.add(cauchy_log(sd_gamma, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_delta, 0, innov_sd_delta_scale)); - lp_accum__.add(cauchy_log(sd_innov_gamma, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_logsd, 0, innov_sd_theta_scale)); - for (int t = 1; t <= T; ++t) { - - lp_accum__.add(normal_log(get_base1(gamma_raw,t,"gamma_raw",1), 0, 1)); - lp_accum__.add(normal_log(get_base1(theta_bar_raw,t,"theta_bar_raw",1), 0, 1)); - if (as_bool(logical_eq(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), 0, 1)); - } - lp_accum__.add(cauchy_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), 0, 2.5)); - lp_accum__.add(cauchy_log(get_base1(sd_theta,t,"sd_theta",1), 0, 2.5)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), 0, 10)); - lp_accum__.add(normal_log(nu_geo_prior, 0, 10)); - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), 0.5, 0.5)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), delta_tbar_prior_mean, delta_tbar_prior_sd)); - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - if (as_bool(logical_gt(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), get_base1(diff_raw,(t - 1),"diff_raw",1), sd_innov_gamma)); - } - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), get_base1(delta_gamma,(t - 1),"delta_gamma",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), get_base1(nu_geo,(t - 1),"nu_geo",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), get_base1(delta_tbar,(t - 1),"delta_tbar",1), sd_innov_delta)); - lp_accum__.add(lognormal_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), log(get_base1(sd_theta_bar,(t - 1),"sd_theta_bar",1)), sd_innov_logsd)); - lp_accum__.add(lognormal_log(get_base1(sd_theta,t,"sd_theta",1), log(get_base1(sd_theta,(t - 1),"sd_theta",1)), sd_innov_logsd)); - if (as_bool((primitive_value(logical_eq(separate_t,0)) && primitive_value(logical_gt(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), get_base1(xi,(t - 1),"xi",1), sd_innov_gamma)); - } - if (as_bool((primitive_value(logical_eq(separate_t,1)) || primitive_value(logical_eq(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - } - for (int q = 1; q <= Q; ++q) { - - if (as_bool(logical_eq(get_base1(l2_only,t,q,"l2_only",1),1))) { - - lp_accum__.add(binomial_log(get_base1(get_base1(SSl2,t,"SSl2",1),q,"SSl2",2), get_base1(get_base1(NNl2,t,"NNl2",1),q,"NNl2",2), get_base1(get_base1(prob_l2,t,"prob_l2",1),q,"prob_l2",2))); - } - for (int g = 1; g <= G; ++g) { - - if (as_bool(logical_eq(get_base1(get_base1(get_base1(MMM,t,"MMM",1),q,"MMM",2),g,"MMM",3),0))) { - - stan::math::assign(pos, (pos + 1)); - stan::math::assign(get_base1_lhs(prob_vec,pos,"prob_vec",1), get_base1(get_base1(get_base1(prob,t,"prob",1),q,"prob",2),g,"prob",3)); - } - } - } - } - lp_accum__.add(binomial_log(s_vec, n_vec, prob_vec)); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - lp_accum__.add(lp__); - return lp_accum__.sum(); - - } // log_prob() - - template - T_ log_prob(Eigen::Matrix& params_r, - std::ostream* pstream = 0) const { - std::vector vec_params_r; - vec_params_r.reserve(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - vec_params_r.push_back(params_r(i)); - std::vector vec_params_i; - return log_prob(vec_params_r, vec_params_i, pstream); - } - - - void get_param_names(std::vector& names__) const { - names__.resize(0); - names__.push_back("diff_raw"); - names__.push_back("disc_raw"); - names__.push_back("xi"); - names__.push_back("gamma_raw"); - names__.push_back("delta_gamma"); - names__.push_back("nu_geo"); - names__.push_back("nu_geo_prior"); - names__.push_back("delta_tbar"); - names__.push_back("theta_bar_raw"); - names__.push_back("sd_theta_bar"); - names__.push_back("sd_theta"); - names__.push_back("sd_gamma"); - names__.push_back("sd_innov_delta"); - names__.push_back("sd_innov_logsd"); - names__.push_back("sd_innov_gamma"); - names__.push_back("theta_bar"); - names__.push_back("diff"); - names__.push_back("kappa"); - names__.push_back("disc"); - names__.push_back("sd_item"); - names__.push_back("var_item"); - names__.push_back("var_theta"); - names__.push_back("var_theta_bar_l2"); - names__.push_back("gamma"); - names__.push_back("mu_theta_bar"); - names__.push_back("mu_gamma"); - names__.push_back("z"); - names__.push_back("z_l2"); - names__.push_back("prob"); - names__.push_back("prob_l2"); - names__.push_back("theta_l2"); - names__.push_back("sd_total"); - } - - - void get_dims(std::vector >& dimss__) const { - dimss__.resize(0); - std::vector dims__; - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(H); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Hprior); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - } - - template - void write_array(RNG& base_rng__, - std::vector& params_r__, - std::vector& params_i__, - std::vector& vars__, - bool include_tparams__ = true, - bool include_gqs__ = true, - std::ostream* pstream__ = 0) const { - vars__.resize(0); - stan::io::reader in__(params_r__,params_i__); - static const char* function__ = "model_2015_12_16_namespace::write_array"; - (void) function__; // dummy call to supress warning - // read-transform, write parameters - vector diff_raw; - size_t dim_diff_raw_0__ = D; - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - diff_raw.push_back(in__.vector_constrain(Q)); - } - vector_d disc_raw = in__.vector_lb_constrain(0,Q); - vector_d xi = in__.vector_constrain(T); - vector gamma_raw; - size_t dim_gamma_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - gamma_raw.push_back(in__.vector_constrain(P)); - } - vector_d delta_gamma = in__.vector_constrain(T); - vector nu_geo; - size_t dim_nu_geo_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - nu_geo.push_back(in__.vector_constrain(H)); - } - vector_d nu_geo_prior = in__.vector_constrain(Hprior); - vector_d delta_tbar = in__.vector_constrain(T); - vector theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - vector_d sd_theta_bar = in__.vector_lb_constrain(0,T); - vector_d sd_theta = in__.vector_lb_constrain(0,T); - double sd_gamma = in__.scalar_lb_constrain(0); - double sd_innov_delta = in__.scalar_lb_constrain(0); - double sd_innov_logsd = in__.scalar_lb_constrain(0); - double sd_innov_gamma = in__.scalar_lb_constrain(0); - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc_raw[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(xi[k_0__]); - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_gamma[k_0__]); - } - for (int k_1__ = 0; k_1__ < H; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(nu_geo[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Hprior; ++k_0__) { - vars__.push_back(nu_geo_prior[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_tbar[k_0__]); - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta_bar[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta[k_0__]); - } - vars__.push_back(sd_gamma); - vars__.push_back(sd_innov_delta); - vars__.push_back(sd_innov_logsd); - vars__.push_back(sd_innov_gamma); - - if (!include_tparams__) return; - // declare and define transformed parameters - double lp__ = 0.0; - (void) lp__; // dummy call to supress warning - stan::math::accumulator lp_accum__; - - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - vector theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector diff(D, (vector_d(static_cast(Q)))); - stan::math::initialize(diff, std::numeric_limits::quiet_NaN()); - stan::math::fill(diff,DUMMY_VAR__); - vector kappa(D, (vector_d(static_cast(Q)))); - stan::math::initialize(kappa, std::numeric_limits::quiet_NaN()); - stan::math::fill(kappa,DUMMY_VAR__); - vector_d disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, std::numeric_limits::quiet_NaN()); - stan::math::fill(disc,DUMMY_VAR__); - vector_d sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_item,DUMMY_VAR__); - vector_d var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_item,DUMMY_VAR__); - vector_d var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_theta,DUMMY_VAR__); - vector var_theta_bar_l2(T, (vector_d(static_cast(G_hier)))); - stan::math::initialize(var_theta_bar_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_theta_bar_l2,DUMMY_VAR__); - vector gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(gamma,DUMMY_VAR__); - vector mu_theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(mu_theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector mu_gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(mu_gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > z(T, (vector(Q, (vector_d(static_cast(G)))))); - stan::math::initialize(z, std::numeric_limits::quiet_NaN()); - stan::math::fill(z,DUMMY_VAR__); - vector > z_l2(T, (vector(Q, (vector_d(static_cast(G_hier)))))); - stan::math::initialize(z_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(z_l2,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G, 0.0))))); - stan::math::initialize(prob, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob,DUMMY_VAR__); - vector > prob_l2(T, (vector(Q, (vector_d(static_cast(G_hier)))))); - stan::math::initialize(prob_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob_l2,DUMMY_VAR__); - vector theta_l2(T, (vector_d(static_cast(G_hier)))); - stan::math::initialize(theta_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_l2,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } else { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), add(multiply(get_base1(gamma,(t - 1),"gamma",1),get_base1(delta_gamma,t,"delta_gamma",1)),multiply(get_base1(ZZ,t,"ZZ",1),get_base1(nu_geo,t,"nu_geo",1)))); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - stan::math::assign(get_base1_lhs(theta_l2,t,"theta_l2",1), multiply(get_base1(WT,t,"WT",1),get_base1(theta_bar,t,"theta_bar",1))); - for (int n = 1; n <= G_hier; ++n) { - { - matrix_d WTdiag(static_cast(G),static_cast(G)); - (void) WTdiag; // dummy to suppress unused var warning - stan::math::initialize(WTdiag, std::numeric_limits::quiet_NaN()); - stan::math::fill(WTdiag,DUMMY_VAR__); - - - for (int g = 1; g <= G; ++g) { - - for (int h = 1; h <= G; ++h) { - - if (as_bool(logical_eq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), get_base1(get_base1(WT,t,"WT",1),n,g,"WT",2)); - } - if (as_bool(logical_neq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), 0); - } - } - } - stan::math::assign(get_base1_lhs(get_base1_lhs(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2), multiply(multiply(transpose(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2))),WTdiag),subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2)))); - } - } - for (int q = 1; q <= Q; ++q) { - { - double sd_tq(0.0); - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_tq,DUMMY_VAR__); - vector sd_l2_tq(G_hier, 0.0); - stan::math::initialize(sd_l2_tq, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_l2_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(sd_l2_tq,n,"sd_l2_tq",1), sqrt((square(sd_tq) + get_base1(get_base1(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2)))); - } - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - for (int g = 1; g <= G; ++g) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // write transformed parameters - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(kappa[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(sd_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(var_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(var_theta[k_0__]); - } - for (int k_1__ = 0; k_1__ < G_hier; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(var_theta_bar_l2[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_gamma[k_0__][k_1__]); - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G_hier; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z_l2[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G_hier; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob_l2[k_0__][k_1__][k_2__]); - } - } - } - for (int k_1__ = 0; k_1__ < G_hier; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_l2[k_0__][k_1__]); - } - } - - if (!include_gqs__) return; - // declare and define generated quantities - vector_d sd_total(static_cast(T)); - (void) sd_total; // dummy to suppress unused var warning - stan::math::initialize(sd_total, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_total,DUMMY_VAR__); - - - try { - for (int t = 1; t <= T; ++t) { - - stan::math::assign(get_base1_lhs(sd_total,t,"sd_total",1), sqrt((variance(get_base1(theta_bar,t,"theta_bar",1)) + square(get_base1(sd_theta,t,"sd_theta",1))))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate generated quantities - check_greater_or_equal(function__,"sd_total",sd_total,0); - - // write generated quantities - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_total[k_0__]); - } - - } - - template - void write_array(RNG& base_rng, - Eigen::Matrix& params_r, - Eigen::Matrix& vars, - bool include_tparams = true, - bool include_gqs = true, - std::ostream* pstream = 0) const { - std::vector params_r_vec(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r_vec[i] = params_r(i); - std::vector vars_vec; - std::vector params_i_vec; - write_array(base_rng,params_r_vec,params_i_vec,vars_vec,include_tparams,include_gqs,pstream); - vars.resize(vars_vec.size()); - for (int i = 0; i < vars.size(); ++i) - vars(i) = vars_vec[i]; - } - - static std::string model_name() { - return "model_2015_12_16"; - } - - - void constrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta_bar_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - - - void unconstrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta_bar_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - -}; // model - -} // namespace - - - - -// Code generated by Stan version 2.14 - -#include - -namespace model_2016_04_20_namespace { - -using std::istream; -using std::string; -using std::stringstream; -using std::vector; -using stan::io::dump; -using stan::math::lgamma; -using stan::model::prob_grad; -using namespace stan::math; - -typedef Eigen::Matrix vector_d; -typedef Eigen::Matrix row_vector_d; -typedef Eigen::Matrix matrix_d; - -static int current_statement_begin__; - -class model_2016_04_20 : public prob_grad { -private: - int G; - int G_hier; - int Q; - int T; - int N; - int N_observed; - int S; - int P; - int H; - int Hprior; - int D; - int constant_item; - int separate_t; - double delta_tbar_prior_mean; - double delta_tbar_prior_sd; - double innov_sd_delta_scale; - double innov_sd_theta_scale; - vector n_vec; - vector s_vec; - vector observed; - vector > > NNl2; - vector > > SSl2; - matrix_d XX; - vector WT; - vector ZZ; - vector ZZ_prior; - matrix_d l2_only; -public: - model_2016_04_20(stan::io::var_context& context__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - typedef boost::ecuyer1988 rng_t; - rng_t base_rng(0); // 0 seed default - ctor_body(context__, base_rng, pstream__); - } - - template - model_2016_04_20(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - ctor_body(context__, base_rng__, pstream__); - } - - template - void ctor_body(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__) { - current_statement_begin__ = -1; - - static const char* function__ = "model_2016_04_20_namespace::model_2016_04_20"; - (void) function__; // dummy call to supress warning - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_i__; - std::vector vals_r__; - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - // initialize member variables - context__.validate_dims("data initialization", "G", "int", context__.to_vec()); - G = int(0); - vals_i__ = context__.vals_i("G"); - pos__ = 0; - G = vals_i__[pos__++]; - context__.validate_dims("data initialization", "G_hier", "int", context__.to_vec()); - G_hier = int(0); - vals_i__ = context__.vals_i("G_hier"); - pos__ = 0; - G_hier = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Q", "int", context__.to_vec()); - Q = int(0); - vals_i__ = context__.vals_i("Q"); - pos__ = 0; - Q = vals_i__[pos__++]; - context__.validate_dims("data initialization", "T", "int", context__.to_vec()); - T = int(0); - vals_i__ = context__.vals_i("T"); - pos__ = 0; - T = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N", "int", context__.to_vec()); - N = int(0); - vals_i__ = context__.vals_i("N"); - pos__ = 0; - N = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N_observed", "int", context__.to_vec()); - N_observed = int(0); - vals_i__ = context__.vals_i("N_observed"); - pos__ = 0; - N_observed = vals_i__[pos__++]; - context__.validate_dims("data initialization", "S", "int", context__.to_vec()); - S = int(0); - vals_i__ = context__.vals_i("S"); - pos__ = 0; - S = vals_i__[pos__++]; - context__.validate_dims("data initialization", "P", "int", context__.to_vec()); - P = int(0); - vals_i__ = context__.vals_i("P"); - pos__ = 0; - P = vals_i__[pos__++]; - context__.validate_dims("data initialization", "H", "int", context__.to_vec()); - H = int(0); - vals_i__ = context__.vals_i("H"); - pos__ = 0; - H = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Hprior", "int", context__.to_vec()); - Hprior = int(0); - vals_i__ = context__.vals_i("Hprior"); - pos__ = 0; - Hprior = vals_i__[pos__++]; - context__.validate_dims("data initialization", "D", "int", context__.to_vec()); - D = int(0); - vals_i__ = context__.vals_i("D"); - pos__ = 0; - D = vals_i__[pos__++]; - context__.validate_dims("data initialization", "constant_item", "int", context__.to_vec()); - constant_item = int(0); - vals_i__ = context__.vals_i("constant_item"); - pos__ = 0; - constant_item = vals_i__[pos__++]; - context__.validate_dims("data initialization", "separate_t", "int", context__.to_vec()); - separate_t = int(0); - vals_i__ = context__.vals_i("separate_t"); - pos__ = 0; - separate_t = vals_i__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_mean", "double", context__.to_vec()); - delta_tbar_prior_mean = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_mean"); - pos__ = 0; - delta_tbar_prior_mean = vals_r__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_sd", "double", context__.to_vec()); - delta_tbar_prior_sd = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_sd"); - pos__ = 0; - delta_tbar_prior_sd = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_delta_scale", "double", context__.to_vec()); - innov_sd_delta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_delta_scale"); - pos__ = 0; - innov_sd_delta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_theta_scale", "double", context__.to_vec()); - innov_sd_theta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_theta_scale"); - pos__ = 0; - innov_sd_theta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "n_vec", "int", context__.to_vec(N)); - validate_non_negative_index("n_vec", "N", N); - n_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("n_vec"); - pos__ = 0; - size_t n_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < n_vec_limit_0__; ++i_0__) { - n_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "s_vec", "int", context__.to_vec(N)); - validate_non_negative_index("s_vec", "N", N); - s_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("s_vec"); - pos__ = 0; - size_t s_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < s_vec_limit_0__; ++i_0__) { - s_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "observed", "int", context__.to_vec(N_observed)); - validate_non_negative_index("observed", "N_observed", N_observed); - observed = std::vector(N_observed,int(0)); - vals_i__ = context__.vals_i("observed"); - pos__ = 0; - size_t observed_limit_0__ = N_observed; - for (size_t i_0__ = 0; i_0__ < observed_limit_0__; ++i_0__) { - observed[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "NNl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("NNl2", "T", T); - validate_non_negative_index("NNl2", "Q", Q); - validate_non_negative_index("NNl2", "G_hier", G_hier); - NNl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("NNl2"); - pos__ = 0; - size_t NNl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < NNl2_limit_2__; ++i_2__) { - size_t NNl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < NNl2_limit_1__; ++i_1__) { - size_t NNl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < NNl2_limit_0__; ++i_0__) { - NNl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "SSl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("SSl2", "T", T); - validate_non_negative_index("SSl2", "Q", Q); - validate_non_negative_index("SSl2", "G_hier", G_hier); - SSl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("SSl2"); - pos__ = 0; - size_t SSl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < SSl2_limit_2__; ++i_2__) { - size_t SSl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < SSl2_limit_1__; ++i_1__) { - size_t SSl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < SSl2_limit_0__; ++i_0__) { - SSl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "XX", "matrix_d", context__.to_vec(G,P)); - validate_non_negative_index("XX", "G", G); - validate_non_negative_index("XX", "P", P); - XX = matrix_d(static_cast(G),static_cast(P)); - vals_r__ = context__.vals_r("XX"); - pos__ = 0; - size_t XX_m_mat_lim__ = G; - size_t XX_n_mat_lim__ = P; - for (size_t n_mat__ = 0; n_mat__ < XX_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < XX_m_mat_lim__; ++m_mat__) { - XX(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - context__.validate_dims("data initialization", "WT", "matrix_d", context__.to_vec(T,G_hier,G)); - validate_non_negative_index("WT", "T", T); - validate_non_negative_index("WT", "G_hier", G_hier); - validate_non_negative_index("WT", "G", G); - WT = std::vector(T,matrix_d(static_cast(G_hier),static_cast(G))); - vals_r__ = context__.vals_r("WT"); - pos__ = 0; - size_t WT_m_mat_lim__ = G_hier; - size_t WT_n_mat_lim__ = G; - for (size_t n_mat__ = 0; n_mat__ < WT_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < WT_m_mat_lim__; ++m_mat__) { - size_t WT_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < WT_limit_0__; ++i_0__) { - WT[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ", "matrix_d", context__.to_vec(T,P,H)); - validate_non_negative_index("ZZ", "T", T); - validate_non_negative_index("ZZ", "P", P); - validate_non_negative_index("ZZ", "H", H); - ZZ = std::vector(T,matrix_d(static_cast(P),static_cast(H))); - vals_r__ = context__.vals_r("ZZ"); - pos__ = 0; - size_t ZZ_m_mat_lim__ = P; - size_t ZZ_n_mat_lim__ = H; - for (size_t n_mat__ = 0; n_mat__ < ZZ_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_m_mat_lim__; ++m_mat__) { - size_t ZZ_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_limit_0__; ++i_0__) { - ZZ[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ_prior", "matrix_d", context__.to_vec(T,P,Hprior)); - validate_non_negative_index("ZZ_prior", "T", T); - validate_non_negative_index("ZZ_prior", "P", P); - validate_non_negative_index("ZZ_prior", "Hprior", Hprior); - ZZ_prior = std::vector(T,matrix_d(static_cast(P),static_cast(Hprior))); - vals_r__ = context__.vals_r("ZZ_prior"); - pos__ = 0; - size_t ZZ_prior_m_mat_lim__ = P; - size_t ZZ_prior_n_mat_lim__ = Hprior; - for (size_t n_mat__ = 0; n_mat__ < ZZ_prior_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_prior_m_mat_lim__; ++m_mat__) { - size_t ZZ_prior_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_prior_limit_0__; ++i_0__) { - ZZ_prior[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "l2_only", "matrix_d", context__.to_vec(T,Q)); - validate_non_negative_index("l2_only", "T", T); - validate_non_negative_index("l2_only", "Q", Q); - l2_only = matrix_d(static_cast(T),static_cast(Q)); - vals_r__ = context__.vals_r("l2_only"); - pos__ = 0; - size_t l2_only_m_mat_lim__ = T; - size_t l2_only_n_mat_lim__ = Q; - for (size_t n_mat__ = 0; n_mat__ < l2_only_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < l2_only_m_mat_lim__; ++m_mat__) { - l2_only(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - - // validate, data variables - check_greater_or_equal(function__,"G",G,1); - check_greater_or_equal(function__,"G_hier",G_hier,1); - check_greater_or_equal(function__,"Q",Q,1); - check_greater_or_equal(function__,"T",T,1); - check_greater_or_equal(function__,"N",N,1); - check_greater_or_equal(function__,"N_observed",N_observed,1); - check_greater_or_equal(function__,"S",S,1); - check_greater_or_equal(function__,"P",P,1); - check_greater_or_equal(function__,"H",H,1); - check_greater_or_equal(function__,"Hprior",Hprior,1); - check_greater_or_equal(function__,"D",D,1); - check_greater_or_equal(function__,"constant_item",constant_item,0); - check_less_or_equal(function__,"constant_item",constant_item,1); - check_greater_or_equal(function__,"separate_t",separate_t,0); - check_less_or_equal(function__,"separate_t",separate_t,1); - check_greater_or_equal(function__,"delta_tbar_prior_sd",delta_tbar_prior_sd,0); - check_greater_or_equal(function__,"innov_sd_delta_scale",innov_sd_delta_scale,0); - check_greater_or_equal(function__,"innov_sd_theta_scale",innov_sd_theta_scale,0); - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"n_vec[k0__]",n_vec[k0__],0); - } - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"s_vec[k0__]",s_vec[k0__],0); - } - check_greater_or_equal(function__,"XX",XX,0); - check_less_or_equal(function__,"XX",XX,1); - for (int k0__ = 0; k0__ < T; ++k0__) { - check_greater_or_equal(function__,"WT[k0__]",WT[k0__],0); - check_less_or_equal(function__,"WT[k0__]",WT[k0__],1); - } - check_greater_or_equal(function__,"l2_only",l2_only,0); - check_less_or_equal(function__,"l2_only",l2_only,1); - // initialize data variables - - try { - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed data - - // set parameter ranges - num_params_r__ = 0U; - param_ranges_i__.clear(); - num_params_r__ += Q * D; - num_params_r__ += Q; - num_params_r__ += T; - num_params_r__ += P * T; - num_params_r__ += T; - num_params_r__ += H * T; - num_params_r__ += Hprior; - num_params_r__ += T; - num_params_r__ += G * T; - num_params_r__ += T; - num_params_r__ += T; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - } - - ~model_2016_04_20() { } - - - void transform_inits(const stan::io::var_context& context__, - std::vector& params_i__, - std::vector& params_r__, - std::ostream* pstream__) const { - stan::io::writer writer__(params_r__,params_i__); - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_r__; - std::vector vals_i__; - - if (!(context__.contains_r("diff_raw"))) - throw std::runtime_error("variable diff_raw missing"); - vals_r__ = context__.vals_r("diff_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "diff_raw", "vector_d", context__.to_vec(D,Q)); - // generate_declaration diff_raw - std::vector diff_raw(D,vector_d(static_cast(Q))); - for (int j1__ = 0U; j1__ < Q; ++j1__) - for (int i0__ = 0U; i0__ < D; ++i0__) - diff_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < D; ++i0__) - try { - writer__.vector_unconstrain(diff_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable diff_raw: ") + e.what()); - } - - if (!(context__.contains_r("disc_raw"))) - throw std::runtime_error("variable disc_raw missing"); - vals_r__ = context__.vals_r("disc_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "disc_raw", "vector_d", context__.to_vec(Q)); - // generate_declaration disc_raw - vector_d disc_raw(static_cast(Q)); - for (int j1__ = 0U; j1__ < Q; ++j1__) - disc_raw(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,disc_raw); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable disc_raw: ") + e.what()); - } - - if (!(context__.contains_r("xi"))) - throw std::runtime_error("variable xi missing"); - vals_r__ = context__.vals_r("xi"); - pos__ = 0U; - context__.validate_dims("initialization", "xi", "vector_d", context__.to_vec(T)); - // generate_declaration xi - vector_d xi(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - xi(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(xi); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable xi: ") + e.what()); - } - - if (!(context__.contains_r("gamma_raw"))) - throw std::runtime_error("variable gamma_raw missing"); - vals_r__ = context__.vals_r("gamma_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "gamma_raw", "vector_d", context__.to_vec(T,P)); - // generate_declaration gamma_raw - std::vector gamma_raw(T,vector_d(static_cast(P))); - for (int j1__ = 0U; j1__ < P; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - gamma_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(gamma_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable gamma_raw: ") + e.what()); - } - - if (!(context__.contains_r("delta_gamma"))) - throw std::runtime_error("variable delta_gamma missing"); - vals_r__ = context__.vals_r("delta_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_gamma", "vector_d", context__.to_vec(T)); - // generate_declaration delta_gamma - vector_d delta_gamma(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_gamma(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_gamma: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo"))) - throw std::runtime_error("variable nu_geo missing"); - vals_r__ = context__.vals_r("nu_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo", "vector_d", context__.to_vec(T,H)); - // generate_declaration nu_geo - std::vector nu_geo(T,vector_d(static_cast(H))); - for (int j1__ = 0U; j1__ < H; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - nu_geo[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(nu_geo[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo_prior"))) - throw std::runtime_error("variable nu_geo_prior missing"); - vals_r__ = context__.vals_r("nu_geo_prior"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo_prior", "vector_d", context__.to_vec(Hprior)); - // generate_declaration nu_geo_prior - vector_d nu_geo_prior(static_cast(Hprior)); - for (int j1__ = 0U; j1__ < Hprior; ++j1__) - nu_geo_prior(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(nu_geo_prior); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo_prior: ") + e.what()); - } - - if (!(context__.contains_r("delta_tbar"))) - throw std::runtime_error("variable delta_tbar missing"); - vals_r__ = context__.vals_r("delta_tbar"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_tbar", "vector_d", context__.to_vec(T)); - // generate_declaration delta_tbar - vector_d delta_tbar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_tbar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_tbar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_tbar: ") + e.what()); - } - - if (!(context__.contains_r("theta_bar_raw"))) - throw std::runtime_error("variable theta_bar_raw missing"); - vals_r__ = context__.vals_r("theta_bar_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "theta_bar_raw", "vector_d", context__.to_vec(T,G)); - // generate_declaration theta_bar_raw - std::vector theta_bar_raw(T,vector_d(static_cast(G))); - for (int j1__ = 0U; j1__ < G; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - theta_bar_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(theta_bar_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable theta_bar_raw: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta_bar"))) - throw std::runtime_error("variable sd_theta_bar missing"); - vals_r__ = context__.vals_r("sd_theta_bar"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta_bar", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta_bar - vector_d sd_theta_bar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta_bar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta_bar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta_bar: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta"))) - throw std::runtime_error("variable sd_theta missing"); - vals_r__ = context__.vals_r("sd_theta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta - vector_d sd_theta(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma"))) - throw std::runtime_error("variable sd_gamma missing"); - vals_r__ = context__.vals_r("sd_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma", "double", context__.to_vec()); - // generate_declaration sd_gamma - double sd_gamma(0); - sd_gamma = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_delta"))) - throw std::runtime_error("variable sd_innov_delta missing"); - vals_r__ = context__.vals_r("sd_innov_delta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_delta", "double", context__.to_vec()); - // generate_declaration sd_innov_delta - double sd_innov_delta(0); - sd_innov_delta = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_delta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_delta: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_logsd"))) - throw std::runtime_error("variable sd_innov_logsd missing"); - vals_r__ = context__.vals_r("sd_innov_logsd"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_logsd", "double", context__.to_vec()); - // generate_declaration sd_innov_logsd - double sd_innov_logsd(0); - sd_innov_logsd = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_logsd); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_logsd: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_gamma"))) - throw std::runtime_error("variable sd_innov_gamma missing"); - vals_r__ = context__.vals_r("sd_innov_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_gamma", "double", context__.to_vec()); - // generate_declaration sd_innov_gamma - double sd_innov_gamma(0); - sd_innov_gamma = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_gamma: ") + e.what()); - } - - params_r__ = writer__.data_r(); - params_i__ = writer__.data_i(); - } - - void transform_inits(const stan::io::var_context& context, - Eigen::Matrix& params_r, - std::ostream* pstream__) const { - std::vector params_r_vec; - std::vector params_i_vec; - transform_inits(context, params_i_vec, params_r_vec, pstream__); - params_r.resize(params_r_vec.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r(i) = params_r_vec[i]; - } - - - template - T__ log_prob(vector& params_r__, - vector& params_i__, - std::ostream* pstream__ = 0) const { - - T__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - T__ lp__(0.0); - stan::math::accumulator lp_accum__; - - // model parameters - stan::io::reader in__(params_r__,params_i__); - - vector > diff_raw; - size_t dim_diff_raw_0__ = D; - diff_raw.reserve(dim_diff_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - if (jacobian__) - diff_raw.push_back(in__.vector_constrain(Q,lp__)); - else - diff_raw.push_back(in__.vector_constrain(Q)); - } - - Eigen::Matrix disc_raw; - (void) disc_raw; // dummy to suppress unused var warning - if (jacobian__) - disc_raw = in__.vector_lb_constrain(0,Q,lp__); - else - disc_raw = in__.vector_lb_constrain(0,Q); - - Eigen::Matrix xi; - (void) xi; // dummy to suppress unused var warning - if (jacobian__) - xi = in__.vector_constrain(T,lp__); - else - xi = in__.vector_constrain(T); - - vector > gamma_raw; - size_t dim_gamma_raw_0__ = T; - gamma_raw.reserve(dim_gamma_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - if (jacobian__) - gamma_raw.push_back(in__.vector_constrain(P,lp__)); - else - gamma_raw.push_back(in__.vector_constrain(P)); - } - - Eigen::Matrix delta_gamma; - (void) delta_gamma; // dummy to suppress unused var warning - if (jacobian__) - delta_gamma = in__.vector_constrain(T,lp__); - else - delta_gamma = in__.vector_constrain(T); - - vector > nu_geo; - size_t dim_nu_geo_0__ = T; - nu_geo.reserve(dim_nu_geo_0__); - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - if (jacobian__) - nu_geo.push_back(in__.vector_constrain(H,lp__)); - else - nu_geo.push_back(in__.vector_constrain(H)); - } - - Eigen::Matrix nu_geo_prior; - (void) nu_geo_prior; // dummy to suppress unused var warning - if (jacobian__) - nu_geo_prior = in__.vector_constrain(Hprior,lp__); - else - nu_geo_prior = in__.vector_constrain(Hprior); - - Eigen::Matrix delta_tbar; - (void) delta_tbar; // dummy to suppress unused var warning - if (jacobian__) - delta_tbar = in__.vector_constrain(T,lp__); - else - delta_tbar = in__.vector_constrain(T); - - vector > theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - theta_bar_raw.reserve(dim_theta_bar_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - if (jacobian__) - theta_bar_raw.push_back(in__.vector_constrain(G,lp__)); - else - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - - Eigen::Matrix sd_theta_bar; - (void) sd_theta_bar; // dummy to suppress unused var warning - if (jacobian__) - sd_theta_bar = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta_bar = in__.vector_lb_constrain(0,T); - - Eigen::Matrix sd_theta; - (void) sd_theta; // dummy to suppress unused var warning - if (jacobian__) - sd_theta = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta = in__.vector_lb_constrain(0,T); - - T__ sd_gamma; - (void) sd_gamma; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma = in__.scalar_lb_constrain(0); - - T__ sd_innov_delta; - (void) sd_innov_delta; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_delta = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_delta = in__.scalar_lb_constrain(0); - - T__ sd_innov_logsd; - (void) sd_innov_logsd; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_logsd = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_logsd = in__.scalar_lb_constrain(0); - - T__ sd_innov_gamma; - (void) sd_innov_gamma; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_gamma = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_gamma = in__.scalar_lb_constrain(0); - - - // transformed parameters - vector > theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(theta_bar, DUMMY_VAR__); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector > diff(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(diff, DUMMY_VAR__); - stan::math::fill(diff,DUMMY_VAR__); - vector > kappa(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(kappa, DUMMY_VAR__); - stan::math::fill(kappa,DUMMY_VAR__); - Eigen::Matrix disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, DUMMY_VAR__); - stan::math::fill(disc,DUMMY_VAR__); - Eigen::Matrix sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, DUMMY_VAR__); - stan::math::fill(sd_item,DUMMY_VAR__); - Eigen::Matrix var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, DUMMY_VAR__); - stan::math::fill(var_item,DUMMY_VAR__); - Eigen::Matrix var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, DUMMY_VAR__); - stan::math::fill(var_theta,DUMMY_VAR__); - vector > var_theta_bar_l2(T, (Eigen::Matrix (static_cast(G_hier)))); - stan::math::initialize(var_theta_bar_l2, DUMMY_VAR__); - stan::math::fill(var_theta_bar_l2,DUMMY_VAR__); - vector > gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(gamma, DUMMY_VAR__); - stan::math::fill(gamma,DUMMY_VAR__); - vector > mu_theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(mu_theta_bar, DUMMY_VAR__); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector > mu_gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(mu_gamma, DUMMY_VAR__); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > > z(T, (vector >(Q, (Eigen::Matrix (static_cast(G)))))); - stan::math::initialize(z, DUMMY_VAR__); - stan::math::fill(z,DUMMY_VAR__); - vector > > z_l2(T, (vector >(Q, (Eigen::Matrix (static_cast(G_hier)))))); - stan::math::initialize(z_l2, DUMMY_VAR__); - stan::math::fill(z_l2,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G))))); - stan::math::initialize(prob, DUMMY_VAR__); - stan::math::fill(prob,DUMMY_VAR__); - vector > > prob_l2(T, (vector >(Q, (Eigen::Matrix (static_cast(G_hier)))))); - stan::math::initialize(prob_l2, DUMMY_VAR__); - stan::math::fill(prob_l2,DUMMY_VAR__); - vector > theta_l2(T, (Eigen::Matrix (static_cast(G_hier)))); - stan::math::initialize(theta_l2, DUMMY_VAR__); - stan::math::fill(theta_l2,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } else { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), add(multiply(get_base1(gamma,(t - 1),"gamma",1),get_base1(delta_gamma,t,"delta_gamma",1)),multiply(get_base1(ZZ,t,"ZZ",1),get_base1(nu_geo,t,"nu_geo",1)))); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - stan::math::assign(get_base1_lhs(theta_l2,t,"theta_l2",1), multiply(get_base1(WT,t,"WT",1),get_base1(theta_bar,t,"theta_bar",1))); - for (int n = 1; n <= G_hier; ++n) { - { - Eigen::Matrix WTdiag(static_cast(G),static_cast(G)); - (void) WTdiag; // dummy to suppress unused var warning - stan::math::initialize(WTdiag, DUMMY_VAR__); - stan::math::fill(WTdiag,DUMMY_VAR__); - - - for (int g = 1; g <= G; ++g) { - - for (int h = 1; h <= G; ++h) { - - if (as_bool(logical_eq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), get_base1(get_base1(WT,t,"WT",1),n,g,"WT",2)); - } - if (as_bool(logical_neq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), 0); - } - } - } - stan::math::assign(get_base1_lhs(get_base1_lhs(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2), multiply(multiply(transpose(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2))),WTdiag),subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2)))); - } - } - for (int q = 1; q <= Q; ++q) { - { - T__ sd_tq; - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, DUMMY_VAR__); - stan::math::fill(sd_tq,DUMMY_VAR__); - vector sd_l2_tq(G_hier); - stan::math::initialize(sd_l2_tq, DUMMY_VAR__); - stan::math::fill(sd_l2_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(sd_l2_tq,n,"sd_l2_tq",1), sqrt((square(sd_tq) + get_base1(get_base1(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2)))); - } - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - for (int g = 1; g <= G; ++g) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(diff[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: diff" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(kappa[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: kappa" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(disc(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: disc" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(sd_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: sd_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(var_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - if (stan::math::is_uninitialized(var_theta(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_theta" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G_hier; ++i1__) { - if (stan::math::is_uninitialized(var_theta_bar_l2[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_theta_bar_l2" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(mu_theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(mu_gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(z[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G_hier; ++i2__) { - if (stan::math::is_uninitialized(z_l2[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z_l2" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(prob[i0__][i1__][i2__])) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G_hier; ++i2__) { - if (stan::math::is_uninitialized(prob_l2[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob_l2" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G_hier; ++i1__) { - if (stan::math::is_uninitialized(theta_l2[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_l2" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - - const char* function__ = "validate transformed params"; - (void) function__; // dummy to suppress unused var warning - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // model body - try { - { - vector prob_vec(N); - stan::math::initialize(prob_vec, DUMMY_VAR__); - stan::math::fill(prob_vec,DUMMY_VAR__); - int pos(0); - (void) pos; // dummy to suppress unused var warning - stan::math::fill(pos, std::numeric_limits::min()); - - - stan::math::assign(pos, 0); - if (as_bool(logical_eq(constant_item,1))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,1,"diff_raw",1), 0, 1)); - } - lp_accum__.add(lognormal_log(disc_raw, 0, 1)); - lp_accum__.add(cauchy_log(sd_gamma, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_delta, 0, innov_sd_delta_scale)); - lp_accum__.add(cauchy_log(sd_innov_gamma, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_logsd, 0, innov_sd_theta_scale)); - for (int t = 1; t <= T; ++t) { - - lp_accum__.add(normal_log(get_base1(gamma_raw,t,"gamma_raw",1), 0, 1)); - lp_accum__.add(normal_log(get_base1(theta_bar_raw,t,"theta_bar_raw",1), 0, 1)); - if (as_bool(logical_eq(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), 0, 1)); - } - lp_accum__.add(cauchy_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), 0, 2.5)); - lp_accum__.add(cauchy_log(get_base1(sd_theta,t,"sd_theta",1), 0, 2.5)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), 0, 10)); - lp_accum__.add(normal_log(nu_geo_prior, 0, 10)); - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), 0.5, 0.5)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), delta_tbar_prior_mean, delta_tbar_prior_sd)); - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - if (as_bool(logical_gt(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), get_base1(diff_raw,(t - 1),"diff_raw",1), sd_innov_gamma)); - } - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), get_base1(delta_gamma,(t - 1),"delta_gamma",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), get_base1(nu_geo,(t - 1),"nu_geo",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), get_base1(delta_tbar,(t - 1),"delta_tbar",1), sd_innov_delta)); - lp_accum__.add(lognormal_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), log(get_base1(sd_theta_bar,(t - 1),"sd_theta_bar",1)), sd_innov_logsd)); - lp_accum__.add(lognormal_log(get_base1(sd_theta,t,"sd_theta",1), log(get_base1(sd_theta,(t - 1),"sd_theta",1)), sd_innov_logsd)); - if (as_bool((primitive_value(logical_eq(separate_t,0)) && primitive_value(logical_gt(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), get_base1(xi,(t - 1),"xi",1), sd_innov_gamma)); - } - if (as_bool((primitive_value(logical_eq(separate_t,1)) || primitive_value(logical_eq(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - } - for (int q = 1; q <= Q; ++q) { - - for (int g = 1; g <= G; ++g) { - - stan::math::assign(pos, (pos + 1)); - stan::math::assign(get_base1_lhs(prob_vec,pos,"prob_vec",1), get_base1(get_base1(get_base1(prob,t,"prob",1),q,"prob",2),g,"prob",3)); - } - } - } - lp_accum__.add(binomial_log(stan::model::rvalue(s_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "s_vec"), stan::model::rvalue(n_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "n_vec"), stan::model::rvalue(prob_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "prob_vec"))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - lp_accum__.add(lp__); - return lp_accum__.sum(); - - } // log_prob() - - template - T_ log_prob(Eigen::Matrix& params_r, - std::ostream* pstream = 0) const { - std::vector vec_params_r; - vec_params_r.reserve(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - vec_params_r.push_back(params_r(i)); - std::vector vec_params_i; - return log_prob(vec_params_r, vec_params_i, pstream); - } - - - void get_param_names(std::vector& names__) const { - names__.resize(0); - names__.push_back("diff_raw"); - names__.push_back("disc_raw"); - names__.push_back("xi"); - names__.push_back("gamma_raw"); - names__.push_back("delta_gamma"); - names__.push_back("nu_geo"); - names__.push_back("nu_geo_prior"); - names__.push_back("delta_tbar"); - names__.push_back("theta_bar_raw"); - names__.push_back("sd_theta_bar"); - names__.push_back("sd_theta"); - names__.push_back("sd_gamma"); - names__.push_back("sd_innov_delta"); - names__.push_back("sd_innov_logsd"); - names__.push_back("sd_innov_gamma"); - names__.push_back("theta_bar"); - names__.push_back("diff"); - names__.push_back("kappa"); - names__.push_back("disc"); - names__.push_back("sd_item"); - names__.push_back("var_item"); - names__.push_back("var_theta"); - names__.push_back("var_theta_bar_l2"); - names__.push_back("gamma"); - names__.push_back("mu_theta_bar"); - names__.push_back("mu_gamma"); - names__.push_back("z"); - names__.push_back("z_l2"); - names__.push_back("prob"); - names__.push_back("prob_l2"); - names__.push_back("theta_l2"); - names__.push_back("sd_total"); - } - - - void get_dims(std::vector >& dimss__) const { - dimss__.resize(0); - std::vector dims__; - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(H); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Hprior); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - } - - template - void write_array(RNG& base_rng__, - std::vector& params_r__, - std::vector& params_i__, - std::vector& vars__, - bool include_tparams__ = true, - bool include_gqs__ = true, - std::ostream* pstream__ = 0) const { - vars__.resize(0); - stan::io::reader in__(params_r__,params_i__); - static const char* function__ = "model_2016_04_20_namespace::write_array"; - (void) function__; // dummy call to supress warning - // read-transform, write parameters - vector diff_raw; - size_t dim_diff_raw_0__ = D; - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - diff_raw.push_back(in__.vector_constrain(Q)); - } - vector_d disc_raw = in__.vector_lb_constrain(0,Q); - vector_d xi = in__.vector_constrain(T); - vector gamma_raw; - size_t dim_gamma_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - gamma_raw.push_back(in__.vector_constrain(P)); - } - vector_d delta_gamma = in__.vector_constrain(T); - vector nu_geo; - size_t dim_nu_geo_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - nu_geo.push_back(in__.vector_constrain(H)); - } - vector_d nu_geo_prior = in__.vector_constrain(Hprior); - vector_d delta_tbar = in__.vector_constrain(T); - vector theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - vector_d sd_theta_bar = in__.vector_lb_constrain(0,T); - vector_d sd_theta = in__.vector_lb_constrain(0,T); - double sd_gamma = in__.scalar_lb_constrain(0); - double sd_innov_delta = in__.scalar_lb_constrain(0); - double sd_innov_logsd = in__.scalar_lb_constrain(0); - double sd_innov_gamma = in__.scalar_lb_constrain(0); - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc_raw[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(xi[k_0__]); - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_gamma[k_0__]); - } - for (int k_1__ = 0; k_1__ < H; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(nu_geo[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Hprior; ++k_0__) { - vars__.push_back(nu_geo_prior[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_tbar[k_0__]); - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta_bar[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta[k_0__]); - } - vars__.push_back(sd_gamma); - vars__.push_back(sd_innov_delta); - vars__.push_back(sd_innov_logsd); - vars__.push_back(sd_innov_gamma); - - if (!include_tparams__) return; - // declare and define transformed parameters - double lp__ = 0.0; - (void) lp__; // dummy call to supress warning - stan::math::accumulator lp_accum__; - - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - vector theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector diff(D, (vector_d(static_cast(Q)))); - stan::math::initialize(diff, std::numeric_limits::quiet_NaN()); - stan::math::fill(diff,DUMMY_VAR__); - vector kappa(D, (vector_d(static_cast(Q)))); - stan::math::initialize(kappa, std::numeric_limits::quiet_NaN()); - stan::math::fill(kappa,DUMMY_VAR__); - vector_d disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, std::numeric_limits::quiet_NaN()); - stan::math::fill(disc,DUMMY_VAR__); - vector_d sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_item,DUMMY_VAR__); - vector_d var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_item,DUMMY_VAR__); - vector_d var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_theta,DUMMY_VAR__); - vector var_theta_bar_l2(T, (vector_d(static_cast(G_hier)))); - stan::math::initialize(var_theta_bar_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_theta_bar_l2,DUMMY_VAR__); - vector gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(gamma,DUMMY_VAR__); - vector mu_theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(mu_theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector mu_gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(mu_gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > z(T, (vector(Q, (vector_d(static_cast(G)))))); - stan::math::initialize(z, std::numeric_limits::quiet_NaN()); - stan::math::fill(z,DUMMY_VAR__); - vector > z_l2(T, (vector(Q, (vector_d(static_cast(G_hier)))))); - stan::math::initialize(z_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(z_l2,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G, 0.0))))); - stan::math::initialize(prob, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob,DUMMY_VAR__); - vector > prob_l2(T, (vector(Q, (vector_d(static_cast(G_hier)))))); - stan::math::initialize(prob_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob_l2,DUMMY_VAR__); - vector theta_l2(T, (vector_d(static_cast(G_hier)))); - stan::math::initialize(theta_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_l2,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } else { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), add(multiply(get_base1(gamma,(t - 1),"gamma",1),get_base1(delta_gamma,t,"delta_gamma",1)),multiply(get_base1(ZZ,t,"ZZ",1),get_base1(nu_geo,t,"nu_geo",1)))); - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - stan::math::assign(get_base1_lhs(theta_l2,t,"theta_l2",1), multiply(get_base1(WT,t,"WT",1),get_base1(theta_bar,t,"theta_bar",1))); - for (int n = 1; n <= G_hier; ++n) { - { - matrix_d WTdiag(static_cast(G),static_cast(G)); - (void) WTdiag; // dummy to suppress unused var warning - stan::math::initialize(WTdiag, std::numeric_limits::quiet_NaN()); - stan::math::fill(WTdiag,DUMMY_VAR__); - - - for (int g = 1; g <= G; ++g) { - - for (int h = 1; h <= G; ++h) { - - if (as_bool(logical_eq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), get_base1(get_base1(WT,t,"WT",1),n,g,"WT",2)); - } - if (as_bool(logical_neq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), 0); - } - } - } - stan::math::assign(get_base1_lhs(get_base1_lhs(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2), multiply(multiply(transpose(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2))),WTdiag),subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2)))); - } - } - for (int q = 1; q <= Q; ++q) { - { - double sd_tq(0.0); - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_tq,DUMMY_VAR__); - vector sd_l2_tq(G_hier, 0.0); - stan::math::initialize(sd_l2_tq, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_l2_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(sd_l2_tq,n,"sd_l2_tq",1), sqrt((square(sd_tq) + get_base1(get_base1(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2)))); - } - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - for (int g = 1; g <= G; ++g) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // write transformed parameters - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(kappa[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(sd_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(var_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(var_theta[k_0__]); - } - for (int k_1__ = 0; k_1__ < G_hier; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(var_theta_bar_l2[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_gamma[k_0__][k_1__]); - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G_hier; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z_l2[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G_hier; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob_l2[k_0__][k_1__][k_2__]); - } - } - } - for (int k_1__ = 0; k_1__ < G_hier; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_l2[k_0__][k_1__]); - } - } - - if (!include_gqs__) return; - // declare and define generated quantities - vector_d sd_total(static_cast(T)); - (void) sd_total; // dummy to suppress unused var warning - stan::math::initialize(sd_total, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_total,DUMMY_VAR__); - - - try { - for (int t = 1; t <= T; ++t) { - - stan::math::assign(get_base1_lhs(sd_total,t,"sd_total",1), sqrt((variance(get_base1(theta_bar,t,"theta_bar",1)) + square(get_base1(sd_theta,t,"sd_theta",1))))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate generated quantities - check_greater_or_equal(function__,"sd_total",sd_total,0); - - // write generated quantities - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_total[k_0__]); - } - - } - - template - void write_array(RNG& base_rng, - Eigen::Matrix& params_r, - Eigen::Matrix& vars, - bool include_tparams = true, - bool include_gqs = true, - std::ostream* pstream = 0) const { - std::vector params_r_vec(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r_vec[i] = params_r(i); - std::vector vars_vec; - std::vector params_i_vec; - write_array(base_rng,params_r_vec,params_i_vec,vars_vec,include_tparams,include_gqs,pstream); - vars.resize(vars_vec.size()); - for (int i = 0; i < vars.size(); ++i) - vars(i) = vars_vec[i]; - } - - static std::string model_name() { - return "model_2016_04_20"; - } - - - void constrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta_bar_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - - - void unconstrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta_bar_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - -}; // model - -} // namespace - - - - -// Code generated by Stan version 2.14 - -#include - -namespace model_2016_09_14_namespace { - -using std::istream; -using std::string; -using std::stringstream; -using std::vector; -using stan::io::dump; -using stan::math::lgamma; -using stan::model::prob_grad; -using namespace stan::math; - -typedef Eigen::Matrix vector_d; -typedef Eigen::Matrix row_vector_d; -typedef Eigen::Matrix matrix_d; - -static int current_statement_begin__; - -class model_2016_09_14 : public prob_grad { -private: - int G; - int G_hier; - int Q; - int T; - int N; - int N_observed; - int S; - int P; - int H; - int Hprior; - int D; - int constant_item; - int separate_t; - double delta_tbar_prior_mean; - double delta_tbar_prior_sd; - double innov_sd_delta_scale; - double innov_sd_theta_scale; - vector n_vec; - vector s_vec; - vector observed; - vector > > NNl2; - vector > > SSl2; - matrix_d XX; - vector WT; - vector ZZ; - vector ZZ_prior; - matrix_d l2_only; -public: - model_2016_09_14(stan::io::var_context& context__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - typedef boost::ecuyer1988 rng_t; - rng_t base_rng(0); // 0 seed default - ctor_body(context__, base_rng, pstream__); - } - - template - model_2016_09_14(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - ctor_body(context__, base_rng__, pstream__); - } - - template - void ctor_body(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__) { - current_statement_begin__ = -1; - - static const char* function__ = "model_2016_09_14_namespace::model_2016_09_14"; - (void) function__; // dummy call to supress warning - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_i__; - std::vector vals_r__; - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - // initialize member variables - context__.validate_dims("data initialization", "G", "int", context__.to_vec()); - G = int(0); - vals_i__ = context__.vals_i("G"); - pos__ = 0; - G = vals_i__[pos__++]; - context__.validate_dims("data initialization", "G_hier", "int", context__.to_vec()); - G_hier = int(0); - vals_i__ = context__.vals_i("G_hier"); - pos__ = 0; - G_hier = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Q", "int", context__.to_vec()); - Q = int(0); - vals_i__ = context__.vals_i("Q"); - pos__ = 0; - Q = vals_i__[pos__++]; - context__.validate_dims("data initialization", "T", "int", context__.to_vec()); - T = int(0); - vals_i__ = context__.vals_i("T"); - pos__ = 0; - T = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N", "int", context__.to_vec()); - N = int(0); - vals_i__ = context__.vals_i("N"); - pos__ = 0; - N = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N_observed", "int", context__.to_vec()); - N_observed = int(0); - vals_i__ = context__.vals_i("N_observed"); - pos__ = 0; - N_observed = vals_i__[pos__++]; - context__.validate_dims("data initialization", "S", "int", context__.to_vec()); - S = int(0); - vals_i__ = context__.vals_i("S"); - pos__ = 0; - S = vals_i__[pos__++]; - context__.validate_dims("data initialization", "P", "int", context__.to_vec()); - P = int(0); - vals_i__ = context__.vals_i("P"); - pos__ = 0; - P = vals_i__[pos__++]; - context__.validate_dims("data initialization", "H", "int", context__.to_vec()); - H = int(0); - vals_i__ = context__.vals_i("H"); - pos__ = 0; - H = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Hprior", "int", context__.to_vec()); - Hprior = int(0); - vals_i__ = context__.vals_i("Hprior"); - pos__ = 0; - Hprior = vals_i__[pos__++]; - context__.validate_dims("data initialization", "D", "int", context__.to_vec()); - D = int(0); - vals_i__ = context__.vals_i("D"); - pos__ = 0; - D = vals_i__[pos__++]; - context__.validate_dims("data initialization", "constant_item", "int", context__.to_vec()); - constant_item = int(0); - vals_i__ = context__.vals_i("constant_item"); - pos__ = 0; - constant_item = vals_i__[pos__++]; - context__.validate_dims("data initialization", "separate_t", "int", context__.to_vec()); - separate_t = int(0); - vals_i__ = context__.vals_i("separate_t"); - pos__ = 0; - separate_t = vals_i__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_mean", "double", context__.to_vec()); - delta_tbar_prior_mean = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_mean"); - pos__ = 0; - delta_tbar_prior_mean = vals_r__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_sd", "double", context__.to_vec()); - delta_tbar_prior_sd = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_sd"); - pos__ = 0; - delta_tbar_prior_sd = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_delta_scale", "double", context__.to_vec()); - innov_sd_delta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_delta_scale"); - pos__ = 0; - innov_sd_delta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_theta_scale", "double", context__.to_vec()); - innov_sd_theta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_theta_scale"); - pos__ = 0; - innov_sd_theta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "n_vec", "int", context__.to_vec(N)); - validate_non_negative_index("n_vec", "N", N); - n_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("n_vec"); - pos__ = 0; - size_t n_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < n_vec_limit_0__; ++i_0__) { - n_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "s_vec", "int", context__.to_vec(N)); - validate_non_negative_index("s_vec", "N", N); - s_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("s_vec"); - pos__ = 0; - size_t s_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < s_vec_limit_0__; ++i_0__) { - s_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "observed", "int", context__.to_vec(N_observed)); - validate_non_negative_index("observed", "N_observed", N_observed); - observed = std::vector(N_observed,int(0)); - vals_i__ = context__.vals_i("observed"); - pos__ = 0; - size_t observed_limit_0__ = N_observed; - for (size_t i_0__ = 0; i_0__ < observed_limit_0__; ++i_0__) { - observed[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "NNl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("NNl2", "T", T); - validate_non_negative_index("NNl2", "Q", Q); - validate_non_negative_index("NNl2", "G_hier", G_hier); - NNl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("NNl2"); - pos__ = 0; - size_t NNl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < NNl2_limit_2__; ++i_2__) { - size_t NNl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < NNl2_limit_1__; ++i_1__) { - size_t NNl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < NNl2_limit_0__; ++i_0__) { - NNl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "SSl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("SSl2", "T", T); - validate_non_negative_index("SSl2", "Q", Q); - validate_non_negative_index("SSl2", "G_hier", G_hier); - SSl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("SSl2"); - pos__ = 0; - size_t SSl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < SSl2_limit_2__; ++i_2__) { - size_t SSl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < SSl2_limit_1__; ++i_1__) { - size_t SSl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < SSl2_limit_0__; ++i_0__) { - SSl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "XX", "matrix_d", context__.to_vec(G,P)); - validate_non_negative_index("XX", "G", G); - validate_non_negative_index("XX", "P", P); - XX = matrix_d(static_cast(G),static_cast(P)); - vals_r__ = context__.vals_r("XX"); - pos__ = 0; - size_t XX_m_mat_lim__ = G; - size_t XX_n_mat_lim__ = P; - for (size_t n_mat__ = 0; n_mat__ < XX_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < XX_m_mat_lim__; ++m_mat__) { - XX(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - context__.validate_dims("data initialization", "WT", "matrix_d", context__.to_vec(T,G_hier,G)); - validate_non_negative_index("WT", "T", T); - validate_non_negative_index("WT", "G_hier", G_hier); - validate_non_negative_index("WT", "G", G); - WT = std::vector(T,matrix_d(static_cast(G_hier),static_cast(G))); - vals_r__ = context__.vals_r("WT"); - pos__ = 0; - size_t WT_m_mat_lim__ = G_hier; - size_t WT_n_mat_lim__ = G; - for (size_t n_mat__ = 0; n_mat__ < WT_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < WT_m_mat_lim__; ++m_mat__) { - size_t WT_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < WT_limit_0__; ++i_0__) { - WT[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ", "matrix_d", context__.to_vec(T,P,H)); - validate_non_negative_index("ZZ", "T", T); - validate_non_negative_index("ZZ", "P", P); - validate_non_negative_index("ZZ", "H", H); - ZZ = std::vector(T,matrix_d(static_cast(P),static_cast(H))); - vals_r__ = context__.vals_r("ZZ"); - pos__ = 0; - size_t ZZ_m_mat_lim__ = P; - size_t ZZ_n_mat_lim__ = H; - for (size_t n_mat__ = 0; n_mat__ < ZZ_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_m_mat_lim__; ++m_mat__) { - size_t ZZ_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_limit_0__; ++i_0__) { - ZZ[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ_prior", "matrix_d", context__.to_vec(T,P,Hprior)); - validate_non_negative_index("ZZ_prior", "T", T); - validate_non_negative_index("ZZ_prior", "P", P); - validate_non_negative_index("ZZ_prior", "Hprior", Hprior); - ZZ_prior = std::vector(T,matrix_d(static_cast(P),static_cast(Hprior))); - vals_r__ = context__.vals_r("ZZ_prior"); - pos__ = 0; - size_t ZZ_prior_m_mat_lim__ = P; - size_t ZZ_prior_n_mat_lim__ = Hprior; - for (size_t n_mat__ = 0; n_mat__ < ZZ_prior_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_prior_m_mat_lim__; ++m_mat__) { - size_t ZZ_prior_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_prior_limit_0__; ++i_0__) { - ZZ_prior[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "l2_only", "matrix_d", context__.to_vec(T,Q)); - validate_non_negative_index("l2_only", "T", T); - validate_non_negative_index("l2_only", "Q", Q); - l2_only = matrix_d(static_cast(T),static_cast(Q)); - vals_r__ = context__.vals_r("l2_only"); - pos__ = 0; - size_t l2_only_m_mat_lim__ = T; - size_t l2_only_n_mat_lim__ = Q; - for (size_t n_mat__ = 0; n_mat__ < l2_only_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < l2_only_m_mat_lim__; ++m_mat__) { - l2_only(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - - // validate, data variables - check_greater_or_equal(function__,"G",G,1); - check_greater_or_equal(function__,"G_hier",G_hier,1); - check_greater_or_equal(function__,"Q",Q,1); - check_greater_or_equal(function__,"T",T,1); - check_greater_or_equal(function__,"N",N,1); - check_greater_or_equal(function__,"N_observed",N_observed,1); - check_greater_or_equal(function__,"S",S,1); - check_greater_or_equal(function__,"P",P,1); - check_greater_or_equal(function__,"H",H,1); - check_greater_or_equal(function__,"Hprior",Hprior,1); - check_greater_or_equal(function__,"D",D,1); - check_greater_or_equal(function__,"constant_item",constant_item,0); - check_less_or_equal(function__,"constant_item",constant_item,1); - check_greater_or_equal(function__,"separate_t",separate_t,0); - check_less_or_equal(function__,"separate_t",separate_t,1); - check_greater_or_equal(function__,"delta_tbar_prior_sd",delta_tbar_prior_sd,0); - check_greater_or_equal(function__,"innov_sd_delta_scale",innov_sd_delta_scale,0); - check_greater_or_equal(function__,"innov_sd_theta_scale",innov_sd_theta_scale,0); - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"n_vec[k0__]",n_vec[k0__],0); - } - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"s_vec[k0__]",s_vec[k0__],0); - } - check_greater_or_equal(function__,"XX",XX,0); - check_less_or_equal(function__,"XX",XX,1); - for (int k0__ = 0; k0__ < T; ++k0__) { - check_greater_or_equal(function__,"WT[k0__]",WT[k0__],0); - check_less_or_equal(function__,"WT[k0__]",WT[k0__],1); - } - check_greater_or_equal(function__,"l2_only",l2_only,0); - check_less_or_equal(function__,"l2_only",l2_only,1); - // initialize data variables - - try { - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed data - - // set parameter ranges - num_params_r__ = 0U; - param_ranges_i__.clear(); - num_params_r__ += Q * D; - num_params_r__ += Q; - num_params_r__ += T; - num_params_r__ += P * T; - num_params_r__ += T; - num_params_r__ += H * T; - num_params_r__ += Hprior; - num_params_r__ += T; - num_params_r__ += G * T; - num_params_r__ += T; - num_params_r__ += T; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - } - - ~model_2016_09_14() { } - - - void transform_inits(const stan::io::var_context& context__, - std::vector& params_i__, - std::vector& params_r__, - std::ostream* pstream__) const { - stan::io::writer writer__(params_r__,params_i__); - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_r__; - std::vector vals_i__; - - if (!(context__.contains_r("diff_raw"))) - throw std::runtime_error("variable diff_raw missing"); - vals_r__ = context__.vals_r("diff_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "diff_raw", "vector_d", context__.to_vec(D,Q)); - // generate_declaration diff_raw - std::vector diff_raw(D,vector_d(static_cast(Q))); - for (int j1__ = 0U; j1__ < Q; ++j1__) - for (int i0__ = 0U; i0__ < D; ++i0__) - diff_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < D; ++i0__) - try { - writer__.vector_unconstrain(diff_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable diff_raw: ") + e.what()); - } - - if (!(context__.contains_r("disc_raw"))) - throw std::runtime_error("variable disc_raw missing"); - vals_r__ = context__.vals_r("disc_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "disc_raw", "vector_d", context__.to_vec(Q)); - // generate_declaration disc_raw - vector_d disc_raw(static_cast(Q)); - for (int j1__ = 0U; j1__ < Q; ++j1__) - disc_raw(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,disc_raw); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable disc_raw: ") + e.what()); - } - - if (!(context__.contains_r("xi"))) - throw std::runtime_error("variable xi missing"); - vals_r__ = context__.vals_r("xi"); - pos__ = 0U; - context__.validate_dims("initialization", "xi", "vector_d", context__.to_vec(T)); - // generate_declaration xi - vector_d xi(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - xi(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(xi); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable xi: ") + e.what()); - } - - if (!(context__.contains_r("gamma_raw"))) - throw std::runtime_error("variable gamma_raw missing"); - vals_r__ = context__.vals_r("gamma_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "gamma_raw", "vector_d", context__.to_vec(T,P)); - // generate_declaration gamma_raw - std::vector gamma_raw(T,vector_d(static_cast(P))); - for (int j1__ = 0U; j1__ < P; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - gamma_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(gamma_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable gamma_raw: ") + e.what()); - } - - if (!(context__.contains_r("delta_gamma"))) - throw std::runtime_error("variable delta_gamma missing"); - vals_r__ = context__.vals_r("delta_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_gamma", "vector_d", context__.to_vec(T)); - // generate_declaration delta_gamma - vector_d delta_gamma(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_gamma(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_gamma: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo"))) - throw std::runtime_error("variable nu_geo missing"); - vals_r__ = context__.vals_r("nu_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo", "vector_d", context__.to_vec(T,H)); - // generate_declaration nu_geo - std::vector nu_geo(T,vector_d(static_cast(H))); - for (int j1__ = 0U; j1__ < H; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - nu_geo[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(nu_geo[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo_prior"))) - throw std::runtime_error("variable nu_geo_prior missing"); - vals_r__ = context__.vals_r("nu_geo_prior"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo_prior", "vector_d", context__.to_vec(Hprior)); - // generate_declaration nu_geo_prior - vector_d nu_geo_prior(static_cast(Hprior)); - for (int j1__ = 0U; j1__ < Hprior; ++j1__) - nu_geo_prior(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(nu_geo_prior); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo_prior: ") + e.what()); - } - - if (!(context__.contains_r("delta_tbar"))) - throw std::runtime_error("variable delta_tbar missing"); - vals_r__ = context__.vals_r("delta_tbar"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_tbar", "vector_d", context__.to_vec(T)); - // generate_declaration delta_tbar - vector_d delta_tbar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_tbar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_tbar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_tbar: ") + e.what()); - } - - if (!(context__.contains_r("theta_bar_raw"))) - throw std::runtime_error("variable theta_bar_raw missing"); - vals_r__ = context__.vals_r("theta_bar_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "theta_bar_raw", "vector_d", context__.to_vec(T,G)); - // generate_declaration theta_bar_raw - std::vector theta_bar_raw(T,vector_d(static_cast(G))); - for (int j1__ = 0U; j1__ < G; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - theta_bar_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(theta_bar_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable theta_bar_raw: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta_bar"))) - throw std::runtime_error("variable sd_theta_bar missing"); - vals_r__ = context__.vals_r("sd_theta_bar"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta_bar", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta_bar - vector_d sd_theta_bar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta_bar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta_bar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta_bar: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta"))) - throw std::runtime_error("variable sd_theta missing"); - vals_r__ = context__.vals_r("sd_theta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta - vector_d sd_theta(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma_geo"))) - throw std::runtime_error("variable sd_gamma_geo missing"); - vals_r__ = context__.vals_r("sd_gamma_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma_geo", "double", context__.to_vec()); - // generate_declaration sd_gamma_geo - double sd_gamma_geo(0); - sd_gamma_geo = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma_geo); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma_geo: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma_demo"))) - throw std::runtime_error("variable sd_gamma_demo missing"); - vals_r__ = context__.vals_r("sd_gamma_demo"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma_demo", "double", context__.to_vec()); - // generate_declaration sd_gamma_demo - double sd_gamma_demo(0); - sd_gamma_demo = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma_demo); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma_demo: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_delta"))) - throw std::runtime_error("variable sd_innov_delta missing"); - vals_r__ = context__.vals_r("sd_innov_delta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_delta", "double", context__.to_vec()); - // generate_declaration sd_innov_delta - double sd_innov_delta(0); - sd_innov_delta = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_delta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_delta: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_logsd"))) - throw std::runtime_error("variable sd_innov_logsd missing"); - vals_r__ = context__.vals_r("sd_innov_logsd"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_logsd", "double", context__.to_vec()); - // generate_declaration sd_innov_logsd - double sd_innov_logsd(0); - sd_innov_logsd = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_logsd); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_logsd: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_gamma"))) - throw std::runtime_error("variable sd_innov_gamma missing"); - vals_r__ = context__.vals_r("sd_innov_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_gamma", "double", context__.to_vec()); - // generate_declaration sd_innov_gamma - double sd_innov_gamma(0); - sd_innov_gamma = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_gamma: ") + e.what()); - } - - params_r__ = writer__.data_r(); - params_i__ = writer__.data_i(); - } - - void transform_inits(const stan::io::var_context& context, - Eigen::Matrix& params_r, - std::ostream* pstream__) const { - std::vector params_r_vec; - std::vector params_i_vec; - transform_inits(context, params_i_vec, params_r_vec, pstream__); - params_r.resize(params_r_vec.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r(i) = params_r_vec[i]; - } - - - template - T__ log_prob(vector& params_r__, - vector& params_i__, - std::ostream* pstream__ = 0) const { - - T__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - T__ lp__(0.0); - stan::math::accumulator lp_accum__; - - // model parameters - stan::io::reader in__(params_r__,params_i__); - - vector > diff_raw; - size_t dim_diff_raw_0__ = D; - diff_raw.reserve(dim_diff_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - if (jacobian__) - diff_raw.push_back(in__.vector_constrain(Q,lp__)); - else - diff_raw.push_back(in__.vector_constrain(Q)); - } - - Eigen::Matrix disc_raw; - (void) disc_raw; // dummy to suppress unused var warning - if (jacobian__) - disc_raw = in__.vector_lb_constrain(0,Q,lp__); - else - disc_raw = in__.vector_lb_constrain(0,Q); - - Eigen::Matrix xi; - (void) xi; // dummy to suppress unused var warning - if (jacobian__) - xi = in__.vector_constrain(T,lp__); - else - xi = in__.vector_constrain(T); - - vector > gamma_raw; - size_t dim_gamma_raw_0__ = T; - gamma_raw.reserve(dim_gamma_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - if (jacobian__) - gamma_raw.push_back(in__.vector_constrain(P,lp__)); - else - gamma_raw.push_back(in__.vector_constrain(P)); - } - - Eigen::Matrix delta_gamma; - (void) delta_gamma; // dummy to suppress unused var warning - if (jacobian__) - delta_gamma = in__.vector_constrain(T,lp__); - else - delta_gamma = in__.vector_constrain(T); - - vector > nu_geo; - size_t dim_nu_geo_0__ = T; - nu_geo.reserve(dim_nu_geo_0__); - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - if (jacobian__) - nu_geo.push_back(in__.vector_constrain(H,lp__)); - else - nu_geo.push_back(in__.vector_constrain(H)); - } - - Eigen::Matrix nu_geo_prior; - (void) nu_geo_prior; // dummy to suppress unused var warning - if (jacobian__) - nu_geo_prior = in__.vector_constrain(Hprior,lp__); - else - nu_geo_prior = in__.vector_constrain(Hprior); - - Eigen::Matrix delta_tbar; - (void) delta_tbar; // dummy to suppress unused var warning - if (jacobian__) - delta_tbar = in__.vector_constrain(T,lp__); - else - delta_tbar = in__.vector_constrain(T); - - vector > theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - theta_bar_raw.reserve(dim_theta_bar_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - if (jacobian__) - theta_bar_raw.push_back(in__.vector_constrain(G,lp__)); - else - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - - Eigen::Matrix sd_theta_bar; - (void) sd_theta_bar; // dummy to suppress unused var warning - if (jacobian__) - sd_theta_bar = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta_bar = in__.vector_lb_constrain(0,T); - - Eigen::Matrix sd_theta; - (void) sd_theta; // dummy to suppress unused var warning - if (jacobian__) - sd_theta = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta = in__.vector_lb_constrain(0,T); - - T__ sd_gamma_geo; - (void) sd_gamma_geo; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma_geo = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma_geo = in__.scalar_lb_constrain(0); - - T__ sd_gamma_demo; - (void) sd_gamma_demo; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma_demo = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma_demo = in__.scalar_lb_constrain(0); - - T__ sd_innov_delta; - (void) sd_innov_delta; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_delta = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_delta = in__.scalar_lb_constrain(0); - - T__ sd_innov_logsd; - (void) sd_innov_logsd; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_logsd = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_logsd = in__.scalar_lb_constrain(0); - - T__ sd_innov_gamma; - (void) sd_innov_gamma; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_gamma = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_gamma = in__.scalar_lb_constrain(0); - - - // transformed parameters - vector > theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(theta_bar, DUMMY_VAR__); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector > diff(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(diff, DUMMY_VAR__); - stan::math::fill(diff,DUMMY_VAR__); - vector > kappa(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(kappa, DUMMY_VAR__); - stan::math::fill(kappa,DUMMY_VAR__); - Eigen::Matrix disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, DUMMY_VAR__); - stan::math::fill(disc,DUMMY_VAR__); - Eigen::Matrix sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, DUMMY_VAR__); - stan::math::fill(sd_item,DUMMY_VAR__); - Eigen::Matrix var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, DUMMY_VAR__); - stan::math::fill(var_item,DUMMY_VAR__); - Eigen::Matrix var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, DUMMY_VAR__); - stan::math::fill(var_theta,DUMMY_VAR__); - vector > var_theta_bar_l2(T, (Eigen::Matrix (static_cast(G_hier)))); - stan::math::initialize(var_theta_bar_l2, DUMMY_VAR__); - stan::math::fill(var_theta_bar_l2,DUMMY_VAR__); - vector > gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(gamma, DUMMY_VAR__); - stan::math::fill(gamma,DUMMY_VAR__); - vector > mu_theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(mu_theta_bar, DUMMY_VAR__); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector > mu_gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(mu_gamma, DUMMY_VAR__); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > > z(T, (vector >(Q, (Eigen::Matrix (static_cast(G)))))); - stan::math::initialize(z, DUMMY_VAR__); - stan::math::fill(z,DUMMY_VAR__); - vector > > z_l2(T, (vector >(Q, (Eigen::Matrix (static_cast(G_hier)))))); - stan::math::initialize(z_l2, DUMMY_VAR__); - stan::math::fill(z_l2,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G))))); - stan::math::initialize(prob, DUMMY_VAR__); - stan::math::fill(prob,DUMMY_VAR__); - vector > > prob_l2(T, (vector >(Q, (Eigen::Matrix (static_cast(G_hier)))))); - stan::math::initialize(prob_l2, DUMMY_VAR__); - stan::math::fill(prob_l2,DUMMY_VAR__); - vector > theta_l2(T, (Eigen::Matrix (static_cast(G_hier)))); - stan::math::initialize(theta_l2, DUMMY_VAR__); - stan::math::fill(theta_l2,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - } else { - - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), ((get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2) * get_base1(delta_gamma,t,"delta_gamma",1)) + multiply(get_base1(get_base1(ZZ,t,"ZZ",1),p,"ZZ",2),get_base1(nu_geo,t,"nu_geo",1)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2)); - } - } - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - stan::math::assign(get_base1_lhs(theta_l2,t,"theta_l2",1), multiply(get_base1(WT,t,"WT",1),get_base1(theta_bar,t,"theta_bar",1))); - for (int n = 1; n <= G_hier; ++n) { - { - Eigen::Matrix WTdiag(static_cast(G),static_cast(G)); - (void) WTdiag; // dummy to suppress unused var warning - stan::math::initialize(WTdiag, DUMMY_VAR__); - stan::math::fill(WTdiag,DUMMY_VAR__); - - - for (int g = 1; g <= G; ++g) { - - for (int h = 1; h <= G; ++h) { - - if (as_bool(logical_eq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), get_base1(get_base1(WT,t,"WT",1),n,g,"WT",2)); - } - if (as_bool(logical_neq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), 0); - } - } - } - stan::math::assign(get_base1_lhs(get_base1_lhs(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2), multiply(multiply(transpose(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2))),WTdiag),subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2)))); - } - } - for (int q = 1; q <= Q; ++q) { - { - T__ sd_tq; - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, DUMMY_VAR__); - stan::math::fill(sd_tq,DUMMY_VAR__); - vector sd_l2_tq(G_hier); - stan::math::initialize(sd_l2_tq, DUMMY_VAR__); - stan::math::fill(sd_l2_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(sd_l2_tq,n,"sd_l2_tq",1), sqrt((square(sd_tq) + get_base1(get_base1(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2)))); - } - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - for (int g = 1; g <= G; ++g) { - - if (as_bool(logical_eq(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(theta_bar,t,"theta_bar",1),g,"theta_bar",2))); - } - if (as_bool(logical_gt(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(diff[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: diff" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(kappa[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: kappa" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(disc(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: disc" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(sd_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: sd_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(var_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - if (stan::math::is_uninitialized(var_theta(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_theta" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G_hier; ++i1__) { - if (stan::math::is_uninitialized(var_theta_bar_l2[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_theta_bar_l2" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(mu_theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(mu_gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(z[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G_hier; ++i2__) { - if (stan::math::is_uninitialized(z_l2[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z_l2" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(prob[i0__][i1__][i2__])) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G_hier; ++i2__) { - if (stan::math::is_uninitialized(prob_l2[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob_l2" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G_hier; ++i1__) { - if (stan::math::is_uninitialized(theta_l2[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_l2" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - - const char* function__ = "validate transformed params"; - (void) function__; // dummy to suppress unused var warning - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // model body - try { - { - vector prob_vec(N); - stan::math::initialize(prob_vec, DUMMY_VAR__); - stan::math::fill(prob_vec,DUMMY_VAR__); - int pos(0); - (void) pos; // dummy to suppress unused var warning - stan::math::fill(pos, std::numeric_limits::min()); - - - stan::math::assign(pos, 0); - if (as_bool(logical_eq(constant_item,1))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,1,"diff_raw",1), 0, 1)); - } - lp_accum__.add(lognormal_log(disc_raw, 0, 1)); - lp_accum__.add(cauchy_log(sd_gamma_geo, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_gamma_demo, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_delta, 0, innov_sd_delta_scale)); - lp_accum__.add(cauchy_log(sd_innov_gamma, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_logsd, 0, innov_sd_theta_scale)); - for (int t = 1; t <= T; ++t) { - - lp_accum__.add(normal_log(get_base1(gamma_raw,t,"gamma_raw",1), 0, 1)); - lp_accum__.add(normal_log(get_base1(theta_bar_raw,t,"theta_bar_raw",1), 0, 1)); - if (as_bool(logical_eq(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), 0, 1)); - } - lp_accum__.add(cauchy_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), 0, 2.5)); - lp_accum__.add(cauchy_log(get_base1(sd_theta,t,"sd_theta",1), 0, 2.5)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), 0, 10)); - lp_accum__.add(normal_log(nu_geo_prior, 0, 10)); - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), 0.5, 0.5)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), delta_tbar_prior_mean, delta_tbar_prior_sd)); - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - if (as_bool(logical_gt(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), get_base1(diff_raw,(t - 1),"diff_raw",1), sd_innov_gamma)); - } - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), get_base1(delta_gamma,(t - 1),"delta_gamma",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), get_base1(nu_geo,(t - 1),"nu_geo",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), get_base1(delta_tbar,(t - 1),"delta_tbar",1), sd_innov_delta)); - lp_accum__.add(lognormal_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), log(get_base1(sd_theta_bar,(t - 1),"sd_theta_bar",1)), sd_innov_logsd)); - lp_accum__.add(lognormal_log(get_base1(sd_theta,t,"sd_theta",1), log(get_base1(sd_theta,(t - 1),"sd_theta",1)), sd_innov_logsd)); - if (as_bool((primitive_value(logical_eq(separate_t,0)) && primitive_value(logical_gt(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), get_base1(xi,(t - 1),"xi",1), sd_innov_gamma)); - } - if (as_bool((primitive_value(logical_eq(separate_t,1)) || primitive_value(logical_eq(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - } - for (int q = 1; q <= Q; ++q) { - - for (int g = 1; g <= G; ++g) { - - stan::math::assign(pos, (pos + 1)); - stan::math::assign(get_base1_lhs(prob_vec,pos,"prob_vec",1), get_base1(get_base1(get_base1(prob,t,"prob",1),q,"prob",2),g,"prob",3)); - } - } - } - lp_accum__.add(binomial_log(stan::model::rvalue(s_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "s_vec"), stan::model::rvalue(n_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "n_vec"), stan::model::rvalue(prob_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "prob_vec"))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - lp_accum__.add(lp__); - return lp_accum__.sum(); - - } // log_prob() - - template - T_ log_prob(Eigen::Matrix& params_r, - std::ostream* pstream = 0) const { - std::vector vec_params_r; - vec_params_r.reserve(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - vec_params_r.push_back(params_r(i)); - std::vector vec_params_i; - return log_prob(vec_params_r, vec_params_i, pstream); - } - - - void get_param_names(std::vector& names__) const { - names__.resize(0); - names__.push_back("diff_raw"); - names__.push_back("disc_raw"); - names__.push_back("xi"); - names__.push_back("gamma_raw"); - names__.push_back("delta_gamma"); - names__.push_back("nu_geo"); - names__.push_back("nu_geo_prior"); - names__.push_back("delta_tbar"); - names__.push_back("theta_bar_raw"); - names__.push_back("sd_theta_bar"); - names__.push_back("sd_theta"); - names__.push_back("sd_gamma_geo"); - names__.push_back("sd_gamma_demo"); - names__.push_back("sd_innov_delta"); - names__.push_back("sd_innov_logsd"); - names__.push_back("sd_innov_gamma"); - names__.push_back("theta_bar"); - names__.push_back("diff"); - names__.push_back("kappa"); - names__.push_back("disc"); - names__.push_back("sd_item"); - names__.push_back("var_item"); - names__.push_back("var_theta"); - names__.push_back("var_theta_bar_l2"); - names__.push_back("gamma"); - names__.push_back("mu_theta_bar"); - names__.push_back("mu_gamma"); - names__.push_back("z"); - names__.push_back("z_l2"); - names__.push_back("prob"); - names__.push_back("prob_l2"); - names__.push_back("theta_l2"); - names__.push_back("sd_total"); - } - - - void get_dims(std::vector >& dimss__) const { - dimss__.resize(0); - std::vector dims__; - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(H); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Hprior); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G_hier); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - } - - template - void write_array(RNG& base_rng__, - std::vector& params_r__, - std::vector& params_i__, - std::vector& vars__, - bool include_tparams__ = true, - bool include_gqs__ = true, - std::ostream* pstream__ = 0) const { - vars__.resize(0); - stan::io::reader in__(params_r__,params_i__); - static const char* function__ = "model_2016_09_14_namespace::write_array"; - (void) function__; // dummy call to supress warning - // read-transform, write parameters - vector diff_raw; - size_t dim_diff_raw_0__ = D; - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - diff_raw.push_back(in__.vector_constrain(Q)); - } - vector_d disc_raw = in__.vector_lb_constrain(0,Q); - vector_d xi = in__.vector_constrain(T); - vector gamma_raw; - size_t dim_gamma_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - gamma_raw.push_back(in__.vector_constrain(P)); - } - vector_d delta_gamma = in__.vector_constrain(T); - vector nu_geo; - size_t dim_nu_geo_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - nu_geo.push_back(in__.vector_constrain(H)); - } - vector_d nu_geo_prior = in__.vector_constrain(Hprior); - vector_d delta_tbar = in__.vector_constrain(T); - vector theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - vector_d sd_theta_bar = in__.vector_lb_constrain(0,T); - vector_d sd_theta = in__.vector_lb_constrain(0,T); - double sd_gamma_geo = in__.scalar_lb_constrain(0); - double sd_gamma_demo = in__.scalar_lb_constrain(0); - double sd_innov_delta = in__.scalar_lb_constrain(0); - double sd_innov_logsd = in__.scalar_lb_constrain(0); - double sd_innov_gamma = in__.scalar_lb_constrain(0); - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc_raw[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(xi[k_0__]); - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_gamma[k_0__]); - } - for (int k_1__ = 0; k_1__ < H; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(nu_geo[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Hprior; ++k_0__) { - vars__.push_back(nu_geo_prior[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_tbar[k_0__]); - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta_bar[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta[k_0__]); - } - vars__.push_back(sd_gamma_geo); - vars__.push_back(sd_gamma_demo); - vars__.push_back(sd_innov_delta); - vars__.push_back(sd_innov_logsd); - vars__.push_back(sd_innov_gamma); - - if (!include_tparams__) return; - // declare and define transformed parameters - double lp__ = 0.0; - (void) lp__; // dummy call to supress warning - stan::math::accumulator lp_accum__; - - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - vector theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector diff(D, (vector_d(static_cast(Q)))); - stan::math::initialize(diff, std::numeric_limits::quiet_NaN()); - stan::math::fill(diff,DUMMY_VAR__); - vector kappa(D, (vector_d(static_cast(Q)))); - stan::math::initialize(kappa, std::numeric_limits::quiet_NaN()); - stan::math::fill(kappa,DUMMY_VAR__); - vector_d disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, std::numeric_limits::quiet_NaN()); - stan::math::fill(disc,DUMMY_VAR__); - vector_d sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_item,DUMMY_VAR__); - vector_d var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_item,DUMMY_VAR__); - vector_d var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_theta,DUMMY_VAR__); - vector var_theta_bar_l2(T, (vector_d(static_cast(G_hier)))); - stan::math::initialize(var_theta_bar_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_theta_bar_l2,DUMMY_VAR__); - vector gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(gamma,DUMMY_VAR__); - vector mu_theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(mu_theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector mu_gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(mu_gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > z(T, (vector(Q, (vector_d(static_cast(G)))))); - stan::math::initialize(z, std::numeric_limits::quiet_NaN()); - stan::math::fill(z,DUMMY_VAR__); - vector > z_l2(T, (vector(Q, (vector_d(static_cast(G_hier)))))); - stan::math::initialize(z_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(z_l2,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G, 0.0))))); - stan::math::initialize(prob, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob,DUMMY_VAR__); - vector > prob_l2(T, (vector(Q, (vector_d(static_cast(G_hier)))))); - stan::math::initialize(prob_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob_l2,DUMMY_VAR__); - vector theta_l2(T, (vector_d(static_cast(G_hier)))); - stan::math::initialize(theta_l2, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_l2,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - } else { - - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), ((get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2) * get_base1(delta_gamma,t,"delta_gamma",1)) + multiply(get_base1(get_base1(ZZ,t,"ZZ",1),p,"ZZ",2),get_base1(nu_geo,t,"nu_geo",1)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2)); - } - } - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - stan::math::assign(get_base1_lhs(theta_l2,t,"theta_l2",1), multiply(get_base1(WT,t,"WT",1),get_base1(theta_bar,t,"theta_bar",1))); - for (int n = 1; n <= G_hier; ++n) { - { - matrix_d WTdiag(static_cast(G),static_cast(G)); - (void) WTdiag; // dummy to suppress unused var warning - stan::math::initialize(WTdiag, std::numeric_limits::quiet_NaN()); - stan::math::fill(WTdiag,DUMMY_VAR__); - - - for (int g = 1; g <= G; ++g) { - - for (int h = 1; h <= G; ++h) { - - if (as_bool(logical_eq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), get_base1(get_base1(WT,t,"WT",1),n,g,"WT",2)); - } - if (as_bool(logical_neq(g,h))) { - - stan::math::assign(get_base1_lhs(WTdiag,g,h,"WTdiag",1), 0); - } - } - } - stan::math::assign(get_base1_lhs(get_base1_lhs(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2), multiply(multiply(transpose(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2))),WTdiag),subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2)))); - } - } - for (int q = 1; q <= Q; ++q) { - { - double sd_tq(0.0); - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_tq,DUMMY_VAR__); - vector sd_l2_tq(G_hier, 0.0); - stan::math::initialize(sd_l2_tq, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_l2_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(sd_l2_tq,n,"sd_l2_tq",1), sqrt((square(sd_tq) + get_base1(get_base1(var_theta_bar_l2,t,"var_theta_bar_l2",1),n,"var_theta_bar_l2",2)))); - } - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - for (int n = 1; n <= G_hier; ++n) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3), ((get_base1(get_base1(theta_l2,t,"theta_l2",1),n,"theta_l2",2) - get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)) / get_base1(sd_l2_tq,n,"sd_l2_tq",1))); - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob_l2,t,"prob_l2",1),q,"prob_l2",2),n,"prob_l2",3), Phi_approx(get_base1(get_base1(get_base1(z_l2,t,"z_l2",1),q,"z_l2",2),n,"z_l2",3))); - } - } - for (int g = 1; g <= G; ++g) { - - if (as_bool(logical_eq(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(theta_bar,t,"theta_bar",1),g,"theta_bar",2))); - } - if (as_bool(logical_gt(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // write transformed parameters - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(kappa[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(sd_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(var_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(var_theta[k_0__]); - } - for (int k_1__ = 0; k_1__ < G_hier; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(var_theta_bar_l2[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_gamma[k_0__][k_1__]); - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G_hier; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z_l2[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G_hier; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob_l2[k_0__][k_1__][k_2__]); - } - } - } - for (int k_1__ = 0; k_1__ < G_hier; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_l2[k_0__][k_1__]); - } - } - - if (!include_gqs__) return; - // declare and define generated quantities - vector_d sd_total(static_cast(T)); - (void) sd_total; // dummy to suppress unused var warning - stan::math::initialize(sd_total, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_total,DUMMY_VAR__); - - - try { - for (int t = 1; t <= T; ++t) { - - stan::math::assign(get_base1_lhs(sd_total,t,"sd_total",1), sqrt((variance(get_base1(theta_bar,t,"theta_bar",1)) + square(get_base1(sd_theta,t,"sd_theta",1))))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate generated quantities - check_greater_or_equal(function__,"sd_total",sd_total,0); - - // write generated quantities - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_total[k_0__]); - } - - } - - template - void write_array(RNG& base_rng, - Eigen::Matrix& params_r, - Eigen::Matrix& vars, - bool include_tparams = true, - bool include_gqs = true, - std::ostream* pstream = 0) const { - std::vector params_r_vec(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r_vec[i] = params_r(i); - std::vector vars_vec; - std::vector params_i_vec; - write_array(base_rng,params_r_vec,params_i_vec,vars_vec,include_tparams,include_gqs,pstream); - vars.resize(vars_vec.size()); - for (int i = 0; i < vars.size(); ++i) - vars(i) = vars_vec[i]; - } - - static std::string model_name() { - return "model_2016_09_14"; - } - - - void constrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_geo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_demo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta_bar_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - - - void unconstrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_geo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_demo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta_bar_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G_hier; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob_l2" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_1__ = 1; k_1__ <= G_hier; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_l2" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - -}; // model - -} // namespace - - - - -// Code generated by Stan version 2.14 - -#include - -namespace model_2017_01_04_namespace { - -using std::istream; -using std::string; -using std::stringstream; -using std::vector; -using stan::io::dump; -using stan::math::lgamma; -using stan::model::prob_grad; -using namespace stan::math; - -typedef Eigen::Matrix vector_d; -typedef Eigen::Matrix row_vector_d; -typedef Eigen::Matrix matrix_d; - -static int current_statement_begin__; - -class model_2017_01_04 : public prob_grad { -private: - int G; - int G_hier; - int Q; - int T; - int N; - int N_observed; - int S; - int P; - int H; - int Hprior; - int D; - int constant_item; - int separate_t; - int hierarchical_model; - double delta_tbar_prior_mean; - double delta_tbar_prior_sd; - double innov_sd_delta_scale; - double innov_sd_theta_scale; - vector n_vec; - vector s_vec; - vector observed; - vector > > NNl2; - vector > > SSl2; - matrix_d XX; - vector WT; - vector ZZ; - vector ZZ_prior; - matrix_d l2_only; -public: - model_2017_01_04(stan::io::var_context& context__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - typedef boost::ecuyer1988 rng_t; - rng_t base_rng(0); // 0 seed default - ctor_body(context__, base_rng, pstream__); - } - - template - model_2017_01_04(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - ctor_body(context__, base_rng__, pstream__); - } - - template - void ctor_body(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__) { - current_statement_begin__ = -1; - - static const char* function__ = "model_2017_01_04_namespace::model_2017_01_04"; - (void) function__; // dummy call to supress warning - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_i__; - std::vector vals_r__; - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - // initialize member variables - context__.validate_dims("data initialization", "G", "int", context__.to_vec()); - G = int(0); - vals_i__ = context__.vals_i("G"); - pos__ = 0; - G = vals_i__[pos__++]; - context__.validate_dims("data initialization", "G_hier", "int", context__.to_vec()); - G_hier = int(0); - vals_i__ = context__.vals_i("G_hier"); - pos__ = 0; - G_hier = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Q", "int", context__.to_vec()); - Q = int(0); - vals_i__ = context__.vals_i("Q"); - pos__ = 0; - Q = vals_i__[pos__++]; - context__.validate_dims("data initialization", "T", "int", context__.to_vec()); - T = int(0); - vals_i__ = context__.vals_i("T"); - pos__ = 0; - T = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N", "int", context__.to_vec()); - N = int(0); - vals_i__ = context__.vals_i("N"); - pos__ = 0; - N = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N_observed", "int", context__.to_vec()); - N_observed = int(0); - vals_i__ = context__.vals_i("N_observed"); - pos__ = 0; - N_observed = vals_i__[pos__++]; - context__.validate_dims("data initialization", "S", "int", context__.to_vec()); - S = int(0); - vals_i__ = context__.vals_i("S"); - pos__ = 0; - S = vals_i__[pos__++]; - context__.validate_dims("data initialization", "P", "int", context__.to_vec()); - P = int(0); - vals_i__ = context__.vals_i("P"); - pos__ = 0; - P = vals_i__[pos__++]; - context__.validate_dims("data initialization", "H", "int", context__.to_vec()); - H = int(0); - vals_i__ = context__.vals_i("H"); - pos__ = 0; - H = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Hprior", "int", context__.to_vec()); - Hprior = int(0); - vals_i__ = context__.vals_i("Hprior"); - pos__ = 0; - Hprior = vals_i__[pos__++]; - context__.validate_dims("data initialization", "D", "int", context__.to_vec()); - D = int(0); - vals_i__ = context__.vals_i("D"); - pos__ = 0; - D = vals_i__[pos__++]; - context__.validate_dims("data initialization", "constant_item", "int", context__.to_vec()); - constant_item = int(0); - vals_i__ = context__.vals_i("constant_item"); - pos__ = 0; - constant_item = vals_i__[pos__++]; - context__.validate_dims("data initialization", "separate_t", "int", context__.to_vec()); - separate_t = int(0); - vals_i__ = context__.vals_i("separate_t"); - pos__ = 0; - separate_t = vals_i__[pos__++]; - context__.validate_dims("data initialization", "hierarchical_model", "int", context__.to_vec()); - hierarchical_model = int(0); - vals_i__ = context__.vals_i("hierarchical_model"); - pos__ = 0; - hierarchical_model = vals_i__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_mean", "double", context__.to_vec()); - delta_tbar_prior_mean = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_mean"); - pos__ = 0; - delta_tbar_prior_mean = vals_r__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_sd", "double", context__.to_vec()); - delta_tbar_prior_sd = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_sd"); - pos__ = 0; - delta_tbar_prior_sd = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_delta_scale", "double", context__.to_vec()); - innov_sd_delta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_delta_scale"); - pos__ = 0; - innov_sd_delta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_theta_scale", "double", context__.to_vec()); - innov_sd_theta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_theta_scale"); - pos__ = 0; - innov_sd_theta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "n_vec", "int", context__.to_vec(N)); - validate_non_negative_index("n_vec", "N", N); - n_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("n_vec"); - pos__ = 0; - size_t n_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < n_vec_limit_0__; ++i_0__) { - n_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "s_vec", "int", context__.to_vec(N)); - validate_non_negative_index("s_vec", "N", N); - s_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("s_vec"); - pos__ = 0; - size_t s_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < s_vec_limit_0__; ++i_0__) { - s_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "observed", "int", context__.to_vec(N_observed)); - validate_non_negative_index("observed", "N_observed", N_observed); - observed = std::vector(N_observed,int(0)); - vals_i__ = context__.vals_i("observed"); - pos__ = 0; - size_t observed_limit_0__ = N_observed; - for (size_t i_0__ = 0; i_0__ < observed_limit_0__; ++i_0__) { - observed[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "NNl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("NNl2", "T", T); - validate_non_negative_index("NNl2", "Q", Q); - validate_non_negative_index("NNl2", "G_hier", G_hier); - NNl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("NNl2"); - pos__ = 0; - size_t NNl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < NNl2_limit_2__; ++i_2__) { - size_t NNl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < NNl2_limit_1__; ++i_1__) { - size_t NNl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < NNl2_limit_0__; ++i_0__) { - NNl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "SSl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("SSl2", "T", T); - validate_non_negative_index("SSl2", "Q", Q); - validate_non_negative_index("SSl2", "G_hier", G_hier); - SSl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("SSl2"); - pos__ = 0; - size_t SSl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < SSl2_limit_2__; ++i_2__) { - size_t SSl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < SSl2_limit_1__; ++i_1__) { - size_t SSl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < SSl2_limit_0__; ++i_0__) { - SSl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "XX", "matrix_d", context__.to_vec(G,P)); - validate_non_negative_index("XX", "G", G); - validate_non_negative_index("XX", "P", P); - XX = matrix_d(static_cast(G),static_cast(P)); - vals_r__ = context__.vals_r("XX"); - pos__ = 0; - size_t XX_m_mat_lim__ = G; - size_t XX_n_mat_lim__ = P; - for (size_t n_mat__ = 0; n_mat__ < XX_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < XX_m_mat_lim__; ++m_mat__) { - XX(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - context__.validate_dims("data initialization", "WT", "matrix_d", context__.to_vec(T,G_hier,G)); - validate_non_negative_index("WT", "T", T); - validate_non_negative_index("WT", "G_hier", G_hier); - validate_non_negative_index("WT", "G", G); - WT = std::vector(T,matrix_d(static_cast(G_hier),static_cast(G))); - vals_r__ = context__.vals_r("WT"); - pos__ = 0; - size_t WT_m_mat_lim__ = G_hier; - size_t WT_n_mat_lim__ = G; - for (size_t n_mat__ = 0; n_mat__ < WT_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < WT_m_mat_lim__; ++m_mat__) { - size_t WT_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < WT_limit_0__; ++i_0__) { - WT[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ", "matrix_d", context__.to_vec(T,P,H)); - validate_non_negative_index("ZZ", "T", T); - validate_non_negative_index("ZZ", "P", P); - validate_non_negative_index("ZZ", "H", H); - ZZ = std::vector(T,matrix_d(static_cast(P),static_cast(H))); - vals_r__ = context__.vals_r("ZZ"); - pos__ = 0; - size_t ZZ_m_mat_lim__ = P; - size_t ZZ_n_mat_lim__ = H; - for (size_t n_mat__ = 0; n_mat__ < ZZ_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_m_mat_lim__; ++m_mat__) { - size_t ZZ_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_limit_0__; ++i_0__) { - ZZ[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ_prior", "matrix_d", context__.to_vec(T,P,Hprior)); - validate_non_negative_index("ZZ_prior", "T", T); - validate_non_negative_index("ZZ_prior", "P", P); - validate_non_negative_index("ZZ_prior", "Hprior", Hprior); - ZZ_prior = std::vector(T,matrix_d(static_cast(P),static_cast(Hprior))); - vals_r__ = context__.vals_r("ZZ_prior"); - pos__ = 0; - size_t ZZ_prior_m_mat_lim__ = P; - size_t ZZ_prior_n_mat_lim__ = Hprior; - for (size_t n_mat__ = 0; n_mat__ < ZZ_prior_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_prior_m_mat_lim__; ++m_mat__) { - size_t ZZ_prior_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_prior_limit_0__; ++i_0__) { - ZZ_prior[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "l2_only", "matrix_d", context__.to_vec(T,Q)); - validate_non_negative_index("l2_only", "T", T); - validate_non_negative_index("l2_only", "Q", Q); - l2_only = matrix_d(static_cast(T),static_cast(Q)); - vals_r__ = context__.vals_r("l2_only"); - pos__ = 0; - size_t l2_only_m_mat_lim__ = T; - size_t l2_only_n_mat_lim__ = Q; - for (size_t n_mat__ = 0; n_mat__ < l2_only_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < l2_only_m_mat_lim__; ++m_mat__) { - l2_only(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - - // validate, data variables - check_greater_or_equal(function__,"G",G,1); - check_greater_or_equal(function__,"G_hier",G_hier,1); - check_greater_or_equal(function__,"Q",Q,1); - check_greater_or_equal(function__,"T",T,1); - check_greater_or_equal(function__,"N",N,1); - check_greater_or_equal(function__,"N_observed",N_observed,1); - check_greater_or_equal(function__,"S",S,1); - check_greater_or_equal(function__,"P",P,1); - check_greater_or_equal(function__,"H",H,1); - check_greater_or_equal(function__,"Hprior",Hprior,1); - check_greater_or_equal(function__,"D",D,1); - check_greater_or_equal(function__,"constant_item",constant_item,0); - check_less_or_equal(function__,"constant_item",constant_item,1); - check_greater_or_equal(function__,"separate_t",separate_t,0); - check_less_or_equal(function__,"separate_t",separate_t,1); - check_greater_or_equal(function__,"hierarchical_model",hierarchical_model,0); - check_less_or_equal(function__,"hierarchical_model",hierarchical_model,1); - check_greater_or_equal(function__,"delta_tbar_prior_sd",delta_tbar_prior_sd,0); - check_greater_or_equal(function__,"innov_sd_delta_scale",innov_sd_delta_scale,0); - check_greater_or_equal(function__,"innov_sd_theta_scale",innov_sd_theta_scale,0); - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"n_vec[k0__]",n_vec[k0__],0); - } - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"s_vec[k0__]",s_vec[k0__],0); - } - check_greater_or_equal(function__,"XX",XX,0); - check_less_or_equal(function__,"XX",XX,1); - for (int k0__ = 0; k0__ < T; ++k0__) { - check_greater_or_equal(function__,"WT[k0__]",WT[k0__],0); - check_less_or_equal(function__,"WT[k0__]",WT[k0__],1); - } - check_greater_or_equal(function__,"l2_only",l2_only,0); - check_less_or_equal(function__,"l2_only",l2_only,1); - // initialize data variables - - try { - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed data - - // set parameter ranges - num_params_r__ = 0U; - param_ranges_i__.clear(); - num_params_r__ += Q * D; - num_params_r__ += Q; - num_params_r__ += T; - num_params_r__ += P * T; - num_params_r__ += T; - num_params_r__ += H * T; - num_params_r__ += Hprior; - num_params_r__ += T; - num_params_r__ += G * T; - num_params_r__ += T; - num_params_r__ += T; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - } - - ~model_2017_01_04() { } - - - void transform_inits(const stan::io::var_context& context__, - std::vector& params_i__, - std::vector& params_r__, - std::ostream* pstream__) const { - stan::io::writer writer__(params_r__,params_i__); - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_r__; - std::vector vals_i__; - - if (!(context__.contains_r("diff_raw"))) - throw std::runtime_error("variable diff_raw missing"); - vals_r__ = context__.vals_r("diff_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "diff_raw", "vector_d", context__.to_vec(D,Q)); - // generate_declaration diff_raw - std::vector diff_raw(D,vector_d(static_cast(Q))); - for (int j1__ = 0U; j1__ < Q; ++j1__) - for (int i0__ = 0U; i0__ < D; ++i0__) - diff_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < D; ++i0__) - try { - writer__.vector_unconstrain(diff_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable diff_raw: ") + e.what()); - } - - if (!(context__.contains_r("disc_raw"))) - throw std::runtime_error("variable disc_raw missing"); - vals_r__ = context__.vals_r("disc_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "disc_raw", "vector_d", context__.to_vec(Q)); - // generate_declaration disc_raw - vector_d disc_raw(static_cast(Q)); - for (int j1__ = 0U; j1__ < Q; ++j1__) - disc_raw(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,disc_raw); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable disc_raw: ") + e.what()); - } - - if (!(context__.contains_r("xi"))) - throw std::runtime_error("variable xi missing"); - vals_r__ = context__.vals_r("xi"); - pos__ = 0U; - context__.validate_dims("initialization", "xi", "vector_d", context__.to_vec(T)); - // generate_declaration xi - vector_d xi(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - xi(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(xi); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable xi: ") + e.what()); - } - - if (!(context__.contains_r("gamma_raw"))) - throw std::runtime_error("variable gamma_raw missing"); - vals_r__ = context__.vals_r("gamma_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "gamma_raw", "vector_d", context__.to_vec(T,P)); - // generate_declaration gamma_raw - std::vector gamma_raw(T,vector_d(static_cast(P))); - for (int j1__ = 0U; j1__ < P; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - gamma_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(gamma_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable gamma_raw: ") + e.what()); - } - - if (!(context__.contains_r("delta_gamma"))) - throw std::runtime_error("variable delta_gamma missing"); - vals_r__ = context__.vals_r("delta_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_gamma", "vector_d", context__.to_vec(T)); - // generate_declaration delta_gamma - vector_d delta_gamma(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_gamma(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_gamma: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo"))) - throw std::runtime_error("variable nu_geo missing"); - vals_r__ = context__.vals_r("nu_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo", "vector_d", context__.to_vec(T,H)); - // generate_declaration nu_geo - std::vector nu_geo(T,vector_d(static_cast(H))); - for (int j1__ = 0U; j1__ < H; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - nu_geo[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(nu_geo[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo_prior"))) - throw std::runtime_error("variable nu_geo_prior missing"); - vals_r__ = context__.vals_r("nu_geo_prior"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo_prior", "vector_d", context__.to_vec(Hprior)); - // generate_declaration nu_geo_prior - vector_d nu_geo_prior(static_cast(Hprior)); - for (int j1__ = 0U; j1__ < Hprior; ++j1__) - nu_geo_prior(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(nu_geo_prior); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo_prior: ") + e.what()); - } - - if (!(context__.contains_r("delta_tbar"))) - throw std::runtime_error("variable delta_tbar missing"); - vals_r__ = context__.vals_r("delta_tbar"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_tbar", "vector_d", context__.to_vec(T)); - // generate_declaration delta_tbar - vector_d delta_tbar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_tbar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_tbar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_tbar: ") + e.what()); - } - - if (!(context__.contains_r("theta_bar_raw"))) - throw std::runtime_error("variable theta_bar_raw missing"); - vals_r__ = context__.vals_r("theta_bar_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "theta_bar_raw", "vector_d", context__.to_vec(T,G)); - // generate_declaration theta_bar_raw - std::vector theta_bar_raw(T,vector_d(static_cast(G))); - for (int j1__ = 0U; j1__ < G; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - theta_bar_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(theta_bar_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable theta_bar_raw: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta_bar"))) - throw std::runtime_error("variable sd_theta_bar missing"); - vals_r__ = context__.vals_r("sd_theta_bar"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta_bar", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta_bar - vector_d sd_theta_bar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta_bar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta_bar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta_bar: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta"))) - throw std::runtime_error("variable sd_theta missing"); - vals_r__ = context__.vals_r("sd_theta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta - vector_d sd_theta(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma_geo"))) - throw std::runtime_error("variable sd_gamma_geo missing"); - vals_r__ = context__.vals_r("sd_gamma_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma_geo", "double", context__.to_vec()); - // generate_declaration sd_gamma_geo - double sd_gamma_geo(0); - sd_gamma_geo = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma_geo); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma_geo: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma_demo"))) - throw std::runtime_error("variable sd_gamma_demo missing"); - vals_r__ = context__.vals_r("sd_gamma_demo"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma_demo", "double", context__.to_vec()); - // generate_declaration sd_gamma_demo - double sd_gamma_demo(0); - sd_gamma_demo = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma_demo); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma_demo: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_delta"))) - throw std::runtime_error("variable sd_innov_delta missing"); - vals_r__ = context__.vals_r("sd_innov_delta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_delta", "double", context__.to_vec()); - // generate_declaration sd_innov_delta - double sd_innov_delta(0); - sd_innov_delta = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_delta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_delta: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_logsd"))) - throw std::runtime_error("variable sd_innov_logsd missing"); - vals_r__ = context__.vals_r("sd_innov_logsd"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_logsd", "double", context__.to_vec()); - // generate_declaration sd_innov_logsd - double sd_innov_logsd(0); - sd_innov_logsd = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_logsd); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_logsd: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_gamma"))) - throw std::runtime_error("variable sd_innov_gamma missing"); - vals_r__ = context__.vals_r("sd_innov_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_gamma", "double", context__.to_vec()); - // generate_declaration sd_innov_gamma - double sd_innov_gamma(0); - sd_innov_gamma = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_gamma: ") + e.what()); - } - - params_r__ = writer__.data_r(); - params_i__ = writer__.data_i(); - } - - void transform_inits(const stan::io::var_context& context, - Eigen::Matrix& params_r, - std::ostream* pstream__) const { - std::vector params_r_vec; - std::vector params_i_vec; - transform_inits(context, params_i_vec, params_r_vec, pstream__); - params_r.resize(params_r_vec.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r(i) = params_r_vec[i]; - } - - - template - T__ log_prob(vector& params_r__, - vector& params_i__, - std::ostream* pstream__ = 0) const { - - T__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - T__ lp__(0.0); - stan::math::accumulator lp_accum__; - - // model parameters - stan::io::reader in__(params_r__,params_i__); - - vector > diff_raw; - size_t dim_diff_raw_0__ = D; - diff_raw.reserve(dim_diff_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - if (jacobian__) - diff_raw.push_back(in__.vector_constrain(Q,lp__)); - else - diff_raw.push_back(in__.vector_constrain(Q)); - } - - Eigen::Matrix disc_raw; - (void) disc_raw; // dummy to suppress unused var warning - if (jacobian__) - disc_raw = in__.vector_lb_constrain(0,Q,lp__); - else - disc_raw = in__.vector_lb_constrain(0,Q); - - Eigen::Matrix xi; - (void) xi; // dummy to suppress unused var warning - if (jacobian__) - xi = in__.vector_constrain(T,lp__); - else - xi = in__.vector_constrain(T); - - vector > gamma_raw; - size_t dim_gamma_raw_0__ = T; - gamma_raw.reserve(dim_gamma_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - if (jacobian__) - gamma_raw.push_back(in__.vector_constrain(P,lp__)); - else - gamma_raw.push_back(in__.vector_constrain(P)); - } - - Eigen::Matrix delta_gamma; - (void) delta_gamma; // dummy to suppress unused var warning - if (jacobian__) - delta_gamma = in__.vector_constrain(T,lp__); - else - delta_gamma = in__.vector_constrain(T); - - vector > nu_geo; - size_t dim_nu_geo_0__ = T; - nu_geo.reserve(dim_nu_geo_0__); - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - if (jacobian__) - nu_geo.push_back(in__.vector_constrain(H,lp__)); - else - nu_geo.push_back(in__.vector_constrain(H)); - } - - Eigen::Matrix nu_geo_prior; - (void) nu_geo_prior; // dummy to suppress unused var warning - if (jacobian__) - nu_geo_prior = in__.vector_constrain(Hprior,lp__); - else - nu_geo_prior = in__.vector_constrain(Hprior); - - Eigen::Matrix delta_tbar; - (void) delta_tbar; // dummy to suppress unused var warning - if (jacobian__) - delta_tbar = in__.vector_constrain(T,lp__); - else - delta_tbar = in__.vector_constrain(T); - - vector > theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - theta_bar_raw.reserve(dim_theta_bar_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - if (jacobian__) - theta_bar_raw.push_back(in__.vector_constrain(G,lp__)); - else - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - - Eigen::Matrix sd_theta_bar; - (void) sd_theta_bar; // dummy to suppress unused var warning - if (jacobian__) - sd_theta_bar = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta_bar = in__.vector_lb_constrain(0,T); - - Eigen::Matrix sd_theta; - (void) sd_theta; // dummy to suppress unused var warning - if (jacobian__) - sd_theta = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta = in__.vector_lb_constrain(0,T); - - T__ sd_gamma_geo; - (void) sd_gamma_geo; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma_geo = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma_geo = in__.scalar_lb_constrain(0); - - T__ sd_gamma_demo; - (void) sd_gamma_demo; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma_demo = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma_demo = in__.scalar_lb_constrain(0); - - T__ sd_innov_delta; - (void) sd_innov_delta; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_delta = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_delta = in__.scalar_lb_constrain(0); - - T__ sd_innov_logsd; - (void) sd_innov_logsd; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_logsd = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_logsd = in__.scalar_lb_constrain(0); - - T__ sd_innov_gamma; - (void) sd_innov_gamma; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_gamma = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_gamma = in__.scalar_lb_constrain(0); - - - // transformed parameters - vector > theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(theta_bar, DUMMY_VAR__); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector > diff(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(diff, DUMMY_VAR__); - stan::math::fill(diff,DUMMY_VAR__); - vector > kappa(D, (Eigen::Matrix (static_cast(Q)))); - stan::math::initialize(kappa, DUMMY_VAR__); - stan::math::fill(kappa,DUMMY_VAR__); - Eigen::Matrix disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, DUMMY_VAR__); - stan::math::fill(disc,DUMMY_VAR__); - Eigen::Matrix sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, DUMMY_VAR__); - stan::math::fill(sd_item,DUMMY_VAR__); - Eigen::Matrix var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, DUMMY_VAR__); - stan::math::fill(var_item,DUMMY_VAR__); - Eigen::Matrix var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, DUMMY_VAR__); - stan::math::fill(var_theta,DUMMY_VAR__); - vector > gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(gamma, DUMMY_VAR__); - stan::math::fill(gamma,DUMMY_VAR__); - vector > mu_theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(mu_theta_bar, DUMMY_VAR__); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector > mu_gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(mu_gamma, DUMMY_VAR__); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > > z(T, (vector >(Q, (Eigen::Matrix (static_cast(G)))))); - stan::math::initialize(z, DUMMY_VAR__); - stan::math::fill(z,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G))))); - stan::math::initialize(prob, DUMMY_VAR__); - stan::math::fill(prob,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - } else { - - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), ((get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2) * get_base1(delta_gamma,t,"delta_gamma",1)) + multiply(get_base1(get_base1(ZZ,t,"ZZ",1),p,"ZZ",2),get_base1(nu_geo,t,"nu_geo",1)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2)); - } - } - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - if (as_bool(logical_eq(hierarchical_model,1))) { - - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - } - if (as_bool(logical_eq(hierarchical_model,0))) { - - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1))); - } - for (int q = 1; q <= Q; ++q) { - { - T__ sd_tq; - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, DUMMY_VAR__); - stan::math::fill(sd_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - } - for (int g = 1; g <= G; ++g) { - - if (as_bool(logical_eq(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(theta_bar,t,"theta_bar",1),g,"theta_bar",2))); - } - if (as_bool(logical_gt(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(diff[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: diff" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < D; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - if (stan::math::is_uninitialized(kappa[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: kappa" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(disc(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: disc" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(sd_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: sd_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < Q; ++i0__) { - if (stan::math::is_uninitialized(var_item(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_item" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - if (stan::math::is_uninitialized(var_theta(i0__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: var_theta" << '[' << i0__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(mu_theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(mu_gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(z[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(prob[i0__][i1__][i2__])) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - - const char* function__ = "validate transformed params"; - (void) function__; // dummy to suppress unused var warning - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // model body - try { - { - vector prob_vec(N); - stan::math::initialize(prob_vec, DUMMY_VAR__); - stan::math::fill(prob_vec,DUMMY_VAR__); - int pos(0); - (void) pos; // dummy to suppress unused var warning - stan::math::fill(pos, std::numeric_limits::min()); - - - stan::math::assign(pos, 0); - if (as_bool(logical_eq(constant_item,1))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,1,"diff_raw",1), 0, 1)); - } - lp_accum__.add(lognormal_log(disc_raw, 0, 1)); - lp_accum__.add(cauchy_log(sd_gamma_geo, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_gamma_demo, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_delta, 0, innov_sd_delta_scale)); - lp_accum__.add(cauchy_log(sd_innov_gamma, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_logsd, 0, innov_sd_theta_scale)); - for (int t = 1; t <= T; ++t) { - - lp_accum__.add(normal_log(get_base1(gamma_raw,t,"gamma_raw",1), 0, 1)); - lp_accum__.add(normal_log(get_base1(theta_bar_raw,t,"theta_bar_raw",1), 0, 1)); - if (as_bool(logical_eq(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), 0, 1)); - } - lp_accum__.add(cauchy_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), 0, 2.5)); - lp_accum__.add(cauchy_log(get_base1(sd_theta,t,"sd_theta",1), 0, 2.5)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), 0, 10)); - lp_accum__.add(normal_log(nu_geo_prior, 0, 10)); - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), 0.5, 0.5)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), delta_tbar_prior_mean, delta_tbar_prior_sd)); - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - if (as_bool(logical_gt(t,1))) { - - if (as_bool(logical_eq(constant_item,0))) { - - lp_accum__.add(normal_log(get_base1(diff_raw,t,"diff_raw",1), get_base1(diff_raw,(t - 1),"diff_raw",1), sd_innov_gamma)); - } - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), get_base1(delta_gamma,(t - 1),"delta_gamma",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), get_base1(nu_geo,(t - 1),"nu_geo",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), get_base1(delta_tbar,(t - 1),"delta_tbar",1), sd_innov_delta)); - lp_accum__.add(lognormal_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), log(get_base1(sd_theta_bar,(t - 1),"sd_theta_bar",1)), sd_innov_logsd)); - lp_accum__.add(lognormal_log(get_base1(sd_theta,t,"sd_theta",1), log(get_base1(sd_theta,(t - 1),"sd_theta",1)), sd_innov_logsd)); - if (as_bool((primitive_value(logical_eq(separate_t,0)) && primitive_value(logical_gt(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), get_base1(xi,(t - 1),"xi",1), sd_innov_gamma)); - } - if (as_bool((primitive_value(logical_eq(separate_t,1)) || primitive_value(logical_eq(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - } - for (int q = 1; q <= Q; ++q) { - - for (int g = 1; g <= G; ++g) { - - stan::math::assign(pos, (pos + 1)); - stan::math::assign(get_base1_lhs(prob_vec,pos,"prob_vec",1), get_base1(get_base1(get_base1(prob,t,"prob",1),q,"prob",2),g,"prob",3)); - } - } - } - lp_accum__.add(binomial_log(stan::model::rvalue(s_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "s_vec"), stan::model::rvalue(n_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "n_vec"), stan::model::rvalue(prob_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "prob_vec"))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - lp_accum__.add(lp__); - return lp_accum__.sum(); - - } // log_prob() - - template - T_ log_prob(Eigen::Matrix& params_r, - std::ostream* pstream = 0) const { - std::vector vec_params_r; - vec_params_r.reserve(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - vec_params_r.push_back(params_r(i)); - std::vector vec_params_i; - return log_prob(vec_params_r, vec_params_i, pstream); - } - - - void get_param_names(std::vector& names__) const { - names__.resize(0); - names__.push_back("diff_raw"); - names__.push_back("disc_raw"); - names__.push_back("xi"); - names__.push_back("gamma_raw"); - names__.push_back("delta_gamma"); - names__.push_back("nu_geo"); - names__.push_back("nu_geo_prior"); - names__.push_back("delta_tbar"); - names__.push_back("theta_bar_raw"); - names__.push_back("sd_theta_bar"); - names__.push_back("sd_theta"); - names__.push_back("sd_gamma_geo"); - names__.push_back("sd_gamma_demo"); - names__.push_back("sd_innov_delta"); - names__.push_back("sd_innov_logsd"); - names__.push_back("sd_innov_gamma"); - names__.push_back("theta_bar"); - names__.push_back("diff"); - names__.push_back("kappa"); - names__.push_back("disc"); - names__.push_back("sd_item"); - names__.push_back("var_item"); - names__.push_back("var_theta"); - names__.push_back("gamma"); - names__.push_back("mu_theta_bar"); - names__.push_back("mu_gamma"); - names__.push_back("z"); - names__.push_back("prob"); - names__.push_back("sd_total"); - } - - - void get_dims(std::vector >& dimss__) const { - dimss__.resize(0); - std::vector dims__; - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(H); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Hprior); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(D); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Q); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - } - - template - void write_array(RNG& base_rng__, - std::vector& params_r__, - std::vector& params_i__, - std::vector& vars__, - bool include_tparams__ = true, - bool include_gqs__ = true, - std::ostream* pstream__ = 0) const { - vars__.resize(0); - stan::io::reader in__(params_r__,params_i__); - static const char* function__ = "model_2017_01_04_namespace::write_array"; - (void) function__; // dummy call to supress warning - // read-transform, write parameters - vector diff_raw; - size_t dim_diff_raw_0__ = D; - for (size_t k_0__ = 0; k_0__ < dim_diff_raw_0__; ++k_0__) { - diff_raw.push_back(in__.vector_constrain(Q)); - } - vector_d disc_raw = in__.vector_lb_constrain(0,Q); - vector_d xi = in__.vector_constrain(T); - vector gamma_raw; - size_t dim_gamma_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - gamma_raw.push_back(in__.vector_constrain(P)); - } - vector_d delta_gamma = in__.vector_constrain(T); - vector nu_geo; - size_t dim_nu_geo_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - nu_geo.push_back(in__.vector_constrain(H)); - } - vector_d nu_geo_prior = in__.vector_constrain(Hprior); - vector_d delta_tbar = in__.vector_constrain(T); - vector theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - vector_d sd_theta_bar = in__.vector_lb_constrain(0,T); - vector_d sd_theta = in__.vector_lb_constrain(0,T); - double sd_gamma_geo = in__.scalar_lb_constrain(0); - double sd_gamma_demo = in__.scalar_lb_constrain(0); - double sd_innov_delta = in__.scalar_lb_constrain(0); - double sd_innov_logsd = in__.scalar_lb_constrain(0); - double sd_innov_gamma = in__.scalar_lb_constrain(0); - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc_raw[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(xi[k_0__]); - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_gamma[k_0__]); - } - for (int k_1__ = 0; k_1__ < H; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(nu_geo[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Hprior; ++k_0__) { - vars__.push_back(nu_geo_prior[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_tbar[k_0__]); - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta_bar[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta[k_0__]); - } - vars__.push_back(sd_gamma_geo); - vars__.push_back(sd_gamma_demo); - vars__.push_back(sd_innov_delta); - vars__.push_back(sd_innov_logsd); - vars__.push_back(sd_innov_gamma); - - if (!include_tparams__) return; - // declare and define transformed parameters - double lp__ = 0.0; - (void) lp__; // dummy call to supress warning - stan::math::accumulator lp_accum__; - - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - vector theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector diff(D, (vector_d(static_cast(Q)))); - stan::math::initialize(diff, std::numeric_limits::quiet_NaN()); - stan::math::fill(diff,DUMMY_VAR__); - vector kappa(D, (vector_d(static_cast(Q)))); - stan::math::initialize(kappa, std::numeric_limits::quiet_NaN()); - stan::math::fill(kappa,DUMMY_VAR__); - vector_d disc(static_cast(Q)); - (void) disc; // dummy to suppress unused var warning - stan::math::initialize(disc, std::numeric_limits::quiet_NaN()); - stan::math::fill(disc,DUMMY_VAR__); - vector_d sd_item(static_cast(Q)); - (void) sd_item; // dummy to suppress unused var warning - stan::math::initialize(sd_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_item,DUMMY_VAR__); - vector_d var_item(static_cast(Q)); - (void) var_item; // dummy to suppress unused var warning - stan::math::initialize(var_item, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_item,DUMMY_VAR__); - vector_d var_theta(static_cast(T)); - (void) var_theta; // dummy to suppress unused var warning - stan::math::initialize(var_theta, std::numeric_limits::quiet_NaN()); - stan::math::fill(var_theta,DUMMY_VAR__); - vector gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(gamma,DUMMY_VAR__); - vector mu_theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(mu_theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector mu_gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(mu_gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > z(T, (vector(Q, (vector_d(static_cast(G)))))); - stan::math::initialize(z, std::numeric_limits::quiet_NaN()); - stan::math::fill(z,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G, 0.0))))); - stan::math::initialize(prob, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob,DUMMY_VAR__); - - - try { - stan::math::assign(disc, multiply(disc_raw,pow(exp(sum(log(disc_raw))),-(inv(Q))))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(sd_item,q,"sd_item",1), inv(get_base1(disc,q,"disc",1))); - } - for (int d = 1; d <= D; ++d) { - - stan::math::assign(get_base1_lhs(diff,d,"diff",1), subtract(get_base1(diff_raw,d,"diff_raw",1),mean(get_base1(diff_raw,1,"diff_raw",1)))); - stan::math::assign(get_base1_lhs(kappa,d,"kappa",1), elt_divide(get_base1(diff,d,"diff",1),disc)); - } - stan::math::assign(var_item, elt_multiply(sd_item,sd_item)); - stan::math::assign(var_theta, elt_multiply(sd_theta,sd_theta)); - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - } else { - - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), ((get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2) * get_base1(delta_gamma,t,"delta_gamma",1)) + multiply(get_base1(get_base1(ZZ,t,"ZZ",1),p,"ZZ",2),get_base1(nu_geo,t,"nu_geo",1)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2)); - } - } - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - if (as_bool(logical_eq(hierarchical_model,1))) { - - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - } - if (as_bool(logical_eq(hierarchical_model,0))) { - - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1))); - } - for (int q = 1; q <= Q; ++q) { - { - double sd_tq(0.0); - (void) sd_tq; // dummy to suppress unused var warning - stan::math::initialize(sd_tq, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_tq,DUMMY_VAR__); - - - stan::math::assign(sd_tq, sqrt((get_base1(var_theta,t,"var_theta",1) + get_base1(var_item,q,"var_item",1)))); - if (as_bool(logical_eq(constant_item,0))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,t,"kappa",1),q,"kappa",2)),sd_tq)); - } - if (as_bool(logical_eq(constant_item,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), divide(subtract(get_base1(theta_bar,t,"theta_bar",1),get_base1(get_base1(kappa,1,"kappa",1),q,"kappa",2)),sd_tq)); - } - for (int g = 1; g <= G; ++g) { - - if (as_bool(logical_eq(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(theta_bar,t,"theta_bar",1),g,"theta_bar",2))); - } - if (as_bool(logical_gt(Q,1))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - check_greater_or_equal(function__,"disc",disc,0); - check_greater_or_equal(function__,"sd_item",sd_item,0); - check_greater_or_equal(function__,"var_item",var_item,0); - check_greater_or_equal(function__,"var_theta",var_theta,0); - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // write transformed parameters - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(diff[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < D; ++k_0__) { - vars__.push_back(kappa[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(disc[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(sd_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < Q; ++k_0__) { - vars__.push_back(var_item[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(var_theta[k_0__]); - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_gamma[k_0__][k_1__]); - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob[k_0__][k_1__][k_2__]); - } - } - } - - if (!include_gqs__) return; - // declare and define generated quantities - vector_d sd_total(static_cast(T)); - (void) sd_total; // dummy to suppress unused var warning - stan::math::initialize(sd_total, std::numeric_limits::quiet_NaN()); - stan::math::fill(sd_total,DUMMY_VAR__); - - - try { - for (int t = 1; t <= T; ++t) { - - stan::math::assign(get_base1_lhs(sd_total,t,"sd_total",1), sqrt((variance(get_base1(theta_bar,t,"theta_bar",1)) + square(get_base1(sd_theta,t,"sd_theta",1))))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate generated quantities - check_greater_or_equal(function__,"sd_total",sd_total,0); - - // write generated quantities - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_total[k_0__]); - } - - } - - template - void write_array(RNG& base_rng, - Eigen::Matrix& params_r, - Eigen::Matrix& vars, - bool include_tparams = true, - bool include_gqs = true, - std::ostream* pstream = 0) const { - std::vector params_r_vec(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r_vec[i] = params_r(i); - std::vector vars_vec; - std::vector params_i_vec; - write_array(base_rng,params_r_vec,params_i_vec,vars_vec,include_tparams,include_gqs,pstream); - vars.resize(vars_vec.size()); - for (int i = 0; i < vars.size(); ++i) - vars(i) = vars_vec[i]; - } - - static std::string model_name() { - return "model_2017_01_04"; - } - - - void constrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_geo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_demo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - - - void unconstrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc_raw" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_geo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_demo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "diff" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= D; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "kappa" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "disc" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= Q; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_item" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "var_theta" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - - if (!include_gqs__) return; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_total" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - } - -}; // model - -} // namespace - - - - -// Code generated by Stan version 2.14 - -#include - -namespace model_2017_01_04_singleissue_namespace { - -using std::istream; -using std::string; -using std::stringstream; -using std::vector; -using stan::io::dump; -using stan::math::lgamma; -using stan::model::prob_grad; -using namespace stan::math; - -typedef Eigen::Matrix vector_d; -typedef Eigen::Matrix row_vector_d; -typedef Eigen::Matrix matrix_d; - -static int current_statement_begin__; - -class model_2017_01_04_singleissue : public prob_grad { -private: - int G; - int G_hier; - int Q; - int T; - int N; - int N_observed; - int S; - int P; - int H; - int Hprior; - int D; - int constant_item; - int separate_t; - double delta_tbar_prior_mean; - double delta_tbar_prior_sd; - double innov_sd_delta_scale; - double innov_sd_theta_scale; - vector n_vec; - vector s_vec; - vector observed; - vector > > NNl2; - vector > > SSl2; - matrix_d XX; - vector WT; - vector ZZ; - vector ZZ_prior; - matrix_d l2_only; -public: - model_2017_01_04_singleissue(stan::io::var_context& context__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - typedef boost::ecuyer1988 rng_t; - rng_t base_rng(0); // 0 seed default - ctor_body(context__, base_rng, pstream__); - } - - template - model_2017_01_04_singleissue(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__ = 0) - : prob_grad(0) { - ctor_body(context__, base_rng__, pstream__); - } - - template - void ctor_body(stan::io::var_context& context__, - RNG& base_rng__, - std::ostream* pstream__) { - current_statement_begin__ = -1; - - static const char* function__ = "model_2017_01_04_singleissue_namespace::model_2017_01_04_singleissue"; - (void) function__; // dummy call to supress warning - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_i__; - std::vector vals_r__; - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - // initialize member variables - context__.validate_dims("data initialization", "G", "int", context__.to_vec()); - G = int(0); - vals_i__ = context__.vals_i("G"); - pos__ = 0; - G = vals_i__[pos__++]; - context__.validate_dims("data initialization", "G_hier", "int", context__.to_vec()); - G_hier = int(0); - vals_i__ = context__.vals_i("G_hier"); - pos__ = 0; - G_hier = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Q", "int", context__.to_vec()); - Q = int(0); - vals_i__ = context__.vals_i("Q"); - pos__ = 0; - Q = vals_i__[pos__++]; - context__.validate_dims("data initialization", "T", "int", context__.to_vec()); - T = int(0); - vals_i__ = context__.vals_i("T"); - pos__ = 0; - T = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N", "int", context__.to_vec()); - N = int(0); - vals_i__ = context__.vals_i("N"); - pos__ = 0; - N = vals_i__[pos__++]; - context__.validate_dims("data initialization", "N_observed", "int", context__.to_vec()); - N_observed = int(0); - vals_i__ = context__.vals_i("N_observed"); - pos__ = 0; - N_observed = vals_i__[pos__++]; - context__.validate_dims("data initialization", "S", "int", context__.to_vec()); - S = int(0); - vals_i__ = context__.vals_i("S"); - pos__ = 0; - S = vals_i__[pos__++]; - context__.validate_dims("data initialization", "P", "int", context__.to_vec()); - P = int(0); - vals_i__ = context__.vals_i("P"); - pos__ = 0; - P = vals_i__[pos__++]; - context__.validate_dims("data initialization", "H", "int", context__.to_vec()); - H = int(0); - vals_i__ = context__.vals_i("H"); - pos__ = 0; - H = vals_i__[pos__++]; - context__.validate_dims("data initialization", "Hprior", "int", context__.to_vec()); - Hprior = int(0); - vals_i__ = context__.vals_i("Hprior"); - pos__ = 0; - Hprior = vals_i__[pos__++]; - context__.validate_dims("data initialization", "D", "int", context__.to_vec()); - D = int(0); - vals_i__ = context__.vals_i("D"); - pos__ = 0; - D = vals_i__[pos__++]; - context__.validate_dims("data initialization", "constant_item", "int", context__.to_vec()); - constant_item = int(0); - vals_i__ = context__.vals_i("constant_item"); - pos__ = 0; - constant_item = vals_i__[pos__++]; - context__.validate_dims("data initialization", "separate_t", "int", context__.to_vec()); - separate_t = int(0); - vals_i__ = context__.vals_i("separate_t"); - pos__ = 0; - separate_t = vals_i__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_mean", "double", context__.to_vec()); - delta_tbar_prior_mean = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_mean"); - pos__ = 0; - delta_tbar_prior_mean = vals_r__[pos__++]; - context__.validate_dims("data initialization", "delta_tbar_prior_sd", "double", context__.to_vec()); - delta_tbar_prior_sd = double(0); - vals_r__ = context__.vals_r("delta_tbar_prior_sd"); - pos__ = 0; - delta_tbar_prior_sd = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_delta_scale", "double", context__.to_vec()); - innov_sd_delta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_delta_scale"); - pos__ = 0; - innov_sd_delta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "innov_sd_theta_scale", "double", context__.to_vec()); - innov_sd_theta_scale = double(0); - vals_r__ = context__.vals_r("innov_sd_theta_scale"); - pos__ = 0; - innov_sd_theta_scale = vals_r__[pos__++]; - context__.validate_dims("data initialization", "n_vec", "int", context__.to_vec(N)); - validate_non_negative_index("n_vec", "N", N); - n_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("n_vec"); - pos__ = 0; - size_t n_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < n_vec_limit_0__; ++i_0__) { - n_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "s_vec", "int", context__.to_vec(N)); - validate_non_negative_index("s_vec", "N", N); - s_vec = std::vector(N,int(0)); - vals_i__ = context__.vals_i("s_vec"); - pos__ = 0; - size_t s_vec_limit_0__ = N; - for (size_t i_0__ = 0; i_0__ < s_vec_limit_0__; ++i_0__) { - s_vec[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "observed", "int", context__.to_vec(N_observed)); - validate_non_negative_index("observed", "N_observed", N_observed); - observed = std::vector(N_observed,int(0)); - vals_i__ = context__.vals_i("observed"); - pos__ = 0; - size_t observed_limit_0__ = N_observed; - for (size_t i_0__ = 0; i_0__ < observed_limit_0__; ++i_0__) { - observed[i_0__] = vals_i__[pos__++]; - } - context__.validate_dims("data initialization", "NNl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("NNl2", "T", T); - validate_non_negative_index("NNl2", "Q", Q); - validate_non_negative_index("NNl2", "G_hier", G_hier); - NNl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("NNl2"); - pos__ = 0; - size_t NNl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < NNl2_limit_2__; ++i_2__) { - size_t NNl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < NNl2_limit_1__; ++i_1__) { - size_t NNl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < NNl2_limit_0__; ++i_0__) { - NNl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "SSl2", "int", context__.to_vec(T,Q,G_hier)); - validate_non_negative_index("SSl2", "T", T); - validate_non_negative_index("SSl2", "Q", Q); - validate_non_negative_index("SSl2", "G_hier", G_hier); - SSl2 = std::vector > >(T,std::vector >(Q,std::vector(G_hier,int(0)))); - vals_i__ = context__.vals_i("SSl2"); - pos__ = 0; - size_t SSl2_limit_2__ = G_hier; - for (size_t i_2__ = 0; i_2__ < SSl2_limit_2__; ++i_2__) { - size_t SSl2_limit_1__ = Q; - for (size_t i_1__ = 0; i_1__ < SSl2_limit_1__; ++i_1__) { - size_t SSl2_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < SSl2_limit_0__; ++i_0__) { - SSl2[i_0__][i_1__][i_2__] = vals_i__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "XX", "matrix_d", context__.to_vec(G,P)); - validate_non_negative_index("XX", "G", G); - validate_non_negative_index("XX", "P", P); - XX = matrix_d(static_cast(G),static_cast(P)); - vals_r__ = context__.vals_r("XX"); - pos__ = 0; - size_t XX_m_mat_lim__ = G; - size_t XX_n_mat_lim__ = P; - for (size_t n_mat__ = 0; n_mat__ < XX_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < XX_m_mat_lim__; ++m_mat__) { - XX(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - context__.validate_dims("data initialization", "WT", "matrix_d", context__.to_vec(T,G_hier,G)); - validate_non_negative_index("WT", "T", T); - validate_non_negative_index("WT", "G_hier", G_hier); - validate_non_negative_index("WT", "G", G); - WT = std::vector(T,matrix_d(static_cast(G_hier),static_cast(G))); - vals_r__ = context__.vals_r("WT"); - pos__ = 0; - size_t WT_m_mat_lim__ = G_hier; - size_t WT_n_mat_lim__ = G; - for (size_t n_mat__ = 0; n_mat__ < WT_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < WT_m_mat_lim__; ++m_mat__) { - size_t WT_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < WT_limit_0__; ++i_0__) { - WT[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ", "matrix_d", context__.to_vec(T,P,H)); - validate_non_negative_index("ZZ", "T", T); - validate_non_negative_index("ZZ", "P", P); - validate_non_negative_index("ZZ", "H", H); - ZZ = std::vector(T,matrix_d(static_cast(P),static_cast(H))); - vals_r__ = context__.vals_r("ZZ"); - pos__ = 0; - size_t ZZ_m_mat_lim__ = P; - size_t ZZ_n_mat_lim__ = H; - for (size_t n_mat__ = 0; n_mat__ < ZZ_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_m_mat_lim__; ++m_mat__) { - size_t ZZ_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_limit_0__; ++i_0__) { - ZZ[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "ZZ_prior", "matrix_d", context__.to_vec(T,P,Hprior)); - validate_non_negative_index("ZZ_prior", "T", T); - validate_non_negative_index("ZZ_prior", "P", P); - validate_non_negative_index("ZZ_prior", "Hprior", Hprior); - ZZ_prior = std::vector(T,matrix_d(static_cast(P),static_cast(Hprior))); - vals_r__ = context__.vals_r("ZZ_prior"); - pos__ = 0; - size_t ZZ_prior_m_mat_lim__ = P; - size_t ZZ_prior_n_mat_lim__ = Hprior; - for (size_t n_mat__ = 0; n_mat__ < ZZ_prior_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < ZZ_prior_m_mat_lim__; ++m_mat__) { - size_t ZZ_prior_limit_0__ = T; - for (size_t i_0__ = 0; i_0__ < ZZ_prior_limit_0__; ++i_0__) { - ZZ_prior[i_0__](m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - } - context__.validate_dims("data initialization", "l2_only", "matrix_d", context__.to_vec(T,Q)); - validate_non_negative_index("l2_only", "T", T); - validate_non_negative_index("l2_only", "Q", Q); - l2_only = matrix_d(static_cast(T),static_cast(Q)); - vals_r__ = context__.vals_r("l2_only"); - pos__ = 0; - size_t l2_only_m_mat_lim__ = T; - size_t l2_only_n_mat_lim__ = Q; - for (size_t n_mat__ = 0; n_mat__ < l2_only_n_mat_lim__; ++n_mat__) { - for (size_t m_mat__ = 0; m_mat__ < l2_only_m_mat_lim__; ++m_mat__) { - l2_only(m_mat__,n_mat__) = vals_r__[pos__++]; - } - } - - // validate, data variables - check_greater_or_equal(function__,"G",G,1); - check_greater_or_equal(function__,"G_hier",G_hier,1); - check_greater_or_equal(function__,"Q",Q,1); - check_greater_or_equal(function__,"T",T,1); - check_greater_or_equal(function__,"N",N,1); - check_greater_or_equal(function__,"N_observed",N_observed,1); - check_greater_or_equal(function__,"S",S,1); - check_greater_or_equal(function__,"P",P,1); - check_greater_or_equal(function__,"H",H,1); - check_greater_or_equal(function__,"Hprior",Hprior,1); - check_greater_or_equal(function__,"D",D,1); - check_greater_or_equal(function__,"constant_item",constant_item,0); - check_less_or_equal(function__,"constant_item",constant_item,1); - check_greater_or_equal(function__,"separate_t",separate_t,0); - check_less_or_equal(function__,"separate_t",separate_t,1); - check_greater_or_equal(function__,"delta_tbar_prior_sd",delta_tbar_prior_sd,0); - check_greater_or_equal(function__,"innov_sd_delta_scale",innov_sd_delta_scale,0); - check_greater_or_equal(function__,"innov_sd_theta_scale",innov_sd_theta_scale,0); - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"n_vec[k0__]",n_vec[k0__],0); - } - for (int k0__ = 0; k0__ < N; ++k0__) { - check_greater_or_equal(function__,"s_vec[k0__]",s_vec[k0__],0); - } - check_greater_or_equal(function__,"XX",XX,0); - check_less_or_equal(function__,"XX",XX,1); - for (int k0__ = 0; k0__ < T; ++k0__) { - check_greater_or_equal(function__,"WT[k0__]",WT[k0__],0); - check_less_or_equal(function__,"WT[k0__]",WT[k0__],1); - } - check_greater_or_equal(function__,"l2_only",l2_only,0); - check_less_or_equal(function__,"l2_only",l2_only,1); - // initialize data variables - - try { - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed data - - // set parameter ranges - num_params_r__ = 0U; - param_ranges_i__.clear(); - num_params_r__ += T; - num_params_r__ += P * T; - num_params_r__ += T; - num_params_r__ += H * T; - num_params_r__ += Hprior; - num_params_r__ += T; - num_params_r__ += G * T; - num_params_r__ += T; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - ++num_params_r__; - } - - ~model_2017_01_04_singleissue() { } - - - void transform_inits(const stan::io::var_context& context__, - std::vector& params_i__, - std::vector& params_r__, - std::ostream* pstream__) const { - stan::io::writer writer__(params_r__,params_i__); - size_t pos__; - (void) pos__; // dummy call to supress warning - std::vector vals_r__; - std::vector vals_i__; - - if (!(context__.contains_r("xi"))) - throw std::runtime_error("variable xi missing"); - vals_r__ = context__.vals_r("xi"); - pos__ = 0U; - context__.validate_dims("initialization", "xi", "vector_d", context__.to_vec(T)); - // generate_declaration xi - vector_d xi(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - xi(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(xi); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable xi: ") + e.what()); - } - - if (!(context__.contains_r("gamma_raw"))) - throw std::runtime_error("variable gamma_raw missing"); - vals_r__ = context__.vals_r("gamma_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "gamma_raw", "vector_d", context__.to_vec(T,P)); - // generate_declaration gamma_raw - std::vector gamma_raw(T,vector_d(static_cast(P))); - for (int j1__ = 0U; j1__ < P; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - gamma_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(gamma_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable gamma_raw: ") + e.what()); - } - - if (!(context__.contains_r("delta_gamma"))) - throw std::runtime_error("variable delta_gamma missing"); - vals_r__ = context__.vals_r("delta_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_gamma", "vector_d", context__.to_vec(T)); - // generate_declaration delta_gamma - vector_d delta_gamma(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_gamma(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_gamma: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo"))) - throw std::runtime_error("variable nu_geo missing"); - vals_r__ = context__.vals_r("nu_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo", "vector_d", context__.to_vec(T,H)); - // generate_declaration nu_geo - std::vector nu_geo(T,vector_d(static_cast(H))); - for (int j1__ = 0U; j1__ < H; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - nu_geo[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(nu_geo[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo: ") + e.what()); - } - - if (!(context__.contains_r("nu_geo_prior"))) - throw std::runtime_error("variable nu_geo_prior missing"); - vals_r__ = context__.vals_r("nu_geo_prior"); - pos__ = 0U; - context__.validate_dims("initialization", "nu_geo_prior", "vector_d", context__.to_vec(Hprior)); - // generate_declaration nu_geo_prior - vector_d nu_geo_prior(static_cast(Hprior)); - for (int j1__ = 0U; j1__ < Hprior; ++j1__) - nu_geo_prior(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(nu_geo_prior); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable nu_geo_prior: ") + e.what()); - } - - if (!(context__.contains_r("delta_tbar"))) - throw std::runtime_error("variable delta_tbar missing"); - vals_r__ = context__.vals_r("delta_tbar"); - pos__ = 0U; - context__.validate_dims("initialization", "delta_tbar", "vector_d", context__.to_vec(T)); - // generate_declaration delta_tbar - vector_d delta_tbar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - delta_tbar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_unconstrain(delta_tbar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable delta_tbar: ") + e.what()); - } - - if (!(context__.contains_r("theta_bar_raw"))) - throw std::runtime_error("variable theta_bar_raw missing"); - vals_r__ = context__.vals_r("theta_bar_raw"); - pos__ = 0U; - context__.validate_dims("initialization", "theta_bar_raw", "vector_d", context__.to_vec(T,G)); - // generate_declaration theta_bar_raw - std::vector theta_bar_raw(T,vector_d(static_cast(G))); - for (int j1__ = 0U; j1__ < G; ++j1__) - for (int i0__ = 0U; i0__ < T; ++i0__) - theta_bar_raw[i0__](j1__) = vals_r__[pos__++]; - for (int i0__ = 0U; i0__ < T; ++i0__) - try { - writer__.vector_unconstrain(theta_bar_raw[i0__]); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable theta_bar_raw: ") + e.what()); - } - - if (!(context__.contains_r("sd_theta_bar"))) - throw std::runtime_error("variable sd_theta_bar missing"); - vals_r__ = context__.vals_r("sd_theta_bar"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_theta_bar", "vector_d", context__.to_vec(T)); - // generate_declaration sd_theta_bar - vector_d sd_theta_bar(static_cast(T)); - for (int j1__ = 0U; j1__ < T; ++j1__) - sd_theta_bar(j1__) = vals_r__[pos__++]; - try { - writer__.vector_lb_unconstrain(0,sd_theta_bar); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_theta_bar: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma_geo"))) - throw std::runtime_error("variable sd_gamma_geo missing"); - vals_r__ = context__.vals_r("sd_gamma_geo"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma_geo", "double", context__.to_vec()); - // generate_declaration sd_gamma_geo - double sd_gamma_geo(0); - sd_gamma_geo = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma_geo); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma_geo: ") + e.what()); - } - - if (!(context__.contains_r("sd_gamma_demo"))) - throw std::runtime_error("variable sd_gamma_demo missing"); - vals_r__ = context__.vals_r("sd_gamma_demo"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_gamma_demo", "double", context__.to_vec()); - // generate_declaration sd_gamma_demo - double sd_gamma_demo(0); - sd_gamma_demo = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_gamma_demo); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_gamma_demo: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_delta"))) - throw std::runtime_error("variable sd_innov_delta missing"); - vals_r__ = context__.vals_r("sd_innov_delta"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_delta", "double", context__.to_vec()); - // generate_declaration sd_innov_delta - double sd_innov_delta(0); - sd_innov_delta = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_delta); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_delta: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_logsd"))) - throw std::runtime_error("variable sd_innov_logsd missing"); - vals_r__ = context__.vals_r("sd_innov_logsd"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_logsd", "double", context__.to_vec()); - // generate_declaration sd_innov_logsd - double sd_innov_logsd(0); - sd_innov_logsd = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_logsd); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_logsd: ") + e.what()); - } - - if (!(context__.contains_r("sd_innov_gamma"))) - throw std::runtime_error("variable sd_innov_gamma missing"); - vals_r__ = context__.vals_r("sd_innov_gamma"); - pos__ = 0U; - context__.validate_dims("initialization", "sd_innov_gamma", "double", context__.to_vec()); - // generate_declaration sd_innov_gamma - double sd_innov_gamma(0); - sd_innov_gamma = vals_r__[pos__++]; - try { - writer__.scalar_lb_unconstrain(0,sd_innov_gamma); - } catch (const std::exception& e) { - throw std::runtime_error(std::string("Error transforming variable sd_innov_gamma: ") + e.what()); - } - - params_r__ = writer__.data_r(); - params_i__ = writer__.data_i(); - } - - void transform_inits(const stan::io::var_context& context, - Eigen::Matrix& params_r, - std::ostream* pstream__) const { - std::vector params_r_vec; - std::vector params_i_vec; - transform_inits(context, params_i_vec, params_r_vec, pstream__); - params_r.resize(params_r_vec.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r(i) = params_r_vec[i]; - } - - - template - T__ log_prob(vector& params_r__, - vector& params_i__, - std::ostream* pstream__ = 0) const { - - T__ DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - T__ lp__(0.0); - stan::math::accumulator lp_accum__; - - // model parameters - stan::io::reader in__(params_r__,params_i__); - - Eigen::Matrix xi; - (void) xi; // dummy to suppress unused var warning - if (jacobian__) - xi = in__.vector_constrain(T,lp__); - else - xi = in__.vector_constrain(T); - - vector > gamma_raw; - size_t dim_gamma_raw_0__ = T; - gamma_raw.reserve(dim_gamma_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - if (jacobian__) - gamma_raw.push_back(in__.vector_constrain(P,lp__)); - else - gamma_raw.push_back(in__.vector_constrain(P)); - } - - Eigen::Matrix delta_gamma; - (void) delta_gamma; // dummy to suppress unused var warning - if (jacobian__) - delta_gamma = in__.vector_constrain(T,lp__); - else - delta_gamma = in__.vector_constrain(T); - - vector > nu_geo; - size_t dim_nu_geo_0__ = T; - nu_geo.reserve(dim_nu_geo_0__); - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - if (jacobian__) - nu_geo.push_back(in__.vector_constrain(H,lp__)); - else - nu_geo.push_back(in__.vector_constrain(H)); - } - - Eigen::Matrix nu_geo_prior; - (void) nu_geo_prior; // dummy to suppress unused var warning - if (jacobian__) - nu_geo_prior = in__.vector_constrain(Hprior,lp__); - else - nu_geo_prior = in__.vector_constrain(Hprior); - - Eigen::Matrix delta_tbar; - (void) delta_tbar; // dummy to suppress unused var warning - if (jacobian__) - delta_tbar = in__.vector_constrain(T,lp__); - else - delta_tbar = in__.vector_constrain(T); - - vector > theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - theta_bar_raw.reserve(dim_theta_bar_raw_0__); - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - if (jacobian__) - theta_bar_raw.push_back(in__.vector_constrain(G,lp__)); - else - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - - Eigen::Matrix sd_theta_bar; - (void) sd_theta_bar; // dummy to suppress unused var warning - if (jacobian__) - sd_theta_bar = in__.vector_lb_constrain(0,T,lp__); - else - sd_theta_bar = in__.vector_lb_constrain(0,T); - - T__ sd_gamma_geo; - (void) sd_gamma_geo; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma_geo = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma_geo = in__.scalar_lb_constrain(0); - - T__ sd_gamma_demo; - (void) sd_gamma_demo; // dummy to suppress unused var warning - if (jacobian__) - sd_gamma_demo = in__.scalar_lb_constrain(0,lp__); - else - sd_gamma_demo = in__.scalar_lb_constrain(0); - - T__ sd_innov_delta; - (void) sd_innov_delta; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_delta = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_delta = in__.scalar_lb_constrain(0); - - T__ sd_innov_logsd; - (void) sd_innov_logsd; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_logsd = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_logsd = in__.scalar_lb_constrain(0); - - T__ sd_innov_gamma; - (void) sd_innov_gamma; // dummy to suppress unused var warning - if (jacobian__) - sd_innov_gamma = in__.scalar_lb_constrain(0,lp__); - else - sd_innov_gamma = in__.scalar_lb_constrain(0); - - - // transformed parameters - vector > theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(theta_bar, DUMMY_VAR__); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector > gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(gamma, DUMMY_VAR__); - stan::math::fill(gamma,DUMMY_VAR__); - vector > mu_theta_bar(T, (Eigen::Matrix (static_cast(G)))); - stan::math::initialize(mu_theta_bar, DUMMY_VAR__); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector > mu_gamma(T, (Eigen::Matrix (static_cast(P)))); - stan::math::initialize(mu_gamma, DUMMY_VAR__); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > > z(T, (vector >(Q, (Eigen::Matrix (static_cast(G)))))); - stan::math::initialize(z, DUMMY_VAR__); - stan::math::fill(z,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G))))); - stan::math::initialize(prob, DUMMY_VAR__); - stan::math::fill(prob,DUMMY_VAR__); - - - try { - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - } else { - - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), ((get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2) * get_base1(delta_gamma,t,"delta_gamma",1)) + multiply(get_base1(get_base1(ZZ,t,"ZZ",1),p,"ZZ",2),get_base1(nu_geo,t,"nu_geo",1)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2)); - } - } - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), get_base1(theta_bar,t,"theta_bar",1)); - for (int g = 1; g <= G; ++g) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < G; ++i1__) { - if (stan::math::is_uninitialized(mu_theta_bar[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_theta_bar" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < P; ++i1__) { - if (stan::math::is_uninitialized(mu_gamma[i0__](i1__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: mu_gamma" << '[' << i0__ << ']' << '[' << i1__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(z[i0__][i1__](i2__))) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: z" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - for (int i0__ = 0; i0__ < T; ++i0__) { - for (int i1__ = 0; i1__ < Q; ++i1__) { - for (int i2__ = 0; i2__ < G; ++i2__) { - if (stan::math::is_uninitialized(prob[i0__][i1__][i2__])) { - std::stringstream msg__; - msg__ << "Undefined transformed parameter: prob" << '[' << i0__ << ']' << '[' << i1__ << ']' << '[' << i2__ << ']'; - throw std::runtime_error(msg__.str()); - } - } - } - } - - const char* function__ = "validate transformed params"; - (void) function__; // dummy to suppress unused var warning - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // model body - try { - { - vector prob_vec(N); - stan::math::initialize(prob_vec, DUMMY_VAR__); - stan::math::fill(prob_vec,DUMMY_VAR__); - int pos(0); - (void) pos; // dummy to suppress unused var warning - stan::math::fill(pos, std::numeric_limits::min()); - - - stan::math::assign(pos, 0); - lp_accum__.add(cauchy_log(sd_gamma_geo, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_gamma_demo, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_delta, 0, innov_sd_delta_scale)); - lp_accum__.add(cauchy_log(sd_innov_gamma, 0, 2.5)); - lp_accum__.add(cauchy_log(sd_innov_logsd, 0, innov_sd_theta_scale)); - for (int t = 1; t <= T; ++t) { - - lp_accum__.add(normal_log(get_base1(gamma_raw,t,"gamma_raw",1), 0, 1)); - lp_accum__.add(normal_log(get_base1(theta_bar_raw,t,"theta_bar_raw",1), 0, 1)); - if (as_bool(logical_eq(t,1))) { - - lp_accum__.add(cauchy_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), 0, 2.5)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), 0, 1)); - lp_accum__.add(normal_log(nu_geo_prior, 0, 1)); - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), 0.5, 0.5)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), delta_tbar_prior_mean, delta_tbar_prior_sd)); - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 1)); - } - if (as_bool(logical_gt(t,1))) { - - lp_accum__.add(normal_log(get_base1(delta_gamma,t,"delta_gamma",1), get_base1(delta_gamma,(t - 1),"delta_gamma",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(nu_geo,t,"nu_geo",1), get_base1(nu_geo,(t - 1),"nu_geo",1), sd_innov_delta)); - lp_accum__.add(normal_log(get_base1(delta_tbar,t,"delta_tbar",1), get_base1(delta_tbar,(t - 1),"delta_tbar",1), sd_innov_delta)); - lp_accum__.add(lognormal_log(get_base1(sd_theta_bar,t,"sd_theta_bar",1), log(get_base1(sd_theta_bar,(t - 1),"sd_theta_bar",1)), sd_innov_logsd)); - if (as_bool((primitive_value(logical_eq(separate_t,0)) && primitive_value(logical_gt(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), get_base1(xi,(t - 1),"xi",1), sd_innov_gamma)); - } - if (as_bool((primitive_value(logical_eq(separate_t,1)) || primitive_value(logical_eq(t,2))))) { - - lp_accum__.add(normal_log(get_base1(xi,t,"xi",1), 0, 10)); - } - } - for (int q = 1; q <= Q; ++q) { - - for (int g = 1; g <= G; ++g) { - - stan::math::assign(pos, (pos + 1)); - stan::math::assign(get_base1_lhs(prob_vec,pos,"prob_vec",1), get_base1(get_base1(get_base1(prob,t,"prob",1),q,"prob",2),g,"prob",3)); - } - } - } - lp_accum__.add(binomial_log(stan::model::rvalue(s_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "s_vec"), stan::model::rvalue(n_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "n_vec"), stan::model::rvalue(prob_vec, stan::model::cons_list(stan::model::index_multi(observed), stan::model::nil_index_list()), "prob_vec"))); - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - lp_accum__.add(lp__); - return lp_accum__.sum(); - - } // log_prob() - - template - T_ log_prob(Eigen::Matrix& params_r, - std::ostream* pstream = 0) const { - std::vector vec_params_r; - vec_params_r.reserve(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - vec_params_r.push_back(params_r(i)); - std::vector vec_params_i; - return log_prob(vec_params_r, vec_params_i, pstream); - } - - - void get_param_names(std::vector& names__) const { - names__.resize(0); - names__.push_back("xi"); - names__.push_back("gamma_raw"); - names__.push_back("delta_gamma"); - names__.push_back("nu_geo"); - names__.push_back("nu_geo_prior"); - names__.push_back("delta_tbar"); - names__.push_back("theta_bar_raw"); - names__.push_back("sd_theta_bar"); - names__.push_back("sd_gamma_geo"); - names__.push_back("sd_gamma_demo"); - names__.push_back("sd_innov_delta"); - names__.push_back("sd_innov_logsd"); - names__.push_back("sd_innov_gamma"); - names__.push_back("theta_bar"); - names__.push_back("gamma"); - names__.push_back("mu_theta_bar"); - names__.push_back("mu_gamma"); - names__.push_back("z"); - names__.push_back("prob"); - } - - - void get_dims(std::vector >& dimss__) const { - dimss__.resize(0); - std::vector dims__; - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(H); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(Hprior); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(P); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - dims__.resize(0); - dims__.push_back(T); - dims__.push_back(Q); - dims__.push_back(G); - dimss__.push_back(dims__); - } - - template - void write_array(RNG& base_rng__, - std::vector& params_r__, - std::vector& params_i__, - std::vector& vars__, - bool include_tparams__ = true, - bool include_gqs__ = true, - std::ostream* pstream__ = 0) const { - vars__.resize(0); - stan::io::reader in__(params_r__,params_i__); - static const char* function__ = "model_2017_01_04_singleissue_namespace::write_array"; - (void) function__; // dummy call to supress warning - // read-transform, write parameters - vector_d xi = in__.vector_constrain(T); - vector gamma_raw; - size_t dim_gamma_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_gamma_raw_0__; ++k_0__) { - gamma_raw.push_back(in__.vector_constrain(P)); - } - vector_d delta_gamma = in__.vector_constrain(T); - vector nu_geo; - size_t dim_nu_geo_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_nu_geo_0__; ++k_0__) { - nu_geo.push_back(in__.vector_constrain(H)); - } - vector_d nu_geo_prior = in__.vector_constrain(Hprior); - vector_d delta_tbar = in__.vector_constrain(T); - vector theta_bar_raw; - size_t dim_theta_bar_raw_0__ = T; - for (size_t k_0__ = 0; k_0__ < dim_theta_bar_raw_0__; ++k_0__) { - theta_bar_raw.push_back(in__.vector_constrain(G)); - } - vector_d sd_theta_bar = in__.vector_lb_constrain(0,T); - double sd_gamma_geo = in__.scalar_lb_constrain(0); - double sd_gamma_demo = in__.scalar_lb_constrain(0); - double sd_innov_delta = in__.scalar_lb_constrain(0); - double sd_innov_logsd = in__.scalar_lb_constrain(0); - double sd_innov_gamma = in__.scalar_lb_constrain(0); - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(xi[k_0__]); - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_gamma[k_0__]); - } - for (int k_1__ = 0; k_1__ < H; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(nu_geo[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < Hprior; ++k_0__) { - vars__.push_back(nu_geo_prior[k_0__]); - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(delta_tbar[k_0__]); - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar_raw[k_0__][k_1__]); - } - } - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(sd_theta_bar[k_0__]); - } - vars__.push_back(sd_gamma_geo); - vars__.push_back(sd_gamma_demo); - vars__.push_back(sd_innov_delta); - vars__.push_back(sd_innov_logsd); - vars__.push_back(sd_innov_gamma); - - if (!include_tparams__) return; - // declare and define transformed parameters - double lp__ = 0.0; - (void) lp__; // dummy call to supress warning - stan::math::accumulator lp_accum__; - - double DUMMY_VAR__(std::numeric_limits::quiet_NaN()); - (void) DUMMY_VAR__; // suppress unused var warning - - vector theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(theta_bar,DUMMY_VAR__); - vector gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(gamma,DUMMY_VAR__); - vector mu_theta_bar(T, (vector_d(static_cast(G)))); - stan::math::initialize(mu_theta_bar, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_theta_bar,DUMMY_VAR__); - vector mu_gamma(T, (vector_d(static_cast(P)))); - stan::math::initialize(mu_gamma, std::numeric_limits::quiet_NaN()); - stan::math::fill(mu_gamma,DUMMY_VAR__); - vector > z(T, (vector(Q, (vector_d(static_cast(G)))))); - stan::math::initialize(z, std::numeric_limits::quiet_NaN()); - stan::math::fill(z,DUMMY_VAR__); - vector > > prob(T, (vector >(Q, (vector(G, 0.0))))); - stan::math::initialize(prob, std::numeric_limits::quiet_NaN()); - stan::math::fill(prob,DUMMY_VAR__); - - - try { - for (int t = 1; t <= T; ++t) { - - if (as_bool((primitive_value(logical_eq(t,1)) || primitive_value(logical_eq(separate_t,1))))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1)))); - } - if (as_bool((primitive_value(logical_gt(t,1)) && primitive_value(logical_eq(separate_t,0))))) { - - if (as_bool(logical_eq(t,2))) { - - stan::math::assign(get_base1_lhs(mu_gamma,t,"mu_gamma",1), multiply(get_base1(ZZ_prior,t,"ZZ_prior",1),nu_geo_prior)); - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_geo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(gamma,t,"gamma",1),p,"gamma",2), (get_base1(get_base1(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2) + (sd_gamma_demo * get_base1(get_base1(gamma_raw,t,"gamma_raw",1),p,"gamma_raw",2)))); - } - } - } else { - - for (int p = 1; p <= P; ++p) { - - if (as_bool(logical_lte(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), ((get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2) * get_base1(delta_gamma,t,"delta_gamma",1)) + multiply(get_base1(get_base1(ZZ,t,"ZZ",1),p,"ZZ",2),get_base1(nu_geo,t,"nu_geo",1)))); - } - if (as_bool(logical_gt(p,S))) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(mu_gamma,t,"mu_gamma",1),p,"mu_gamma",2), get_base1(get_base1(gamma,(t - 1),"gamma",1),p,"gamma",2)); - } - } - stan::math::assign(get_base1_lhs(gamma,t,"gamma",1), add(get_base1(mu_gamma,t,"mu_gamma",1),multiply(sd_innov_gamma,get_base1(gamma_raw,t,"gamma_raw",1)))); - } - stan::math::assign(get_base1_lhs(mu_theta_bar,t,"mu_theta_bar",1), add(add(get_base1(xi,t,"xi",1),multiply(XX,get_base1(gamma,t,"gamma",1))),multiply(get_base1(theta_bar,(t - 1),"theta_bar",1),get_base1(delta_tbar,t,"delta_tbar",1)))); - } - stan::math::assign(get_base1_lhs(theta_bar,t,"theta_bar",1), add(get_base1(mu_theta_bar,t,"mu_theta_bar",1),multiply(get_base1(sd_theta_bar,t,"sd_theta_bar",1),get_base1(theta_bar_raw,t,"theta_bar_raw",1)))); - for (int q = 1; q <= Q; ++q) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(z,t,"z",1),q,"z",2), get_base1(theta_bar,t,"theta_bar",1)); - for (int g = 1; g <= G; ++g) { - - stan::math::assign(get_base1_lhs(get_base1_lhs(get_base1_lhs(prob,t,"prob",1),q,"prob",2),g,"prob",3), Phi_approx(get_base1(get_base1(get_base1(z,t,"z",1),q,"z",2),g,"z",3))); - } - } - } - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate transformed parameters - for (int k0__ = 0; k0__ < T; ++k0__) { - for (int k1__ = 0; k1__ < Q; ++k1__) { - for (int k2__ = 0; k2__ < G; ++k2__) { - check_greater_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],0); - check_less_or_equal(function__,"prob[k0__][k1__][k2__]",prob[k0__][k1__][k2__],1); - } - } - } - - // write transformed parameters - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(gamma[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < G; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_theta_bar[k_0__][k_1__]); - } - } - for (int k_1__ = 0; k_1__ < P; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(mu_gamma[k_0__][k_1__]); - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(z[k_0__][k_1__][k_2__]); - } - } - } - for (int k_2__ = 0; k_2__ < G; ++k_2__) { - for (int k_1__ = 0; k_1__ < Q; ++k_1__) { - for (int k_0__ = 0; k_0__ < T; ++k_0__) { - vars__.push_back(prob[k_0__][k_1__][k_2__]); - } - } - } - - if (!include_gqs__) return; - // declare and define generated quantities - - - try { - } catch (const std::exception& e) { - stan::lang::rethrow_located(e,current_statement_begin__); - // Next line prevents compiler griping about no return - throw std::runtime_error("*** IF YOU SEE THIS, PLEASE REPORT A BUG ***"); - } - - // validate generated quantities - - // write generated quantities - } - - template - void write_array(RNG& base_rng, - Eigen::Matrix& params_r, - Eigen::Matrix& vars, - bool include_tparams = true, - bool include_gqs = true, - std::ostream* pstream = 0) const { - std::vector params_r_vec(params_r.size()); - for (int i = 0; i < params_r.size(); ++i) - params_r_vec[i] = params_r(i); - std::vector vars_vec; - std::vector params_i_vec; - write_array(base_rng,params_r_vec,params_i_vec,vars_vec,include_tparams,include_gqs,pstream); - vars.resize(vars_vec.size()); - for (int i = 0; i < vars.size(); ++i) - vars(i) = vars_vec[i]; - } - - static std::string model_name() { - return "model_2017_01_04_singleissue"; - } - - - void constrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_geo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_demo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - - if (!include_gqs__) return; - } - - - void unconstrained_param_names(std::vector& param_names__, - bool include_tparams__ = true, - bool include_gqs__ = true) const { - std::stringstream param_name_stream__; - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "xi" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_gamma" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= H; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= Hprior; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "nu_geo_prior" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "delta_tbar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar_raw" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_theta_bar" << '.' << k_0__; - param_names__.push_back(param_name_stream__.str()); - } - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_geo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_gamma_demo"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_delta"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_logsd"; - param_names__.push_back(param_name_stream__.str()); - param_name_stream__.str(std::string()); - param_name_stream__ << "sd_innov_gamma"; - param_names__.push_back(param_name_stream__.str()); - - if (!include_gqs__ && !include_tparams__) return; - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= G; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_theta_bar" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_1__ = 1; k_1__ <= P; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "mu_gamma" << '.' << k_0__ << '.' << k_1__; - param_names__.push_back(param_name_stream__.str()); - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "z" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - for (int k_2__ = 1; k_2__ <= G; ++k_2__) { - for (int k_1__ = 1; k_1__ <= Q; ++k_1__) { - for (int k_0__ = 1; k_0__ <= T; ++k_0__) { - param_name_stream__.str(std::string()); - param_name_stream__ << "prob" << '.' << k_0__ << '.' << k_1__ << '.' << k_2__; - param_names__.push_back(param_name_stream__.str()); - } - } - } - - if (!include_gqs__) return; - } - -}; // model - -} // namespace - - - - -#endif diff --git a/tests/testthat.R b/tests/testthat.R new file mode 100644 index 0000000..3d96e77 --- /dev/null +++ b/tests/testthat.R @@ -0,0 +1,6 @@ +library(testthat) +library(dgo) + +# https://stackoverflow.com/questions/12410694/rbundler-build-error-cannot-open-file-startup-rs-no-such-file-or-directory#27994299 +Sys.setenv("R_TESTS" = "") +test_check("dgo") diff --git a/tests/testthat.r b/tests/testthat.r deleted file mode 100644 index f89bd30..0000000 --- a/tests/testthat.r +++ /dev/null @@ -1,4 +0,0 @@ -library(testthat) -library(dgo) - -test_check("dgo") diff --git a/tests/testthat/d_agg_n_vec.Rds b/tests/testthat/d_agg_n_vec.Rds index a4a0761..57b69d8 100644 Binary files a/tests/testthat/d_agg_n_vec.Rds and b/tests/testthat/d_agg_n_vec.Rds differ diff --git a/tests/testthat/d_agg_s_vec.Rds b/tests/testthat/d_agg_s_vec.Rds index 5088763..0c75ba9 100644 Binary files a/tests/testthat/d_agg_s_vec.Rds and b/tests/testthat/d_agg_s_vec.Rds differ diff --git a/tests/testthat/setup.r b/tests/testthat/setup.r index d4fce91..e4afbd7 100644 --- a/tests/testthat/setup.r +++ b/tests/testthat/setup.r @@ -1,6 +1,3 @@ -# load for debugging -library(testthat) - min_item_call <- function(...) { default <- list(item_data = opinion, item_names = "abortion", diff --git a/tests/testthat/test-defaults.r b/tests/testthat/test-defaults.r index 4423907..5019e21 100644 --- a/tests/testthat/test-defaults.r +++ b/tests/testthat/test-defaults.r @@ -1,42 +1,66 @@ source("setup.r") -suppressMessages({ - - context("default values") - - test_that('filters take correct defaults', { - d_min <- min_item_call() - expect_identical(d_min$control@time_filter, sort(unique(opinion$year))) - expect_identical(d_min$control@geo_filter, sort(unique(opinion$state))) - expect_identical(d_min$control@min_survey_filter, 1L) - expect_identical(d_min$control@min_t_filter, 1L) - }) - - test_that("time and geo defaults include values in aggregate_data", { - d_agg = min_agg_call() - expect_equal(sort(unique(c(opinion$year, aggregates$year))), - d_agg$control@time_filter) - expect_equal(sort(unique(c(opinion$state, aggregates$state))), - d_agg$control@geo_filter) - }) - - test_that("time and geo defaults include disjoint values in aggregate_data", { - disjoint_geo_time <- data.table::data.table( - race = "white", female = "male", year = 0, item = "abortion", - state = "foo", n_grp = 10, s_grp = 10) - disjoint_geo_time <- data.table::rbindlist(list(aggregates, disjoint_geo_time)) - d_disjoint_agg <- min_agg_call(aggregate_data = disjoint_geo_time) - expect_equal(sort(unique(c(opinion$year, 0))), d_disjoint_agg$control@time_filter) - expect_equal(sort(unique(c(opinion$state, "foo"))), d_disjoint_agg$control@geo_filter) - }) - - test_that('constant_item defaults to TRUE', { - expect_true(min_item_call()$control@constant_item) - }) - - test_that('aggregate_item_names defaults to unique items in aggregate_data', { - d_agg <- min_agg_call() - expect_equal(d_agg$control@aggregate_item_names, - sort(unique(aggregates[n_grp > 0, item]))) - }) +context("default values") + +test_that('filters take correct defaults', { + d_min <- shape(item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female") + expect_identical(d_min$control@time_filter, sort(unique(opinion$year))) + expect_identical(d_min$control@geo_filter, sort(unique(opinion$state))) + expect_identical(d_min$control@min_survey_filter, 1L) + expect_identical(d_min$control@min_t_filter, 1L) +}) + +test_that("time and geo defaults include values in aggregate_data", { + data(aggregates) + d_agg <- shape(aggregate_data = aggregates, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = c("female", "race3")) + expect_equal(sort(unique(c(opinion$year, aggregates$year))), + d_agg$control@time_filter) + expect_equal(sort(unique(c(opinion$state, aggregates$state))), + d_agg$control@geo_filter) +}) + +test_that("time and geo defaults include disjoint values in aggregate_data", { + data(aggregates) + data.table::setDT(aggregates) + disjoint_geo_time <- data.table::data.table( year = 0, state = "foo", race = + "white", female = "male", item = "abortion", n_grp = 10, s_grp = 10) + disjoint_geo_time <- data.table::rbindlist(list(aggregates, disjoint_geo_time)) + + d_disjoint_agg <- shape(aggregate_data = disjoint_geo_time, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = c("female", "race3")) + expect_equal(sort(unique(c(opinion$year, 0))), d_disjoint_agg$control@time_filter) + expect_equal(sort(unique(c(opinion$state, "foo"))), d_disjoint_agg$control@geo_filter) }) + +test_that('constant_item defaults to TRUE', { + min_item_call <- shape(item_data = opinion, item_names = "abortion", + time_name = "year", geo_name = "state", group_names = "female") + expect_true(min_item_call$control@constant_item) +}) + +test_that('aggregate_item_names defaults to unique items in aggregate_data', { + data(aggregates) + data.table::setDT(aggregates) + d_agg <- shape(aggregate_data = aggregates, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = c("female", "race3")) + expect_equal(d_agg$control@aggregate_item_names, + sort(unique(aggregates[n_grp > 0, item]))) +}) + diff --git a/tests/testthat/test-dgirtfit.r b/tests/testthat/test-dgirtfit.r index 6447725..a790fbf 100644 --- a/tests/testthat/test-dgirtfit.r +++ b/tests/testthat/test-dgirtfit.r @@ -1,43 +1,62 @@ -suppressMessages({ - library(data.table) - context("dgirtfit class") - - suppressWarnings({ - sink("/dev/null", type = "output") - res <- dgirt(toy_dgirt_in, iter = 5, chains = 1, seed = 42) - sink() - }) +context("dgirtfit class") + +suppressWarnings({ + data(toy_dgirt_in) + data(opinion) + test_iter <- 5 + test_chains <- 1 + dgirt_ret <- dgirt(toy_dgirt_in, iter = test_iter, chains = test_chains, seed = 42) + dgmrp_in <- shape(opinion, item_names = "abortion", time_name = "year", + geo_name = "state", group_names = "race3", geo_filter = c("CA", "GA")) + dgmrp_ret <- dgmrp(dgmrp_in, iter = test_iter, chains = test_chains, seed = 42) +}) + +test_that("dgirt returns class dgirt_fit", { + expect_s4_class(dgirt_ret, "dgirt_fit") + expect_s4_class(dgirt_ret, "dgo_fit") + expect_true(inherits(dgirt_ret, "stanfit")) +}) + +test_that("dgmrp returns class dgmrp_fit/dgo_fit/stanfit", { + expect_s4_class(dgmrp_ret, "dgmrp_fit") + expect_s4_class(dgmrp_ret, "dgo_fit") + expect_true(inherits(dgmrp_ret, "stanfit")) +}) - test_that("dgirt returns class dgirt_fit", { - expect_s4_class(res, "dgirt_fit") - expect_s4_class(res, "dgo_fit") - expect_true(inherits(res, "stanfit")) +test_that("dgirt accepts a user model", { + dgirt_fit <- dgirt(toy_dgirt_in, iter = test_iter, chains = test_chains, + version = "user-version.stan") + expect_equal(dgirt_fit@stanmodel@model_name, "user-version") + expect_error(dgirt(toy_dgirt_in, iter = test_iter, chains = test_chains, + version = "nonexistent_file.stan"), "should give the name of a model") +}) + +test_that("dgmrp accepts a user model", { + dgmrp_fit <- dgmrp(dgmrp_in, iter = test_iter, chains = test_chains, + version = "user-version.stan") + expect_equal(dgmrp_fit@stanmodel@model_name, "user-version") + expect_error(dgmrp(dgmrp_in, iter = test_iter, chains = test_chains, + version = "nonexistent_file.stan"), "should give the name of a model") +}) + +for (ret in c(dgirt_ret, dgmrp_ret)) { + + test_that("further arguments pass to rstan via ...", { + expect_equal(length(ret@stan_args), test_chains) + expect_true(all(sapply(ret@stan_args, function(x) x$iter) == + test_iter)) }) - test_that("dgmrp returns class dgmrp_fit/dgo_fit/stanfit", { - suppressMessages({ - dgmrp_in <- shape(opinion, item_names = "abortion", time_name = "year", - geo_name = "state", group_names = "race3", geo_filter = c("CA", "GA")) - }) - sink("/dev/null", type = "output") - dgmrp_result <- dgmrp(dgmrp_in, iter = 5, chains = 1, seed = 42) - sink() - expect_s4_class(dgmrp_result, "dgmrp_fit") - expect_s4_class(dgmrp_result, "dgo_fit") - expect_true(inherits(dgmrp_result, "stanfit")) + test_that("defaults pass to rstan", { + expect_true(all(sapply(ret@stan_args, function(x) x$init_r) == + 1L)) }) test_that("dgirt methods work", { - suppressWarnings({ - sink("/dev/null", type = "output") - res <- dgirt(toy_dgirt_in, iter = 5, chains = 1, seed = 42) - sink() - }) - expect_output(print(res), "dgirt samples from") - expect_output(summary(res), "dgirt samples from") - expect_is(summary(res, verbose = TRUE), "list") - - tab <- get_posterior_mean(res) + expect_output(print(ret), "dgirt samples from") + expect_output(summary(ret), "dgirt samples from") + expect_is(summary(ret, verbose = TRUE), "list") + tab <- get_posterior_mean(ret) expect_named(tab, c(attr(tab, "id_vars"), "mean")) }) @@ -61,4 +80,5 @@ suppressMessages({ expect_equal(tab$value, unname(unlist(sf))) }) -}) +} + diff --git a/tests/testthat/test-dgirtin.r b/tests/testthat/test-dgirtin.r new file mode 100644 index 0000000..a3c655e --- /dev/null +++ b/tests/testthat/test-dgirtin.r @@ -0,0 +1,32 @@ +context("dgirt_in methods") + +data(aggregates) +aggregate_items <- unique(aggregates$item) +shaped <- shape(opinion, item_names = "abortion", aggregate_data = aggregates, + aggregate_item_names = aggregate_items, time_name = "year", geo_name = + "state", group_names = c("race3", "female")) + +test_that("by argument to get_n works", { + data(toy_dgirt_in) + expect_named(get_n(toy_dgirt_in, by = "state"), c("state", "n")) + expect_named(get_n(toy_dgirt_in, by = c("state", "race3")), c("state", "race3", "n")) +}) + +test_that("aggregate_name argument to get_n works", { + expect_named(get_n(shaped, aggregate_name = "state"), c("state", "n")) +}) + +test_that("by argument to get_item_n works", { + data(toy_dgirt_in) + item_names <- c("affirmative_action", "gaymarriage_amendment") + expect_named(get_item_n(toy_dgirt_in, by = "state"), c("state", item_names)) + expect_named(get_item_n(toy_dgirt_in, by = c("state", "race3")), c("state", + "race3", item_names)) +}) + +test_that("by argument to get_item_n works with aggregate data", { + expect_true("year" %in% names(get_item_n(shaped, aggregate_data = TRUE, by = + "year"))) + expect_true(all(c("year", "race3") %in% names(get_item_n(shaped, + aggregate_data = TRUE, by = c("year", "race3"))))) +}) diff --git a/tests/testthat/test-dichotomize.r b/tests/testthat/test-dichotomize.r index e6728b9..7bb225a 100644 --- a/tests/testthat/test-dichotomize.r +++ b/tests/testthat/test-dichotomize.r @@ -22,5 +22,5 @@ test_that("dichotomizing item responses works", { expect_equal(dichotomize_cpp(ordered(c("a", "b"),levels = c("b", "a"))), data.frame(X_gt1 = c(1, 0))) - expect_error(dichotomize_cpp("a"), "not compatible") -}) \ No newline at end of file + expect_error(dichotomize_cpp("a"), "not compatible", ignore.case = TRUE) +}) diff --git a/tests/testthat/test-input-validation.r b/tests/testthat/test-input-validation.r index be818ca..4e551ad 100644 --- a/tests/testthat/test-input-validation.r +++ b/tests/testthat/test-input-validation.r @@ -1,85 +1,115 @@ source("setup.r") -suppressMessages({ - context("variation in inputs") +context("variation in inputs") - test_that("no variation in time (a single period) is OK", { - expect_silent(suppressMessages({ - d_in = shape(opinion[year == 2006], - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight")})) - expect_silent({ - sink("/dev/null", type = "output") - d_out = dgirt(d_in, iter = 30, chains = 1) - as.data.frame(d_out) - sink() - }) - }) +test_that("no variation in time (a single period) is OK", { + data(opinion) + data.table::setDT(opinion) + expect_silent(suppressMessages({ + d_in = shape(opinion[year == 2006], + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + survey_name = "source", + weight_name = "weight")})) +}) + +test_that("no variation in survey identifier is OK", { + data(opinion) + data.table::setDT(opinion) + data(targets) + expect_silent(suppressMessages({ + d_in = shape(opinion[source == "CCES_2006"], + target_data = targets, + raking = ~ state, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + survey_name = "source", + weight_name = "weight")})) +}) + +test_that("no variation in geography produces an error", { + data(opinion) + data.table::setDT(opinion) + expect_error(suppressMessages({ + d_in = shape(opinion[state == "MA"], + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + survey_name = "source", + weight_name = "weight") + }), "state doesn't vary in item_data") +}) - test_that("no variation in survey identifier is OK", { - expect_silent(suppressMessages({ - d_in = shape(opinion[source == "CCES_2006"], - target_data = targets, - raking = ~ state, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight")})) - expect_silent({ - sink("/dev/null", type = "output") - d_out = dgirt(d_in, iter = 30, chains = 1) - as.data.frame(d_out) - sink() - }) - }) +test_that("no variation in grouping produces an error", { + data(opinion) + data.table::setDT(opinion) + expect_error(suppressMessages({ + d_in = shape(opinion[female == "female"], + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + survey_name = "source", + weight_name = "weight") + }), "female doesn't vary in item_data") +}) - test_that("no variation in geography produces an error", { - expect_error(suppressMessages({ - d_in = shape(opinion[state == "MA"], - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight") - }), "state doesn't vary in item_data") - }) +test_that("NAs in unused subsets of modifier_data are fine", { + data(opinion) + data(states) + states[states$year == 2008, "income_percapita"] <- NA + expect_silent(suppressMessages(shape(opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + modifier_data = states, + modifier_names = "income_percapita", + time_filter = 2009:2010, + survey_name = "source", + weight_name = "weight"))) +}) - test_that("no variation in grouping produces an error", { - expect_error(suppressMessages({ - d_in = shape(opinion[female == "female"], - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight") - }), "female doesn't vary in item_data") - }) +test_that("NAs in restricted modifier_data produce an error", { + data(opinion) + data(states) + states[states$year == 2008, "income_percapita"] <- NA + expect_error(suppressMessages(shape(opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + modifier_data = states, + modifier_names = "income_percapita", + time_filter = 2008:2009, + survey_name = "source", + weight_name = "weight")), + "NA values") +}) - test_that("NAs in unused subsets of modifier_data are fine", { - states[states$year == 2008, "income_percapita"] <- NA - expect_silent(suppressMessages(shape(opinion, +test_that("omitting weight variable is allowed", { + data(opinion) + data(states) + expect_silent(suppressMessages(shape(opinion, item_names = "abortion", time_name = "year", geo_name = "state", group_names = "female", modifier_data = states, modifier_names = "income_percapita", - time_filter = 2009:2010, - survey_name = "source", - weight_name = "weight"))) - }) + time_filter = 2008:2009, + survey_name = "source"))) +}) - test_that("NAs in restricted modifier_data produce an error", { - states[states$year == 2008, "income_percapita"] <- NA - expect_error(suppressMessages(shape(opinion, +test_that("omitting survey variable is allowed", { + data(opinion) + data(states) + expect_silent(suppressMessages(shape(opinion, item_names = "abortion", time_name = "year", geo_name = "state", @@ -87,34 +117,7 @@ suppressMessages({ modifier_data = states, modifier_names = "income_percapita", time_filter = 2008:2009, - survey_name = "source", - weight_name = "weight")), - "NA values") - }) - - test_that("omitting weight variable is allowed", { - expect_silent(suppressMessages(shape(opinion, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - modifier_data = states, - modifier_names = "income_percapita", - time_filter = 2008:2009, - survey_name = "source"))) - }) - - test_that("omitting survey variable is allowed", { - expect_silent(suppressMessages(shape(opinion, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - modifier_data = states, - modifier_names = "income_percapita", - time_filter = 2008:2009, - weight_name = "weight"))) - }) + weight_name = "weight"))) +}) -}) diff --git a/tests/testthat/test-item_coercion.R b/tests/testthat/test-item_coercion.R index 2c6f0ea..0c105aa 100644 --- a/tests/testthat/test-item_coercion.R +++ b/tests/testthat/test-item_coercion.R @@ -1,7 +1,6 @@ context("item coercion") test_that("item coercion works", { - # TODO roll this up into loops Ctrl <- setClass("Ctrl", slots = c("item_names")) ctrl <- new("Ctrl", item_names = "item") diff --git a/tests/testthat/test-ns_vec.r b/tests/testthat/test-ns_vec.r index 098a4cb..1d75911 100644 --- a/tests/testthat/test-ns_vec.r +++ b/tests/testthat/test-ns_vec.r @@ -1,87 +1,87 @@ -source("setup.r") -suppressMessages({ +context("n/s vectors") - context("n/s vectors") +test_that("counts for minimal call haven't changed", { + d_min <- shape(item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + survey_name = "source", + weight_name = "weight") + expect_equal_to_reference(d_min$n_vec, "d_min_n_vec.Rds") + expect_equal_to_reference(d_min$s_vec, "d_min_s_vec.Rds") +}) - test_that("counts for minimal call haven't changed", { - d_min <- shape(item_data = opinion, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight") - expect_equal_to_reference(d_min$n_vec, "d_min_n_vec.Rds") - expect_equal_to_reference(d_min$s_vec, "d_min_s_vec.Rds") - }) +test_that("counts for call with aggregates haven't changed", { + d_agg <- shape(aggregate_data = aggregates, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = c("female", "race3"), + survey_name = "source", + weight_name = "weight", + time_filter = c(2006:2010), + aggregate_item_names = "hlthcare_binary") +expect_equal_to_reference(d_agg$n_vec, "d_agg_n_vec.Rds") +expect_equal_to_reference(d_agg$s_vec, "d_agg_s_vec.Rds") +}) - test_that("counts for call with aggregates haven't changed", { +test_that("unobserved groups are added to group counts", { + d <- shape(item_data = opinion, + time_filter = c(0, 2006), + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + survey_name = "source", + weight_name = "weight") + expect_equal(unique(d$group_counts$year), c(0, 2006)) +}) + +test_that("n_vec and s_vec have expected order", { + data(aggregates) + data.table::setDT(aggregates) + aggregates <- aggregates[, .(n_grp = sum(n_grp), s_grp = sum(s_grp)), by = + c("year", "state", "female", "item")] d_agg <- shape(aggregate_data = aggregates, item_data = opinion, item_names = "abortion", + modifier_data = states[states$year %in% 2006:2010, ], + modifier_names = "prop_evangelicals", + t1_modifier_names = "income_percapita", time_name = "year", geo_name = "state", - group_names = "female", + group_names = c("female"), survey_name = "source", weight_name = "weight", - time_filter = c(2006:2010), - aggregate_item_names = "hlthcare_binary") - expect_equal_to_reference(d_agg$n_vec, "d_agg_n_vec.Rds") - expect_equal_to_reference(d_agg$s_vec, "d_agg_s_vec.Rds") - }) - - test_that("unobserved groups are added to group counts", { - d <- shape(item_data = opinion, - time_filter = c(0, 2006), - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight") - expect_equal(unique(d$group_counts$year), c(0, 2006)) - }) + time_filter = c(2006:2008), + aggregate_item_names = "hlthcare_binary", + standardize = TRUE) + ctrl <- d_agg$control + n_vec_names <- as.data.table(tstrsplit(names(d_agg$n_vec), "__")) + colnames(n_vec_names) <- c(ctrl@time_name, ctrl@geo_name, ctrl@group_names, + "item") + n_vec_names[, year := type.convert(year)] - test_that("n_vec and s_vec have expected order", { - d_agg <- shape(aggregate_data = aggregates, - item_data = opinion, - item_names = "abortion", - modifier_data = states[states$year %in% 2006:2010, ], - modifier_names = "prop_evangelicals", - t1_modifier_names = "income_percapita", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight", - time_filter = c(2006:2008), - aggregate_item_names = "hlthcare_binary", - standardize = TRUE) - ctrl <- d_agg$control - n_vec_names <- as.data.table(tstrsplit(names(d_agg$n_vec), "__")) - colnames(n_vec_names) <- c(ctrl@time_name, ctrl@geo_name, ctrl@group_names, - "item") - n_vec_names[, year := type.convert(year)] + # we loop over t, q, and g in that order; time should vary slowest + t_order <- rep(ctrl@time_filter, each = d_agg$G * d_agg$Q) + expect_equal(t_order, n_vec_names[[ctrl@time_name]]) - # we loop over t, q, and g in that order; time should vary slowest - t_order <- rep(ctrl@time_filter, each = d_agg$G * d_agg$Q) - expect_equal(t_order, n_vec_names[[ctrl@time_name]]) - - # within each t iterate over q - q_order <- rep(d_agg$gt_items, each = d_agg$G, times = d_agg$T) - expect_equal(q_order, n_vec_names[["item"]]) - - # within each q iterate over g; group levels are the interaction of geo - # levels and demographic levels, and geo varies fastest, iterated over for - # each demographic level - group_levels <- unique(c(d_agg$item_data[[ctrl@group_names]], - d_agg$aggregate_data[[ctrl@group_names]])) - geo_order <- rep(ctrl@geo_filter, times = d_agg$T * d_agg$Q * - length(group_levels)) - expect_equal(geo_order, n_vec_names[[ctrl@geo_name]]) - g_order <- rep(group_levels, each = length(ctrl@geo_filter), - times = d_agg$Q * d_agg$T) - expect_equal(g_order, n_vec_names[[ctrl@group_names]]) - }) + # within each t iterate over q + q_order <- rep(d_agg$gt_items, each = d_agg$G, times = d_agg$T) + expect_equal(q_order, n_vec_names[["item"]]) + # within each q iterate over g; group levels are the interaction of geo + # levels and demographic levels, and geo varies fastest, iterated over for + # each demographic level + group_levels <- unique(c(d_agg$item_data[[ctrl@group_names]], + d_agg$aggregate_data[[ctrl@group_names]])) + geo_order <- rep(ctrl@geo_filter, times = d_agg$T * d_agg$Q * + length(group_levels)) + expect_equal(geo_order, n_vec_names[[ctrl@geo_name]]) + g_order <- rep(group_levels, each = length(ctrl@geo_filter), + times = d_agg$Q * d_agg$T) + expect_equal(g_order, n_vec_names[[ctrl@group_names]]) }) + diff --git a/tests/testthat/test-poststratify.r b/tests/testthat/test-poststratify.r index eb3a4dd..3d339c4 100644 --- a/tests/testthat/test-poststratify.r +++ b/tests/testthat/test-poststratify.r @@ -3,11 +3,7 @@ context("poststratification") test_that("dispatch seems to work", { suppressMessages(library(data.table)) data(toy_dgirtfit) - data(targets) - setDT(targets) - targets <- targets[year %in% 2006:2008, - list("proportion" = sum(proportion)), - by = c("year", "state", "race3")] + data(annual_state_race_targets) expect_silent(poststratify(toy_dgirtfit, target_data = annual_state_race_targets, pars = 'theta_bar', @@ -15,11 +11,6 @@ test_that("dispatch seems to work", { aggregated_names = 'race3')) estimates <- as.data.frame(toy_dgirtfit) - data(targets) - setDT(targets) - targets <- targets[year %in% 2006:2008, - list("proportion" = sum(proportion)), - by = c("year", "state", "race3")] expect_silent(poststratify(estimates, annual_state_race_targets, strata_names = c("year", "state"), @@ -64,16 +55,16 @@ test_that("omitted arguments produce errors", { test_that("missing variables produce stop", { data(targets) expect_error(poststratify(toy_dgirtfit, target_data = targets, - strata_names = "foo", aggregate = "foo"), - "foo .* isn't a name in the table of estimates") + strata_names = "foo", aggregate = "bar"), + "foo in strata_names but not the table of estimates") expect_error(poststratify(toy_dgirtfit, target_data = annual_state_race_targets[, -1], strata_names = "state", aggregate = "race3"), - "state .* isn't a name in target_data") + "state in strata_names but not target_data") }) test_that("poststratify works for gamma, gamma_raw, and theta_bar", { - params <- index_names[c("gamma", "gamma_raw", "theta_bar")] + params <- dgo:::index_names[c("gamma", "gamma_raw", "theta_bar")] data(toy_dgirtfit) data(annual_state_race_targets) for (i in seq_along(params)) { @@ -98,7 +89,15 @@ test_that("poststratify works for gamma, gamma_raw, and theta_bar", { } }) -test_that("variables duplicated between strata_ and group_names produce a stop", { - # expect_error(poststratify(toy_dgirtfit, target_data = targets, - # strata_names = "race3")) +test_that("variables duplicated across arguments is an error", { + # dgirfit method + expect_error(poststratify(toy_dgirtfit, target_data = + annual_state_race_targets, strata_names = c("state", "year", "race3"), + aggregated_names = "race3"), "more than once") + + # dataframe method + est_table <- as.data.frame(toy_dgirtfit) + expect_error(poststratify(est_table, target_data = + annual_state_race_targets, strata_names = c("state", "year", "race3"), + aggregated_names = "race3"), "more than once") }) diff --git a/tests/testthat/test-raking.r b/tests/testthat/test-raking.r index 548d7b2..ec84bec 100644 --- a/tests/testthat/test-raking.r +++ b/tests/testthat/test-raking.r @@ -1,247 +1,246 @@ source("setup.r") -suppressMessages({ - - context("raking") - - test_that("basic syntax works", { - data.table::setDT(annual_state_race_targets) - annual_state_race_targets = annual_state_race_targets[year %in% 2006:2010] - expect_silent(suppressMessages(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = ~ state))) - expect_silent(suppressMessages(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = list(~ state, ~ year)))) - expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = ~ state + year)))) - expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = list(~ state + year, ~ race3))))) - expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = list(~ race3))))) - expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = ~ race3)))) - expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = list(~ year, ~ race3))))) - }) - - test_that("raking variables must exist", { +context("raking") + +test_that("basic syntax works", { + data(annual_state_race_targets) + data.table::setDT(annual_state_race_targets) + annual_state_race_targets = annual_state_race_targets[year %in% 2006:2010] + expect_silent(suppressMessages(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = ~ state))) + expect_silent(suppressMessages(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = list(~ state, ~ year)))) + expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = ~ state + year)))) + expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = list(~ state + year, ~ race3))))) + expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = list(~ race3))))) + expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = ~ race3)))) + expect_silent(suppressWarnings(suppressMessages(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = list(~ year, ~ race3))))) +}) + +test_that("raking variables must exist", { + data(annual_state_race_targets) # raking gives a single formula - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = ~ source), - "\"source\" is a raking formula term but isn't a variable name in \"target_data\"") - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", - raking = ~ proportion), - "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") - - # raking gives a list of formulas - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", survey_name = "source", - raking = list(~ source, ~ weight)), - "\"source\" is a raking formula term but isn't a variable name in \"target_data\"") - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", survey_name = "source", - raking = list(~ proportion, ~ weight)), - "\"weight\" is a raking formula term but isn't a variable name in \"target_data\"") - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", survey_name = "source", - raking = list(~ proportion, ~ proportion)), - "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", survey_name = "source", - raking = list(~ state, ~ proportion)), - "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") - - # raking gives formulas with operators - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", survey_name = "source", - raking = list(~ state + weight)), - "\"weight\" is a raking formula term but isn't a variable name in \"target_data\"") - expect_error(min_item_call(target_data = annual_state_race_targets, - weight_name = "weight", survey_name = "source", - raking = list(~ state + proportion)), - "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") - }) - - set_up_sample = function(w) { - # From the warpbreaks data, create a sample with the unique combinations of - # wool and tension, where wool \in A, B and tension \in L, M, H. All - # observations are in the same time period and each has a sampling weight. - # For example, if w = 1: - # wool tension t weight - # 1: A L 1 1 - # 2: A M 1 1 - # 3: A H 1 1 - # 4: B L 1 1 - # 5: B M 1 1 - # 6: B H 1 1 - data(warpbreaks) - toy_data = warpbreaks - setDT(toy_data)[, `:=`(t = 1), by = c("wool", "tension")] - toy_data = unique(toy_data, by = c("wool", "tension")) - toy_data[, weight := w] - toy_data[, breaks := NULL] - toy_data[] - } - - set_up_pop = function(props) { - # Set up population margins for the warpbreaks data from which the - # combinations of wool and tension are sampled with equal probability. - data(warpbreaks) - toy_targets = unique(setDT(warpbreaks)[, .(wool, tension)]) - toy_targets[, t := 1] - toy_targets[, proportion := 1 / .N] - toy_targets[] - } - - sum_by = function(tab, index) { - tapply(tab$raked_weight, tab[[index]], sum) - } - - setClass("Ctrl", slots = c("time_name", "weight_name", - "proportion_name", "raking"), prototype = list(time_name = "t", - weight_name = "weight", "proportion_name" = "proportion")) - - test_that("raking has no effect if weights reflect population margins", { - toy_data = set_up_sample(w = 1) - toy_targets = set_up_pop(props = NULL) - - # raking should have no effect in a balanced sample whose observations are - # weighted equally, regardless of the raking specification - - ctrl = new("Ctrl", raking = ~ wool) - rake_result = weight(copy(toy_data), toy_targets, ctrl) - # weight is the original weight; raked_weight is the raked weight - expect_equal(rake_result$weight, rake_result$raked_weight) - - ctrl = new("Ctrl", raking = ~ wool + tension) - rake_result = weight(copy(toy_data), toy_targets, ctrl) - expect_equal(rake_result$weight, rake_result$raked_weight) - - ctrl = new("Ctrl", raking = ~ tension) - rake_result = weight(copy(toy_data), toy_targets, ctrl) - expect_equal(rake_result$weight, rake_result$raked_weight) - - ctrl = new("Ctrl", raking = list(~ wool, ~ tension)) - rake_result = weight(copy(toy_data), toy_targets, ctrl) - expect_equal(rake_result$weight, rake_result$raked_weight) - }) - - test_that("raking equalizes weights when they should be equal", { - - # Population proportions for combinations of wool and tension are equal, - # but in the sample wool A is downweighted 2:1 compared to wool B. - toy_data = set_up_sample(w = rep(c(0.5, 1), each = 3)) - toy_targets = set_up_pop(props = NULL) - ctrl = new("Ctrl", raking = ~ wool) - toy_data - - # When raking on wool, we should recover equal weights - rake_result = weight(copy(toy_data), toy_targets, ctrl) - expect_equal(rake_result$raked_weight, rep(1, 6)) - - ctrl = new("Ctrl", raking = ~ tension) - # When raking on tension, the weights appear correct; the sum of weights - # within each combination of wool and tension is equal. In the raked weights - # the 2:1 downweighting of wool A to B should persist. - rake_result = weight(copy(toy_data), toy_targets, ctrl) - sums = sum_by(rake_result, "wool") - expect_equal(unname(sums["A"]/sums["B"]), 0.5) - - # Now set up the sample such that wool A + tension L is unobserved, and all - # observations are given equal weight. - toy_data = set_up_sample(w = 1) - toy_data = toy_data[-1] - toy_targets = set_up_pop(props = NULL) - - # When raking on wool-tension, there's no observation we can upweight to - # balance the sample. - ctrl = new("Ctrl", raking = ~ wool + tension) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - expect_equal(unique(rake_result$raked_weight), 1) - - # When raking on wool, the sum of raked weights within wool A and wool B - # should be equal. - ctrl = new("Ctrl", raking = ~ wool) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - sums = rake_result[, .(sums = sum(raked_weight)), by = "wool"][["sums"]] - expect_length(unique(sums), 1) - - # When raking on tension, the observation with tension L should be - # upweighted 2:1 against the others. Equivalently, the sum of weights in - # tensions L, M, and H should be the same. - ctrl = new("Ctrl", raking = list(~ tension)) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - sums = rake_result[, .(sums = sum(raked_weight)), by = "tension"][["sums"]] - expect_length(unique(sums), 1) - - # When raking on wool and tension, order matters! In the sample, wool A is - # underweighted 2:3 and tension L is underweighted 1:2. - - # When raking on wool, then tension, wool A remains underweighted 2:3 and - # tension weights are made equal. - ctrl = new("Ctrl", raking = list(~ wool, ~ tension)) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - wool_sums = sum_by(rake_result, "wool") - tension_sums = sum_by(rake_result, "tension") - expect_length(unique(tension_sums), 1) - expect_length(unique(wool_sums), 2) - - # When raking on tension, then wool, wool weights are made equal; tension L - # is still underweighted, but 2:3 instead of 1:2. - ctrl = new("Ctrl", raking = list(~ tension, ~ wool)) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - wool_sums = sum_by(rake_result, "wool") - tension_sums = sum_by(rake_result, "tension") - expect_length(unique(tension_sums), 2) - expect_length(unique(wool_sums), 1) - - toy_data = rbind(set_up_sample(w = 1), set_up_sample(w = 2)) - toy_targets = set_up_pop(props = NULL) - - # # When raking on wool-tension, there's no observation we can upweight to - # # balance the sample. - ctrl = new("Ctrl", raking = ~ wool + tension) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - expect_equal(length(unique(rake_result$raked_weight)), 2) - - # When raking on wool, the sum of raked weights within wool A and wool B - # should be equal. - ctrl = new("Ctrl", raking = ~ wool) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - sums = rake_result[, .(sums = sum(raked_weight)), by = "wool"][["sums"]] - expect_length(unique(sums), 1) - - # When raking on tension, the observation with tension L should be - # upweighted 2:1 against the others. Equivalently, the sum of weights in - # tensions L, M, and H should be the same. - ctrl = new("Ctrl", raking = list(~ tension)) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - sums = rake_result[, .(sums = sum(raked_weight)), by = "tension"][["sums"]] - expect_length(unique(sums), 1) - - # When raking on wool, then tension, weights are made equal - ctrl = new("Ctrl", raking = list(~ wool, ~ tension)) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - wool_sums = sum_by(rake_result, "wool") - tension_sums = sum_by(rake_result, "tension") - Reduce(expect_equal, wool_sums) - Reduce(expect_equal, tension_sums) - - # When raking on tension, then wool, weights are made equal - ctrl = new("Ctrl", raking = list(~ tension, ~ wool)) - rake_result = suppressWarnings(weight(copy(toy_data), toy_targets, ctrl)) - wool_sums = sum_by(rake_result, "wool") - tension_sums = sum_by(rake_result, "tension") - Reduce(expect_equal, wool_sums) - Reduce(expect_equal, tension_sums) - }) + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = ~ source), + "\"source\" is a raking formula term but isn't a variable name in \"target_data\"") + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", + raking = ~ proportion), + "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") + + # raking gives a list of formulas + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", survey_name = "source", + raking = list(~ source, ~ weight)), + "\"source\" is a raking formula term but isn't a variable name in \"target_data\"") + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", survey_name = "source", + raking = list(~ proportion, ~ weight)), + "\"weight\" is a raking formula term but isn't a variable name in \"target_data\"") + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", survey_name = "source", + raking = list(~ proportion, ~ proportion)), + "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", survey_name = "source", + raking = list(~ state, ~ proportion)), + "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") + + # raking gives formulas with operators + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", survey_name = "source", + raking = list(~ state + weight)), + "\"weight\" is a raking formula term but isn't a variable name in \"target_data\"") + expect_error(min_item_call(target_data = annual_state_race_targets, + weight_name = "weight", survey_name = "source", + raking = list(~ state + proportion)), + "\"proportion\" is a raking formula term but isn't a variable name in \"item_data\"") +}) +set_up_sample = function(w) { + # From the warpbreaks data, create a sample with the unique combinations of + # wool and tension, where wool \in A, B and tension \in L, M, H. All + # observations are in the same time period and each has a sampling weight. + # For example, if w = 1: + # wool tension t weight + # 1: A L 1 1 + # 2: A M 1 1 + # 3: A H 1 1 + # 4: B L 1 1 + # 5: B M 1 1 + # 6: B H 1 1 + data(warpbreaks) + toy_data = warpbreaks + data.table::setDT(toy_data)[, `:=`(t = 1), by = c("wool", "tension")] + toy_data = unique(toy_data, by = c("wool", "tension")) + toy_data[, weight := w] + toy_data[, breaks := NULL] + toy_data[] +} + +set_up_pop = function(props) { + # Set up population margins for the warpbreaks data from which the + # combinations of wool and tension are sampled with equal probability. + data(warpbreaks) + toy_targets = unique(data.table::setDT(warpbreaks)[, .(wool, tension)]) + toy_targets[, t := 1] + toy_targets[, proportion := 1 / .N] + toy_targets[] +} + +sum_by = function(tab, index) { + tapply(tab$raked_weight, tab[[index]], sum) +} + +setClass("Ctrl", slots = c("time_name", "weight_name", + "proportion_name", "raking"), prototype = list(time_name = "t", + weight_name = "weight", "proportion_name" = "proportion")) + +test_that("raking has no effect if weights reflect population margins", { + toy_data = set_up_sample(w = 1) + toy_targets = set_up_pop(props = NULL) + + # raking should have no effect in a balanced sample whose observations are + # weighted equally, regardless of the raking specification + + ctrl = new("Ctrl", raking = ~ wool) + rake_result = dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl) + # weight is the original weight; raked_weight is the raked weight + expect_equal(rake_result$weight, rake_result$raked_weight) + + ctrl = new("Ctrl", raking = ~ wool + tension) + rake_result = dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl) + expect_equal(rake_result$weight, rake_result$raked_weight) + + ctrl = new("Ctrl", raking = ~ tension) + rake_result = dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl) + expect_equal(rake_result$weight, rake_result$raked_weight) + + ctrl = new("Ctrl", raking = list(~ wool, ~ tension)) + rake_result = dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl) + expect_equal(rake_result$weight, rake_result$raked_weight) }) + +test_that("raking equalizes weights when they should be equal", { + + # Population proportions for combinations of wool and tension are equal, + # but in the sample wool A is downweighted 2:1 compared to wool B. + toy_data = set_up_sample(w = rep(c(0.5, 1), each = 3)) + toy_targets = set_up_pop(props = NULL) + ctrl = new("Ctrl", raking = ~ wool) + toy_data + + # When raking on wool, we should recover equal weights + rake_result = dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl) + expect_equal(rake_result$raked_weight, rep(1, 6)) + + ctrl = new("Ctrl", raking = ~ tension) + # When raking on tension, the weights appear correct; the sum of weights + # within each combination of wool and tension is equal. In the raked weights + # the 2:1 downweighting of wool A to B should persist. + rake_result = dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl) + sums = sum_by(rake_result, "wool") + expect_equal(unname(sums["A"]/sums["B"]), 0.5) + + # Now set up the sample such that wool A + tension L is unobserved, and all + # observations are given equal weight. + toy_data = set_up_sample(w = 1) + toy_data = toy_data[-1] + toy_targets = set_up_pop(props = NULL) + + # When raking on wool-tension, there's no observation we can upweight to + # balance the sample. + ctrl = new("Ctrl", raking = ~ wool + tension) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + expect_equal(unique(rake_result$raked_weight), 1) + + # When raking on wool, the sum of raked weights within wool A and wool B + # should be equal. + ctrl = new("Ctrl", raking = ~ wool) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + sums = rake_result[, .(sums = sum(raked_weight)), by = "wool"][["sums"]] + expect_length(unique(sums), 1) + + # When raking on tension, the observation with tension L should be + # upweighted 2:1 against the others. Equivalently, the sum of weights in + # tensions L, M, and H should be the same. + ctrl = new("Ctrl", raking = list(~ tension)) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + sums = rake_result[, .(sums = sum(raked_weight)), by = "tension"][["sums"]] + expect_length(unique(sums), 1) + + # When raking on wool and tension, order matters! In the sample, wool A is + # underweighted 2:3 and tension L is underweighted 1:2. + + # When raking on wool, then tension, wool A remains underweighted 2:3 and + # tension weights are made equal. + ctrl = new("Ctrl", raking = list(~ wool, ~ tension)) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + wool_sums = sum_by(rake_result, "wool") + tension_sums = sum_by(rake_result, "tension") + expect_length(unique(tension_sums), 1) + expect_length(unique(wool_sums), 2) + + # When raking on tension, then wool, wool weights are made equal; tension L + # is still underweighted, but 2:3 instead of 1:2. + ctrl = new("Ctrl", raking = list(~ tension, ~ wool)) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + wool_sums = sum_by(rake_result, "wool") + tension_sums = sum_by(rake_result, "tension") + expect_length(unique(tension_sums), 2) + expect_length(unique(wool_sums), 1) + + toy_data = rbind(set_up_sample(w = 1), set_up_sample(w = 2)) + toy_targets = set_up_pop(props = NULL) + + # # When raking on wool-tension, there's no observation we can upweight to + # # balance the sample. + ctrl = new("Ctrl", raking = ~ wool + tension) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + expect_equal(length(unique(rake_result$raked_weight)), 2) + + # When raking on wool, the sum of raked weights within wool A and wool B + # should be equal. + ctrl = new("Ctrl", raking = ~ wool) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + sums = rake_result[, .(sums = sum(raked_weight)), by = "wool"][["sums"]] + expect_length(unique(sums), 1) + + # When raking on tension, the observation with tension L should be + # upweighted 2:1 against the others. Equivalently, the sum of weights in + # tensions L, M, and H should be the same. + ctrl = new("Ctrl", raking = list(~ tension)) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + sums = rake_result[, .(sums = sum(raked_weight)), by = "tension"][["sums"]] + expect_length(unique(sums), 1) + + # When raking on wool, then tension, weights are made equal + ctrl = new("Ctrl", raking = list(~ wool, ~ tension)) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + wool_sums = sum_by(rake_result, "wool") + tension_sums = sum_by(rake_result, "tension") + Reduce(expect_equal, wool_sums) + Reduce(expect_equal, tension_sums) + + # When raking on tension, then wool, weights are made equal + ctrl = new("Ctrl", raking = list(~ tension, ~ wool)) + rake_result = suppressWarnings(dgo:::weight(data.table::copy(toy_data), toy_targets, ctrl)) + wool_sums = sum_by(rake_result, "wool") + tension_sums = sum_by(rake_result, "tension") + Reduce(expect_equal, wool_sums) + Reduce(expect_equal, tension_sums) +}) + diff --git a/tests/testthat/test-restrict.r b/tests/testthat/test-restrict.r index de65377..228cb78 100644 --- a/tests/testthat/test-restrict.r +++ b/tests/testthat/test-restrict.r @@ -1,128 +1,150 @@ source("setup.r") -suppressMessages({ - - context("restricting input data") - - test_that("filters aren't accepted if too restrictive", { - - expect_error(new("Control", geo_filter = "AK", time_name = "time", geo_name - = "state", group_names = "foo", time_filter = 2006:2007, standardize = TRUE, - constant_item = TRUE, min_survey_filter = 1, min_t_filter = 1), - "if specified \"geo_filter\" should give at least two local geographic areas") - - expect_error(suppressMessages(min_modifier_call(geo_filter = "AK")), - "if specified \"geo_filter\" should give at least two local geographic areas") - - }) - - context("restricting modifier data") - - test_that("groups unobserved in item_data are dropped from modifier_data", { - # TODO - }) - - context("standardizing modifier data") - - test_that("standardize argument for modifier_data works", { - - data(states) - std_res <- min_modifier_call(standardize = TRUE) - expect_true(std_res$control@standardize) - expect_equivalent(mean(std_res$modifier_data$prop_evangelicals), 0) - expect_equivalent(sd(std_res$modifier_data$prop_evangelicals), 1) - - nonstd_res <- min_modifier_call(standardize = FALSE) - expect_false(nonstd_res$control@standardize) - expect_equivalent(mean(nonstd_res$modifier_data$prop_evangelicals), - mean(states$prop_evangelicals[states$year %in% 2006:2010])) - expect_equivalent(sd(nonstd_res$modifier_data$prop_evangelicals), - sd(states$prop_evangelicals[states$year %in% 2006:2010])) - }) - - context("keeping id_vars in item_data") - - test_that("id_vars are kept in item_data", { - opinion$respondent = 1:nrow(opinion) - d_min = min_modifier_call(item_data = opinion, id_vars = "respondent") - expect_true("respondent" %in% names(d_min$item_data)) - }) - - test_that("id_vars can be NULL", { - expect_silent(suppressMessages(min_modifier_call(id_vars = NULL))) - }) - - test_that("id_vars has to exist if specified", { - expect_error(min_modifier_call(id_vars = "foo"), - "\"id_vars\" should give variable names in \"item_data\"") - }) - - context("disjoint item and modifier groups") - - agg_disjoint <- data.table::data.table( - race = "white", female = "male", year = 0, item = "abortion", - state = "foo", n_grp = 1, s_grp = 1) - agg_disjoint <- data.table::rbindlist(list(aggregates, agg_disjoint)) - agg_disjoint = agg_disjoint[n_grp > 0] - d_disjoint_agg <- min_agg_call(aggregate_data = agg_disjoint, - aggregate_item_names = unique(agg_disjoint$item)) - - test_that("all items in `aggregate_data` are used", { - expect_equal(d_disjoint_agg$control@item_names, - sort(unique("abortion", d_disjoint_agg$item))) - expect_equal(sort(unique(d_disjoint_agg$group_counts$item)), - # "abortion" is given as the `item_names` argument - # to min_agg_call() - sort(c("abortion_gt1", unique(agg_disjoint$item)))) - }) - - test_that("all periods in `aggregate_data` are used by default", { - expect_equal(d_disjoint_agg$control@time_filter, - sort(c(unique(opinion$year), 0))) - expect_equal(sort(unique(d_disjoint_agg$group_counts[["year"]])), - sort(c(unique(opinion$year), 0))) - }) - - test_that("all geos in `aggregate_data` are used by default", { - expect_equal(d_disjoint_agg$control@geo_filter, - sort(c(unique(opinion$state), "foo"))) - expect_equal(sort(unique(d_disjoint_agg$group_counts[["state"]])), - sort(c(unique(opinion$state), "foo"))) - }) - - test_that("periods in `aggregate_data` can be restricted by time_filter", { - years = 2006:2008 - d_filtered <- min_agg_call(aggregate_data = agg_disjoint, - aggregate_item_names = unique(agg_disjoint$item), - time_filter = years) - expect_equal(d_filtered$control@time_filter, years) - expect_equal(sort(unique(d_filtered$group_counts[["year"]])), years) - }) - - test_that("geo in `aggregate_data` can be restricted by geo_filter", { - geos = c("AK", "WI") - d_filtered <- min_agg_call(aggregate_data = agg_disjoint, - aggregate_item_names = unique(agg_disjoint$item), - geo_filter = geos) - expect_equal(d_filtered$control@geo_filter, geos) - expect_equal(sort(unique(d_filtered$group_counts[["state"]])), geos) - }) - - test_that("all groups in `aggregate_data` are used", { - disjoint_groups <- data.table::data.table( - race = "white", female = "other", year = 2006, item = "abortion", - state = "AK", n_grp = 1, s_grp = 1) - aggregates <- data.table::rbindlist(list(aggregates, disjoint_groups)) - d_disjoint_groups <- min_agg_call(aggregate_data = aggregates, - aggregate_item_names = unique(aggregates$item)) - expect_equal(sort(unique(d_disjoint_groups$group_counts[["female"]])), - c("female", "male", "other")) - }) - - test_that("stop_if_any_na works", { - d <- data.frame(a = NA, b = 1, stringsAsFactors = FALSE) - expect_error(stop_if_any_na(d, "a"), "NA values") - expect_error(stop_if_any_na(d, c("a", "b")), "NA values") - expect_silent(stop_if_any_na(d, "b")) - }) + +context("restricting input data") + +test_that("filters aren't accepted if too restrictive", { + + expect_error(new("Control", geo_filter = "AK", time_name = "time", geo_name + = "state", group_names = "foo", time_filter = 2006:2007, standardize = TRUE, + constant_item = TRUE, min_survey_filter = 1, min_t_filter = 1), + "if specified \"geo_filter\" should give at least two local geographic areas") + + expect_error(suppressMessages(min_modifier_call(geo_filter = "AK")), + "if specified \"geo_filter\" should give at least two local geographic areas") }) + +context("restricting modifier data") + +test_that("groups unobserved in item_data are dropped from modifier_data", { + ctrl <- new("Control", geo_name = "state", time_name = "year", standardize = + TRUE, constant_item = TRUE, min_survey_filter = 1, min_t_filter = 1, + modifier_names = "prop_urban") + data(states) + data.table::setDT(states) + group_grid <- data.table::data.table(year = 1930:1931, state = "AK") + restricted <- dgo:::restrict_modifier(states, group_grid, ctrl) + expect_equivalent(group_grid[, c("year", "state")], + restricted[, c("year", "state")]) +}) + +context("standardizing modifier data") + +test_that("standardize argument for modifier_data works", { + + data(states) + std_res <- min_modifier_call(standardize = TRUE) + expect_true(std_res$control@standardize) + expect_equivalent(mean(std_res$modifier_data$prop_evangelicals), 0) + expect_equivalent(sd(std_res$modifier_data$prop_evangelicals), 1) + + nonstd_res <- min_modifier_call(standardize = FALSE) + expect_false(nonstd_res$control@standardize) + expect_equivalent(mean(nonstd_res$modifier_data$prop_evangelicals), + mean(states$prop_evangelicals[states$year %in% 2006:2010])) + expect_equivalent(sd(nonstd_res$modifier_data$prop_evangelicals), + sd(states$prop_evangelicals[states$year %in% 2006:2010])) +}) + +context("keeping id_vars in item_data") + +test_that("id_vars are kept in item_data", { + opinion$respondent = 1:nrow(opinion) + d_min = min_modifier_call(item_data = opinion, id_vars = "respondent") + expect_true("respondent" %in% names(d_min$item_data)) +}) + +test_that("id_vars can be NULL", { + expect_silent(suppressMessages(min_modifier_call(id_vars = NULL))) +}) + +test_that("id_vars has to exist if specified", { + expect_error(min_modifier_call(id_vars = "foo"), + "\"id_vars\" should give variable names in \"item_data\"") +}) + +context("disjoint item and modifier groups") +data(aggregates) +agg_disjoint <- data.table::data.table( + year = 0 ,state = "foo", race3 = "white", female = "male", item = + "abortion", n_grp = 1, s_grp = 1) +agg_disjoint <- data.table::rbindlist(list(aggregates, agg_disjoint)) +agg_disjoint = agg_disjoint[n_grp > 0] +d_disjoint_agg <- shape(aggregate_data = agg_disjoint, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = c("female", "race3")) + +test_that("all items in `aggregate_data` are used", { + expect_equal(d_disjoint_agg$control@item_names, + sort(unique("abortion", d_disjoint_agg$item))) + expect_equal(sort(unique(d_disjoint_agg$group_counts$item)), + # "abortion" is given as the `item_names` argument + # to min_agg_call() + sort(c("abortion_gt1", unique(agg_disjoint$item)))) +}) + +test_that("all periods in `aggregate_data` are used by default", { + expect_equal(d_disjoint_agg$control@time_filter, + sort(c(unique(opinion$year), 0))) + expect_equal(sort(unique(d_disjoint_agg$group_counts[["year"]])), + sort(c(unique(opinion$year), 0))) +}) + +test_that("all geos in `aggregate_data` are used by default", { + expect_equal(d_disjoint_agg$control@geo_filter, + sort(c(unique(opinion$state), "foo"))) + expect_equal(sort(unique(d_disjoint_agg$group_counts[["state"]])), + sort(c(unique(opinion$state), "foo"))) +}) + +test_that("periods in `aggregate_data` can be restricted by time_filter", { + years = 2006:2008 + d_filtered <- shape(aggregate_data = agg_disjoint, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + time_filter = years, + group_names = c("female", "race3")) + expect_equal(d_filtered$control@time_filter, years) + expect_equal(sort(unique(d_filtered$group_counts[["year"]])), years) +}) + +test_that("geo in `aggregate_data` can be restricted by geo_filter", { + geos = c("AK", "WI") + d_filtered <- shape(aggregate_data = agg_disjoint, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + geo_filter = geos, + group_names = c("female", "race3")) + expect_equal(d_filtered$control@geo_filter, geos) + expect_equal(sort(unique(d_filtered$group_counts[["state"]])), geos) +}) + +test_that("all groups in `aggregate_data` are used", { + data(aggregates) + disjoint_groups <- data.table::data.table(year = 2006, state = "AK", race3 = + "white", female = "other", item = "abortion", n_grp = 1, s_grp = 1) + aggregates <- data.table::rbindlist(list(aggregates, disjoint_groups)) + d_disjoint_groups <- shape(aggregate_data = aggregates, + item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = c("female", "race3")) + expect_equal(sort(unique(d_disjoint_groups$group_counts[["female"]])), + c("female", "male", "other")) +}) + +test_that("stop_if_any_na works", { + d <- data.frame(a = NA, b = 1, stringsAsFactors = FALSE) + expect_error(dgo:::stop_if_any_na(d, "a"), "NA values") + expect_error(dgo:::stop_if_any_na(d, c("a", "b")), "NA values") + expect_silent(dgo:::stop_if_any_na(d, "b")) +}) + diff --git a/tests/testthat/test-shape_misc.r b/tests/testthat/test-shape_misc.r index 303840b..4da4897 100644 --- a/tests/testthat/test-shape_misc.r +++ b/tests/testthat/test-shape_misc.r @@ -1,34 +1,57 @@ source("setup.r") -suppressMessages({ - - context("shape calls") - - test_that("minimal calls are successful", { - expect_silent(suppressMessages(min_item_call())) - expect_silent(suppressMessages(min_modifier_call())) - expect_silent(suppressMessages(min_groupless_call())) - }) - - d_min <- min_item_call(survey_name = "source", weight_name = "weight") - d_mod <- min_modifier_call() - d_nogroups <- min_groupless_call() - - context("shape return values are valid") - - test_that("dgirtIn creation works", { - expect_is(d_min, "dgirtIn") - expect_is(d_min, "R6") - expect_is(d_min$control, "Control") - expect_true(isS4(d_min$control)) - }) - - test_that("*_name arguments appear in control@*_name", { - expect_identical(d_min$control@item_names, "abortion") - expect_identical(d_min$control@geo_name, "state") - expect_identical(d_min$control@time_name, "year") - expect_identical(d_min$control@group_names, "female") - expect_identical(d_min$control@survey_name, "source") - expect_identical(d_min$control@weight_name, "weight") - }) +context("shape calls") + +test_that("minimal calls are successful", { + expect_silent(suppressMessages(shape(item_data = opinion, item_names = + "abortion", time_name = "year", geo_name = "state", group_names = + "female"))) + expect_silent(suppressMessages(shape(item_data = opinion, item_names = + "abortion", time_name = "year", geo_name = "state", group_names = + "female", modifier_data = states, modifier_names = + "prop_evangelicals", t1_modifier_names = "prop_evangelicals"))) + expect_silent(suppressMessages(shape(item_data = opinion, item_names = + "abortion", time_name = "year", geo_name = "state"))) +}) + +d_min <- shape(item_data = opinion, item_names = "abortion", time_name = + "year", geo_name = "state", group_names = "female", survey_name = "source", +weight_name = "weight") +d_mod <- shape(item_data = opinion, item_names = "abortion", time_name = + "year", geo_name = "state", group_names = "female", modifier_data = states, + modifier_names = "prop_evangelicals", t1_modifier_names = "prop_evangelicals") +d_nogroups <- shape(item_data = opinion, item_names = "abortion", time_name = + "year", geo_name = "state") + +context("shape return values are valid") + +test_that("dgirtIn creation works", { + expect_is(d_min, "dgirtIn") + expect_is(d_min, "R6") + expect_is(d_min$control, "Control") + expect_true(isS4(d_min$control)) }) + +test_that("*_name arguments appear in control@*_name", { + expect_identical(d_min$control@item_names, "abortion") + expect_identical(d_min$control@geo_name, "state") + expect_identical(d_min$control@time_name, "year") + expect_identical(d_min$control@group_names, "female") + expect_identical(d_min$control@survey_name, "source") + expect_identical(d_min$control@weight_name, "weight") + expect_identical(d_mod$control@modifier_names, "prop_evangelicals") + expect_identical(d_nogroups$control@group_names, NULL) +}) + +test_that("setDT_data works as expected", { + data(opinion) + expect_is(opinion, "data.frame") + expect_true(!inherits(opinion, "data.table")) + item_data <- dgo:::set_copy_dt(opinion) + expect_is(item_data, "data.table") + item_data <- NULL + expect_true(!is.null(opinion)) + item_data <- dgo:::set_copy_dt(item_data) + expect_true(is.null(item_data)) +}) + diff --git a/tests/testthat/test-types.r b/tests/testthat/test-types.r index 65f5775..247cfbe 100644 --- a/tests/testthat/test-types.r +++ b/tests/testthat/test-types.r @@ -1,146 +1,138 @@ source("setup.r") -suppressMessages({ - - context("input types") - - data(opinion) - data(states) - - d_min <- min_item_call() - d_mod <- min_modifier_call() - - test_that("minimal shape calls are successful", { - expect_silent(suppressMessages(min_item_call())) - expect_silent(suppressMessages(min_modifier_call())) - expect_silent(suppressMessages(min_groupless_call())) - }) - - test_that("stop_if_empty works", { - x <- data.frame() - expect_error(stop_if_empty(x), "all dimensions of x should be positive") - }) - - test_that("check_count works", { - expect_silent(check_count(cars, "speed")) - }) - - test_that("check_count catches non-integers", { - data(cars) - cars$speed <- cars$speed + 0.5 - expect_error(check_count(cars, "speed"), - "values of \"speed\" in cars should be positive integers") - }) - - test_that("check_count catches negative numbers", { - data(cars) - cars$speed <- cars$speed * -1 - expect_error(check_count(cars, "speed"), - "values of \"speed\" in cars should be positive integers") - }) - - test_that("factor values for geo_name in item_data produce a warning", { - opinion$state <- as.factor(opinion$state) - expect_warning(min_item_call(item_data = opinion), "Coercing factor") - }) - - test_that("numeric values for geo_name produce an error", { - opinion$state <- suppressWarnings(as.numeric(opinion$state)) - expect_error(min_item_call(item_data = opinion), "should be character or factor") - }) - - test_that("factor values for geo_name in modifier_data produce a warning", { - states$state = as.factor(states$state) - expect_warning(min_modifier_call(modifier_data = states), "Coercing factor") - }) - - test_that("numeric values for geo_name in modifier data produce an error", { - states$state = suppressWarnings(as.numeric(states$state)) - expect_error(min_modifier_call(modifier_data = states), "should be character or factor") - }) - - test_that("numeric values for group_names in item_data produce an error", { - opinion$female <- suppressWarnings(as.numeric(opinion$female)) - expect_error(min_item_call(item_data = opinion), "should be character or factor") - }) - - test_that("factor values for group_names in item_data produce a warning", { - opinion$female <- as.factor(opinion$female) - expect_warning(min_item_call(item_data = opinion), "Coercing factor") - }) - - test_that("factor values for just one of group_names in item_data produce a warning", { - opinion$race <- as.factor(opinion$race) - expect_warning(shape(opinion, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = c("female", "race")), - "Coercing factor") - }) - - test_that("item variables can be any type", { - items <- c("abortion", "affirmative_action", "stemcell_research", - "gaymarriage_amendment") - opinion[[items[1]]] <- as.character(opinion[[items[1]]]) - opinion[[items[2]]] <- as.ordered(opinion[[items[2]]]) - opinion[[items[3]]] <- as.logical(opinion[[items[3]]]) - opinion[[items[4]]] <- as.factor(opinion[[items[4]]]) - expect_silent(suppressMessages(min_item_call(item_data = opinion, - item_names = items))) - }) - - test_that("factor values of survey_name produce a warning", { - opinion$source <- as.factor(opinion$source) - expect_warning(min_item_call(item_data = opinion, survey_name = "source"), - "Coercing factor") - }) - - test_that("numeric values of survey_name produce an error", { - opinion$source <- suppressWarnings(as.numeric(opinion$source)) - expect_error(min_item_call(item_data = opinion, survey_name = "source"), - "should be character or factor") - }) - - test_that("non-integer values of time_name in item_data produce an error", { - opinion$year <- opinion$year + 0.5 - expect_error(min_item_call(item_data = opinion), "should be integer") - }) - - test_that("factor values of time_name in item_data produce an error", { - opinion$year <- as.factor(opinion$year) - expect_error(min_item_call(item_data = opinion), "should be integer") - }) - - test_that("character values of time_name in item_data produce an error", { - opinion$year <- as.character(opinion$year) - expect_error(min_item_call(item_data = opinion), "should be integer") - }) - - test_that("non-integer values of time_name in modifier_data work", { - states$year <- states$year + 0.5 - expect_error(min_modifier_call(modifier_data = states)) - }) - - test_that("factor values of time_name in modifier_data produce a warning", { - states$year <- as.factor(states$year) - expect_error(min_modifier_call(modifier_data = states), "should be integer or numeric") - }) - - test_that("character values of time_name in modifier_data produce an error", { - states$year <- as.character(states$year) - expect_error(min_modifier_call(modifier_data = states), "should be integer or numeric") - }) - - test_that("character values of weight_name in item_data produce an error", { - opinion$weight <- suppressWarnings(as.character(opinion$weight)) - expect_error(suppressWarnings(min_item_call(item_data = opinion, - weight_name = "weight")), "should be numeric") - }) - - test_that("factor values of weight_name in item_data produce an error", { - opinion$weight <- suppressWarnings(as.factor(opinion$weight)) - expect_error(min_item_call(item_data = opinion, weight_name = "weight"), - "should be numeric") - }) +context("input types") + +d_min <- shape(item_data = opinion, item_names = "abortion", time_name = + "year", geo_name = "state", group_names = "female") +d_mod <- shape(item_data = opinion, item_names = "abortion", time_name = + "year", geo_name = "state", group_names = "female", modifier_data = states, + modifier_names = "prop_evangelicals", t1_modifier_names = "prop_evangelicals") + +test_that("stop_if_empty works", { + x <- data.frame() + expect_error(dgo:::stop_if_empty(x), "all dimensions of x should be positive") +}) + +test_that("check_count works", { + expect_silent(dgo:::check_count(cars, "speed")) +}) + +test_that("check_count catches non-integers", { + data(cars) + cars$speed <- cars$speed + 0.5 + expect_error(dgo:::check_count(cars, "speed"), + "values of \"speed\" in cars should be positive integers") +}) + +test_that("check_count catches negative numbers", { + data(cars) + cars$speed <- cars$speed * -1 + expect_error(dgo:::check_count(cars, "speed"), + "values of \"speed\" in cars should be positive integers") +}) + +test_that("factor values for geo_name in item_data produce a warning", { + opinion$state <- as.factor(opinion$state) + expect_warning(min_item_call(item_data = opinion), "Coercing factor") +}) + +test_that("numeric values for geo_name produce an error", { + opinion$state <- suppressWarnings(as.numeric(opinion$state)) + expect_error(min_item_call(item_data = opinion), "should be one of: character, factor") }) + +test_that("factor values for geo_name in modifier_data produce a warning", { + states$state = as.factor(states$state) + expect_warning(min_modifier_call(modifier_data = states), "Coercing factor") +}) + +test_that("numeric values for geo_name in modifier data produce an error", { + states$state = suppressWarnings(as.numeric(states$state)) + expect_error(min_modifier_call(modifier_data = states), "should be one of: character, factor") +}) + +test_that("numeric values for group_names in item_data produce an error", { + opinion$female <- suppressWarnings(as.numeric(opinion$female)) + expect_error(min_item_call(item_data = opinion), "should be one of: character, factor") +}) + +test_that("factor values for group_names in item_data produce a warning", { + opinion$female <- as.factor(opinion$female) + expect_warning(min_item_call(item_data = opinion), "Coercing factor") +}) + +test_that("factor values for just one of group_names in item_data produce a warning", { + opinion$race <- as.factor(opinion$race) + expect_warning(shape(opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = c("female", "race")), + "Coercing factor") +}) + +test_that("item variables can be any type", { + items <- c("abortion", "affirmative_action", "stemcell_research", + "gaymarriage_amendment") + opinion[[items[1]]] <- as.character(opinion[[items[1]]]) + opinion[[items[2]]] <- as.ordered(opinion[[items[2]]]) + opinion[[items[3]]] <- as.logical(opinion[[items[3]]]) + opinion[[items[4]]] <- as.factor(opinion[[items[4]]]) + expect_silent(suppressMessages(min_item_call(item_data = opinion, + item_names = items))) +}) + +test_that("factor values of survey_name produce a warning", { + opinion$source <- as.factor(opinion$source) + expect_warning(min_item_call(item_data = opinion, survey_name = "source"), + "Coercing factor") +}) + +test_that("numeric values of survey_name produce an error", { + opinion$source <- suppressWarnings(as.numeric(opinion$source)) + expect_error(min_item_call(item_data = opinion, survey_name = "source"), + "should be one of: character, factor") +}) + +test_that("non-integer values of time_name in item_data produce an error", { + opinion$year <- opinion$year + 0.5 + expect_error(min_item_call(item_data = opinion), "should be integer") +}) + +test_that("factor values of time_name in item_data produce an error", { + opinion$year <- as.factor(opinion$year) + expect_error(min_item_call(item_data = opinion), "should be one of: integer, numeric") +}) + +test_that("character values of time_name in item_data produce an error", { + opinion$year <- as.character(opinion$year) + expect_error(min_item_call(item_data = opinion), "should be one of: integer, numeric") +}) + +test_that("non-integer values of time_name in modifier_data work", { + states$year <- states$year + 0.5 + expect_error(min_modifier_call(modifier_data = states)) +}) + +test_that("factor values of time_name in modifier_data produce a warning", { + states$year <- as.factor(states$year) + expect_error(min_modifier_call(modifier_data = states), "should be one of: integer, numeric") +}) + +test_that("character values of time_name in modifier_data produce an error", { + states$year <- as.character(states$year) + expect_error(min_modifier_call(modifier_data = states), "should be one of: integer, numeric") +}) + +test_that("character values of weight_name in item_data produce an error", { + opinion$weight <- suppressWarnings(as.character(opinion$weight)) + expect_error(suppressWarnings(min_item_call(item_data = opinion, + weight_name = "weight")), "should be one of: numeric") +}) + +test_that("factor values of weight_name in item_data produce an error", { + opinion$weight <- suppressWarnings(as.factor(opinion$weight)) + expect_error(min_item_call(item_data = opinion, weight_name = "weight"), + "should be one of: numeric") +}) + diff --git a/tests/testthat/test-varnames.r b/tests/testthat/test-varnames.r index ad78ee7..0354d53 100644 --- a/tests/testthat/test-varnames.r +++ b/tests/testthat/test-varnames.r @@ -1,105 +1,102 @@ source("setup.r") -suppressMessages({ - d_min <- min_item_call() - d_mod <- min_modifier_call() +d_min <- min_item_call() +d_mod <- min_modifier_call() - context("validation with valid_names") +context("validation with valid_names") - toy_table = data.frame(a = 1, b = 2) - Ctrl <- setClass("Ctrl", slots = list("valid_name" = "character", - "valid_names" = "character", "invalid_name" = "character", - "invalid_names" = "character", "partial" = "character", - "dupe_names" = "character", "missing_name" = "character", - "null_name" = "character")) +toy_table = data.frame(a = 1, b = 2) +Ctrl <- setClass("Ctrl", slots = list("valid_name" = "character", + "valid_names" = "character", "invalid_name" = "character", + "invalid_names" = "character", "partial" = "character", + "dupe_names" = "character", "missing_name" = "character", + "null_name" = "character")) - ctrl <- new("Ctrl", - valid_name = "a", - valid_names = c("a", "b"), - invalid_name = "x", - invalid_names = c("x", "y"), - partial = c("a", "x"), - dupe_names = c("a", "a"), - missing_name = "", - null_name = character(0)) +ctrl <- new("Ctrl", + valid_name = "a", + valid_names = c("a", "b"), + invalid_name = "x", + invalid_names = c("x", "y"), + partial = c("a", "x"), + dupe_names = c("a", "a"), + missing_name = "", + null_name = character(0)) - test_that("valid_names works with an S4 and length requirement", { - is_name <- valid_names(toy_table, ctrl, 1) - expect_silent(is_name("valid_name")) - expect_error(is_name("valid_names"), ".*should be length 1, not 2.*") - expect_error(is_name("valid_names"), ".*should be length 1, not 2.*") - expect_error(is_name("invalid_name"), ".*should give a variable name in.*") - expect_error(is_name("invalid_names"), ".*should be length 1, not 2.*") - expect_error(is_name("partial"), ".*should be length 1, not 2.*") - expect_error(is_name("dupe_names"), ".*should be length 1, not 2.*") - expect_error(is_name("missing_name"), ".*should give a variable name in.*") - expect_error(is_name("null_name"), ".*is required when using.*") +test_that("valid_names works with an S4 and length requirement", { + is_name <- dgo:::valid_names(toy_table, ctrl, 1) + expect_silent(is_name("valid_name")) + expect_error(is_name("valid_names"), ".*should be length 1, not 2.*") + expect_error(is_name("invalid_name"), ".*should give a variable name in.*") + expect_error(is_name("invalid_names"), ".*should be length 1, not 2.*") + expect_error(is_name("partial"), ".*should be length 1, not 2.*") + expect_error(is_name("dupe_names"), ".*should be length 1, not 2.*") + expect_error(is_name("missing_name"), ".*should give a variable name in.*") + expect_error(is_name("null_name"), ".*is required when using.*") }) - test_that("valid_names works with an S4 and no length requirement", { - are_names <- valid_names(toy_table, ctrl) - expect_silent(are_names("valid_name")) - expect_silent(are_names("valid_names")) - expect_error(are_names("invalid_name"), ".*should give variable names in.*") - expect_error(are_names("invalid_names"), ".*should give variable names in.*") - expect_error(are_names("partial"), ".*should give variable names in.*") - expect_error(are_names("dupe_names"), ".*should give unique names") - expect_error(are_names("missing_name"), ".*should give variable names in.*") - expect_error(are_names("null_name"), ".*is required when using.*") - }) +test_that("valid_names works with an S4 and no length requirement", { + are_names <- dgo:::valid_names(toy_table, ctrl) + expect_silent(are_names("valid_name")) + expect_silent(are_names("valid_names")) + expect_error(are_names("invalid_name"), ".*should give variable names in.*") + expect_error(are_names("invalid_names"), ".*should give variable names in.*") + expect_error(are_names("partial"), ".*should give variable names in.*") + expect_error(are_names("dupe_names"), ".*should give unique names") + expect_error(are_names("missing_name"), ".*should give variable names in.*") + expect_error(are_names("null_name"), ".*is required when using.*") +}) - test_that("valid_names works with plain character names and a length requirement", { - toy_table = data.frame(a = 1, b = 2) - is_name <- valid_names(toy_table, NULL, 1) - expect_silent(is_name("a")) - expect_silent(is_name(c("a", "b"))) - expect_error(is_name("z"), ".*should give a variable name in.*") - expect_error(is_name(2), ".*should give a variable name in.*") - }) +test_that("valid_names works with plain character names and a length requirement", { + toy_table = data.frame(a = 1, b = 2) + is_name <- dgo:::valid_names(toy_table, NULL, 1) + expect_silent(is_name("a")) + expect_silent(is_name(c("a", "b"))) + expect_error(is_name("z"), ".*should give a variable name in.*") + expect_error(is_name(2), ".*should give a variable name in.*") +}) - test_that("valid_names works with plain character names and no length requirement", { - are_names <- valid_names(toy_table, NULL, 0) - expect_silent(are_names(c("a", "b"))) - expect_error(are_names(c("a", "z")), ".*should give variable names in.*") - }) +test_that("valid_names works with plain character names and no length requirement", { + are_names <- dgo:::valid_names(toy_table, NULL, 0) + expect_silent(are_names(c("a", "b"))) + expect_error(are_names(c("a", "z")), ".*should give variable names in.*") +}) - context("required arguments for modifier_data") +context("required arguments for modifier_data") - test_that("either modifier_names or t1_modifier_names is required", { - expect_silent(suppressMessages(shape(opinion, - modifier_data = states, - t1_modifier_names = "prop_evangelicals", - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female"))) - expect_silent(suppressMessages(shape(opinion, - modifier_data = states, - modifier_names = "prop_evangelicals", - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female"))) - expect_error(suppressMessages(shape(opinion, - modifier_data = states, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female")), - "Either \"modifier_names\" or \"t1_modifier_names\" is required ", - "when using modifier data") - }) +test_that("either modifier_names or t1_modifier_names is required", { + expect_silent(suppressMessages(shape(opinion, + modifier_data = states, + t1_modifier_names = "prop_evangelicals", + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female"))) + expect_silent(suppressMessages(shape(opinion, + modifier_data = states, + modifier_names = "prop_evangelicals", + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female"))) + expect_error(suppressMessages(shape(opinion, + modifier_data = states, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female")), + paste("Either \"modifier_names\" or \"t1_modifier_names\" is required", + "when using modifier data")) +}) - context("required arguments for target_data") +context("required arguments for target_data") - expect_error(shape(opinion, - target_data = targets, - proportion_name = "proportion", - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - survey_name = "source", - weight_name = "weight"), - "raking.*required when using.*target_data") -}) + expect_error(shape(opinion, + target_data = targets, + proportion_name = "proportion", + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + survey_name = "source", + weight_name = "weight"), + "raking.*required when using.*target_data") diff --git a/tests/testthat/test-zz.r b/tests/testthat/test-zz.r index 7b56178..1564da3 100644 --- a/tests/testthat/test-zz.r +++ b/tests/testthat/test-zz.r @@ -1,106 +1,105 @@ source("setup.r") -suppressMessages({ - - d_min <- min_item_call() - d_mod <- min_modifier_call(standardize = FALSE) - data(states) - data.table::setDT(states) - states = states[year %in% 2006:2010] - - context("hierarchical parameter names") - - hier_names <- c(sort(unique(states$state))[-1], "femalemale") - - test_that('hier_name and ZZ dimnames match', { - expect_identical(hier_names, d_mod$hier_names) - expect_identical(hier_names, dimnames(d_mod$ZZ)[[2]]) - expect_identical(dimnames(d_mod$ZZ)[[3]], "prop_evangelicals") - expect_identical(dimnames(d_mod$ZZ_prior)[[3]], "prop_evangelicals") - }) - - context("hierarchical parameter counts") - - test_that('hier_names is a P-vector', { - expect_identical(length(hier_names), d_mod$P) - }) - - test_that('S is the count of geographic units - 1', { - expect_identical(d_min$S, length(d_min$geo_observed) - 1) - }) - - context("hierarchical modifier is numeric") - - test_that('values in ZZ are also numeric', { - expect_true(is.numeric(d_mod$ZZ)) - }) - - test_that('modifier values appear in the correct rows of ZZ', { - zz <- reshape2::acast(states[, .(year, state, prop_evangelicals)], - year ~ state ~ "prop_evangelicals", - value.var = 'prop_evangelicals', drop = FALSE) - # omit first hierarchical parameter - zz <- zz[, -1L, , drop = FALSE] - expect_identical(zz, d_mod$ZZ[, -dim(d_mod$ZZ)[2], , drop = FALSE]) - }) - - test_that('elements in ZZ corresponding to the grouping variable are zeroed', { - expect_identical(d_mod$ZZ[, length(hier_names), 1L], - setNames(rep(0, length(unique(states$year))), unique(states$year))) - }) - - context("hierarchical modifier is character") - - test_that('character values of modifier are dummied', { - # in legacy code, gave this error: Error in shape_hierarchical_data(level2, - # level2_modifiers, group_grid_t, : non-numeric values in hierarchical data. - # Factor handling probably failed. Possible quick fix: omit or manually dummy - # out any factors in 'level2_modifiers' or 'level2_period1_modif iers'. - expect_error(min_modifier_call(modifier_names = "region", - t1_modifier_names = "region"), - "should be integer or numeric") - }) - - test_that('elements in ZZ corresponding to the grouping variable are zeroed', { - expect_identical(d_mod$ZZ[, length(hier_names), 1L], - setNames(rep(0, length(unique(states$year))), unique(states$year))) - }) - - context("hierarchical modifier variable is factor") - - test_that('factor values of modifier are dummied', { - states$region <- as.factor(states$region) - expect_error(min_modifier_call(modifier_names = "region", - t1_modifier_names = "region"), - "should be integer or numeric") - }) - - test_that('ZZ is zeroed appropriately when only t1_modifier_names is given', { - - d_t1_only <- shape(item_data = opinion, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - modifier_data = states, - t1_modifier_names = "prop_evangelicals") - expect_true(all(d_t1_only$ZZ == 0)) - expect_identical(hier_names, d_t1_only$hier_names) - expect_identical(hier_names, dimnames(d_t1_only$ZZ)[[2]]) - expect_identical(dimnames(d_t1_only$ZZ)[[3]], "") - }) - - test_that('ZZ_prior defaults to ZZ', { - - d_tprime_only <- shape(item_data = opinion, - item_names = "abortion", - time_name = "year", - geo_name = "state", - group_names = "female", - modifier_data = states, - modifier_names = "prop_evangelicals") - expect_identical(d_tprime_only$ZZ_prior, d_tprime_only$ZZ) - expect_identical(hier_names, d_tprime_only$hier_names) - expect_identical(hier_names, dimnames(d_tprime_only$ZZ_prior)[[2]]) - }) +d_min <- min_item_call() +d_mod <- min_modifier_call(standardize = FALSE) +data(states) +data.table::setDT(states) +states = states[year %in% 2006:2010] + +context("hierarchical parameter names") + +hier_names <- c(sort(unique(states$state))[-1], "femalemale") + +test_that('hier_name and ZZ dimnames match', { + expect_identical(hier_names, d_mod$hier_names) + expect_identical(hier_names, dimnames(d_mod$ZZ)[[2]]) + expect_identical(dimnames(d_mod$ZZ)[[3]], "prop_evangelicals") + expect_identical(dimnames(d_mod$ZZ_prior)[[3]], "prop_evangelicals") +}) + +context("hierarchical parameter counts") + +test_that('hier_names is a P-vector', { + expect_identical(length(hier_names), d_mod$P) +}) + +test_that('S is the count of geographic units - 1', { + geo_observed <- length(unique(d_min$group_grid_t$state)) + expect_identical(d_min$S, geo_observed - 1) +}) + +context("hierarchical modifier is numeric") + +test_that('values in ZZ are also numeric', { + expect_true(is.numeric(d_mod$ZZ)) +}) + +test_that('modifier values appear in the correct rows of ZZ', { + zz <- reshape2::acast(states[, .(year, state, prop_evangelicals)], + year ~ state ~ "prop_evangelicals", + value.var = 'prop_evangelicals', drop = FALSE) + # omit first hierarchical parameter + zz <- zz[, -1L, , drop = FALSE] + expect_identical(zz, d_mod$ZZ[, -dim(d_mod$ZZ)[2], , drop = FALSE]) +}) + +test_that('elements in ZZ corresponding to the grouping variable are zeroed', { + expect_identical(d_mod$ZZ[, length(hier_names), 1L], + setNames(rep(0, length(unique(states$year))), unique(states$year))) +}) + +context("hierarchical modifier is character") + +test_that('character values of modifier are dummied', { + # in legacy code, gave this error: Error in shape_hierarchical_data(level2, + # level2_modifiers, group_grid_t, : non-numeric values in hierarchical data. + # Factor handling probably failed. Possible quick fix: omit or manually dummy + # out any factors in 'level2_modifiers' or 'level2_period1_modif iers'. + expect_error(min_modifier_call(modifier_names = "region", + t1_modifier_names = "region"), + "should be one of: integer, numeric") +}) + +test_that('elements in ZZ corresponding to the grouping variable are zeroed', { + expect_identical(d_mod$ZZ[, length(hier_names), 1L], + setNames(rep(0, length(unique(states$year))), unique(states$year))) +}) + +context("hierarchical modifier variable is factor") + +test_that('factor values of modifier are dummied', { + states$region <- as.factor(states$region) + expect_error(min_modifier_call(modifier_names = "region", + t1_modifier_names = "region"), + "should be one of: integer, numeric") +}) + +test_that('ZZ is zeroed appropriately when only t1_modifier_names is given', { + + d_t1_only <- shape(item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + modifier_data = states, + t1_modifier_names = "prop_evangelicals") + expect_true(all(d_t1_only$ZZ == 0)) + expect_identical(hier_names, d_t1_only$hier_names) + expect_identical(hier_names, dimnames(d_t1_only$ZZ)[[2]]) + expect_identical(dimnames(d_t1_only$ZZ)[[3]], "") }) + +test_that('ZZ_prior defaults to ZZ', { + + d_tprime_only <- shape(item_data = opinion, + item_names = "abortion", + time_name = "year", + geo_name = "state", + group_names = "female", + modifier_data = states, + modifier_names = "prop_evangelicals") + expect_identical(d_tprime_only$ZZ_prior, d_tprime_only$ZZ) + expect_identical(hier_names, d_tprime_only$hier_names) + expect_identical(hier_names, dimnames(d_tprime_only$ZZ_prior)[[2]]) +}) + diff --git a/exec/2016_09_14.stan b/tests/testthat/user-version.stan similarity index 85% rename from exec/2016_09_14.stan rename to tests/testthat/user-version.stan index 19bb958..b35873a 100644 --- a/exec/2016_09_14.stan +++ b/tests/testthat/user-version.stan @@ -12,6 +12,7 @@ data { int D; ## number of difficulty parameters per question int constant_item; ## indicator for constant item parameters int separate_t; ## indicator for no over-time smoothing + int hierarchical_model; ## Flag for whether to run hierarchical model, 1=T real delta_tbar_prior_mean; real delta_tbar_prior_sd; real innov_sd_delta_scale; @@ -60,15 +61,11 @@ transformed parameters { vector[Q] var_item; ## item variance vector[T] var_theta; ## within-group variance of theta ## var. of theta_bar w/in each level-two group **NOT CONSTRAINED TO BE POSITIVE** - vector[G_hier] var_theta_bar_l2[T]; vector[P] gamma[T]; ## hierarchical parameters (adjusted) vector[G] mu_theta_bar[T]; ## linear predictor for group means vector[P] mu_gamma[T]; vector[G] z[T, Q]; ## array of vectors of group deviates - vector[G_hier] z_l2[T, Q]; ## real prob[T, Q, G]; ## array of probabilities - vector[G_hier] prob_l2[T, Q]; ## array of probabilities - vector[G_hier] theta_l2[T]; ## second-level group abililities ## scale (product = 1) disc = disc_raw * pow(exp(sum(log(disc_raw))), (-inv(Q))); for (q in 1:Q) { @@ -130,48 +127,22 @@ transformed parameters { ##mu_theta_bar[t] = theta_bar[t - 1] * delta_tbar[t] + XX * gamma[t]; } ## Matt trick for group means - theta_bar[t] = mu_theta_bar[t] + sd_theta_bar[t] * theta_bar_raw[t]; #!# - ## Weighted average of group means (weights must sum to 1) - theta_l2[t] = WT[t] * theta_bar[t]; ## G_hierx1 = G_hierxG * Gx1 - for (n in 1:G_hier) { - matrix[G, G] WTdiag; - for (g in 1:G) { - for (h in 1:G) { - if (g == h) { - WTdiag[g, h] = WT[t][n][g]; - } - if (g != h) { - WTdiag[g, h] = 0; - } - } - } - ## (y - w'y)' W (y - w'y) = weighted variance - var_theta_bar_l2[t][n] = (theta_bar[t] - theta_l2[t, n])' * WTdiag * - (theta_bar[t] - theta_l2[t, n]); + if (hierarchical_model==1){ + theta_bar[t] = mu_theta_bar[t] + sd_theta_bar[t] * theta_bar_raw[t]; #!# } + if (hierarchical_model==0){ + theta_bar[t] = sd_theta_bar[t] * theta_bar_raw[t]; #!# + } +# theta_bar[t] = mu_theta_bar[t] + sd_theta_bar[t] * theta_bar_raw[t]; #!# for (q in 1:Q) { ## loop over questions real sd_tq; - real sd_l2_tq[G_hier]; sd_tq = sqrt(var_theta[t] + var_item[q]); - for (n in 1:G_hier) { - sd_l2_tq[n] = sqrt(square(sd_tq) + var_theta_bar_l2[t, n]); - } ## Group-level IRT model if (constant_item == 0) { z[t, q] = (theta_bar[t] - kappa[t][q]) / sd_tq; - for (n in 1:G_hier) { - z_l2[t, q, n] = - (theta_l2[t, n] - kappa[t][q]) / sd_l2_tq[n]; - prob_l2[t, q, n] = Phi_approx(z_l2[t, q, n]); - } } if (constant_item == 1) { z[t, q] = (theta_bar[t] - kappa[1][q]) / sd_tq; - for (n in 1:G_hier) { - z_l2[t, q, n] = - (theta_l2[t, n] - kappa[1][q]) / sd_l2_tq[n]; - prob_l2[t, q, n] = Phi_approx(z_l2[t, q, n]); - } } for (g in 1:G) { ## loop over groups if (Q == 1) { @@ -243,11 +214,6 @@ model { } for (q in 1:Q) { ## loop over questions - # skip until implemented - # if (l2_only[t, q] == 1) { - # ## Second-level mean - # SSl2[t, q] ~ binomial(NNl2[t, q], prob_l2[t, q]); - # } for (g in 1:G) { ## loop over groups pos = pos + 1; prob_vec[pos] = prob[t, q, g]; diff --git a/tools/make_cpp.R b/tools/make_cpp.R deleted file mode 100644 index 2fdb706..0000000 --- a/tools/make_cpp.R +++ /dev/null @@ -1,58 +0,0 @@ -# Part of the rstanarm package for estimating model parameters -# Copyright (C) 2015 Trustees of Columbia University -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 3 -# of the License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -options(warn = 3L) -stan_files <- dir("exec", pattern = "stan$", full.names = TRUE) -cat("#ifndef MODELS_HPP", "#define MODELS_HPP", - "#define STAN__SERVICES__COMMAND_HPP", "#include ", - sapply(stan_files, FUN = function(f) { - cppcode <- rstan::stanc_builder(f, - isystem = file.path("inst", "chunks"))$cppcode - cppcode <- gsub("typedef.*stan_model.*;", "", cppcode, perl = TRUE) - return(cppcode) - }), "#endif", file = file.path("src", "include", "models.hpp"), - sep = "\n", append = FALSE) - -options("useFancyQuotes" = FALSE) - -sapply(sub(".stan", "", basename(stan_files), fixed = TRUE), function(f) { - Rcpp::exposeClass(class = paste0("model_", f), - constructors = list(c("SEXP", "SEXP")), - fields = character(), - methods = c("call_sampler", - "param_names", - "param_names_oi", - "param_fnames_oi", - "param_dims", - "param_dims_oi", - "update_param_oi", - "param_oi_tidx", - "grad_log_prob", - "log_prob", - "unconstrain_pars", - "constrain_pars", - "num_pars_unconstrained", - "unconstrained_param_names", - "constrained_param_names"), - file = paste0(f, "Module.cc"), - header = '#include "include/models.hpp"', - module = paste0("stan_fit4", f, "_mod"), - CppClass = paste0("rstan::stan_fit "), - Rfile = FALSE) - return(invisible(NULL)) -}) diff --git a/wercker.yml b/wercker.yml deleted file mode 100644 index 0b557b6..0000000 --- a/wercker.yml +++ /dev/null @@ -1,5 +0,0 @@ -box: rocker/hadleyverse -build: - steps: - - jimhester/r-dependencies - - jimhester/r-check