|
| 1 | +# |
| 2 | +# ccdrAlgorithm-mvn.R |
| 3 | +# ccdrAlgorithm |
| 4 | +# |
| 5 | +# Created by Bryon Aragam (local) on 1/15/17. |
| 6 | +# Copyright (c) 2014-2017 Bryon Aragam. All rights reserved. |
| 7 | +# |
| 8 | + |
| 9 | +#' Generate data from a DAG |
| 10 | +#' |
| 11 | +#' Given a Gaussian DAG, generate data from the underlying distribution. |
| 12 | +#' Equivalently, generate data from a multivariate normal distribution given |
| 13 | +#' one of its SEM. Can generate both observational and intervention data. |
| 14 | +#' |
| 15 | +#' If \code{ivn = NULL}, then \code{n} observational samples are drawn. For each |
| 16 | +#' component of \code{ivn} that is not \code{NULL}, interventional samples will |
| 17 | +#' be drawn with the values of each node specified in the component. |
| 18 | +#' |
| 19 | +#' @param graph DAG in \code{\link{edgeList}} format. |
| 20 | +#' @param params Vector of parameters. Last p elements correspond to variances (p = number of nodes in \code{graph}), initial elements correspond to edge weights. |
| 21 | +#' @param n Number of samples to draw. |
| 22 | +#' @param ivn List of interventions (see \code{\link[sparsebnUtils]{sparsebnData}}). Must be a \code{list} with exactly \code{n} components. |
| 23 | +#' @param ivn.rand If \code{TRUE}, random N(0,1) values will be drawn for each intervention. Otherwise, these values need to supplied manually in \code{ivn}. |
| 24 | +#' |
| 25 | +#' @examples |
| 26 | +#' |
| 27 | +#' ### Generate observational data |
| 28 | +#' gr <- sparsebnUtils::random.graph(5, 5) # use sparsebnUtils package to generate a random graph |
| 29 | +#' gr.params <- runif(10) # there are 5 coefficients + 5 variances |
| 30 | +#' data.obs <- ccdrAlgorithm::generate_mvn_data(graph = gr, |
| 31 | +#' n = 100, |
| 32 | +#' params = gr.params) |
| 33 | +#' |
| 34 | +#' ### Generate experimental data |
| 35 | +#' ivn <- as.list(c(rep("V1", 50), rep("V2", 50))) # 50 interventions on V1, 50 interventions on V2 |
| 36 | +#' data.ivn <- ccdrAlgorithm::generate_mvn_data(graph = gr, |
| 37 | +#' n = 100, |
| 38 | +#' params = gr.params, |
| 39 | +#' ivn = ivn) |
| 40 | +#' |
| 41 | +#' @export |
| 42 | +generate_mvn_data <- function(graph, params, n = 1, ivn = NULL, ivn.rand = TRUE){ |
| 43 | + ### This function requires the 'igraph' package to be installed |
| 44 | + if (!requireNamespace("igraph", quietly = TRUE)) { |
| 45 | + stop("The igraph package is required for the method 'generate_mvn_data'. Please install it using install.packages(\"igraph\").", call. = FALSE) |
| 46 | + } |
| 47 | + |
| 48 | + stopifnot(sparsebnUtils::is.edgeList(graph)) |
| 49 | + stopifnot(is.numeric(params)) |
| 50 | + stopifnot(length(params) == sparsebnUtils::num.edges(graph) + sparsebnUtils::num.nodes(graph)) |
| 51 | + |
| 52 | + if(is.null(names(graph))){ |
| 53 | + stop("Input 'graph' requires node names!") |
| 54 | + } |
| 55 | + |
| 56 | + if(!is.null(ivn)){ |
| 57 | + stopifnot(is.list(ivn)) |
| 58 | + stopifnot(length(ivn) == n) |
| 59 | + |
| 60 | + ### Generate random intervention values |
| 61 | + if(ivn.rand){ |
| 62 | + ivn <- lapply(ivn, function(x) sapply(x, function(x) rnorm(n = 1, mean = 0, sd = 1))) # assume standard normal |
| 63 | + # ivn <- lapply(ivn, function(x) sapply(x, function(x) 1)) # debugging |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + ### Need this to ensure the output has the same order as the input |
| 68 | + ### after things get shuffled around |
| 69 | + original_node_order <- names(graph) |
| 70 | + |
| 71 | + ### Get topological sort |
| 72 | + ### Note that the check for the igraph pkg occurs in sparsebnUtils::to_igraph |
| 73 | + topsort <- names(igraph::topo_sort(sparsebnUtils::to_igraph(graph))) |
| 74 | + |
| 75 | + nnode <- length(original_node_order) |
| 76 | + vars <- utils::tail(params, nnode) # parameters associated with variances |
| 77 | + names(vars) <- original_node_order |
| 78 | + coefs <- params[1:(length(params) - nnode)] # parameters associated with edge weights |
| 79 | + sp <- sparsebnUtils::as.sparse(graph) |
| 80 | + sp$vals <- coefs # previous line leaves NAs for values in sparse object; need to fill these in |
| 81 | + edgelist <- sparse_to_edgeWeightList(sp, original_node_order) |
| 82 | + nodes <- names(edgelist) # this will be sorted according to the topological order |
| 83 | + |
| 84 | + ### The old way, efficient for obs data only |
| 85 | + # x <- replicate(n, generate_mvn_vector(edgelist, nodes, topsort, vars)) |
| 86 | + # x <- t(x)[, original_node_order] |
| 87 | + |
| 88 | + x <- vector("list", length = n) |
| 89 | + for(i in 1:n){ |
| 90 | + x[[i]] <- generate_mvn_vector(edgelist, nodes, topsort, vars, ivn = ivn[[i]]) |
| 91 | + } |
| 92 | + x <- do.call("rbind", x) |
| 93 | + |
| 94 | + ### Permute columns back to original ordering |
| 95 | + x <- x[, original_node_order] |
| 96 | + x |
| 97 | +} |
| 98 | + |
| 99 | +generate_mvn_vector <- function(edgelist, nodes, topsort, vars = NULL, ivn = NULL){ |
| 100 | + normal_seed <- sapply(vars, function(x) rnorm(n = 1, mean = 0, sd = sqrt(x))) |
| 101 | + gen_dag_vector_R(edgelist, nodes, topsort, seed = normal_seed, ivn = ivn) |
| 102 | +} |
| 103 | + |
| 104 | +# |
| 105 | +# edgelist = graph information |
| 106 | +# nodes = names of nodes in graph |
| 107 | +# topsort = topological sort (indexed by node names) |
| 108 | +# seed = random noise (Gaussian); bias term (binary) |
| 109 | +# ivn = named vector of intervention values (do(child = x)) |
| 110 | +# |
| 111 | +gen_dag_vector_R <- function(edgelist, nodes, topsort, seed, ivn = NULL){ |
| 112 | + nnode <- length(edgelist) |
| 113 | + x <- numeric(nnode) |
| 114 | + names(x) <- nodes |
| 115 | + ivnnames <- names(ivn) |
| 116 | + |
| 117 | + for(j in seq_along(topsort)){ |
| 118 | + child <- topsort[j] |
| 119 | + |
| 120 | + if(child %in% ivnnames){ |
| 121 | + ### If node is intervened on, fix value according to input in 'ivn' |
| 122 | + x[child] <- ivn[child] |
| 123 | + } else{ |
| 124 | + ### If no intervention, use DAG to determine value from parents |
| 125 | + parents <- edgelist[[child]]$parents |
| 126 | + weights <- edgelist[[child]]$weights |
| 127 | + nparents <- length(parents) |
| 128 | + if(nparents > 0){ |
| 129 | + ### Iterate over parents and add associated effects |
| 130 | + for(i in seq_along(parents)){ |
| 131 | + this.par <- parents[i] |
| 132 | + x[child] <- x[child] + weights[i] * x[this.par] |
| 133 | + # x[child] <- x[child] + weights[i] * x[index[i]] # equivalent to above line |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + ### Add noise: This is a crucial step. If nothing is added here, the |
| 138 | + ### output will be all zeroes since the root node(s) will |
| 139 | + ### have x[child] = 0 at this point. |
| 140 | + ### |
| 141 | + ### Gaussian model: This is random error ~ N(0, vars[j]) |
| 142 | + ### Logistic model: This a (deterministic) bias term |
| 143 | + x[child] <- x[child] + seed[child] |
| 144 | + } |
| 145 | + |
| 146 | + } |
| 147 | + |
| 148 | + x |
| 149 | +} |
| 150 | + |
| 151 | +sparse_to_edgeWeightList <- function(x, nodes){ |
| 152 | + stopifnot(sparsebnUtils::is.sparse((x))) |
| 153 | + # sp <- sparsebnUtils::as.sparse(x) # NOTE: no longer a bottleneck under sparsebnUtils v0.0.4 |
| 154 | + |
| 155 | + # nodes <- colnames(x) |
| 156 | + stopifnot(x$dim[1] == x$dim[2]) |
| 157 | + |
| 158 | + out <- lapply(vector("list", length = x$dim[1]), function(z) list(parents = character(0), index = integer(0), weights = numeric(0))) |
| 159 | + names(out) <- nodes |
| 160 | + for(j in seq_along(x$cols)){ |
| 161 | + child <- x$cols[[j]] |
| 162 | + parent <- x$rows[[j]] |
| 163 | + weight <- x$vals[[j]] |
| 164 | + parents <- c(out[[child]]$parents, nodes[parent]) # !!! THIS IS SLOW |
| 165 | + index <- c(out[[child]]$index, parent) # !!! THIS IS SLOW |
| 166 | + weights <- c(out[[child]]$weights, weight) # !!! THIS IS SLOW |
| 167 | + out[[nodes[child]]] <- list(parents = parents, index = index, weights = weights) |
| 168 | + } |
| 169 | + |
| 170 | + out |
| 171 | +} |
0 commit comments