R/dag_to_cpdag.R

Defines functions DAGtoCPDAG.cia_chain DAGtoCPDAG.cia_chains DAGtoCPDAG.matrix DAGtoCPDAG

Documented in DAGtoCPDAG

#' Convert DAG to CPDAG
#' 
#' @description
#' Converts a directed acyclic graph (DAG) into it's equivalence class 
#' corresponding to a completed partially directed acyclic graph (CPDAG).
#' 
#' @param x A matrix, cia_chain, or cia_chains object. When it is a chain(s)
#' object the state must be an adjacency matrix.
#' @returns x Returns same object type converted to a CPDAG.
#' 
#' @examples
#' dag <- UniformlySampleDAG(LETTERS[1:3])
#' DAGtoCPDAG(dag)
#' 
#' @export
DAGtoCPDAG <- function(x) UseMethod('DAGtoCPDAG')

#' @export
DAGtoCPDAG.matrix <- function(x) {
  
  cpdag_mat <- x |>
    toBNLearn() |>
    bnlearn::cpdag() |>
    toMatrix()
  
  return(cpdag_mat)
}

#' @export
DAGtoCPDAG.cia_chains <- function(x) {
  
  n_chains <- length(x)
  
  cl <- parallel::makeCluster(n_chains)
  doParallel::registerDoParallel(cl)
  i <- NULL
  chains <- foreach::foreach(i = 1:n_chains) %dopar% {
    DAGtoCPDAG(x[[i]])
  }
  parallel::stopCluster(cl)
  
  chains <- new_cia_chains(chains)
  
  return(chains)
}

#' @export
DAGtoCPDAG.cia_chain <- function(x) {
  
  x$state <- lapply(x$state, DAGtoCPDAG)
  
  return(x)
}

Try the cia package in your browser

Any scripts or data that you put into this service are public.

cia documentation built on April 4, 2025, 5:23 a.m.