diff --git a/DESCRIPTION b/DESCRIPTION index b324b90..9871364 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: HydeNet Type: Package Title: Hybrid Bayesian Networks Using R and JAGS -Version: 0.10.5 +Version: 0.10.8-01 Author: Jarrod E. Dalton and Benjamin Nutter Maintainer: Benjamin Nutter @@ -37,6 +37,7 @@ Imports: utils Suggests: knitr, + RCurl, survival, testthat VignetteBuilder: knitr @@ -45,4 +46,4 @@ LazyLoad: yes LazyData: true URL: https://github.com/nutterb/HydeNet, BugReports: https://github.com/nutterb/HydeNet/issues -RoxygenNote: 5.0.1 +RoxygenNote: 6.0.1 diff --git a/NAMESPACE b/NAMESPACE index 295469e..070e569 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -15,7 +15,7 @@ S3method(modelToNode,survreg) S3method(modelToNode,xtabs) S3method(plot,HydeNetwork) S3method(print,HydeNetwork) -S3method(print,HydePosterior) +S3method(print,HydeSim) S3method(print,cpt) S3method(summary,HydeNetwork) S3method(update,HydeNetwork) @@ -30,7 +30,9 @@ export("%>%") export(HydeNetwork) export(HydePlotOptions) export(HydePosterior) +export(HydeSim) export(bindPosterior) +export(bindSim) export(compileDecisionModel) export(compileJagsModel) export(cpt) @@ -53,7 +55,6 @@ export(writeNetworkModel) import(nnet) importFrom(dplyr,bind_rows) importFrom(dplyr,group_by_) -importFrom(dplyr,mutate) importFrom(dplyr,summarise) importFrom(gRbase,dag) importFrom(gRbase,graphNEL2adjMAT) @@ -65,7 +66,6 @@ importFrom(stats,as.formula) importFrom(stats,coef) importFrom(stats,terms) importFrom(stats,update) -importFrom(stringr,perl) importFrom(stringr,str_extract) importFrom(stringr,str_extract_all) importFrom(stringr,str_split_fixed) diff --git a/R/Hyde-package.R b/R/Hyde-package.R index 4bba86b..00a4854 100644 --- a/R/Hyde-package.R +++ b/R/Hyde-package.R @@ -7,7 +7,7 @@ #' probability distributions, where each node represents a random variable and #' each edge represents conditionality. The full joint distribution is #' therefore factorized as a product of conditional densities, where each node -#' is assumed to be independent of its non-desendents given information on its +#' is assumed to be independent of its non-descendants given information on its #' parent nodes. Since exact, closed-form algorithms are computationally #' burdensome for inference within hybrid networks that contain a combination #' of continuous and discrete nodes, particle-based approximation techniques diff --git a/R/HydeNetwork.R b/R/HydeNetwork.R index f872c93..109e2b0 100644 --- a/R/HydeNetwork.R +++ b/R/HydeNetwork.R @@ -44,7 +44,7 @@ #' to fitter functions. #' \item \code{nodeParams} A named list. Each element is a vector of parameters #' that will be expected by JAGS. -#' \item \code{fromData} A named list with the logical value of wheather parameters +#' \item \code{fromData} A named list with the logical value of whether parameters #' should be estimated from the data. #' \item \code{nodeData} A named list with the data for each node. If a node's #' entry in \code{fromData} is \code{TRUE} and \code{nodeData} is \code{NULL}, @@ -200,7 +200,7 @@ HydeNetwork.formula <- function(nodes, data=NULL, ...) FUN = is.factor, FUN.VALUE = logical(1))] factorLevels[factor_vars] <- - lapply(X = data[, factor_vars, drop = FALSE], + lapply(X = data[factor_vars], FUN = levels) } @@ -354,7 +354,7 @@ HydeNetwork_nodeFormula <- function(x, parents, data, fromData) { if (is.null(parents[[x]])) { - if (fromData[[names(parents)[x]]] & !is.numeric(data[, names(parents)[x]])) + if (fromData[[names(parents)[x]]] & !is.numeric(data[[names(parents)[x]]])) { f <- paste("~ ", names(parents)[x]) } @@ -381,24 +381,24 @@ HydeNetwork_nodeFitter <- function(node_name, data, parents) { return(NULL) } - else if (is.numeric(data[, node_name])) + else if (is.numeric(data[[node_name]])) { return("lm") } - else if (is.factor(data[, node_name]) & is.null(parents[[node_name]])) + else if (is.factor(data[[node_name]]) & is.null(parents[[node_name]])) { return("xtabs") } - else if (is.factor(data[, node_name]) & - all(vapply(parents[[node_name]], function(p) is.factor(data[, p]), logical(1)))) + else if (is.factor(data[[node_name]]) & + all(vapply(parents[[node_name]], function(p) is.factor(data[[p]]), logical(1)))) { return("cpt") } - else if (is.factor(data[, node_name]) & nlevels(data[, node_name]) == 2) + else if (is.factor(data[[node_name]]) & nlevels(data[[node_name]]) == 2) { return("glm") } - else if (is.factor(data[, node_name]) & nlevels(data[, node_name]) > 2) + else if (is.factor(data[[node_name]]) & nlevels(data[[node_name]]) > 2) { return("multinom") } @@ -417,10 +417,10 @@ HydeNetwork_nodeType <- function(node_name, data, parents, nodeFitter) if (node_name %in% names(data)) { if ((is.null(parents[[node_name]]) && - !is.numeric(data[, node_name])) || + !is.numeric(data[[node_name]])) || (!is.null(parents[[node_name]]) && - !is.numeric(data[, node_name]) && - nlevels(data[, node_name]) > 2)) + !is.numeric(data[[node_name]]) && + nlevels(data[[node_name]]) > 2)) { return('dcat') } @@ -429,10 +429,10 @@ HydeNetwork_nodeType <- function(node_name, data, parents, nodeFitter) return('dcat') } else if ((is.null(parents[[node_name]]) && - !is.numeric(data[, node_name])) || + !is.numeric(data[[node_name]])) || (!is.null(parents[[node_name]]) && - !is.numeric(data[, node_name]) && - nlevels(data[, node_name]) == 2)) + !is.numeric(data[[node_name]]) && + nlevels(data[[node_name]]) == 2)) { return('dbern') } diff --git a/R/HydePosterior.R b/R/HydePosterior.R index 16ed717..040a4c2 100644 --- a/R/HydePosterior.R +++ b/R/HydePosterior.R @@ -1,8 +1,8 @@ -#' @name HydePosterior -#' @export HydePosterior +#' @name HydeSim +#' @export HydeSim #' -#' @title Posterior Distributions of a Decision Network -#' @description The posterior distributions of the decision network can be +#' @title Simulated Distributions of a Decision Network +#' @description The simulated distributions of the decision network can be #' evaluated to determine the probabilistic outcomes based on the decision #' inputs in the model as well as subject specific factors. #' @@ -18,7 +18,7 @@ #' forced into \code{variable.names} if not already provided. This is #' recommended, especially if you will be binding multiple JAGS runs #' together. -#' @param bind Logical. If \code{TRUE}, posterior distributions will be bound into +#' @param bind Logical. If \code{TRUE}, simulated distributions will be bound into #' a single data frame. If \code{FALSE}, the standard output from \code{rjags} #' is returned. #' @@ -27,16 +27,12 @@ #' the rows of the policy/decision matrix given in the \code{data} argument #' of \code{compileJagsNetwork}. #' -#' @return A list of class \code{HydePosterior} with elements \code{codas} +#' @return A list of class \code{HydeSim} with elements \code{codas} #' (the MCMC matrices from \code{coda.samples}), \code{observed} (the values #' of the variables that were observed), \code{dag} (the dag object for #' convenience in displaying the network), and \code{factorRef} (giving the #' mappings of factor levels to factor variables). #' -#' The only rationale for giving this object its own class was because it -#' produces an enormous amount of material to be printed. A distinct -#' \code{print} method has been written for this object. -#' #' @author Jarrod Dalton and Benjamin Nutter #' #' @examples @@ -53,20 +49,20 @@ #' compiledNet <- compileJagsModel(Net, n.chains=5) #' #' #* Generate the posterior distribution -#' Posterior <- HydePosterior(compiledNet, +#' Posterior <- HydeSim(compiledNet, #' variable.names = c("d.dimer", "death"), #' n.iter = 1000) #' #' #* Posterior Distributions for a Decision Model #' Net <- setDecisionNodes(Net, angio, treat) #' decisionNet <- compileDecisionModel(Net, n.chains=5) -#' decisionsPost <- HydePosterior(decisionNet, +#' decisionsPost <- HydeSim(decisionNet, #' variable.names = c("d.dimer", "death"), #' n.iter = 1000) #' #' -HydePosterior <- function(cHN, variable.names, n.iter, thin=1, ..., +HydeSim <- function(cHN, variable.names, n.iter, thin=1, ..., monitor_observed=TRUE, bind=TRUE) { if (monitor_observed) @@ -121,10 +117,10 @@ HydePosterior <- function(cHN, variable.names, n.iter, thin=1, ..., - class(HydePost) <- "HydePosterior" + class(HydePost) <- "HydeSim" if (bind) { - bindPosterior(HydePost) + bindSim(HydePost) } else { @@ -132,3 +128,12 @@ HydePosterior <- function(cHN, variable.names, n.iter, thin=1, ..., } } + +#' @rdname HydeSim +#' @export + +HydePosterior <- function(...) +{ + message("`HydePoseterior` has been deprecated and replaced by `HydeSim`") + HydeSim(...) +} diff --git a/R/HydeUtilities.R b/R/HydeUtilities.R index 491d438..678f66e 100644 --- a/R/HydeUtilities.R +++ b/R/HydeUtilities.R @@ -1,12 +1,10 @@ #' @name HydeUtilities -#' @importFrom dplyr group_by_ -#' @importFrom dplyr mutate #' @importFrom magrittr %>% #' @export %>% #' #' @title Hyde Network Utility Functions #' @description The functions described below are unexported functions that -#' are used internally by \code{HydeNet} to prepare modify network objects +#' are used internally by \code{HydeNet} to prepare and modify network objects #' and prepare JAGS code. #' #' @details @@ -25,7 +23,7 @@ #' #' \code{matchLevelNumber}: Assigns the correct numeric value of a level to #' a factor variable in a model. This is called from within -#' \code{makeJagsRead}. +#' \code{makeJagsReady}. #' #' \code{matchVars}: Given a list of existing node names, the terms of a formula #' are matched to the node names. This allows functions to be used in @@ -89,8 +87,6 @@ termName <- function(term, reg) } #' @rdname HydeUtilities -#' @importFrom stringr perl -#' @importFrom stringr str_extract #' #' @param node Character string indicating a node in a network #' @param network A Hyde Network Object diff --git a/R/PolicyMatrix.R b/R/PolicyMatrix.R index 1f98540..332a5b5 100644 --- a/R/PolicyMatrix.R +++ b/R/PolicyMatrix.R @@ -29,19 +29,19 @@ #' enforced. Thus, it is possible to include numeric values in a decision #' matrix. #' -#' Policy matrices can be passed to \code{HydePosterior} to run posterior +#' Policy matrices can be passed to \code{HydeSim} to run posterior #' distributions on each row of the policy matrix. There is nothing #' particularly special about the policy matrices returned by #' \code{policyMatrix}; they are simply data frame that require names drawn #' from the nodes in the network. Any data frame can be passed to -#' \code{HydePosterior} and a check is done there to confirm all of the +#' \code{HydeSim} and a check is done there to confirm all of the #' column names match a node in the network. #' #' Whenever a node is identified as a deterministic node, its policy values #' are forced to \code{NULL}, regardless of what the user has specified. #' #' @return Returns a data frame built by \code{expand.grid} and intended to be -#' used with \code{HydePosterior}. +#' used with \code{HydeSim}. #' #' @author Jarrod Dalton and Benjamin Nutter #' diff --git a/R/bindPosterior.R b/R/bindPosterior.R index 10ecf31..f12b7f2 100644 --- a/R/bindPosterior.R +++ b/R/bindPosterior.R @@ -1,19 +1,19 @@ -#' @name bindPosterior +#' @name bindSim #' @importFrom dplyr bind_rows -#' @export bindPosterior +#' @export bindSim #' -#' @title Bind Posterior Distributions -#' @description After determining the posterior distributions are satisfactory, -#' it can be advantageous to bind the posterior distributions together in +#' @title Bind Simulated Distributions +#' @description After determining the simulated distributions are satisfactory, +#' it can be advantageous to bind the simulated distributions together in #' order to aggregate values and perform other manipulations and analyses. #' -#' @param hydePost An object of class \code{HydePosterior} +#' @param hydeSim An object of class \code{HydeSim} #' @param relabel_factor Logical. If \code{TRUE}, factors that had been #' converted to integers for the JAGS code can be relabelled as factors #' for additional analysis in R. #' #' @details For the purposes of this function, it is assumed that if the -#' posterior distributions are satisfactory, the multiple chains in a run +#' simulated distributions are satisfactory, the multiple chains in a run #' can be bound together. Subsequently, the multiple runs are bound #' together. Lastly, the factors are relabeled, if requested. #' @@ -32,31 +32,31 @@ #' #' compiledNet <- compileJagsModel(Net, n.chains=5) #' -#' #* Generate the posterior distribution -#' Posterior <- HydePosterior(compiledNet, -#' variable.names = c("d.dimer", "death"), -#' n.iter=1000) +#' #* Generate the simulated distribution +#' Simulated <- HydeSim(compiledNet, +#' variable.names = c("d.dimer", "death"), +#' n.iter=1000) #' -#' Bound <- bindPosterior(Posterior) +#' Bound <- bindSim(Simulated) #' #' #* Bind a Decision Network #' #* Note: angio shouldn't really be a decision node. #' #* We use it here for illustration #' Net <- setDecisionNodes(Net, angio, treat) #' compiledDecision <- compileDecisionModel(Net, n.chains=5) -#' PosteriorDecision <- HydePosterior(compiledDecision, -#' variable.names = c("d.dimer", "death"), -#' n.iter = 1000) +#' SimulatedDecision <- HydeSim(compiledDecision, +#' variable.names = c("d.dimer", "death"), +#' n.iter = 1000) #' -bindPosterior <- function(hydePost, relabel_factor=TRUE) +bindSim <- function(hydeSim, relabel_factor=TRUE) { - if (class(hydePost$codas) == "mcmc.list") + if (class(hydeSim$codas) == "mcmc.list") { bound <- dplyr::bind_rows( - lapply(seq_along(hydePost[["codas"]]), + lapply(seq_along(hydeSim[["codas"]]), bind_chains_mcmclist, - hydePost + hydeSim ) ) } @@ -64,7 +64,7 @@ bindPosterior <- function(hydePost, relabel_factor=TRUE) { bound <- dplyr::bind_rows( - lapply(hydePost[["codas"]], + lapply(hydeSim[["codas"]], bind_chains_list ) ) @@ -74,12 +74,12 @@ bindPosterior <- function(hydePost, relabel_factor=TRUE) #* replace the integers as factors. if (relabel_factor) { - factors_to_relabel <- names(bound)[names(bound) %in% names(hydePost$factorRef)] + factors_to_relabel <- names(bound)[names(bound) %in% names(hydeSim$factorRef)] for(i in factors_to_relabel) { bound[i] <- factor(bound[[i]], - levels=hydePost$factorRef[[i]]$value, - labels=hydePost$factorRef[[i]]$label) + levels=hydeSim$factorRef[[i]]$value, + labels=hydeSim$factorRef[[i]]$label) } } @@ -92,9 +92,9 @@ bindPosterior <- function(hydePost, relabel_factor=TRUE) #**** bind_chains_mcmclist is used when there is a single network (not a decision network) #**** bind_chains_list is used when a list of mcmclists is being bound, such as #**** when a decision network was run. -bind_chains_mcmclist <- function(mcmc, hydePost) +bind_chains_mcmclist <- function(mcmc, hydeSim) { - as.data.frame(hydePost$codas[[mcmc]]) %>% + as.data.frame(hydeSim$codas[[mcmc]]) %>% dplyr::mutate_( chain_index = ~mcmc, obs_index = ~1:n() @@ -115,3 +115,13 @@ bind_chains_list <- function(mcmc) ) %>% dplyr::bind_rows() } + + +#' @rdname bindSim +#' @export + +bindPosterior <- function(hydeSim, relabel_factor=TRUE) +{ + message("`bindPosterior` is deprecated and replaced by `bindSim`") + bindSim(hydeSim, relabel_factor=relabel_factor) +} \ No newline at end of file diff --git a/R/compileDecisionModel.R b/R/compileDecisionModel.R index 37ad321..ebc3cca 100644 --- a/R/compileDecisionModel.R +++ b/R/compileDecisionModel.R @@ -29,7 +29,7 @@ #' decision options are extracted from the JAGS statement returned by #' \code{writeJagsModel}. #' -#' The options for each decision nodes (if there are multiple nodes) are +#' The options for each decision node (if there are multiple nodes) are #' combined via \code{expand.grid} to make a table of all possible decisions. #' Each row of this table is passed as a list to the \code{data} argument #' of \code{jags.model} (via \code{compileJagsModel}) and a list of JAGS diff --git a/R/compileJagsModel.R b/R/compileJagsModel.R index 28f17f2..0aa229f 100644 --- a/R/compileJagsModel.R +++ b/R/compileJagsModel.R @@ -38,9 +38,9 @@ #' compiledNet <- compileJagsModel(Net, n.chains=5) #' #' #* Generate the posterior distribution -#' Posterior <- HydePosterior(compiledNet, -#' variable.names = c("d.dimer", "death"), -#' n.iter = 1000) +#' Posterior <- HydeSim(compiledNet, +#' variable.names = c("d.dimer", "death"), +#' n.iter = 1000) #' Posterior #' #' #* For a single model (ie, not a decision model), the user may choose to @@ -61,14 +61,15 @@ compileJagsModel <- function(network, data=NULL, ...) cpt_arrays <- makeCptArrays(network) #* The utilty function is in the #* file for compileDecisionModel - + jags <- rjags::jags.model( file = textConnection(writeNetworkModel(network)), data = if (is.null(data) & length(cpt_arrays) == 0) { - sys.frame(sys.parent()) + sys.frame(sys.parent()) + # .GlobalEnv } else { diff --git a/R/cpt.R b/R/cpt.R index e7b4aed..ed6d8c4 100644 --- a/R/cpt.R +++ b/R/cpt.R @@ -136,7 +136,7 @@ cpt.list <- function(x, data, wt, ...) #******** UNEXPORTED FUNCTION cpt_workhorse <- function(variables, dependentVar, independentVars, - data, wt, ...) + data, wt, na.rm=FALSE, ...) { wt_text <- if (missing(wt)) @@ -162,14 +162,24 @@ cpt_workhorse <- function(variables, dependentVar, independentVars, checkmate::assertDataFrame(data) - n <- nrow(data) - checkmate::assertSubset(variables, choices = names(data)) - lapply(data[, variables], + lapply(data[variables], checkmate::assertFactor, add = coll) + + vars <- c(dependentVar, independentVars) + + #check for NAs, remove if the user wants + completeData <- data %>% dplyr::filter(stats::complete.cases(.)) + if((nrow(data) != nrow(completeData)) * !na.rm){ + coll$push("Missing values in the supplied variable(s). See help('cpt')") + } + checkmate::reportAssertions(coll) + + data <- completeData + n <- nrow(data) if(missing(wt)) { @@ -213,7 +223,6 @@ cpt_workhorse <- function(variables, dependentVar, independentVars, checkmate::reportAssertions(coll) - vars <- c(dependentVar, independentVars) ..vars <- lapply(X = vars, FUN = as.symbol) ..independentVars <- lapply(X = independentVars, @@ -222,6 +231,7 @@ cpt_workhorse <- function(variables, dependentVar, independentVars, data <- dplyr::bind_cols(dplyr::tbl_df(data[,vars]), dplyr::tbl_df(data.frame(wt = wt))) + joint <- data %>% dplyr::group_by_(.dots = ..vars) %>% @@ -242,7 +252,7 @@ cpt_workhorse <- function(variables, dependentVar, independentVars, cpt[is.na(cpt)] <- 0 - model <- data[, c(names(dimnames(cpt)), "wt")] + model <- data[c(names(dimnames(cpt)), "wt")] if ("wt" %in% names(model) && !is.null(wt_text)) { diff --git a/R/data.R b/R/data.R index 6eff5ea..e06ba76 100644 --- a/R/data.R +++ b/R/data.R @@ -212,13 +212,17 @@ #' @format A data frame with 30 rows and 7 variables: #' \describe{ #' \item{DistName}{Distribution Name} -#' \item{FnName}{Function Name} +#' \item{FnName}{JAGS Function Name} +#' \item{FnNameR}{R Function Name} #' \item{xLow}{Minimum value for x, the random variable} #' \item{xHigh}{Maximum value for x, the random variable} -#' \item{Parameters}{Names of the parameters} +#' \item{Parameters}{Names of the JAGS parameters} +#' \item{RParameter}{R function argument name} #' \item{paramLimit}{Limits on the parameter} #' \item{paramLogic}{The text of a logical check used in \code{setNode} to #' ensure stated parameters are valid.} +#' \item{Rsupport}{Logical value, indicating if an R equivalent is +#' supported by \code{HydeNet}} #' } #' @source \url{http://people.math.aau.dk/~kkb/Undervisning/Bayes14/sorenh/docs/jags_user_manual.pdf} "jagsDists" diff --git a/R/expectedVariables.R b/R/expectedVariables.R index 62a997e..d1735ef 100644 --- a/R/expectedVariables.R +++ b/R/expectedVariables.R @@ -20,8 +20,7 @@ #' \code{returnVector} will generally be set to \code{FALSE} for most uses, #' but can be set to \code{TRUE} for use in error checking. For example, #' in \code{setNode}, if not all of the parents have been given a coefficient -#' (or if too few coefficients have been given), the vector of names is usually -#' more useful for giving informative error messages. +#' (or if too few coefficients have been given), the vector of names is supplied. #' #' @author Jarrod Dalton and Benjamin Nutter #' @examples @@ -68,7 +67,35 @@ expectedParameters <- function(network, node, returnVector=FALSE) node <- as.character(substitute(node)) inputs <- network[["nodeType"]][[node]] - params <- jagsDists[["Parameters"]][jagsDists[["FnName"]] == inputs] + params <- jagsDists[["RParameter"]][jagsDists[["FnName"]] == inputs] + + names(params) <- jagsDists[["Parameters"]][jagsDists[["FnName"]] == inputs] + + if (returnVector) + { + return(params) + } + else + { + cat( + paste( + paste( + paste0(params, "= "), + collapse=", " + ) + ) + ) + } +} + + +expectedParameters_ <- function(network, node, returnVector=FALSE) +{ + inputs <- network[["nodeType"]][[node]] + + params <- jagsDists[["RParameter"]][jagsDists[["FnName"]] == inputs] + + names(params) <- jagsDists[["Parameters"]][jagsDists[["FnName"]] == inputs] if (returnVector) { diff --git a/R/factorFormula.R b/R/factorFormula.R index 1e121bb..649c2ed 100644 --- a/R/factorFormula.R +++ b/R/factorFormula.R @@ -16,14 +16,9 @@ #' @details It is assumed that factor variables will be used in logical #' comparisons of the format \code{[variable_name] == '[factor_level]'} and #' only this pattern is recognized in the text search. Single or -#' double quotes may be used around the level, and the spaces aroudn the +#' double quotes may be used around the level, and the spaces around the #' \code{==} are optional. #' -#' While there are certainly limitations to this function that we have -#' not yet found, we believe it covers the majority of cases in which -#' it is useful. More complex cases that can't be handled by -#' \code{factorFormula} may require writing native JAGS code. -#' #' @author Jarrod Dalton and Benjamin Nutter #' #' @examples diff --git a/R/factorRegex.R b/R/factorRegex.R index 7eeb4f1..1e22b36 100644 --- a/R/factorRegex.R +++ b/R/factorRegex.R @@ -4,8 +4,7 @@ #' @title Produce Regular Expressions for Extracting Factor Names and Levels #' @description A utility function to produce a regular expression that can #' separate factor names and factor levels in the \code{broom::tidy()$term} -#' output. At some point, this may have to become a method to accomodate -#' different model types, but I haven't run into that problem yet. +#' output. #' #' @param fit a model object #' @@ -40,7 +39,3 @@ factorRegex <- function(fit){ NULL } } - - - - diff --git a/R/inputCPT.R b/R/inputCPT.R index a12f184..db7cf57 100644 --- a/R/inputCPT.R +++ b/R/inputCPT.R @@ -169,7 +169,7 @@ inputCPT_workhorse <- function(variables, dependentVar, independentVars, " as the complement of the inputted probabilities Pr(", dependentVar, " != ",factorLevels[[dependentVar]][1]," | ", paste(independentVars,collapse=", "), ").\n", hbar,sep="") - data <- data[data[,dependentVar] %in% levels(data[,dependentVar])[-1],] + data <- data[data[dependentVar] %in% levels(data[dependentVar])[-1],] cat("Enter the following conditional probabilities:\n") } else @@ -180,7 +180,7 @@ inputCPT_workhorse <- function(variables, dependentVar, independentVars, cat("Use '' to halt execution.\n", "To go back one step and re-enter, enter ''.\n", hbar, sep="") - formattedDepVarLvls <- format(as.character(data[,dependentVar]), + formattedDepVarLvls <- format(as.character(data[dependentVar]), width = facValWidths[dependentVar]) noNegativeProbs <- FALSE @@ -251,7 +251,7 @@ inputCPT_workhorse <- function(variables, dependentVar, independentVars, complementProbs <- plyr::ddply(data, independentVars, function(data) c("wt" = 1-sum(data[["wt"]]))) - complementProbs[,dependentVar] <- levels(data[, dependentVar])[1] + complementProbs[,dependentVar] <- levels(data[dependentVar])[1] data <- rbind(data, complementProbs) if(min(data$wt)>=0) { diff --git a/R/modelToNode.R b/R/modelToNode.R index c1faaa1..a900a6f 100644 --- a/R/modelToNode.R +++ b/R/modelToNode.R @@ -15,9 +15,7 @@ #' #' @description For models built with \code{xtabs}, although a data frame may be #' passed when building the model, it is not stored in the object. Thus, -#' the data used to construct the models are not carried with the node. However, -#' the JAGS code is built appropriate from the object and this should be of -#' little concern. +#' the data used to construct the models are not carried with the node. modelToNode <- function(model, nodes, ...) { diff --git a/R/plot.HydeNetwork.R b/R/plot.HydeNetwork.R index d98aa1f..fdd7d60 100644 --- a/R/plot.HydeNetwork.R +++ b/R/plot.HydeNetwork.R @@ -4,7 +4,7 @@ #' @method plot HydeNetwork #' #' -#' @title Plotting Utilities Probabilistic Graphical Network +#' @title Plotting Utilities for Probabilistic Graphical Network #' @description Generate and customize plots of a \code{HydeNetwork} #' class network. \code{HydeNet} provides some initial defaults for standard #' variable nodes, deterministic nodes, decision nodes, and utility nodes. @@ -61,8 +61,7 @@ #' \url{http://rich-iannone.github.io/DiagrammeR/graphviz_and_mermaid.html}\cr #' See especially the section on Attributes #' -#' \url{http://graphviz.org/}\cr -#' \url{http://graphviz.org/content/attrs} +#' \url{http://graphviz.org/} #' #' @examples #' \dontrun{ diff --git a/R/print.HydeNetwork.R b/R/print.HydeNetwork.R index 05821d7..c05b77c 100644 --- a/R/print.HydeNetwork.R +++ b/R/print.HydeNetwork.R @@ -28,7 +28,7 @@ #' print(Net, d.dimer) #' #' Net <- setNode(Net, d.dimer, -#' nodeType='dnorm', mu=fromData(), tau=fromData(), +#' nodeType='dnorm', mean=fromData(), sd=fromData(), #' nodeFormula = d.dimer ~ pregnant + pe, #' nodeFitter='lm') #' print(Net, d.dimer) diff --git a/R/print.HydePosterior.R b/R/print.HydePosterior.R index cd1e73d..e57e039 100644 --- a/R/print.HydePosterior.R +++ b/R/print.HydePosterior.R @@ -1,11 +1,11 @@ -#' @name print.HydePosterior +#' @name print.HydeSim #' @export -#' @method print HydePosterior +#' @method print HydeSim #' -#' @title Print a Hyde Posterior Distribution Object -#' @description Prints a brief description of a HydePosterior object. +#' @title Print a Hyde Simulated Distribution Object +#' @description Prints a brief description of a HydeSim object. #' -#' @param x a \code{HydePosterior} object +#' @param x a \code{HydeSim} object #' @param ... additional arguments to be passed to print methods. Currently #' none in use. #' @@ -30,19 +30,19 @@ #' #' #* Generate the posterior distribution for the model (but not the #' #* decision model) -#' Posterior <- HydePosterior(compiledNet, +#' Posterior <- HydeSim(compiledNet, #' variable.names = c("d.dimer", "death"), #' n.iter = 1000) #' Posterior #' #' #* Generate the posterior for the decision model #' Decision <- compileDecisionModel(Net, n.chains=5) -#' Posterior_decision <- HydePosterior(Decision, +#' Posterior_decision <- HydeSim(Decision, #' variable.names = c("d.dimer", "death"), #' n.iter = 1000) #' -print.HydePosterior <- function(x, ...){ +print.HydeSim <- function(x, ...){ n_distributions <- if (class(x$codas) == "mcmc.list") { diff --git a/R/rewriteHydeFormula.R b/R/rewriteHydeFormula.R index bc67416..294f3fe 100644 --- a/R/rewriteHydeFormula.R +++ b/R/rewriteHydeFormula.R @@ -8,8 +8,7 @@ #' @title Rewrite HydeNetwork Graph Model Formula #' @description This is a convenience function used to assist in the updating #' of \code{HydeNetwork} network objects. It makes it possible to add and -#' subtract individual parent relationships without deleting an entire node. -#' It's still a work in progress. +#' subtract individual parent relationships without deleting an entire node. #' #' @param old_form The current formula in a \code{HydeNetwork} object. #' @param new_form The formula specifications to be added diff --git a/R/setNode.R b/R/setNode.R index e9f0e71..aceb0b7 100644 --- a/R/setNode.R +++ b/R/setNode.R @@ -11,17 +11,16 @@ #' #' @param network A \code{HydeNetwork}. #' @param node A node within \code{network}. This does not have to be quoted. -#' @param nodeType a valid distribution function from JAGS. See the data set -#' in \code{data(jagsDists)} for a complete list. +#' @param nodeType a valid distribution. See the data set +#' in \code{data(jagsDists)} for a complete list of available distributions. +#' See "Choosing a Node Type" #' @param nodeFitter the fitting function, such as \code{lm} or \code{glm}. This #' will probably only be needed when \code{fromData = TRUE}. #' @param nodeFormula A formula object specifying the relationship between a #' node and its parents. It must use as a term every parent of \code{node}. This formula #' will be pushed through the unexported function \code{factorFormula}. See #' "Coding Factor Levels" for more details. -#' @param fitterArgs Additional arguments to be passed to \code{fitter}. This does not -#' yet have any effect as I haven't yet decided out where to store this and -#' how to implement the fitting. +#' @param fitterArgs Additional arguments to be passed to \code{fitter}. #' @param decision A value of either \code{"current"} or a logical value. #' If \code{"current"}, the current value of the setting is retained. This allows #' decision nodes set by \code{setDecisionNode} to retain the classification as a @@ -46,7 +45,7 @@ #' \code{network} has a data object. #' @param ... parameters to be passed to the JAGS distribution function. Each parameter #' in the distribution function must be named. For -#' example, the parameters to pass to \code{dnorm} would be \code{mu='', tau=''}. +#' example, the parameters to pass to \code{dnorm} would be \code{mean='', sd=''}. #' The required parameters can be looked up using the #' \code{expectedParameters} function. If parameters are to be estimated #' from the data, the functions \code{fromData} and \code{fromFormula} may @@ -97,6 +96,26 @@ #' will cause the model to be fit and the JAGS code for the parameters to be #' stored in the \code{nodeParams} attribute. #' +#' @return +#' Returns the modified \code{HydeNetwork} object. +#' +#' @section Choosing a Node Type: +#' Many of the distribution functions defined in JAGS have an equivalen +#' distribution function in R. You may inspect the \code{jagsDists} data +#' frame to see the function names in each language. You may specify +#' the distribution function using the R name and it will be translated +#' to the equivalent JAGS function. +#' +#' You may still use the JAGS names, which allows you to specify a +#' distribution in JAGS that does not have an R equivalent listed. Note, +#' however, that where R functions are supported, \code{HydeNet} anticipates +#' the parameter names to be given following R conventions (See +#' the \code{RParameter} column of \code{jagsDists}.) +#' +#' Of particular interest are \code{dbern} and \code{dcat}, which are +#' functions in JAGS that have no immediate equivalent in R. They provide +#' Bernoulli and Multinomial distributions, respectively. +#' #' @section Coding Factor Levels: #' The \code{nodeFormula} argument will accept any valid R formula. If desired, you #' may use a specific formulation to indicate the presence of factor levels in the @@ -118,7 +137,7 @@ #' The validation of parameters is performed by comparing the values provided with #' the limits defined in the \code{jagsDists$paramLogic} variable. (look at #' \code{data(jagsDists, data='HydeNet')}. For most node types, validation will -#' be peformed for numeric variables. For deterministic variables, the validation +#' be performed for numeric variables. For deterministic variables, the validation #' will only check that the parameter definition is a formula. #' #' It is possible to pass character strings as definitions, but when this is done, @@ -148,7 +167,7 @@ #' print(Net, d.dimer) #' #' #* Manually change the precision -#' Net <- setNode(Net, d.dimer, nodeType='dnorm', mu=fromFormula(), tau=1/2.65, +#' Net <- setNode(Net, d.dimer, nodeType='dnorm', mean=fromFormula(), sd=sqrt(2.65), #' nodeFormula = d.dimer ~ pregnant * pe, #' nodeFitter='lm') #' print(Net, d.dimer) @@ -215,11 +234,32 @@ setNode <- function(network, node, nodeType, exp_param <- eval(substitute(expectedParameters(network = network, node = node, returnVector = TRUE))) - params <- list(...)[exp_param] + + params <- list(...) + + names(params)[!exp_param %in% names(params)] <- + exp_param[!exp_param %in% names(params)] + + + params <- params[exp_param] + + # JAGS dnorm expects tau = 1/variance. + # HydeNet accepts sd, so we need to transform this. + if (nodeType == "dnorm") + { + if ("sd" %in% names(params)) + if (is.numeric(params[["sd"]])) + params[["sd"]] <- 1 / params[["sd"]]^2 + } checkmate::assertSubset(x = exp_param, choices = names(params), add = coll) + orig_names <- names(params) + + names(params) <- + jagsDists[["Parameters"]][jagsDists$FnName == nodeType & + jagsDists$RParameter %in% names(params)] if (validate){ valid <- validateParameters(params, network[["nodeType"]][[node.t]]) @@ -234,7 +274,7 @@ setNode <- function(network, node, nodeType, if (!all(valid)) { not_valid <- which(!valid) - msg <- paste0("Please define ", names(params)[not_valid], " such that ", names(valid)[not_valid], + msg <- paste0("Please define ", orig_names[not_valid], " such that ", names(valid)[not_valid], " (or use validate=FALSE).") msg <- paste(msg, collapse="\n") coll$push(msg) @@ -254,7 +294,6 @@ setNode <- function(network, node, nodeType, choices = "determ", add = coll) - if (any(sapply(X = network$parents, FUN = function(p, t) t %in% p, node.t))) coll$push("Utility nodes may not have children.") @@ -285,7 +324,7 @@ setNode <- function(network, node, nodeType, { network[["nodeData"]][[node.t]] <- nodeData } - + if (!is.null(factorLevels)) { nodeFitter <- diff --git a/R/summary.HydeNetwork.R b/R/summary.HydeNetwork.R index c2da4b9..b5948b9 100644 --- a/R/summary.HydeNetwork.R +++ b/R/summary.HydeNetwork.R @@ -48,26 +48,26 @@ summary.HydeNetwork <- function(object, ...) decision_node_summary <- function(object, nodes) { name_summary <- summarise_node_name(nodes) - parent_summary <- summarise_parents(object, nodes, max(nchar(name_summary))) - policy_summary <- summarise_policy(object, nodes, - max(nchar(name_summary)), - max(nchar(parent_summary))) - + ns_charwid <- ifelse(length(name_summary)>0, max(nchar(name_summary)), 0) + parent_summary <- summarise_parents(object, nodes, ns_charwid) + ps_charwid <- ifelse(length(parent_summary)>0, max(nchar(parent_summary)), 0) + policy_summary <- summarise_policy(object, nodes, ns_charwid, ps_charwid) paste0(name_summary, parent_summary, policy_summary, collapse = "\n") } utility_node_summary <- function(object, nodes) { name_summary <- summarise_node_name(nodes) - parent_summary <- summarise_parents(object, nodes, max(nchar(name_summary)), end_sep = "") - + ns_charwid <- ifelse(length(name_summary)>0, max(nchar(name_summary)), 0) + parent_summary <- summarise_parents(object, nodes, ns_charwid, end_sep = "") paste0(name_summary, parent_summary, collapse = "\n") } random_node_summary <- function(object, nodes) { name_summary <- summarise_node_name(nodes) - parent_summary <- summarise_parents(object, nodes, max(nchar(name_summary))) + ns_charwid <- ifelse(length(name_summary)>0, max(nchar(name_summary)), 0) + parent_summary <- summarise_parents(object, nodes, ns_charwid, end_sep = "") type_summary <- summarise_type(object, nodes) paste0(name_summary, parent_summary, type_summary, collapse = "\n") @@ -76,9 +76,8 @@ random_node_summary <- function(object, nodes) summarise_node_name <- function(nodes, max.width = 20) { - max.width <- min(c(max.width, - max(nchar(nodes)) + 3)) - + if(length(nodes)>0) max.width <- min(c(max.width, max(nchar(nodes))+3)) + ifelse(test = nchar(nodes) > (max.width - 2), yes = paste0(substr(nodes, 1, 14), "... | "), no = paste0(stringr::str_pad(string = nodes, @@ -104,11 +103,12 @@ summarise_parents <- function(object, nodes, name_width, end_sep = " | ") yes = "1 parent", no = paste0(nparents, " parents ")), parents) + parents <- + stringr::str_pad(string = parents, + width = ifelse(length(parents)>0, max(nchar(parents)), 0)+1, + side = "right") - paste0(stringr::str_pad(string = parents, - width = max(nchar(parents)), - side = "right"), - end_sep) + if(length(parents)>0) paste0(parents, end_sep) else "" } summarise_policy <- function(object, nodes, name_width, parent_width) diff --git a/R/sysdata.rda b/R/sysdata.rda index 29e94d0..d53dd06 100644 Binary files a/R/sysdata.rda and b/R/sysdata.rda differ diff --git a/R/update.HydeNetwork.R b/R/update.HydeNetwork.R index e11fcf7..6b353d4 100644 --- a/R/update.HydeNetwork.R +++ b/R/update.HydeNetwork.R @@ -12,11 +12,8 @@ #' none are used. #' #' @details Adding or removing nodes is fairly straightforward if you are -#' removing a complete node (along with its parents). If you just wish to -#' remove a parent, this doesn't work well yet. I will have to work out -#' a solution to remove parent relationships individually. I had hoped -#' there would be an \code{update.dag} method, but no luck. This will continue -#' to be developed in the future, but the arguments will remain the same. +#' removing a complete node (along with its parents). Removing a parent +#' will generate a warning that the child nodes may need to be redefined. #' #' @author Jarrod Dalton and Benjamin Nutter #' diff --git a/R/writeJagsFormula.R b/R/writeJagsFormula.R index 2dd1532..1410b79 100644 --- a/R/writeJagsFormula.R +++ b/R/writeJagsFormula.R @@ -69,7 +69,8 @@ writeJagsFormula.glm <- function(fit, nodes, bern = bern, ...) { if (fit[["family"]][["family"]] == "gaussian" & fit[["family"]][["link"]] == "identity") { - return(writeJagsFormula.lm(fit)) + return(writeJagsFormula.lm(fit, + descriptors = c("term", "term_plain", "level"))) } mdl <- suppressWarnings( @@ -83,7 +84,7 @@ writeJagsFormula.glm <- function(fit, nodes, bern = bern, ...) mdl <- makeJagsReady(mdl, factorRef = factor_reference(stats::model.frame(fit)), bern = bern) %>% - mutate(term_plain = gsub(pattern = ":", + dplyr::mutate(term_plain = gsub(pattern = ":", replacement = "*", x = term_plain)) @@ -131,7 +132,7 @@ writeJagsFormula.lm <- function(fit, nodes, bern, ...) mdl <- makeJagsReady(mdl, factorRef = factor_reference(stats::model.frame(fit)), bern = bern) %>% - mutate(term_plain = gsub(pattern = ":", + dplyr::mutate(term_plain = gsub(pattern = ":", replacement = "*", x = term_plain)) diff --git a/R/writeJagsModel.R b/R/writeJagsModel.R index 88cc7d6..2b6fb46 100644 --- a/R/writeJagsModel.R +++ b/R/writeJagsModel.R @@ -26,6 +26,7 @@ #' @seealso \code{\link{writeJagsFormula}} #' #' @examples +#' \dontrun{ #' #* NOTE: writeJagsModel isn't an exported function #' data(PE, package='HydeNet') #' Net <- HydeNetwork(~ wells + @@ -37,6 +38,7 @@ #' data = PE) #' HydeNet:::writeJagsModel(Net, 'pe') #' HydeNet:::writeJagsModel(Net, 'treat') +#' } #' @@ -49,15 +51,12 @@ writeJagsModel <- function(network, node) node_params <- network[["nodeParams"]][[node_str]] params <- - eval( - substitute( - expectedParameters(network = network, - node = node, - returnVector = TRUE - ) - ) - ) - + expectedParameters_(network = network, + node = node, + returnVector = TRUE) + + names(node_params) <- names(params) + switch( network[["nodeType"]][[node_str]], "dbern" = writeJagsModel_dbern(network = network, diff --git a/cran-comments.md b/cran-comments.md index cec4676..e8cdb21 100644 --- a/cran-comments.md +++ b/cran-comments.md @@ -1,15 +1,13 @@ -This update fixes errors introduced with `DiagrammeR` 0.9.0 +This update provides fixes to design features that failed to meet the specification design. It permits the user to define distribution parameters using either the R distribution function argument, or the JAGS distribution function argument. ## Test environments -* win-builder (release) -* local windows install R 3.3.2 -* local windows install R-devel 2017-01-05 r71919 +* win-builder (devel 2017-09-12 r73242) +* Local Linux install R 3.4.3 (Ubuntu 16.05.3 LTS) +* Travis CI Linux install R 3.4.2 (Ubuntu 14.04.5 LTS) ## R CMD check results -A NOTE was returned by win-builder (release and devel) regarding -potential spelling errors; all words in the DESCRIPTION file are -correctly spelled. +There were no findings from the CHECK results ## Downstream dependencies There are no downstream dependencies for this package diff --git a/data/jagsDists.RData b/data/jagsDists.RData index 2e263e8..710fc26 100644 Binary files a/data/jagsDists.RData and b/data/jagsDists.RData differ diff --git a/data/jagsFunctions.RData b/data/jagsFunctions.RData index 5f370f2..d425221 100644 Binary files a/data/jagsFunctions.RData and b/data/jagsFunctions.RData differ diff --git a/man/BJDealer.Rd b/man/BJDealer.Rd index 3736504..2153886 100644 --- a/man/BJDealer.Rd +++ b/man/BJDealer.Rd @@ -26,4 +26,3 @@ cards; only one of the dealer's cards is shown, and this is called the "upcard") } \keyword{datasets} - diff --git a/man/BlackJack.Rd b/man/BlackJack.Rd index bab96e5..0d99aed 100644 --- a/man/BlackJack.Rd +++ b/man/BlackJack.Rd @@ -167,4 +167,3 @@ BlackJack <- setUtilityNodes(BlackJack, payoff) } \keyword{datasets} - diff --git a/man/BlackJackTrain.Rd b/man/BlackJackTrain.Rd index 9443611..7f2937c 100644 --- a/man/BlackJackTrain.Rd +++ b/man/BlackJackTrain.Rd @@ -31,4 +31,3 @@ BlackJackTrain These are simulated data on 1,000 Black Jack hands. } \keyword{datasets} - diff --git a/man/Hyde-package.Rd b/man/Hyde-package.Rd index a2eafd7..9e344dd 100644 --- a/man/Hyde-package.Rd +++ b/man/Hyde-package.Rd @@ -1,8 +1,8 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/Hyde-package.R \name{Hyde-package} -\alias{Hyde} \alias{Hyde-package} +\alias{Hyde} \title{Hydbrid Decision Networks} \description{ Facilities for easy implementation of hybrid Bayesian networks @@ -10,7 +10,7 @@ using R. Bayesian networks are directed acyclic graphs representing joint probability distributions, where each node represents a random variable and each edge represents conditionality. The full joint distribution is therefore factorized as a product of conditional densities, where each node -is assumed to be independent of its non-desendents given information on its +is assumed to be independent of its non-descendants given information on its parent nodes. Since exact, closed-form algorithms are computationally burdensome for inference within hybrid networks that contain a combination of continuous and discrete nodes, particle-based approximation techniques @@ -20,4 +20,3 @@ Econometric analyses (maximum expected utility under competing policies, value of information) involving decision and utility nodes are also supported. } - diff --git a/man/HydeNetSummaries.Rd b/man/HydeNetSummaries.Rd index 1a8861e..5e24314 100644 --- a/man/HydeNetSummaries.Rd +++ b/man/HydeNetSummaries.Rd @@ -19,4 +19,3 @@ Summaries of \code{HydeNetwork}, compiled network, and \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/HydeNetwork.Rd b/man/HydeNetwork.Rd index c5f0c9d..64a1840 100644 --- a/man/HydeNetwork.Rd +++ b/man/HydeNetwork.Rd @@ -37,7 +37,7 @@ list with the following components: to fitter functions. \item \code{nodeParams} A named list. Each element is a vector of parameters that will be expected by JAGS. - \item \code{fromData} A named list with the logical value of wheather parameters + \item \code{fromData} A named list with the logical value of whether parameters should be estimated from the data. \item \code{nodeData} A named list with the data for each node. If a node's entry in \code{fromData} is \code{TRUE} and \code{nodeData} is \code{NULL}, @@ -116,4 +116,3 @@ print(bagNet) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/HydePosterior.Rd b/man/HydeSim.Rd similarity index 77% rename from man/HydePosterior.Rd rename to man/HydeSim.Rd index 491c38a..98fc8af 100644 --- a/man/HydePosterior.Rd +++ b/man/HydeSim.Rd @@ -1,11 +1,14 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/HydePosterior.R -\name{HydePosterior} +\name{HydeSim} +\alias{HydeSim} \alias{HydePosterior} -\title{Posterior Distributions of a Decision Network} +\title{Simulated Distributions of a Decision Network} \usage{ -HydePosterior(cHN, variable.names, n.iter, thin = 1, ..., - monitor_observed = TRUE, bind = TRUE) +HydeSim(cHN, variable.names, n.iter, thin = 1, ..., monitor_observed = TRUE, + bind = TRUE) + +HydePosterior(...) } \arguments{ \item{cHN}{A \code{compiledHydeNetwork} object as returned by @@ -26,23 +29,19 @@ forced into \code{variable.names} if not already provided. This is recommended, especially if you will be binding multiple JAGS runs together.} -\item{bind}{Logical. If \code{TRUE}, posterior distributions will be bound into +\item{bind}{Logical. If \code{TRUE}, simulated distributions will be bound into a single data frame. If \code{FALSE}, the standard output from \code{rjags} is returned.} } \value{ -A list of class \code{HydePosterior} with elements \code{codas} +A list of class \code{HydeSim} with elements \code{codas} (the MCMC matrices from \code{coda.samples}), \code{observed} (the values of the variables that were observed), \code{dag} (the dag object for convenience in displaying the network), and \code{factorRef} (giving the - mappings of factor levels to factor variables). - - The only rationale for giving this object its own class was because it - produces an enormous amount of material to be printed. A distinct - \code{print} method has been written for this object. + mappings of factor levels to factor variables). } \description{ -The posterior distributions of the decision network can be +The simulated distributions of the decision network can be evaluated to determine the probabilistic outcomes based on the decision inputs in the model as well as subject specific factors. } @@ -66,14 +65,14 @@ Net <- HydeNetwork(~ wells + compiledNet <- compileJagsModel(Net, n.chains=5) #* Generate the posterior distribution -Posterior <- HydePosterior(compiledNet, +Posterior <- HydeSim(compiledNet, variable.names = c("d.dimer", "death"), n.iter = 1000) #* Posterior Distributions for a Decision Model Net <- setDecisionNodes(Net, angio, treat) decisionNet <- compileDecisionModel(Net, n.chains=5) -decisionsPost <- HydePosterior(decisionNet, +decisionsPost <- HydeSim(decisionNet, variable.names = c("d.dimer", "death"), n.iter = 1000) @@ -82,4 +81,3 @@ decisionsPost <- HydePosterior(decisionNet, \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/HydeUtilities.Rd b/man/HydeUtilities.Rd index fba21c4..1edba64 100644 --- a/man/HydeUtilities.Rd +++ b/man/HydeUtilities.Rd @@ -2,18 +2,18 @@ % Please edit documentation in R/HydeUtilities.R \name{HydeUtilities} \alias{HydeUtilities} -\alias{dataframeFactors} +\alias{termName} \alias{decisionOptions} -\alias{factor_reference} -\alias{makeFactorRef} \alias{makeJagsReady} \alias{matchLevelNumber} \alias{matchVars} \alias{nodeFromFunction} \alias{policyMatrixValues} \alias{polyToPow} -\alias{termName} \alias{validateParameters} +\alias{makeFactorRef} +\alias{dataframeFactors} +\alias{factor_reference} \title{Hyde Network Utility Functions} \usage{ termName(term, reg) @@ -84,7 +84,7 @@ a reference table (another data frame) is returned.} } \description{ The functions described below are unexported functions that - are used internally by \code{HydeNet} to prepare modify network objects + are used internally by \code{HydeNet} to prepare and modify network objects and prepare JAGS code. } \details{ @@ -103,7 +103,7 @@ The functions described below are unexported functions that \code{matchLevelNumber}: Assigns the correct numeric value of a level to a factor variable in a model. This is called from within - \code{makeJagsRead}. + \code{makeJagsReady}. \code{matchVars}: Given a list of existing node names, the terms of a formula are matched to the node names. This allows functions to be used in @@ -135,4 +135,3 @@ The functions described below are unexported functions that \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/PE.Rd b/man/PE.Rd index ca2029d..900aa91 100644 --- a/man/PE.Rd +++ b/man/PE.Rd @@ -24,4 +24,3 @@ PE These are simulated data on 10,000 cases with suspected pulmonary embolism at a hospital. } \keyword{datasets} - diff --git a/man/Resolution.cpt.Rd b/man/Resolution.cpt.Rd index 8d9f53b..deb484c 100644 --- a/man/Resolution.cpt.Rd +++ b/man/Resolution.cpt.Rd @@ -12,4 +12,3 @@ Resolution.cpt This is a conditional probability table used in the emesis example of the JSS article. } \keyword{datasets} - diff --git a/man/SE.cpt.Rd b/man/SE.cpt.Rd index d90d1ca..4d9ae70 100644 --- a/man/SE.cpt.Rd +++ b/man/SE.cpt.Rd @@ -12,4 +12,3 @@ SE.cpt This is a conditional probability table used in the emesis example of the JSS article. } \keyword{datasets} - diff --git a/man/TranslateFormula.Rd b/man/TranslateFormula.Rd index 4309679..dcd05b3 100644 --- a/man/TranslateFormula.Rd +++ b/man/TranslateFormula.Rd @@ -26,10 +26,9 @@ Only a limited subset of R functions are recognized here, but no \code{jagsFunctions} data set (use \code{data(jagsFunctions)} to review). } -\author{ -Jarrod Dalton and Benjamin Nutter -} \references{ \url{http://people.math.aau.dk/~kkb/Undervisning/Bayes14/sorenh/docs/jags_user_manual.pdf} } - +\author{ +Jarrod Dalton and Benjamin Nutter +} diff --git a/man/bindPosterior.Rd b/man/bindSim.Rd similarity index 62% rename from man/bindPosterior.Rd rename to man/bindSim.Rd index 6af3d92..a1155cd 100644 --- a/man/bindPosterior.Rd +++ b/man/bindSim.Rd @@ -1,26 +1,29 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/bindPosterior.R -\name{bindPosterior} +\name{bindSim} +\alias{bindSim} \alias{bindPosterior} -\title{Bind Posterior Distributions} +\title{Bind Simulated Distributions} \usage{ -bindPosterior(hydePost, relabel_factor = TRUE) +bindSim(hydeSim, relabel_factor = TRUE) + +bindPosterior(hydeSim, relabel_factor = TRUE) } \arguments{ -\item{hydePost}{An object of class \code{HydePosterior}} +\item{hydeSim}{An object of class \code{HydeSim}} \item{relabel_factor}{Logical. If \code{TRUE}, factors that had been converted to integers for the JAGS code can be relabelled as factors for additional analysis in R.} } \description{ -After determining the posterior distributions are satisfactory, - it can be advantageous to bind the posterior distributions together in +After determining the simulated distributions are satisfactory, + it can be advantageous to bind the simulated distributions together in order to aggregate values and perform other manipulations and analyses. } \details{ For the purposes of this function, it is assumed that if the - posterior distributions are satisfactory, the multiple chains in a run + simulated distributions are satisfactory, the multiple chains in a run can be bound together. Subsequently, the multiple runs are bound together. Lastly, the factors are relabeled, if requested. } @@ -37,24 +40,23 @@ Net <- HydeNetwork(~ wells + compiledNet <- compileJagsModel(Net, n.chains=5) -#* Generate the posterior distribution -Posterior <- HydePosterior(compiledNet, - variable.names = c("d.dimer", "death"), - n.iter=1000) +#* Generate the simulated distribution +Simulated <- HydeSim(compiledNet, + variable.names = c("d.dimer", "death"), + n.iter=1000) -Bound <- bindPosterior(Posterior) +Bound <- bindSim(Simulated) #* Bind a Decision Network #* Note: angio shouldn't really be a decision node. #* We use it here for illustration Net <- setDecisionNodes(Net, angio, treat) compiledDecision <- compileDecisionModel(Net, n.chains=5) -PosteriorDecision <- HydePosterior(compiledDecision, - variable.names = c("d.dimer", "death"), - n.iter = 1000) +SimulatedDecision <- HydeSim(compiledDecision, + variable.names = c("d.dimer", "death"), + n.iter = 1000) } \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/chain.Rd b/man/chain.Rd index ea61b80..66d76cb 100644 --- a/man/chain.Rd +++ b/man/chain.Rd @@ -1,8 +1,8 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/chain.R \name{\%>\%} -\alias{\%$\%} \alias{\%>\%} +\alias{\%$\%} \title{Chain together multiple operations.} \usage{ lhs \%>\% rhs @@ -23,4 +23,3 @@ This is a copy of the documentation for \code{\%$\%} in regarding documentation. Please see the \code{magrittr} documenation for the complete and current documentation. } - diff --git a/man/compileDecisionModel.Rd b/man/compileDecisionModel.Rd index f4a54fc..6d61085 100644 --- a/man/compileDecisionModel.Rd +++ b/man/compileDecisionModel.Rd @@ -42,7 +42,7 @@ Nodes at which a decision can be made, such as the decision to decision options are extracted from the JAGS statement returned by \code{writeJagsModel}. - The options for each decision nodes (if there are multiple nodes) are + The options for each decision node (if there are multiple nodes) are combined via \code{expand.grid} to make a table of all possible decisions. Each row of this table is passed as a list to the \code{data} argument of \code{jags.model} (via \code{compileJagsModel}) and a list of JAGS @@ -77,11 +77,10 @@ custom_policy <- policyMatrix(Net, angio = c("Negative", "Positive")) decision3 <- compileDecisionModel(Net, custom_policy) -} -\author{ -Jarrod Dalton and Benjamin Nutter } \seealso{ \code{\link{policyMatrix}} \code{\link{compileJagsModel}} } - +\author{ +Jarrod Dalton and Benjamin Nutter +} diff --git a/man/compileJagsModel.Rd b/man/compileJagsModel.Rd index 51d13ac..a99ce00 100644 --- a/man/compileJagsModel.Rd +++ b/man/compileJagsModel.Rd @@ -45,26 +45,23 @@ Net <- HydeNetwork(~ wells + compiledNet <- compileJagsModel(Net, n.chains=5) #* Generate the posterior distribution -Posterior <- HydePosterior(compiledNet, - variable.names = c("d.dimer", "death"), - n.iter = 1000) +Posterior <- HydeSim(compiledNet, + variable.names = c("d.dimer", "death"), + n.iter = 1000) Posterior #* For a single model (ie, not a decision model), the user may choose to #* use the \\code{rjags} function \\code{coda.samples}. #* However, this does not have a succinct print method - library(rjags) - s <- coda.samples(compiledNet$jags, variable.names = c("d.dimer", "death"), n.iter=1000) -} -\author{ -Benjamin Nutter } \seealso{ \code{jags.model} } - +\author{ +Benjamin Nutter +} diff --git a/man/cpt.Rd b/man/cpt.Rd index a18a02e..5eb6fda 100644 --- a/man/cpt.Rd +++ b/man/cpt.Rd @@ -116,4 +116,3 @@ inputCPT(wetGrass ~ rain + morning, \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/expectedVariables.Rd b/man/expectedVariables.Rd index 4376e7a..c89499b 100644 --- a/man/expectedVariables.Rd +++ b/man/expectedVariables.Rd @@ -1,8 +1,8 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/expectedVariables.R \name{expectedVariables} -\alias{expectedParameters} \alias{expectedVariables} +\alias{expectedParameters} \title{List Expected Parameter Names and Expected Variables Names} \usage{ expectedVariables(network, node, returnVector = FALSE) @@ -32,8 +32,7 @@ appropriate estimates of the regression coefficients for the model. \code{returnVector} will generally be set to \code{FALSE} for most uses, but can be set to \code{TRUE} for use in error checking. For example, in \code{setNode}, if not all of the parents have been given a coefficient -(or if too few coefficients have been given), the vector of names is usually -more useful for giving informative error messages. +(or if too few coefficients have been given), the vector of names is supplied. } \examples{ data(PE, package="HydeNet") @@ -54,4 +53,3 @@ expectedParameters(Net, wells, returnVector=TRUE) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/factorFormula.Rd b/man/factorFormula.Rd index c7cbbea..27d64b1 100644 --- a/man/factorFormula.Rd +++ b/man/factorFormula.Rd @@ -23,13 +23,8 @@ When working in R, it is often more convenient to work in It is assumed that factor variables will be used in logical comparisons of the format \code{[variable_name] == '[factor_level]'} and only this pattern is recognized in the text search. Single or - double quotes may be used around the level, and the spaces aroudn the - \code{==} are optional. - - While there are certainly limitations to this function that we have - not yet found, we believe it covers the majority of cases in which - it is useful. More complex cases that can't be handled by - \code{factorFormula} may require writing native JAGS code. + double quotes may be used around the level, and the spaces around the + \code{==} are optional. } \examples{ \dontrun{ @@ -48,4 +43,3 @@ factorFormula(form = payoff ~ (death == 'No') + (pe == 'Yes'), \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/factorRegex.Rd b/man/factorRegex.Rd index 163e8af..c85c78f 100644 --- a/man/factorRegex.Rd +++ b/man/factorRegex.Rd @@ -12,8 +12,7 @@ factorRegex(fit) \description{ A utility function to produce a regular expression that can separate factor names and factor levels in the \code{broom::tidy()$term} - output. At some point, this may have to become a method to accomodate - different model types, but I haven't run into that problem yet. + output. } \examples{ data(PE, package = "HydeNet") @@ -24,4 +23,3 @@ HydeNet:::factorRegex(g6) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/inputCPTExample.Rd b/man/inputCPTExample.Rd index b7285af..0f658d7 100644 --- a/man/inputCPTExample.Rd +++ b/man/inputCPTExample.Rd @@ -17,4 +17,3 @@ illustrated in the article being submitted to JSS. It is saved as an object named \code{h} in the article. } \keyword{datasets} - diff --git a/man/jagsDists.Rd b/man/jagsDists.Rd index 2114d34..e354803 100644 --- a/man/jagsDists.Rd +++ b/man/jagsDists.Rd @@ -7,13 +7,17 @@ \format{A data frame with 30 rows and 7 variables: \describe{ \item{DistName}{Distribution Name} - \item{FnName}{Function Name} + \item{FnName}{JAGS Function Name} + \item{FnNameR}{R Function Name} \item{xLow}{Minimum value for x, the random variable} \item{xHigh}{Maximum value for x, the random variable} - \item{Parameters}{Names of the parameters} + \item{Parameters}{Names of the JAGS parameters} + \item{RParameter}{R function argument name} \item{paramLimit}{Limits on the parameter} \item{paramLogic}{The text of a logical check used in \code{setNode} to ensure stated parameters are valid.} + \item{Rsupport}{Logical value, indicating if an R equivalent is + supported by \code{HydeNet}} }} \source{ \url{http://people.math.aau.dk/~kkb/Undervisning/Bayes14/sorenh/docs/jags_user_manual.pdf} @@ -25,4 +29,3 @@ jagsDists A dataset listing the JAGS probability distributions and their parameters } \keyword{datasets} - diff --git a/man/jagsFunctions.Rd b/man/jagsFunctions.Rd index 963a78f..f1ef788 100644 --- a/man/jagsFunctions.Rd +++ b/man/jagsFunctions.Rd @@ -20,4 +20,3 @@ jagsFunctions A dataset listing the JAGS functions and their R equivalents. } \keyword{datasets} - diff --git a/man/mergeDefaultPlotOpts.Rd b/man/mergeDefaultPlotOpts.Rd index b5d62bd..af9a37b 100644 --- a/man/mergeDefaultPlotOpts.Rd +++ b/man/mergeDefaultPlotOpts.Rd @@ -14,4 +14,3 @@ mergeDefaultPlotOpts(network, node_df) \description{ rdname plot.HydeNetwork } - diff --git a/man/modelToNode.Rd b/man/modelToNode.Rd index 998bf08..c22bc51 100644 --- a/man/modelToNode.Rd +++ b/man/modelToNode.Rd @@ -2,8 +2,8 @@ % Please edit documentation in R/modelToNode.R \name{modelToNode} \alias{modelToNode} -\alias{modelToNode.cpt} \alias{modelToNode.default} +\alias{modelToNode.cpt} \alias{modelToNode.glm} \alias{modelToNode.lm} \alias{modelToNode.multinom} @@ -41,8 +41,5 @@ In cases where model objects may already be fit and established, For models built with \code{xtabs}, although a data frame may be passed when building the model, it is not stored in the object. Thus, - the data used to construct the models are not carried with the node. However, - the JAGS code is built appropriate from the object and this should be of - little concern. + the data used to construct the models are not carried with the node. } - diff --git a/man/plot.HydeNetwork.Rd b/man/plot.HydeNetwork.Rd index 471fa64..41637b8 100644 --- a/man/plot.HydeNetwork.Rd +++ b/man/plot.HydeNetwork.Rd @@ -1,20 +1,19 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/plot.HydeNetwork.R \name{plot.HydeNetwork} -\alias{HydePlotOptions} -\alias{customNode} -\alias{mapEdges} -\alias{mergeCustomEdges} -\alias{mergeCustomNodes} \alias{plot.HydeNetwork} \alias{plotHydeNetwork} -\title{Plotting Utilities Probabilistic Graphical Network} +\alias{mergeCustomNodes} +\alias{mapEdges} +\alias{mergeCustomEdges} +\alias{customNode} +\alias{HydePlotOptions} +\title{Plotting Utilities for Probabilistic Graphical Network} \source{ \url{http://rich-iannone.github.io/DiagrammeR/graphviz_and_mermaid.html}\cr See especially the section on Attributes - \url{http://graphviz.org/}\cr - \url{http://graphviz.org/content/attrs} + \url{http://graphviz.org/} } \usage{ \method{plot}{HydeNetwork}(x, customNodes = NULL, customEdges = NULL, ..., @@ -70,7 +69,6 @@ defaults node attribute settings for each variable type.} \item{restorePackageDefaults}{A logical value. When TRUE, the original package defaults are restored.} } - \description{ Generate and customize plots of a \code{HydeNetwork} class network. \code{HydeNet} provides some initial defaults for standard @@ -81,30 +79,6 @@ Generate and customize plots of a \code{HydeNetwork} by invoking \code{HydePlotOptions}. Node attributes are more fully explained in the documentation for the \code{DiagrammeR} package. Individual nodes may be define with \code{customNode}. - -GraphViz is an enormous set of resources for customizing and we - cannot adequately describe them all here. See 'Sources' for links - to additional documentation from the \code{DiagrammeR} package and the - GraphViz website. - - With its default settings, \code{HydeNet} makes use of five node - attributes for plotting networks. These are - \itemize{ - \item style: By default, set to 'filled', but may also take 'striped', - 'wedged', or 'radial'. - \item fillcolor: The hexadecimal or X11 color name. In styles 'striped', - 'wedged', or 'radial', this may take multiple colors separated by a - colon (:). - \item shape: the node shape. May take the values 'oval', 'diamond', - 'egg', 'ellipse', 'square', 'triangle', or 'rect' - \item fontcolor: The color of the node label. - \item color: The color of the node's border. - } - - \code{HydeNet} assumes the GraphViz defaults for edge nodes (arrows). - - See the Plotting Hyde Networks vignette (\code{vignette("HydeNetPlots")}) - for a more thorough explanation of plotting networks. } \details{ GraphViz is an enormous set of resources for customizing and we @@ -172,4 +146,3 @@ plot(BlackJack, \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/policyMatrix.Rd b/man/policyMatrix.Rd index 8b6af92..5e8c523 100644 --- a/man/policyMatrix.Rd +++ b/man/policyMatrix.Rd @@ -1,8 +1,8 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/PolicyMatrix.R \name{policyMatrix} -\alias{defaultPolicyMatrix} \alias{policyMatrix} +\alias{defaultPolicyMatrix} \title{Construct Policy and Decision Matrices} \usage{ policyMatrix(network, ..., useDefaultPolicies = TRUE) @@ -21,7 +21,7 @@ has default policy values, the user supplied values take precedence.} } \value{ Returns a data frame built by \code{expand.grid} and intended to be - used with \code{HydePosterior}. + used with \code{HydeSim}. } \description{ It may be of interest to compare posterior distributions of @@ -45,12 +45,12 @@ When \code{...} is not used, the default policy matrix is defined enforced. Thus, it is possible to include numeric values in a decision matrix. - Policy matrices can be passed to \code{HydePosterior} to run posterior + Policy matrices can be passed to \code{HydeSim} to run posterior distributions on each row of the policy matrix. There is nothing particularly special about the policy matrices returned by \code{policyMatrix}; they are simply data frame that require names drawn from the nodes in the network. Any data frame can be passed to - \code{HydePosterior} and a check is done there to confirm all of the + \code{HydeSim} and a check is done there to confirm all of the column names match a node in the network. Whenever a node is identified as a deterministic node, its policy values @@ -79,4 +79,3 @@ policyMatrix(Net, treat="No", angio = c("No", "Yes")) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/print.HydeNetwork.Rd b/man/print.HydeNetwork.Rd index 2324b9f..03047fe 100644 --- a/man/print.HydeNetwork.Rd +++ b/man/print.HydeNetwork.Rd @@ -34,7 +34,7 @@ print(Net) print(Net, d.dimer) Net <- setNode(Net, d.dimer, - nodeType='dnorm', mu=fromData(), tau=fromData(), + nodeType='dnorm', mean=fromData(), sd=fromData(), nodeFormula = d.dimer ~ pregnant + pe, nodeFitter='lm') print(Net, d.dimer) @@ -43,4 +43,3 @@ print(Net, d.dimer) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/print.HydePosterior.Rd b/man/print.HydeSim.Rd similarity index 79% rename from man/print.HydePosterior.Rd rename to man/print.HydeSim.Rd index d2e7136..352509e 100644 --- a/man/print.HydePosterior.Rd +++ b/man/print.HydeSim.Rd @@ -1,19 +1,19 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/print.HydePosterior.R -\name{print.HydePosterior} -\alias{print.HydePosterior} -\title{Print a Hyde Posterior Distribution Object} +\name{print.HydeSim} +\alias{print.HydeSim} +\title{Print a Hyde Simulated Distribution Object} \usage{ -\method{print}{HydePosterior}(x, ...) +\method{print}{HydeSim}(x, ...) } \arguments{ -\item{x}{a \code{HydePosterior} object} +\item{x}{a \code{HydeSim} object} \item{...}{additional arguments to be passed to print methods. Currently none in use.} } \description{ -Prints a brief description of a HydePosterior object. +Prints a brief description of a HydeSim object. } \details{ Prints the number of posterior distributions, chains, and @@ -35,14 +35,14 @@ compiledNet <- compileJagsModel(Net, n.chains=5) #* Generate the posterior distribution for the model (but not the #* decision model) -Posterior <- HydePosterior(compiledNet, +Posterior <- HydeSim(compiledNet, variable.names = c("d.dimer", "death"), n.iter = 1000) Posterior #* Generate the posterior for the decision model Decision <- compileDecisionModel(Net, n.chains=5) -Posterior_decision <- HydePosterior(Decision, +Posterior_decision <- HydeSim(Decision, variable.names = c("d.dimer", "death"), n.iter = 1000) @@ -50,4 +50,3 @@ Posterior_decision <- HydePosterior(Decision, \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/print.cpt.Rd b/man/print.cpt.Rd index 55461ce..7564efa 100644 --- a/man/print.cpt.Rd +++ b/man/print.cpt.Rd @@ -17,4 +17,3 @@ Just a wrapper to strip the attributes off, change the class, and print the arra \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/rewriteHydeFormula.Rd b/man/rewriteHydeFormula.Rd index e021671..5d911d3 100644 --- a/man/rewriteHydeFormula.Rd +++ b/man/rewriteHydeFormula.Rd @@ -14,8 +14,7 @@ rewriteHydeFormula(old_form, new_form) \description{ This is a convenience function used to assist in the updating of \code{HydeNetwork} network objects. It makes it possible to add and - subtract individual parent relationships without deleting an entire node. - It's still a work in progress. + subtract individual parent relationships without deleting an entire node. } \details{ To allow changes to be made on the node-parent level, the formulae @@ -36,4 +35,3 @@ To allow changes to be made on the node-parent level, the formulae \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/setDecisionNodes.Rd b/man/setDecisionNodes.Rd index 3047b99..2649bc2 100644 --- a/man/setDecisionNodes.Rd +++ b/man/setDecisionNodes.Rd @@ -27,4 +27,3 @@ Depending on how your Hyde Network was built, you may not have \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/setNode.Rd b/man/setNode.Rd index 26cdd88..4dc0cbe 100644 --- a/man/setNode.Rd +++ b/man/setNode.Rd @@ -1,9 +1,9 @@ % Generated by roxygen2: do not edit by hand % Please edit documentation in R/setNode.R \name{setNode} +\alias{setNode} \alias{fromData} \alias{fromFormula} -\alias{setNode} \title{Set Node Relationships} \usage{ setNode(network, node, nodeType, nodeFitter, nodeFormula, fitterArgs = list(), @@ -21,8 +21,9 @@ fromFormula() \item{node}{A node within \code{network}. This does not have to be quoted.} -\item{nodeType}{a valid distribution function from JAGS. See the data set -in \code{data(jagsDists)} for a complete list.} +\item{nodeType}{a valid distribution. See the data set +in \code{data(jagsDists)} for a complete list of available distributions. +See "Choosing a Node Type"} \item{nodeFitter}{the fitting function, such as \code{lm} or \code{glm}. This will probably only be needed when \code{fromData = TRUE}.} @@ -32,9 +33,7 @@ node and its parents. It must use as a term every parent of \code{node}. This f will be pushed through the unexported function \code{factorFormula}. See "Coding Factor Levels" for more details.} -\item{fitterArgs}{Additional arguments to be passed to \code{fitter}. This does not -yet have any effect as I haven't yet decided out where to store this and -how to implement the fitting.} +\item{fitterArgs}{Additional arguments to be passed to \code{fitter}.} \item{decision}{A value of either \code{"current"} or a logical value. If \code{"current"}, the current value of the setting is retained. This allows @@ -63,7 +62,7 @@ from the data object in \code{network}. Defaults to \code{TRUE} whenever \item{...}{parameters to be passed to the JAGS distribution function. Each parameter in the distribution function must be named. For -example, the parameters to pass to \code{dnorm} would be \code{mu='', tau=''}. +example, the parameters to pass to \code{dnorm} would be \code{mean='', sd=''}. The required parameters can be looked up using the \code{expectedParameters} function. If parameters are to be estimated from the data, the functions \code{fromData} and \code{fromFormula} may @@ -103,6 +102,9 @@ values are provided, \code{policyMatrix} and \code{compileDecisionModel} are likely to return errors when they are called. Policy values may also be set with \code{setPolicyValues} after a network has been defined.} } +\value{ +Returns the modified \code{HydeNetwork} object. +} \description{ The relationship between a node and its parents must be defined before the appropriate JAGS model statement can be constructed. @@ -126,6 +128,25 @@ The functions \code{fromFormula()} and \code{fromData()} help to control will cause the model to be fit and the JAGS code for the parameters to be stored in the \code{nodeParams} attribute. } +\section{Choosing a Node Type}{ + +Many of the distribution functions defined in JAGS have an equivalen +distribution function in R. You may inspect the \code{jagsDists} data +frame to see the function names in each language. You may specify +the distribution function using the R name and it will be translated +to the equivalent JAGS function. + +You may still use the JAGS names, which allows you to specify a +distribution in JAGS that does not have an R equivalent listed. Note, +however, that where R functions are supported, \code{HydeNet} anticipates +the parameter names to be given following R conventions (See +the \code{RParameter} column of \code{jagsDists}.) + +Of particular interest are \code{dbern} and \code{dcat}, which are +functions in JAGS that have no immediate equivalent in R. They provide +Bernoulli and Multinomial distributions, respectively. +} + \section{Coding Factor Levels}{ The \code{nodeFormula} argument will accept any valid R formula. If desired, you @@ -150,7 +171,7 @@ translate correctly. The validation of parameters is performed by comparing the values provided with the limits defined in the \code{jagsDists$paramLogic} variable. (look at \code{data(jagsDists, data='HydeNet')}. For most node types, validation will -be peformed for numeric variables. For deterministic variables, the validation +be performed for numeric variables. For deterministic variables, the validation will only check that the parameter definition is a formula. It is possible to pass character strings as definitions, but when this is done, @@ -166,6 +187,7 @@ The two exceptions to this rule are when you pass \code{fromFormula()} and without warning, since the definition will be built by \code{HydeNet} and be proper JAGS code (barring any bugs, of course). } + \examples{ data(PE, package="HydeNet") Net <- HydeNetwork(~ wells + @@ -178,7 +200,7 @@ Net <- HydeNetwork(~ wells + print(Net, d.dimer) #* Manually change the precision -Net <- setNode(Net, d.dimer, nodeType='dnorm', mu=fromFormula(), tau=1/2.65, +Net <- setNode(Net, d.dimer, nodeType='dnorm', mean=fromFormula(), sd=sqrt(2.65), nodeFormula = d.dimer ~ pregnant * pe, nodeFitter='lm') print(Net, d.dimer) @@ -187,4 +209,3 @@ print(Net, d.dimer) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/setNodeModels.Rd b/man/setNodeModels.Rd index bfcec70..87138d8 100644 --- a/man/setNodeModels.Rd +++ b/man/setNodeModels.Rd @@ -45,4 +45,3 @@ writeNetworkModel(Net, pretty=TRUE) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/setPolicyValues.Rd b/man/setPolicyValues.Rd index 089eb27..7cef37c 100644 --- a/man/setPolicyValues.Rd +++ b/man/setPolicyValues.Rd @@ -28,4 +28,3 @@ By default, \code{HydeNet} uses factor levels for policy \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/update.HydeNetwork.Rd b/man/update.HydeNetwork.Rd index b086d08..13782aa 100644 --- a/man/update.HydeNetwork.Rd +++ b/man/update.HydeNetwork.Rd @@ -20,11 +20,8 @@ Add or remove nodes or add parents within a \code{HydeNetwork} } \details{ Adding or removing nodes is fairly straightforward if you are - removing a complete node (along with its parents). If you just wish to - remove a parent, this doesn't work well yet. I will have to work out - a solution to remove parent relationships individually. I had hoped - there would be an \code{update.dag} method, but no luck. This will continue - to be developed in the future, but the arguments will remain the same. + removing a complete node (along with its parents). Removing a parent + will generate a warning that the child nodes may need to be redefined. } \examples{ data(PE, package="HydeNet") @@ -44,4 +41,3 @@ plot(Net) \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/vectorProbs.Rd b/man/vectorProbs.Rd index b92e450..74ba6c6 100644 --- a/man/vectorProbs.Rd +++ b/man/vectorProbs.Rd @@ -29,4 +29,3 @@ vectorProbs(c(1, 2, 3), "wells") \author{ Jarrod Dalton and Benjamin Nutter } - diff --git a/man/writeJagsFormula.Rd b/man/writeJagsFormula.Rd index 96bb63c..c220afa 100644 --- a/man/writeJagsFormula.Rd +++ b/man/writeJagsFormula.Rd @@ -62,10 +62,9 @@ writeJagsFormula(fit, nodes=c("d.dimer", "pregnant", "pe")) fit.glm <- glm(death ~ pe + treat, data=PE, family="binomial") writeJagsFormula(fit.glm, nodes=c("death", "pe", "treat")) } -\author{ -Jarrod Dalton and Benjamin Nutter -} \seealso{ \code{\link{writeJagsModel}}, \code{\link{writeNetworkModel}} } - +\author{ +Jarrod Dalton and Benjamin Nutter +} diff --git a/man/writeJagsModel.Rd b/man/writeJagsModel.Rd index 4bbb450..071f651 100644 --- a/man/writeJagsModel.Rd +++ b/man/writeJagsModel.Rd @@ -2,9 +2,9 @@ % Please edit documentation in R/writeJagsModel.R \name{writeJagsModel} \alias{writeJagsModel} +\alias{writeJagsModel_default} \alias{writeJagsModel_dbern} \alias{writeJagsModel_dcat} -\alias{writeJagsModel_default} \alias{writeJagsModel_determ} \alias{writeJagsModel_dnorm} \alias{writeJagsModel_dnorm_default} @@ -55,6 +55,7 @@ The manipulations are performed on the \code{nodeParams} element estimating them from the data. } \examples{ +\dontrun{ #* NOTE: writeJagsModel isn't an exported function data(PE, package='HydeNet') Net <- HydeNetwork(~ wells + @@ -66,12 +67,12 @@ Net <- HydeNetwork(~ wells + data = PE) HydeNet:::writeJagsModel(Net, 'pe') HydeNet:::writeJagsModel(Net, 'treat') - } -\author{ -Jarrod Dalton and Benjamin Nutter + } \seealso{ \code{\link{writeJagsFormula}} } - +\author{ +Jarrod Dalton and Benjamin Nutter +} diff --git a/man/writeNetworkModel.Rd b/man/writeNetworkModel.Rd index 7d9e1f8..616d8c4 100644 --- a/man/writeNetworkModel.Rd +++ b/man/writeNetworkModel.Rd @@ -35,11 +35,10 @@ writeNetworkModel(Net) #* Something a little easier on the eyes. writeNetworkModel(Net, pretty=TRUE) -} -\author{ -Jarrod Dalton and Benjamin Nutter } \seealso{ \code{\link{writeJagsModel}}, \code{\link{writeJagsFormula}} } - +\author{ +Jarrod Dalton and Benjamin Nutter +} diff --git a/tests/testthat/test-HydePosterior.R b/tests/testthat/test-HydePosterior.R index 4338040..d7d61f8 100644 --- a/tests/testthat/test-HydePosterior.R +++ b/tests/testthat/test-HydePosterior.R @@ -1,4 +1,4 @@ -context("HydePosterior") +context("HydeSim") data(PE, package="HydeNet") Net <- HydeNetwork(~ wells + @@ -10,52 +10,52 @@ Net <- HydeNetwork(~ wells + data = PE) compiledNet <- compileJagsModel(Net, n.chains=5) -test_that("Unbound HydePosterior returns object of class HydePosterior", +test_that("Unbound HydeSim returns object of class HydeSim", { - Posterior <- HydePosterior(compiledNet, + Posterior <- HydeSim(compiledNet, variable.names = c("d.dimer", "death"), n.iter = 1000, bind = FALSE) expect_equal(class(Posterior), - "HydePosterior") + "HydeSim") }) -test_that("Bound HydePosterior returns object of class data.frame", +test_that("Bound HydeSim returns object of class data.frame", { - Posterior <- HydePosterior(compiledNet, + Posterior <- HydeSim(compiledNet, variable.names = c("d.dimer", "death"), n.iter = 1000) expect_equal(class(Posterior), "data.frame") }) -test_that("Unbound HydePosterior print method", +test_that("Unbound HydeSim print method", { - Posterior <- HydePosterior(compiledNet, + Posterior <- HydeSim(compiledNet, variable.names = c("d.dimer", "death"), n.iter = 1000, bind = FALSE) expect_output(print(Posterior)) }) -test_that("bindPosterior returns relabeled data", +test_that("bindSim returns relabeled data", { - Posterior <- HydePosterior(compiledNet, + Posterior <- HydeSim(compiledNet, variable.names = c("d.dimer", "death"), n.iter = 1000, bind = FALSE) - Bound <- bindPosterior(Posterior) + Bound <- bindSim(Posterior) expect_equal(class(Bound$death), "factor") }) -test_that("bindPosterior returns relabeled data", +test_that("bindSim returns relabeled data", { - Posterior <- HydePosterior(compiledNet, + Posterior <- HydeSim(compiledNet, variable.names = c("d.dimer", "death"), n.iter = 1000, bind = FALSE) - Bound <- bindPosterior(Posterior, relabel_factor = FALSE) + Bound <- bindSim(Posterior, relabel_factor = FALSE) expect_equal(class(Bound$death), "numeric") }) \ No newline at end of file diff --git a/tests/testthat/test-bindPosterior.R b/tests/testthat/test-bindPosterior.R index 91eb61c..81bbfd7 100644 --- a/tests/testthat/test-bindPosterior.R +++ b/tests/testthat/test-bindPosterior.R @@ -1,4 +1,4 @@ -context("bindPosterior") +context("bindSim") data(PE, package="HydeNet") Net <- HydeNetwork(~ wells + @@ -10,11 +10,11 @@ Net <- HydeNetwork(~ wells + data = PE) %>% setDecisionNodes(treat, angio) Post <- compileDecisionModel(Net) %>% - HydePosterior(variable.names = c("wells", "treat", "death"), + HydeSim(variable.names = c("wells", "treat", "death"), n.iter = 100, bind = FALSE) -test_that("bindPosterior from Decision Model", +test_that("bindSim from Decision Model", { - expect_silent(bindPosterior(Post)) + expect_silent(bindSim(Post)) }) diff --git a/tests/testthat/test-print.HydePosterior.R b/tests/testthat/test-print.HydePosterior.R index 3f77873..021c2c3 100644 --- a/tests/testthat/test-print.HydePosterior.R +++ b/tests/testthat/test-print.HydePosterior.R @@ -1,4 +1,4 @@ -context("print.HydePosterior") +context("print.HydeSim") data(PE, package="HydeNet") Net <- HydeNetwork(~ wells + @@ -10,9 +10,9 @@ Net <- HydeNetwork(~ wells + data = PE) compiledNet <- compileJagsModel(Net, n.chains=5, data = list(pe = "Yes")) -test_that("print.HydePosterior with observed values", +test_that("print.HydeSim with observed values", { - expect_output(print(HydePosterior(compiledNet, + expect_output(print(HydeSim(compiledNet, variable.names = c("wells", "death"), n.iter = 100, bind = FALSE))) }) \ No newline at end of file diff --git a/tests/testthat/test-setNode.R b/tests/testthat/test-setNode.R index 4652630..d4791dd 100644 --- a/tests/testthat/test-setNode.R +++ b/tests/testthat/test-setNode.R @@ -10,22 +10,22 @@ Net <- HydeNetwork(~ wells + test_that("decision argument warning", { - expect_warning(setNode(Net, treat, nodeType = "dbern", decision = "yes", p = .5)) + expect_warning(setNode(Net, treat, nodeType = "dbern", decision = "yes", prob = .5)) }) test_that("utility error: utilties must be deterministic and not have children", { - expect_error(setNode(Net, treat, nodeType = "dbern", utility = TRUE, p =.5)) + expect_error(setNode(Net, treat, nodeType = "dbern", utility = TRUE, prob =.5)) }) test_that("validation error", { - expect_error(setNode(Net, treat, nodeType = "dbern", p = 1.2)) + expect_error(setNode(Net, treat, nodeType = "dbern", prob = 1.2)) }) test_that("fit the model for dbern", { - expect_silent(setNode(Net, treat, nodeType = "dbern", p = fromData(), + expect_silent(setNode(Net, treat, nodeType = "dbern", prob = fromData(), fitModel = TRUE)) }) @@ -38,7 +38,7 @@ test_that("fit the model for dcat", test_that("fit the model for dnorm", { expect_silent(setNode(Net, d.dimer, nodeType = "dnorm", - mu = fromData(), tau = fromData(), + mean = fromData(), sd = fromData(), fitModel = TRUE)) }) diff --git a/vignettes/DecisionNetworks.Rmd b/vignettes/DecisionNetworks.Rmd index 61c40ba..af61cc6 100644 --- a/vignettes/DecisionNetworks.Rmd +++ b/vignettes/DecisionNetworks.Rmd @@ -281,7 +281,7 @@ net <- setNodeModels(net, glm.hit1, glm.hit2, glm.hit3) Alternatively, decision nodes can be deterministic in nature. In this case, we interpret the function which sets the value of these nodes depending on the value(s) of its parent node(s) as a deterministic strategy that is chosen by the actor. Within the blackjack network, we might envision such a strategy by the following rule, which would be applicable to all three hit decisions in the network: choose 'hit' when the current point total is less than 15. -**Utility nodes** are restricted to be deterministic nodes with no descendents. In the blackjack example, for instance, we would assign the payoff utility node as follows: +**Utility nodes** are restricted to be deterministic nodes with no descendants. In the blackjack example, for instance, we would assign the payoff utility node as follows: ```{r} net <- setNode(net, payoff, "determ", define=fromFormula(), @@ -317,7 +317,7 @@ compiledNet <- compileJagsModel(net, data = evidence, n.chains = 3, n.adapt = 5000) -post <- HydePosterior(compiledNet, +post <- HydeSim(compiledNet, variable.names = trackedVars, n.iter=10000) @@ -345,7 +345,7 @@ policies <- data.frame(hit1 = c(0,1,1,1), (Note: we have included a convenience function called `policyMatrix()` when all combinations of decision node values are of interest. This function is a wrapper for `expand.grid()`; see `help(policyMatrix)` for details.) -In the MEU analysis, the goal is to characterize the distribution of utility under the competing policies. This amounts to sampling posterior distributions of utility nodes under varying sets of values for the decision nodes. In `HydeNet`, this is done by 1) using the function `compileDecisionModel()` to create a list of `compiledHydeNetwork` objects (one object corresponding to each policy); 2) feeding that list to `HydePosterior()` to get a list of `coda.samples` objects; and finally 3) feeding the list of `coda.samples` objects to `bindPosterior()` to get a single posterior sample matrix for each policy: +In the MEU analysis, the goal is to characterize the distribution of utility under the competing policies. This amounts to sampling posterior distributions of utility nodes under varying sets of values for the decision nodes. In `HydeNet`, this is done by 1) using the function `compileDecisionModel()` to create a list of `compiledHydeNetwork` objects (one object corresponding to each policy); 2) feeding that list to `HydeSim()` to get a list of `coda.samples` objects; and finally 3) feeding the list of `coda.samples` objects to `bindPosterior()` to get a single posterior sample matrix for each policy: ```{r, echo=FALSE} set.seed(39482820) @@ -355,7 +355,7 @@ set.seed(39482820) compiledNets <- compileDecisionModel(net, policyMatrix = policies) samples <- lapply(compiledNets, - HydePosterior, + HydeSim, variable.names = trackedVars, n.iter=10000) diff --git a/vignettes/GettingStartedWithHydeNet.Rmd b/vignettes/GettingStartedWithHydeNet.Rmd index 5937071..ea51e0d 100644 --- a/vignettes/GettingStartedWithHydeNet.Rmd +++ b/vignettes/GettingStartedWithHydeNet.Rmd @@ -84,7 +84,7 @@ There are many options for manual specification of node distributions. Please re ### Network Visualization -We have implemented a plot method for `HydeNetwork` objects, using the [`DiagrammeR`](http://cran.r-project.org/package=DiagrammeR) library by Richard Iannone et al. While not implemented in this simple example, there are different default node shapes and colors for random variable nodes, deterministic nodes, decision nodes and utility nodes. See our **"Building and Customizing HydeNet Plots"** vignette (`vignette("HydeNetPlots", package = "HydeNet")`)for details on customization. +We have implemented a plot method for `HydeNetwork` objects, using the [`DiagrammeR`](https://CRAN.R-project.org/package=DiagrammeR) library by Richard Iannone et al. While not implemented in this simple example, there are different default node shapes and colors for random variable nodes, deterministic nodes, decision nodes and utility nodes. See our **"Building and Customizing HydeNet Plots"** vignette (`vignette("HydeNetPlots", package = "HydeNet")`)for details on customization. ```{r, fig.width = 5, eval=FALSE} plot(carNet) @@ -184,7 +184,7 @@ autoNet <- HydeNetwork(~ wells data = PE) autoNet <- setNode(autoNet, treat, nodeFormula = treat ~ poly(d.dimer, 2) + angio, - p = fromData()) + prob = fromData()) ``` ```{r, echo=FALSE} print(autoNet, treat) @@ -206,7 +206,7 @@ autoNet <- HydeNetwork(~ wells data = PE) autoNet <- setNode(autoNet, treat, nodeFormula = treat ~ poly(d.dimer, 2) + angio, - p = fromData()) + prob = fromData()) print(autoNet, treat) ``` diff --git a/vignettes/HydeNetPlots.Rmd b/vignettes/HydeNetPlots.Rmd index 49da571..5cbc486 100644 --- a/vignettes/HydeNetPlots.Rmd +++ b/vignettes/HydeNetPlots.Rmd @@ -154,7 +154,19 @@ plot(BlackJack, ## Conclusion `HydeNet` is a tool to assist in generating and evaluating hybrid decision networks. Displaying the network is an important aspect of communicating the relationships established by your network. The `HydeNet` plotting tools provide the basic functionality needed to express both generic and customized plots suitable for sharing and evaluating network models. +```{r, include = FALSE} +if (!RCurl::url.exists("http://www.graphviz.org/about")) +{ + stop("Graphviz link does not exist. Find a new link") +} + +if (!RCurl::url.exists("http://www.bicyclecards.com/how-to-play/blackjack/")) +{ + stop("Blackjack rules URL does not exist. Find a new link") +} +``` + ## References [1] Graphviz, "About Graphviz," Retrieved from [http://www.graphviz.org/About.php](http://www.graphviz.org/About.php). -[2] Bicycle Cards, "Blackjack," Retrieved from [http://www.bicyclecards.com/card-games/rule/blackjack](http://www.bicyclecards.com/card-games/rule/blackjack]. \ No newline at end of file +[2] Bicycle Cards, "Blackjack," Retrieved from [http://www.bicyclecards.com/how-to-play/blackjack/](http://www.bicyclecards.com/how-to-play/blackjack/]. \ No newline at end of file diff --git a/vignettes/WorkingWithHydeNetObjects.Rmd b/vignettes/WorkingWithHydeNetObjects.Rmd index 0b23b7b..cec085f 100644 --- a/vignettes/WorkingWithHydeNetObjects.Rmd +++ b/vignettes/WorkingWithHydeNetObjects.Rmd @@ -170,7 +170,7 @@ The most straightforward way to specify distributions for root nodes, or nodes w ```{r} net <- setNode(network = net, node = pregnant, - nodeType = "dbern", p=.4) + nodeType = "dbern", prob=.4) net ``` @@ -184,7 +184,7 @@ Univariate normal distributions are specified using `nodeType = "dnorm"`. We wil ```{r} net <- setNode(net, wells, nodeType = "dnorm", - mu = 5, tau = 1 / (1.5^2)) + mean = 5, sd = 1.5) net$nodeType$wells net$nodeParams$wells @@ -232,59 +232,16 @@ net <- setNode(net, wells, ```{r, eval=FALSE} data(jagsDists, package='HydeNet') -jagsDists[,c(1,2,5,6)] -``` - -|DistName |FnName |Parameters |paramLimit | -|:-------------------------|:----------|:----------|:------------------| -|Beta |dbeta |a |> 0 | -|Beta |dbeta |b |> 0 | -|Chi-square |dchisqr |k |> 0 | -|Double exponential |ddexp |mu | | -|Double exponential |ddexp |tau |> 0 | -|Exponential |dexp |lambda |> 0 | -|F |df |n |> 0 | -|F |df |mu |> 0 | -|Gamma |dgamma |r |> 0 | -|Gamma |dgamma |lambda |> 0 | -|Generalized gamma |dgen.gamma |r |> 0 | -|Generalized gamma |dgen.gamma |b |> 0 | -|Generalized gamma |dgen.gamma |lambda |> 0 | -|Logistic |dlogis |mu | | -|Logistic |dlogis |tau |> 0 | -|Log-normal |dlnorm |mu | | -|Log-normal |dlnorm |tau |> 0 | -|Noncentral chi-square |dnchisqr |k |> 0 | -|Noncentral chi-square |dnchisqr |delta |>= 0 | -|Normal |dnorm |mu | | -|Normal |dnorm |tau |>= 0 | -|Pareto |dpar |alpha |> 0 | -|Pareto |dpar |alpha |> c | -|Student t |dt |mu | | -|Student t |dt |tau |> 0 | -|Student t |dt |k |> 0 | -|Uniform |dunif |a |< b | -|Uniform |dunif |b |> a | -|Weibull |dweib |nu |> 0 | -|Weibull |dweib |lambda |> 0 | -|Beta Binomial |dbetabin |a |> 0 | -|Beta Binomial |dbetabin |b |> 0 | -|Beta Binomial |dbetabin |n |> 0 | -|Bernoulli |dbern |p |0 < p < 1 | -|Binomial |dbin |p |0 < p < 1 | -|Binomial |dbin |n |> 0 | -|Categorical |dcat |pi |> 0 | -|Noncentral hypergeometric |dhyper |n1 |> 0 | -|Noncentral hypergeometric |dhyper |n2 |> 0 | -|Noncentral hypergeometric |dhyper |m1 |0 < m1 < (n1 + n2) | -|Noncentral hypergeometric |dhyper |psi | | -|Negative Binomial |dnegbin |p |0 < p < 1 | -|Negative Binomial |dnegbin |r |> 0 | -|Poisson |dpois |lambda |> 0 | +jagsDists[,c(1:3, 6:8)] +``` + +```{r, echo = FALSE} +knitr::kable(jagsDists[, c(1:3, 6:8)]) +``` So, to assign a Weibull distribution to a node *XYZ*, we would use the following code: ```{r, eval=FALSE} -net <- setNode(net, XYZ, nodeType = "dweib", nu=2, lambda=5) +net <- setNode(net, XYZ, nodeType = "dweib", shape=2, scale=5) ``` @@ -306,7 +263,7 @@ For OLS models, `nodeType="dnorm"` can be used. We use a regression equation to ```{r} net <- setNode(net, d.dimer, nodeType="dnorm", - mu=fromFormula(), tau=1/30, #sigma^2 = 30 + mean=fromFormula(), sd=sqrt(30), #sigma^2 = 30 nodeFormula = d.dimer ~ 210 + 29*pregnant + 68*pe) net$nodeType$d.dimer @@ -318,14 +275,14 @@ Or, alternatively, one may directly specify JAGS code for the parameters as char ```{r, eval=FALSE} net <- setNode(net, d.dimer, nodeType="dnorm", - mu="210 + 29*pregnant + 68*pe", tau=1/30) + mean="210 + 29*pregnant + 68*pe", sd = sqrt(30)) ``` However, the model syntax is flexible, allowing for alternative distributions to be used if desired. For example, maybe the distribution of the residuals has heavy tails; here, the (non-standardized) Student's *t* distribution could be used: ```{r, eval=FALSE} net <- setNode(net, d.dimer, nodeType="dt", - mu="210 + 29*pregnant + 68*pe", tau=1/20, k=2) + mean="210 + 29*pregnant + 68*pe", sd=sqrt(20), df=2) ``` @@ -336,39 +293,9 @@ data(jagsFunctions, package='HydeNet') jagsFunctions ``` -|jags_function |r_function |r_package | -|:-------------|:----------|:---------| -|abs |abs |base | -|arccos |acos |base | -|arccosh |acosh |base | -|arcsin |asin |base | -|arcsinh |asinh |base | -|arctan |atan |base | -|arctanh |atanh |base | -|cos |cos |base | -|cosh |cosh |base | -|cloglog |cloglog |VGAM | -|equals |== |base | -|exp |exp |base | -|icloglog | | | -|ifelse |ifelse |base | -|ilogit |logit |VGAM | -|log |log |base | -|logfact | | | -|loggam | | | -|logit |logit |VGAM | -|phi |pnorm |base | -|pow |^ |base | -|probit |probit |VGAM | -|round |ceiling |base | -|sin |sin |base | -|sinh |sinh |base | -|sqrt |sqrt |base | -|step |>= 0 |base | -|tan |tan |base | -|tanh |tanh |base | -|trunc |floor |base | - +```{r, echo = FALSE} +knitr::kable(jagsFunctions) +``` #### Logistic Regression @@ -377,7 +304,7 @@ If the intercept and slope coefficients of a logistic regression model are known ```{r} equation <- "-6.3 + 0.02*d.dimer + 2.9*angio - 0.005*d.dimer*angio" net <- setNode(net, treat, nodeType="dbern", - p=paste("ilogit(", equation, ")"), + prob=paste("ilogit(", equation, ")"), validate=FALSE) ``` diff --git a/z_supplemental/Supplemental_Data_Management.R b/z_supplemental/Supplemental_Data_Management.R index c04befa..2fcc06b 100644 --- a/z_supplemental/Supplemental_Data_Management.R +++ b/z_supplemental/Supplemental_Data_Management.R @@ -10,14 +10,14 @@ write.csv(PE, "C:/Users/nutterb/Documents/GitHub/HydeNet/z_supplemental/PE.csv", na="", row.names=FALSE) #* Read in edited data files -jagsDists <- read.csv("C:/Users/nutterb/Documents/GitHub/HydeNet/z_supplemental/jagsDists.csv", +jagsDists <- read.csv("/home/benjamin/GitHub/HydeNet/z_supplemental/jagsDists.csv", stringsAsFactors=FALSE) -jagsFunctions <- read.csv("C:/Users/nutterb/Documents/GitHub/HydeNet/z_supplemental/jagsFunctions.csv", +jagsFunctions <- read.csv("/home/benjamin/GitHub/HydeNet/z_supplemental/jagsFunctions.csv", stringsAsFactors=FALSE) -PE <- read.csv("C:/Users/nutterb/Documents/GitHub/HydeNet/z_supplemental/PE.csv", +PE <- read.csv("/home/benjamin/GitHub/HydeNet/z_supplemental/PE.csv", stringsAsFactors=FALSE) #* Save the data files as package resources -save(jagsDists, file="C:/Users/nutterb/Documents/GitHub/HydeNet/data/jagsDists.Rdata") -save(jagsFunctions, file="C:/Users/nutterb/Documents/GitHub/HydeNet/data/jagsFunctions.Rdata") -save(jagsDists, jagsFunctions, file="C:/Users/nutterb/Documents/GitHub/HydeNet/R/sysdata.Rda") +save(jagsDists, file="/home/benjamin/GitHub/HydeNet/data/jagsDists.RData") +save(jagsFunctions, file="/home/benjamin/GitHub/HydeNet/data/jagsFunctions.RData") +save(jagsDists, jagsFunctions, file="/home/benjamin/GitHub/HydeNet/R/sysdata.rda") diff --git a/z_supplemental/jagsDists.csv b/z_supplemental/jagsDists.csv index d663195..b28b6d6 100644 --- a/z_supplemental/jagsDists.csv +++ b/z_supplemental/jagsDists.csv @@ -1,46 +1,46 @@ -DistName,FnName,xLow,xHigh,Parameters,paramLimit,paramLogic -Beta,dbeta,0,1,a,> 0,a > 0 -Beta,dbeta,0,1,b,> 0,b > 0 -Chi-square,dchisqr,0,,k,> 0,k > 0 -Double exponential,ddexp,,,mu,,is.numeric(mu) -Double exponential,ddexp,,,tau,> 0,tau > 0 -Exponential,dexp,0,,lambda,> 0,lambda > 0 -F,df,0,,n,> 0,n > 0 -F,df,0,,mu,> 0,mu > 0 -Gamma,dgamma,0,,r,> 0 ,r > 0 -Gamma,dgamma,0,,lambda,> 0,lambda > 0 -Generalized gamma,dgen.gamma,0,,r,> 0,r > 0 -Generalized gamma,dgen.gamma,0,,b,> 0,b > 0 -Generalized gamma,dgen.gamma,0,,lambda,> 0,lambda > 0 -Logistic,dlogis,,,mu,,is.numeric(mu) -Logistic,dlogis,,,tau,> 0,tau > 0 -Log-normal,dlnorm,0,,mu,,is.numeric(mu) -Log-normal,dlnorm,0,,tau,> 0,tau > 0 -Noncentral chi-square,dnchisqr,0,,k,> 0,k > 0 -Noncentral chi-square,dnchisqr,0,,delta,>= 0,delta >= 0 -Normal,dnorm,,,mu,,is.numeric(mu) -Normal,dnorm,,,tau,>= 0,tau >= 0 -Pareto,dpar,c,,alpha,> 0,alpha > 0 -Pareto,dpar,c,,alpha,> c,alpha > 0 -Student t,dt,,,mu,,is.numeric(mu) -Student t,dt,,,tau,> 0,tau > 0 -Student t,dt,,,k,> 0,k > 0 -Uniform,dunif,a,b,a,< b,a < b -Uniform,dunif,a,b,b,> a,b > a -Weibull,dweib,0,,nu,> 0,nu > 0 -Weibull,dweib,0,,lambda,> 0,lambda > 0 -Beta Binomial,dbetabin,0,n,a,> 0,a > 0 -Beta Binomial,dbetabin,0,n,b,> 0,b > 0 -Beta Binomial,dbetabin,0,n,n,> 0,n > 0 -Bernoulli,dbern,0,1,p,0 < p < 1,0 < p & p < 1 -Binomial,dbin,0,n,p,0 < p < 1,0 < p & p < 1 -Binomial,dbin,0,n,n,> 0,n > 0 -Categorical,dcat,,,pi,> 0,pi > 0 -Noncentral hypergeometric,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",n1,> 0,n1 > 0 -Noncentral hypergeometric,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",n2,> 0,n2 > 0 -Noncentral hypergeometric,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",m1,0 < m1 < (n1 + n2),0 < m1 & m1 < (n1 + n2) -Noncentral hypergeometric,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",psi,,is.numeric(psi) -Negative Binomial,dnegbin,0,,p,0 < p < 1,0 < p & p < 1 -Negative Binomial,dnegbin,0,,r,> 0,r > 0 -Poisson,dpois,0,,lambda,> 0,lambda > 0 -Deterministic,determ,,,define,,plyr::is.formula(define) +DistName,FnName,FnNameR,xLow,xHigh,Parameters,RParameter,paramLimit,paramLogic,Rsupport +Beta,dbeta,dbeta,0,1,a,shape1,> 0,a > 0,TRUE +Beta,dbeta,dbeta,0,1,b,shape2,> 0,b > 0,TRUE +Chi-square,dchisqr,dchisq,0,,k,df,> 0,k > 0,TRUE +Double exponential,ddexp,,,,,mu,,is.numeric(mu),FALSE +Double exponential,ddexp,,,,,tau,> 0,tau > 0,FALSE +Exponential,dexp,dexp,0,,lambda,rate,> 0,lambda > 0,TRUE +F,df,df,0,,n,df1,> 0,n > 0,TRUE +F,df,df,0,,mu,df2,> 0,mu > 0,TRUE +Gamma,dgamma,dgamma,0,,r,shape,> 0 ,r > 0,TRUE +Gamma,dgamma,dgamma,0,,lambda,rate,> 0,lambda > 0,TRUE +Generalized gamma,dgen.gamma,,0,,r,,> 0,r > 0,FALSE +Generalized gamma,dgen.gamma,,0,,b,,> 0,b > 0,FALSE +Generalized gamma,dgen.gamma,,0,,lambda,,> 0,lambda > 0,FALSE +Logistic,dlogis,dlogis,,,mu,location,,is.numeric(mu),TRUE +Logistic,dlogis,dlogis,,,tau,scale,> 0,tau > 0,TRUE +Log-normal,dlnorm,dlnorm,0,,mu,meanlog,,is.numeric(mu),TRUE +Log-normal,dlnorm,dlnorm,0,,tau,sdlog,> 0,tau > 0,TRUE +Noncentral chi-square,dnchisqr,,0,,k,,> 0,k > 0,FALSE +Noncentral chi-square,dnchisqr,,0,,delta,,>= 0,delta >= 0,FALSE +Normal,dnorm,dnorm,,,mu,mean,,is.numeric(mu),TRUE +Normal,dnorm,dnorm,,,tau,sd,>= 0,tau >= 0,TRUE +Pareto,dpar,,c,,alpha,,> 0,alpha > 0,FALSE +Pareto,dpar,,c,,alpha,,> c,alpha > 0,FALSE +Student t,dt,dt,,,mu,mean,,is.numeric(mu),FALSE +Student t,dt,dt,,,tau,sd,> 0,tau > 0,FALSE +Student t,dt,dt,,,k,df,> 0,k > 0,TRUE +Uniform,dunif,dunif,a,b,a,min,< b,a < b,TRUE +Uniform,dunif,dunif,a,b,b,max,> a,b > a,TRUE +Weibull,dweib,dweib,0,,nu,shape,> 0,nu > 0,TRUE +Weibull,dweib,dweib,0,,lambda,scale,> 0,lambda > 0,TRUE +Beta Binomial,dbetabin,,0,n,,a,> 0,a > 0,TRUE +Beta Binomial,dbetabin,,0,n,,b,> 0,b > 0,TRUE +Beta Binomial,dbetabin,,0,n,,n,> 0,n > 0,TRUE +Bernoulli,dbern,,0,1,p,prob,0 < p < 1,0 < p & p < 1,FALSE +Binomial,dbin,dbin,0,n,p,prob,0 < p < 1,0 < p & p < 1,TRUE +Binomial,dbin,dbin,0,n,n,size,> 0,n > 0,TRUE +Categorical,dcat,,,,pi,pi,> 0,pi > 0,FALSE +Noncentral hypergeometric,dhyper,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",n1,,> 0,n1 > 0,FALSE +Noncentral hypergeometric,dhyper,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",n2,,> 0,n2 > 0,FALSE +Noncentral hypergeometric,dhyper,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",m1,,0 < m1 < (n1 + n2),0 < m1 & m1 < (n1 + n2),FALSE +Noncentral hypergeometric,dhyper,dhyper,"max(0, (n1 + n2) - m1)","min(n1, m1)",psi,,,is.numeric(psi),FALSE +Negative Binomial,dnegbin,,0,,p,,0 < p < 1,0 < p & p < 1,FALSE +Negative Binomial,dnegbin,,0,,r,,> 0,r > 0,FALSE +Poisson,dpois,dpois,0,,lambda,lambda,> 0,lambda > 0,TRUE +Deterministic,determ,,,,define,define,,plyr::is.formula(define),FALSE