| Title: | Causal Graph Interface |
| Version: | 1.0.0 |
| Description: | Create, query, and modify causal graphs. 'caugi' (Causal Graph Interface) is a causality-first, high performance graph package that provides a simple interface to build, structure, and examine causal relationships. |
| License: | MIT + file LICENSE |
| Language: | en-US |
| URL: | https://caugi.org/ |
| BugReports: | https://github.com/frederikfabriciusbjerre/caugi/issues |
| Depends: | R (≥ 4.2) |
| Imports: | data.table, fastmap, grid, S7, stats, methods |
| Suggests: | bnlearn, dagitty, devtools, ggm, graph, gRbase, igraph, jsonlite, knitr, MASS, Matrix, rextendr, rmarkdown, testthat |
| VignetteBuilder: | knitr |
| Config/rextendr/version: | 0.4.2 |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.3 |
| SystemRequirements: | Cargo (Rust's package manager), rustc >= 1.80.0, xz |
| Config/Needs/website: | rmarkdown |
| NeedsCompilation: | yes |
| Packaged: | 2026-01-22 10:07:22 UTC; jola |
| Author: | Frederik Fabricius-Bjerre [aut, cre, cph],
Johan Larsson |
| Maintainer: | Frederik Fabricius-Bjerre <frederik@fabriciusbjerre.dk> |
| Repository: | CRAN |
| Date/Publication: | 2026-01-22 11:00:13 UTC |
caugi (Causal Graph Interface)
Description
Create, query, and modify causal graphs. 'caugi' (Causal Graph Interface) is a causality-first, high performance graph package that provides a simple interface to build, structure, and examine causal relationships.
Author(s)
Maintainer: Frederik Fabricius-Bjerre frederik@fabriciusbjerre.dk [copyright holder]
Authors:
Johan Larsson johan@jolars.co (ORCID)
Michael Sachs sachsmc@gmail.com (ORCID)
See Also
Useful links:
Fit items on a line
Description
Helper function to determine how many items can fit on a line of given width, considering an indent.
Usage
.caugi_fit_on_line(items, width, indent)
Arguments
items |
A character vector of item labels. |
width |
An integer specifying the total line width. |
indent |
An integer specifying the indent width. |
Value
An integer indicating how many items fit on the line.
Create the state environment for a caugi (internal)
Description
Internal function to create the state environment for a
caugi. This function is not intended to be used directly by users.
Usage
.cg_state(nodes, edges, ptr, built, simple, class, name_index_map)
Arguments
nodes |
A |
edges |
A |
ptr |
A pointer to the underlying Rust graph structure
(or |
built |
Logical; whether the graph has been built. |
simple |
Logical; whether the graph is simple (no parallel edges or self-loops). |
class |
Character; one of |
name_index_map |
A |
Value
An environment containing the graph state.
Collect edges and nodes
Description
Collect edges (via .parse_edge_arg) and explicitly declared nodes (no edges).
Usage
.collect_edges_nodes(calls)
Arguments
calls |
A list of expressions from caugi(...) |
Value
A list with two elements:
edges: a
data.tablewith columnsfrom,edge,todeclared: a character vector of explicitly declared nodes
Combine terms with '+'
Description
Combine a list of terms into a single left-associative '+' call.
Usage
.combine_plus(terms)
Arguments
terms |
A list of expressions to combine. |
Value
A single expression combining the terms with '+'.
Does the expression contain an edge call?
Description
Recursively check if the expression contains any edge call.
Usage
.contains_edge(expr)
Arguments
expr |
An expression to check |
Value
TRUE if the expression contains an edge call, FALSE otherwise
Edge constructor
Description
Internal function to construct edges for caugi objects.
Usage
.edge_constructor(from = character(), edge = character(), to = character())
Arguments
from |
Character vector of source node names. |
edge |
Character vector of edge glyphs. |
to |
Character vector of target node names. |
Value
A data.table object with columns from, edge, and to.
Edge constructor using indices.
Description
Internal function to construct edges for caugi objects using indices.
Usage
.edge_constructor_idx(from_idx, edge, to_idx, node_names)
Arguments
from_idx |
Integer vector of source node indices. |
edge |
Character vector of edge glyphs. |
to_idx |
Integer vector of target node indices. |
node_names |
Character vector of node names. |
Value
A data.table object with columns from, edge, and to.
Get edge operators
Description
This function gets the default caugi edge operators
Usage
.edge_ops_get()
Value
The current edge operators of the caugi environment
Edge specification infix operators
Description
These infix operators are used to specify edges in
caugi(). This function helps build infix operators.
Usage
.edge_spec(from_sym, to_expr, glyph)
Arguments
from_sym |
A symbol representing the source node. |
to_expr |
An expression representing the target node(s).
Can be a symbol, string, number, |
glyph |
A string representing the edge glyph (e.g., |
Value
A data.table with columns from, to, and edge.
Infer edge type from anterior relationships
Description
Given two adjacent nodes, infers the edge type (directed, bidirected, or undirected) based on whether each node is in the anterior of the other combined with the conditioning set.
Usage
.edge_type_from_anteriors(node_a, node_b, cond_vars, anteriors_list)
Arguments
node_a |
First node name. |
node_b |
Second node name. |
cond_vars |
Conditioning variables. |
anteriors_list |
Pre-computed list of anteriors for all nodes. |
Value
A single-row data.table with from, edge, to columns.
Turn edge units into a data.table of edges
Description
Convert a list of edge units into a data.table with columns
from, edge, and to.
Usage
.edge_units_to_dt(units)
Arguments
units |
A list of edge units, each with |
Value
A data.table with columns from, edge, and to.
Expand node expressions
Description
Expand node expressions: symbol, "B", c(...), +, (...)
Usage
.expand_nodes(expr, env = parent.frame())
Arguments
expr |
An expression representing nodes. |
Value
A character vector of node names.
Helper to expand the right-hand side of an edge specification
Description
This function expands the right-hand side of an edge
specification into a character vector of target node names. It handles
various forms of input, including symbols, calls with +, calls with c(),
and character literals.
Usage
.expand_targets(expr)
Arguments
expr |
An expression representing the target node(s). |
Value
A character vector of target node names.
Flatten a chained edge expression
Description
Given a chained edge expression, flatten it into its terms and operators.
Usage
.flatten_edge_chain(call_expr)
Arguments
call_expr |
A call expression representing a chained edge. |
Value
A list with two elements, terms and ops.
Build edges data.table from verb call.
Description
Internal helper to build edges data.table from verb call.
Usage
.get_edges(from, edge, to, calls, simple = TRUE)
Arguments
from |
Character vector of source node names. |
edge |
Character vector of edge types. |
to |
Character vector of target node names. |
calls |
List of calls from |
simple |
Logical, whether the graph is simple or not. |
Value
A data.table with columns from, edge, and to.
Get nodes data.table from verb call.
Description
Internal helper to build nodes data.table from verb call.
Usage
.get_nodes(name, calls)
Arguments
name |
Character vector of node names. |
calls |
List of calls from |
Value
A data.table with column name for node names.
Output object of getter queries
Description
Helper to format the output of getter queries.
Usage
.getter_output(cg, idx0, nodes)
Arguments
cg |
A |
idx0 |
A vector of zero-based node indices. |
nodes |
A vector of node names. |
Value
A list of character vectors, each a set of node names. If only one node is requested, returns a character vector.
Get edge operators
Description
This function gets the default caugi edge glyphs
Usage
.glyph_map_get()
Value
The current edge glyphs of the caugi environment
Get glyph for an operator
Description
Get the glyph string for a given edge operator symbol.
Usage
.glyph_of(op_sym)
Arguments
op_sym |
A symbol representing the edge operator (e.g., |
Value
A string representing the edge glyph (e.g., "-->").
Is it an edge call / expression?
Description
This function checks if the expression is an edge call
Usage
.is_edge_call(expr)
Arguments
expr |
An expression to check |
Value
TRUE if the expression is an edge call, FALSE otherwise
Is it a node expr?
Description
Check if the expression is a valid node expression: symbol, string, number, c(...), +, (...)
Usage
.is_node_expr(expr)
Arguments
expr |
An expression to check |
Value
TRUE if the expression is a valid node expression, FALSE otherwise
Mark a caugi as not built.
Description
When a caugi is modified, it should be marked as not
built. This function sets the built attribute to FALSE. Thereby, the Rust
backend and the R frontend does not match, and at one point, the
caugi will need to be rebuild for it to be queried.
Usage
.mark_not_built(cg)
Arguments
cg |
A |
Value
The same caugi object, but with the built attribute set to
FALSE.
Node constructor
Description
A simple wrapper creating a data.table object with a single column name.
Usage
.node_constructor(names = character(), sort = FALSE)
Arguments
names |
Character vector of node names. |
sort |
Logical indicating whether to sort the node names. |
Details
The reason this exists is so if changes should be made in the future, it is
easy to simply change this constructor, rather than changing the calls to
data.table all over the place.
Value
A data.table object with a single column name.
Check if nodes are NOT m-separated for all conditioning subsets
Description
Tests whether two nodes fail to be m-separated for every possible
conditioning set formed from other_nodes combined with cond_vars.
If they are never separated, they must be adjacent in the resulting graph.
Usage
.not_m_separated_for_all_subsets(cg, node_a, node_b, other_nodes, cond_vars)
Arguments
cg |
A |
node_a |
First node name. |
node_b |
Second node name. |
other_nodes |
Other remaining nodes to form conditioning sets from. |
cond_vars |
Conditioning variables (always included in conditioning). |
Value
TRUE if nodes are not m-separated for any subset (i.e., adjacent).
Parse one caugi(...) argument
Description
Parse one caugi(...) argument into edge units
Usage
.parse_edge_arg(expr)
Arguments
expr |
An expression representing an edge with nodes |
Value
A list of edge units, each with lhs, rhs, and glyph.
Register a new edge operator
Description
Register a new edge operator for use in caugi().
Usage
.register_edge(glyph)
Arguments
glyph |
A string representing the edge glyph (e.g., |
Value
The operator name (e.g., "%-->%"), invisibly.
Resolve node name or index to 0-based index.
Description
Internal helper function to resolve either a node name or a
node index to a 0-based index.
.resolve_idx0_get uses get on the fastmap and expects a single value,
while .resolve_idx0_mget uses mget and can return multiple values.
Usage
.resolve_idx0_get(nm_idx_map, node_name = NULL, node_index = NULL)
.resolve_idx0_mget(nm_idx_map, node_name = NULL, node_index = NULL)
Arguments
nm_idx_map |
A |
node_name |
Optional character vector of node names. |
node_index |
Optional numeric vector of 1-based node indices. |
See Also
Create an edge unit from lhs, op, rhs
Description
Create an edge unit from lhs, op, rhs expressions.
Usage
.segment_units(lhs_term, op_chr, rhs_term)
Arguments
lhs_term |
An expression for the left-hand side nodes. |
op_chr |
A string representing the edge operator glyph. |
rhs_term |
An expression for the right-hand side nodes. |
Value
A list with elements lhs, rhs, and glyph.
Set names to an object
Description
Only made to avoid using stats::setNames.
Usage
.set_names(object = nm, nm)
Arguments
object |
An R object to which names are to be assigned. |
nm |
A character vector of names to assign to the object. |
Value
The input object with the assigned names.
Expand target expressions with =
Description
Split any expression into top-level '+' terms (fully flattened).
Usage
.split_plus(expr)
Arguments
expr |
An expression representing nodes. |
Value
A character vector of node names.
Update nodes and edges of a caugi
Description
Internal helper to add or remove nodes/edges and mark graph as not built.
Usage
.update_caugi(
cg,
nodes = NULL,
edges = NULL,
action = c("add", "remove"),
inplace = FALSE
)
Arguments
cg |
A |
nodes |
A |
edges |
A |
action |
One of |
inplace |
Logical, whether to modify the graph inplace or not. |
Value
The updated caugi object.
Convert a graph pointer to a caugi S7 object
Description
Convert a graph pointer from Rust to a caugi to a
S7 object.
Usage
.view_to_caugi(ptr, node_names = NULL)
Arguments
ptr |
A pointer to the underlying Rust graph structure. |
node_names |
Optional character vector of node names. If |
Value
A caugi object representing the graph.
Compose Plots Horizontally
Description
Arrange two plots side-by-side with configurable spacing. The + and |
operators are equivalent and can be used interchangeably. Compositions can
be nested to create complex multi-plot layouts.
Arguments
e1 |
A |
e2 |
A |
Details
The spacing between plots is controlled by the global option
caugi_options()$plot$spacing, which defaults to grid::unit(1, "lines").
Compositions can be nested arbitrarily:
-
p1 + p2- two plots side-by-side -
(p1 + p2) + p3- three plots in a row -
(p1 + p2) / p3- two plots on top, one below
Value
A caugi_plot object containing the composed layout
See Also
caugi_options() for configuring spacing and default styles
Other plotting:
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
caugi_plot(),
divide-caugi_plot-caugi_plot,
plot()
Examples
cg1 <- caugi(A %-->% B, B %-->% C)
cg2 <- caugi(X %-->% Y, Y %-->% Z)
p1 <- plot(cg1, main = "Graph 1")
p2 <- plot(cg2, main = "Graph 2")
# Horizontal composition
p1 + p2
p1 | p2 # equivalent
# Adjust spacing
caugi_options(plot = list(spacing = grid::unit(2, "lines")))
p1 + p2
Compute an adjustment set
Description
Computes an adjustment set for X -> Y in a DAG.
Usage
adjustment_set(
cg,
X = NULL,
Y = NULL,
X_index = NULL,
Y_index = NULL,
type = c("optimal", "parents", "backdoor")
)
Arguments
cg |
A |
X, Y |
Node names. |
X_index, Y_index |
Optional numeric 1-based indices. |
type |
One of |
Details
Types supported:
-
"parents":\bigcup \mathrm{Pa}(X)minusX \cup Y -
"backdoor": Pearl backdoor formula -
"optimal": O-set (only for singlexand singley)
Value
A character vector of node names representing the adjustment set.
See Also
Other adjustment:
all_adjustment_sets_admg(),
all_backdoor_sets(),
d_separated(),
is_valid_adjustment_admg(),
is_valid_backdoor()
Examples
cg <- caugi(
C %-->% X,
X %-->% F,
X %-->% D,
A %-->% X,
A %-->% K,
K %-->% Y,
D %-->% Y,
D %-->% G,
Y %-->% H,
class = "DAG"
)
adjustment_set(cg, "X", "Y", type = "parents") # C, A
adjustment_set(cg, "X", "Y", type = "backdoor") # C, A
adjustment_set(cg, "X", "Y", type = "optimal") # K
Adjustment Identification Distance
Description
Compute the Adjustment Identification Distance (AID) between two
graphs using the gadjid Rust package.
Usage
aid(truth, guess, type = c("oset", "ancestor", "parent"), normalized = TRUE)
Arguments
truth |
A |
guess |
A |
type |
A character string specifying the type of AID to compute.
Options are |
normalized |
Logical; if |
Value
A numeric representing the AID between the two graphs, if
normalized = TRUE, or an integer count if normalized = FALSE.
See Also
Examples
set.seed(1)
truth <- generate_graph(n = 100, m = 200, class = "DAG")
guess <- generate_graph(n = 100, m = 200, class = "DAG")
aid(truth, guess) # 0.0187
Get all valid adjustment sets in an ADMG
Description
Enumerates all valid adjustment sets for estimating the causal
effect of X on Y in an ADMG, up to a specified maximum size.
Usage
all_adjustment_sets_admg(
cg,
X = NULL,
Y = NULL,
X_index = NULL,
Y_index = NULL,
minimal = TRUE,
max_size = 3L
)
Arguments
cg |
A |
X, Y |
Node names (can be vectors for multiple treatments/outcomes). |
X_index, Y_index |
Optional 1-based indices. |
minimal |
Logical; if |
max_size |
Integer; maximum size of sets to consider (default 3). |
Value
A list of character vectors, each a valid adjustment set (possibly empty list if none exist).
See Also
Other adjustment:
adjustment_set(),
all_backdoor_sets(),
d_separated(),
is_valid_adjustment_admg(),
is_valid_backdoor()
Examples
cg <- caugi(
L %-->% X,
X %-->% Y,
L %-->% Y,
M %-->% Y,
class = "ADMG"
)
all_adjustment_sets_admg(cg, X = "X", Y = "Y", minimal = TRUE)
# Returns {L} as minimal adjustment set
Get all backdoor sets up to a certain size.
Description
This function returns the backdoor sets up to size max_size,
which per default is set to 10.
Usage
all_backdoor_sets(
cg,
X = NULL,
Y = NULL,
X_index = NULL,
Y_index = NULL,
minimal = TRUE,
max_size = 3L
)
Arguments
cg |
A |
X, Y |
Single node name. |
X_index, Y_index |
Optional 1-based indices (exclusive with name args). |
minimal |
Logical; if |
max_size |
Integer; maximum size of sets to consider (default 3). |
Value
A list of character vectors, each an adjustment set (possibly empty).
See Also
Other adjustment:
adjustment_set(),
all_adjustment_sets_admg(),
d_separated(),
is_valid_adjustment_admg(),
is_valid_backdoor()
Examples
cg <- caugi(
C %-->% X,
X %-->% F,
X %-->% D,
A %-->% X,
A %-->% K,
K %-->% Y,
D %-->% Y,
D %-->% G,
Y %-->% H,
class = "DAG"
)
all_backdoor_sets(cg, X = "X", Y = "Y", max_size = 3L, minimal = FALSE)
#> [[1]]
#> [1] "A"
#>
#> [[2]]
#> [1] "K"
#>
#> [[3]]
#> [1] "C" "A"
#>
#> [[4]]
#> [1] "C" "K"
#>
#> [[5]]
#> [1] "A" "K"
#>
#> [[6]]
#> [1] "C" "A" "K"
all_backdoor_sets(cg, X = "X", Y = "Y", max_size = 3L, minimal = TRUE)
#> [[1]]
#> [1] "A"
#>
#> [[2]]
#> [1] "K"
Get ancestors of nodes in a caugi
Description
Get ancestors of nodes in a caugi
Usage
ancestors(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
ancestors(cg, "A") # NULL
ancestors(cg, index = 2) # "A"
ancestors(cg, "B") # "A"
ancestors(cg, c("B", "C"))
#> $B
#> [1] "A"
#>
#> $C
#> [1] "A" "B"
Get anteriors of nodes in a caugi
Description
Get the anterior set of nodes in a graph. The anterior set (Richardson and Spirtes, 2002) includes all nodes reachable by following paths where every edge is either undirected or directed toward the target node.
For DAGs, the anterior set equals the ancestor set (since there are no undirected edges). For PDAGs, it includes both ancestors and nodes reachable via undirected edges.
Usage
anteriors(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
References
Richardson, T. and Spirtes, P. (2002). Ancestral graph Markov models. The Annals of Statistics, 30(4):962-1030.
See Also
Other queries:
ancestors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
# PDAG example with directed and undirected edges
cg <- caugi(
A %-->% B %---% C,
B %-->% D,
class = "PDAG"
)
anteriors(cg, "A") # NULL (no anteriors)
anteriors(cg, "C") # A, B
anteriors(cg, "D") # A, B, C
# For DAGs, anteriors equals ancestors
cg_dag <- caugi(
A %-->% B %-->% C,
class = "DAG"
)
anteriors(cg_dag, "C") # A, B
Convert a caugi to an adjacency matrix
Description
Does not take other edge types than the one found in a PDAG.
Usage
as_adjacency(x)
Arguments
x |
A |
Value
An integer 0/1 adjacency matrix with row/col names.
See Also
Other conversions:
as_bnlearn(),
as_caugi(),
as_dagitty(),
as_igraph()
Examples
cg <- caugi(
A %-->% B,
class = "DAG"
)
adj <- as_adjacency(cg)
Convert a caugi to a bnlearn network
Description
Convert a caugi to a bnlearn network
Usage
as_bnlearn(x)
Arguments
x |
A |
Value
A bnlearn DAG.
See Also
Other conversions:
as_adjacency(),
as_caugi(),
as_dagitty(),
as_igraph()
Examples
cg <- caugi(
A %-->% B,
class = "DAG"
)
g_bn <- as_bnlearn(cg)
Convert to a caugi
Description
Convert an object to a caugi. The object can be a
graphNEL, matrix, tidygraph, daggity, bn, or igraph.
Usage
as_caugi(
x,
class = c("DAG", "PDAG", "ADMG", "PAG", "UNKNOWN"),
simple = TRUE,
build = TRUE,
collapse = FALSE,
collapse_to = "---",
...
)
Arguments
x |
An object to convert to a |
class |
"DAG", "PDAG", "ADMG", "PAG", or "UNKNOWN".
"PAG" is only supported for integer coded matrices.
"ADMG" is for Acyclic Directed Mixed Graphs (with |
simple |
logical. If |
build |
logical. If |
collapse |
logical. If |
collapse_to |
Character string to use as the edge glyph when collapsing.
Should be a registered symmetrical edge glyph. Default is |
... |
Additional arguments passed to specific methods. |
Details
For matrices, as_caugi assumes that the rows are the from nodes
and the columns are the to nodes. Thus, for a graph, G: A –> B, we would
have that G["A", "B"] == 1 and G["B", "A"] == 0.
For PAGs, the integer codes are as follows (as used in pcalg):
0: no edge
1: circle (e.g.,
A o-o BorA o-- B)2: arrowhead (e.g.,
A --> BorA o-> B)3: tail (e.g.,
A o-- BorA --- B)
Value
A caugi object.
See Also
Other conversions:
as_adjacency(),
as_bnlearn(),
as_dagitty(),
as_igraph()
Examples
# igraph
ig <- igraph::graph_from_literal(A - +B, B - +C)
cg_ig <- as_caugi(ig, class = "DAG")
# graphNEL
gn <- graph::graphNEL(nodes = c("A", "B", "C"), edgemode = "directed")
gn <- graph::addEdge("A", "B", gn)
gn <- graph::addEdge("B", "C", gn)
cg_gn <- as_caugi(gn, class = "DAG")
# adjacency matrix
m <- matrix(0L, 3, 3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
m["A", "B"] <- 1L
m["B", "C"] <- 1L
cg_adj <- as_caugi(m, class = "DAG")
# bnlearn
bn <- bnlearn::model2network("[A][B|A][C|B]")
cg_bn <- as_caugi(bn, class = "DAG")
# dagitty
dg <- dagitty::dagitty("dag {
A -> B
B -> C
}")
cg_dg <- as_caugi(dg, class = "DAG")
cg <- caugi(A %-->% B %-->% C, class = "DAG")
# check that all nodes are equal in all graph objects
for (cg_converted in list(cg_ig, cg_gn, cg_adj, cg_bn, cg_dg)) {
stopifnot(identical(nodes(cg), nodes(cg_converted)))
stopifnot(identical(edges(cg), edges(cg_converted)))
}
# collapse mutual edges
ig2 <- igraph::graph_from_literal(A - +B, B - +A, C - +D)
cg2 <- as_caugi(ig2, class = "PDAG", collapse = TRUE, collapse_to = "---")
# coded integer matrix for PAGs (pcalg style)
nm <- c("A", "B", "C", "D")
M <- matrix(0L, 4, 4, dimnames = list(nm, nm))
# A --> B
M["A", "B"] <- 2L # mark at B end
M["B", "A"] <- 3L # mark at A end
# A --- C
M["A", "C"] <- 3L
M["C", "A"] <- 3L
# B o-> C
M["B", "C"] <- 2L
M["C", "B"] <- 1L
# C o-o D
M["C", "D"] <- 1L
M["D", "C"] <- 1L
cg <- as_caugi(M, class = "PAG")
Convert a caugi to a dagitty graph
Description
Convert a caugi to a dagitty graph
Usage
as_dagitty(x)
Arguments
x |
A |
Value
A dagitty object.
See Also
Other conversions:
as_adjacency(),
as_bnlearn(),
as_caugi(),
as_igraph()
Examples
cg <- caugi(
A %-->% B,
class = "DAG"
)
g_dg <- as_dagitty(cg)
Convert a caugi to an igraph object
Description
Convert a caugi to an igraph object
Usage
as_igraph(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Value
An igraph object representing the same graph structure.
See Also
Other conversions:
as_adjacency(),
as_bnlearn(),
as_caugi(),
as_dagitty()
Examples
cg <- caugi(
A %-->% B,
class = "DAG"
)
ig <- as_igraph(cg)
Build the graph now
Description
If a caugi has been modified (nodes or edges added or
removed), it is marked as not built, i.e cg@built = FALSE.
This function builds the graph using the Rust backend and updates the
internal pointer to the graph. If the graph is already built, it is returned.
Usage
build(cg, ...)
Arguments
cg |
A |
... |
Not used. |
Value
The built caugi object.
See Also
Other verbs:
caugi_verbs
Examples
# initialize empty graph and build slowly
cg <- caugi(class = "PDAG")
cg <- cg |>
add_nodes(c("A", "B", "C", "D", "E")) |> # A, B, C, D, E
add_edges(A %-->% B %-->% C) |> # A --> B --> C, D, E
set_edges(B %---% C) # A --> B --- C, D, E
cg <- remove_edges(cg, B %---% C) |> # A --> B, C, D, E
remove_nodes(c("C", "D", "E")) # A --> B
# verbs do not build the Rust backend
cg@built # FALSE
build(cg)
cg@built # TRUE
Create a caugi from edge expressions.
Description
Create a caugi from a series of edge expressions using
infix operators. Nodes can be specified as symbols, strings, or numbers.
The following edge operators are supported by default:
-
%-->%for directed edges (A –> B) -
%---%for undirected edges (A — B) -
%<->%for bidirected edges (A <-> B) -
%o->%for partially directed edges (A o-> B) -
%--o%for partially undirected edges (A –o B) -
%o-o%for partial edges (A o-o B)
You can register additional edge types using register_caugi_edge().
Usage
caugi(
...,
from = NULL,
edge = NULL,
to = NULL,
nodes = NULL,
edges_df = NULL,
simple = TRUE,
build = TRUE,
class = c("AUTO", "DAG", "UG", "PDAG", "ADMG", "AG", "UNKNOWN"),
state = NULL
)
Arguments
... |
Edge expressions using the supported infix operators, or
nodes given by symbols or strings. Multiple edges can be
combined using |
from |
Character vector of source node names.
Optional; mutually exclusive with |
edge |
Character vector of edge types.
Optional; mutually exclusive with |
to |
Character vector of target node names.
Optional; mutually exclusive with |
nodes |
Character vector of node names to declare as isolated nodes.
An optional, but recommended, option is to provide all node names in the
graph, including those that appear in edges. If |
edges_df |
Optional data.frame or data.table with columns
|
simple |
Logical; if |
build |
Logical; if |
class |
Character; one of |
state |
For internal use. Build a graph by supplying a pre-constructed state environment. |
Value
A caugi S7 object containing the nodes, edges, and a
pointer to the underlying Rust graph structure.
Examples
# create a simple DAG (using NSE)
cg <- caugi(
A %-->% B + C,
B %-->% D,
class = "DAG"
)
# create a PDAG with undirected edges (using NSE)
cg2 <- caugi(
A %-->% B + C,
B %---% D,
E, # no neighbors for this node
class = "PDAG"
)
# create a DAG (using SE)
cg3 <- caugi(
from = c("A", "A", "B"),
edge = c("-->", "-->", "-->"),
to = c("B", "C", "D"),
nodes = c("A", "B", "C", "D", "E"),
class = "DAG"
)
# create a non-simple graph
cg4 <- caugi(
A %-->% B,
B %-->% A,
class = "UNKNOWN",
simple = FALSE
)
cg4@simple # FALSE
cg4@built # TRUE
cg4@graph_class # "UNKNOWN"
# create graph, but don't built Rust object yet, which is needed for queries
cg5 <- caugi(
A %-->% B + C,
B %-->% D,
class = "DAG",
build = FALSE
)
cg5@built # FALSE
Default options for caugi
Description
Returns the default options for the caugi package. Useful for resetting options to their original state.
Usage
caugi_default_options()
Value
A list of default options for caugi.
See Also
caugi_options() for setting and getting options
Examples
# Get defaults
caugi_default_options()
# Reset to defaults
caugi_options(caugi_default_options())
Deserialize caugi Graph from JSON String
Description
Converts a JSON string in the native caugi format back to a caugi graph.
This is a lower-level function; consider using read_caugi() for
reading from files.
Usage
caugi_deserialize(json, lazy = FALSE)
Arguments
json |
Character string containing the JSON representation. |
lazy |
Logical; if |
Value
A caugi object.
See Also
Other export:
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(A %-->% B, class = "DAG")
json <- caugi_serialize(cg)
cg2 <- caugi_deserialize(json)
S7 Class for DOT Export
Description
An S7 object that wraps a DOT format string for displaying caugi graphs. When printed interactively, displays the DOT string cleanly.
Usage
caugi_dot(content)
Arguments
content |
A character string containing the DOT format graph. |
See Also
Other export:
caugi_deserialize(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
S7 Base Class for Caugi Exports
Description
A base class for all caugi export formats. Provides common structure and behavior for different export formats (DOT, GraphML, etc.).
Usage
caugi_export(content = character(0), format = character(0))
Arguments
content |
A character string containing the exported graph. |
format |
A character string indicating the export format. |
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
S7 Class for GraphML Export
Description
An S7 object that wraps a GraphML format string for caugi graphs.
Usage
caugi_graphml(content)
Arguments
content |
A character string containing the GraphML format graph. |
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Compute Graph Layout
Description
Computes node coordinates for graph visualization using specified layout algorithm. If the graph has not been built yet, it will be built automatically before computing the layout.
Usage
caugi_layout(
x,
method = c("auto", "sugiyama", "fruchterman-reingold", "kamada-kawai", "bipartite",
"tiered"),
packing_ratio = 1.618034,
...
)
Arguments
x |
A |
method |
Character string specifying the layout method. Options:
|
packing_ratio |
Aspect ratio for packing disconnected components
(width/height). Default is the golden ratio (1.618) which works well with
widescreen displays. Use |
... |
Additional arguments passed to the specific layout function.
For bipartite layouts, use |
Value
A data.frame with columns name, x, and y containing node
names and their coordinates.
Layout Algorithms
Sugiyama (Hierarchical Layout)
Optimized for directed acyclic graphs (DAGs). Places nodes in layers to emphasize hierarchical structure and causal flow from top to bottom. Edges are routed to minimize crossings. Best for visualizing clear cause-effect relationships. Only works with directed edges.
Fruchterman-Reingold (Spring-Electrical)
Fast force-directed layout using a spring-electrical model. Treats edges as springs and nodes as electrically charged particles. Produces organic, symmetric layouts with uniform edge lengths. Good for general-purpose visualization and works with all edge types. Results are deterministic.
Kamada-Kawai (Stress Minimization)
High-quality force-directed layout that minimizes "stress" by making Euclidean distances proportional to graph-theoretic distances. Better preserves the global structure and path lengths compared to Fruchterman-Reingold. Ideal for publication-quality visualizations where accurate distance representation matters. Works with all edge types and produces deterministic results.
Source
Fruchterman, T. M. J., & Reingold, E. M. (1991). Graph drawing by force-directed placement. Software: Practice and Experience, 21(11), 1129-1164. doi:10.1002/spe.4380211102
Kamada, T., & Kawai, S. (1989). An algorithm for drawing general undirected graphs. Information Processing Letters, 31(1), 7-15. doi:10.1016/0020-0190(89)90102-6
Sugiyama, K., Tagawa, S., & Toda, M. (1981). Methods for visual understanding of hierarchical system structures. IEEE Transactions on Systems, Man, and Cybernetics, 11(2), 109-125. doi:10.1109/TSMC.1981.4308636
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
caugi_plot(),
divide-caugi_plot-caugi_plot,
plot()
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
# Default: auto-selects best layout
layout <- caugi_layout(cg)
# Auto-selects tiered when tiers provided
cg_tiered <- caugi(X1 %-->% M1, X2 %-->% M2, M1 %-->% Y, M2 %-->% Y)
tiers <- list(c("X1", "X2"), c("M1", "M2"), "Y")
layout_auto <- caugi_layout(cg_tiered, tiers = tiers) # Uses "tiered"
# Explicitly use hierarchical layout
layout_sug <- caugi_layout(cg, method = "sugiyama")
# Use force-directed for organic appearance
layout_fr <- caugi_layout(cg, method = "fruchterman-reingold")
# Use stress minimization for publication quality
layout_kk <- caugi_layout(cg, method = "kamada-kawai")
# Bipartite layout with auto-detected partition
cg_bp <- caugi(A %-->% X, A %-->% Y, B %-->% X, B %-->% Y)
layout_bp_rows <- caugi_layout(
cg_bp,
method = "bipartite",
orientation = "rows"
)
# Explicit partition
partition <- c(TRUE, TRUE, FALSE, FALSE)
layout_bp_cols <- caugi_layout(
cg_bp,
method = "bipartite",
partition = partition,
orientation = "columns"
)
# Tiered layout with three tiers
cg_tiered <- caugi(
X1 %-->% M1 + M2,
X2 %-->% M1 + M2,
M1 %-->% Y,
M2 %-->% Y
)
tiers <- list(c("X1", "X2"), c("M1", "M2"), "Y")
layout_tiered <- caugi_layout(
cg_tiered,
method = "tiered",
tiers = tiers,
orientation = "rows"
)
Bipartite Graph Layout
Description
Computes node coordinates for bipartite graphs, placing nodes in two parallel lines (rows or columns) based on a partition. If the graph has not been built yet, it will be built automatically before computing the layout.
Usage
caugi_layout_bipartite(x, partition = NULL, orientation = c("columns", "rows"))
Arguments
x |
A |
partition |
Optional logical vector indicating node partitions.
Nodes with |
orientation |
Character string specifying the layout orientation:
|
Value
A data.frame with columns name, x, and y containing node
names and their coordinates.
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
caugi_plot(),
divide-caugi_plot-caugi_plot,
plot()
Examples
# Create a bipartite graph (causes -> effects)
cg <- caugi(A %-->% X, A %-->% Y, B %-->% X, B %-->% Y)
partition <- c(TRUE, TRUE, FALSE, FALSE) # A, B = causes, X, Y = effects
# Two horizontal rows (causes on top)
layout_rows <- caugi_layout_bipartite(cg, partition, orientation = "rows")
# Two vertical columns (causes on right)
layout_cols <- caugi_layout_bipartite(cg, partition, orientation = "columns")
Fruchterman-Reingold Force-Directed Layout
Description
Computes node coordinates using the Fruchterman-Reingold force-directed layout algorithm. Fast spring-electrical model that treats edges as springs and nodes as electrically charged particles. Produces organic, symmetric layouts with uniform edge lengths. Works with all edge types and produces deterministic results.
Usage
caugi_layout_fruchterman_reingold(x, packing_ratio = 1.618034, ...)
Arguments
x |
A |
packing_ratio |
Aspect ratio for packing disconnected components
(width/height). Default is the golden ratio (1.618) which works well with
widescreen displays. Use |
... |
Ignored. For future extensibility. |
Value
A data.frame with columns name, x, and y containing node
names and their coordinates.
Source
Fruchterman, T. M. J., & Reingold, E. M. (1991). Graph drawing by force-directed placement. Software: Practice and Experience, 21(11), 1129-1164. doi:10.1002/spe.4380211102
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
caugi_plot(),
divide-caugi_plot-caugi_plot,
plot()
Examples
cg <- caugi(
A %-->% B,
B %<->% C,
C %-->% D
)
layout <- caugi_layout_fruchterman_reingold(cg)
Kamada-Kawai Stress Minimization Layout
Description
Computes node coordinates using the Kamada-Kawai stress minimization algorithm. High-quality force-directed layout that minimizes "stress" by making Euclidean distances proportional to graph-theoretic distances. Better preserves global structure and path lengths compared to Fruchterman-Reingold. Ideal for publication-quality visualizations. Works with all edge types and produces deterministic results.
Usage
caugi_layout_kamada_kawai(x, packing_ratio = 1.618034, ...)
Arguments
x |
A |
packing_ratio |
Aspect ratio for packing disconnected components
(width/height). Default is the golden ratio (1.618) which works well with
widescreen displays. Use |
... |
Ignored. For future extensibility. |
Value
A data.frame with columns name, x, and y containing node
names and their coordinates.
Source
Kamada, T., & Kawai, S. (1989). An algorithm for drawing general undirected graphs. Information Processing Letters, 31(1), 7-15. doi:10.1016/0020-0190(89)90102-6
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
caugi_plot(),
divide-caugi_plot-caugi_plot,
plot()
Examples
cg <- caugi(
A %-->% B,
B %<->% C,
C %-->% D
)
layout <- caugi_layout_kamada_kawai(cg)
Sugiyama Hierarchical Layout
Description
Computes node coordinates using the Sugiyama hierarchical layout algorithm. Optimized for directed acyclic graphs (DAGs), placing nodes in layers to emphasize hierarchical structure and causal flow from top to bottom.
Usage
caugi_layout_sugiyama(x, packing_ratio = 1.618034, ...)
Arguments
x |
A |
packing_ratio |
Aspect ratio for packing disconnected components
(width/height). Default is the golden ratio (1.618) which works well with
widescreen displays. Use |
... |
Ignored. For future extensibility. |
Value
A data.frame with columns name, x, and y containing node
names and their coordinates.
Source
Sugiyama, K., Tagawa, S., & Toda, M. (1981). Methods for visual understanding of hierarchical system structures. IEEE Transactions on Systems, Man, and Cybernetics, 11(2), 109-125. doi:10.1109/TSMC.1981.4308636
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_tiered(),
caugi_plot(),
divide-caugi_plot-caugi_plot,
plot()
Examples
cg <- caugi(A %-->% B + C, B %-->% D, C %-->% D, class = "DAG")
layout <- caugi_layout_sugiyama(cg)
Tiered Graph Layout
Description
Computes node coordinates for graphs with multiple tiers (layers), placing nodes in parallel rows or columns based on tier assignments. If the graph has not been built yet, it will be built automatically before computing the layout.
Usage
caugi_layout_tiered(x, tiers, orientation = c("columns", "rows"))
Arguments
x |
A |
tiers |
Tier assignments specifying which tier each node belongs to. Can be provided in multiple formats:
All nodes must be assigned to a tier, all tiers must be non-empty, and tier indices must be consecutive starting from 0 or 1. |
orientation |
Character string specifying the layout orientation:
|
Value
A data.frame with columns name, x, y, and tier containing
node names, their coordinates, and tier assignments (0-indexed). The
returned data.frame also has an orientation attribute storing the
orientation used. When passed to plot(), tier information is
automatically extracted, so you don't need to specify tiers again.
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_plot(),
divide-caugi_plot-caugi_plot,
plot()
Examples
# Create a three-tier causal graph (exposures -> mediators -> outcome)
cg <- caugi(
X1 %-->% M1 + M2,
X2 %-->% M1 + M2,
M1 %-->% Y,
M2 %-->% Y
)
# Option 1: Named list (tier names are just labels)
tiers <- list(
exposures = c("X1", "X2"),
mediators = c("M1", "M2"),
outcome = "Y"
)
layout_rows <- caugi_layout_tiered(cg, tiers, orientation = "rows")
# Option 2: Named numeric vector (0-indexed or 1-indexed both work)
tiers <- c(X1 = 1, X2 = 1, M1 = 2, M2 = 2, Y = 3)
layout_cols <- caugi_layout_tiered(cg, tiers, orientation = "columns")
# Option 3: Data.frame
tiers <- data.frame(
name = c("X1", "X2", "M1", "M2", "Y"),
tier = c(1, 1, 2, 2, 3)
)
layout <- caugi_layout_tiered(cg, tiers, orientation = "rows")
# The layout includes tier information, so plot() works without passing tiers
plot(cg, layout = layout)
S7 Class for Mermaid Export
Description
An S7 object that wraps a Mermaid format string for displaying caugi graphs. When printed interactively, displays the Mermaid string cleanly.
Usage
caugi_mermaid(content)
Arguments
content |
A character string containing the Mermaid format graph. |
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Get or set global options for caugi
Description
Configure global defaults for caugi, including plot composition spacing and default visual styles for nodes, edges, labels, and titles.
Usage
caugi_options(...)
Arguments
... |
Named values to update options with, or unnamed option names to retrieve. To query all options, call without arguments. |
Details
Currently supported options are nested under the plot key:
-
spacing: Agrid::unit()controlling space between composed plots (default:grid::unit(1, "lines")) -
node_style: List of default node appearance parameters:-
fill: Fill color (default:"lightgrey") -
padding: Padding around labels in mm (default:2) -
size: Size multiplier (default:1)
-
-
edge_style: List of default edge appearance parameters:-
arrow_size: Arrow size in mm (default:3) -
circle_size: Radius of endpoint circles for partial edges in mm (default:1.5) -
fill: Arrow/line color (default:"black")
-
-
label_style: List of label text parameters (seegrid::gpar()) -
title_style: List of title text parameters:-
col: Text color (default:"black") -
fontface: Font face (default:"bold") -
fontsize: Font size in pts (default:14.4)
-
Options set via caugi_options() serve as global defaults that can be
overridden by arguments to plot().
Value
When setting, returns (invisibly) the previous values for the updated options. When getting (no arguments or unnamed character vector), returns the requested options.
See Also
plot() for per-plot style arguments, grid::gpar() for
available graphical parameters
Examples
# Query all options
caugi_options()
# Query specific option
caugi_options("plot")
# Set plot spacing
caugi_options(plot = list(spacing = grid::unit(2, "lines")))
# Set default node style
caugi_options(plot = list(
node_style = list(fill = "lightblue", padding = 3)
))
# Set multiple options at once
caugi_options(plot = list(
spacing = grid::unit(1.5, "lines"),
node_style = list(fill = "lightblue", padding = 3),
edge_style = list(arrow_size = 4, fill = "darkgray"),
title_style = list(col = "blue", fontsize = 16)
))
# Reset to defaults
caugi_options(caugi_default_options())
S7 Class for caugi Plot
Description
An S7 object that wraps a grid gTree for displaying caugi graphs. Similar to ggplot objects, these are created by the plot method but not drawn until explicitly printed or plotted. This allows for returning plot objects from functions and controlling when/where they are displayed.
Usage
caugi_plot(grob = NULL)
Arguments
grob |
A grid gTree representing the graph plot. |
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
divide-caugi_plot-caugi_plot,
plot()
Serialize caugi Graph to JSON String
Description
Converts a caugi graph to a JSON string in the native caugi format.
This is a lower-level function; consider using write_caugi() for
writing to files.
Usage
caugi_serialize(x, comment = NULL, tags = NULL)
Arguments
x |
A |
comment |
Optional character string with a comment about the graph. |
tags |
Optional character vector of tags for categorizing the graph. |
Value
A character string containing the JSON representation.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(A %-->% B, class = "DAG")
json <- caugi_serialize(cg)
cat(json)
Manipulate nodes and edges of a caugi
Description
Add, remove, or and set nodes or edges to / from a caugi
object. Edges can be specified using expressions with the infix operators.
Alternatively, the edges to be added are specified using the
from, edge, and to arguments.
Usage
add_edges(cg, ..., from = NULL, edge = NULL, to = NULL, inplace = FALSE)
remove_edges(cg, ..., from = NULL, edge = NULL, to = NULL, inplace = FALSE)
set_edges(cg, ..., from = NULL, edge = NULL, to = NULL, inplace = FALSE)
add_nodes(cg, ..., name = NULL, inplace = FALSE)
remove_nodes(cg, ..., name = NULL, inplace = FALSE)
Arguments
cg |
A |
... |
Expressions specifying edges to add using the infix operators,
or nodes to add using unquoted names, vectors via |
from |
Character vector of source node names. Default is |
edge |
Character vector of edge types. Default is |
to |
Character vector of target node names. Default is |
inplace |
Logical, whether to modify the graph inplace or not.
If |
name |
Character vector of node names. Default is |
Details
Caugi graph verbs
Value
The updated caugi.
Functions
-
add_edges(): Add edges. -
remove_edges(): Remove edges. -
set_edges(): Set edge type for given pair(s). -
add_nodes(): Add nodes. -
remove_nodes(): Remove nodes.
See Also
Other verbs:
build()
Examples
# initialize empty graph and build slowly
cg <- caugi(class = "PDAG")
cg <- cg |>
add_nodes(c("A", "B", "C", "D", "E")) |> # A, B, C, D, E
add_edges(A %-->% B %-->% C) |> # A --> B --> C, D, E
set_edges(B %---% C) # A --> B --- C, D, E
cg <- remove_edges(cg, B %---% C) |> # A --> B, C, D, E
remove_nodes(c("C", "D", "E")) # A --> B
# verbs do not build the Rust backend
cg@built # FALSE
build(cg)
cg@built # TRUE
Get children of nodes in a caugi
Description
Get children of nodes in a graph (nodes with directed edges pointing OUT
from the target nodes).
This is equivalent to neighbors(cg, nodes, mode = "out").
Usage
children(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
ancestors(),
anteriors(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
children(cg, "A") # "B"
children(cg, index = 2) # "C"
children(cg, "B") # "C"
children(cg, c("B", "C"))
#> $B
#> [1] "C"
#>
#> $C
#> NULL
Marginalize and/or condition on variables in an ancestral graph (AG)
Description
Marginalize variables out of an AG, and/or condition on variables. Depending on the structure, it could produce a graph with directed, bidirected, and undirected edges.
Usage
condition_marginalize(cg, cond_vars = NULL, marg_vars = NULL)
Arguments
cg |
A |
cond_vars |
Character vector of nodes to condition on. |
marg_vars |
Character vector of nodes to marginalize over. |
Value
A caugi object of class "AG".
References
Definition 4.2.1 in Thomas Richardson. Peter Spirtes. "Ancestral graph Markov models." Ann. Statist. 30 (4) 962 - 1030, August 2002. doi:10.1214/aos/1031689015
See Also
Other operations:
exogenize(),
latent_project(),
moralize(),
mutate_caugi(),
skeleton()
Examples
mg <- caugi(
U %-->% X + Y,
A %-->% X,
B %-->% Y,
class = "DAG"
)
condition_marginalize(mg, marg_vars = "U") # ADMG
condition_marginalize(mg, cond_vars = "U") # DAG
Are X and Y d-separated given Z?
Description
Checks whether every node in X is d-separated from every node
in Y given Z in a DAG.
Usage
d_separated(
cg,
X = NULL,
Y = NULL,
Z = NULL,
X_index = NULL,
Y_index = NULL,
Z_index = NULL
)
Arguments
cg |
A |
X, Y, Z |
Node selectors: character vector of names, unquoted expression
(supports |
X_index, Y_index, Z_index |
Optional numeric 1-based indices (exclusive
with |
Value
TRUE if d-separated, FALSE otherwise.
See Also
Other adjustment:
adjustment_set(),
all_adjustment_sets_admg(),
all_backdoor_sets(),
is_valid_adjustment_admg(),
is_valid_backdoor()
Examples
cg <- caugi(
C %-->% X,
X %-->% F,
X %-->% D,
A %-->% X,
A %-->% K,
K %-->% Y,
D %-->% Y,
D %-->% G,
Y %-->% H,
class = "DAG"
)
d_separated(cg, "X", "Y", Z = c("A", "D")) # TRUE
d_separated(cg, "X", "Y", Z = NULL) # FALSE
Get descendants of nodes in a caugi
Description
Get descendants of nodes in a caugi
Usage
descendants(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
ancestors(),
anteriors(),
children(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
descendants(cg, "A") # "B" "C"
descendants(cg, index = 2) # "C"
descendants(cg, "B") # "C"
descendants(cg, c("B", "C"))
#> $B
#> [1] "C"
#>
#> $C
#> NULL
Get districts (c-components) of an ADMG
Description
Get the districts (c-components) of an ADMG. A district is a maximal set of nodes connected via bidirected edges.
Usage
districts(cg)
Arguments
cg |
A |
Value
A list of character vectors, each containing the nodes in a district.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
A %<->% C,
D %<->% E,
class = "ADMG"
)
districts(cg)
# Returns list with districts: {A, C}, {B}, {D, E}
Compose Plots Vertically
Description
Stack two plots vertically with configurable spacing. Compositions can be nested to create complex multi-plot layouts.
Arguments
e1 |
A |
e2 |
A |
Details
The spacing between plots is controlled by the global option
caugi_options()$plot$spacing, which defaults to grid::unit(1, "lines").
Compositions can be nested arbitrarily:
-
p1 / p2- two plots stacked vertically -
p1 / p2 / p3- three plots in a column -
(p1 + p2) / p3- two plots on top, one below
Value
A caugi_plot object containing the composed layout
See Also
caugi_options() for configuring spacing and default styles
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
caugi_plot(),
plot()
Examples
cg1 <- caugi(A %-->% B, B %-->% C)
cg2 <- caugi(X %-->% Y, Y %-->% Z)
p1 <- plot(cg1, main = "Graph 1")
p2 <- plot(cg2, main = "Graph 2")
# Vertical composition
p1 / p2
# Mixed composition
(p1 + p2) / p1
Infix operators for edge specifications
Description
These operators are used to specify edges in caugi().
Should be used internally in caugi() calls.
Usage
lhs %-->% rhs
lhs %---% rhs
lhs %<->% rhs
lhs %o-o% rhs
lhs %--o% rhs
lhs %o->% rhs
Arguments
lhs |
The left-hand side node expression. |
rhs |
The right-hand side node expression. |
Value
A data.table with columns from, to, and edge.
Get the edge types of a caugi.
Description
Get the edge types of a caugi.
Usage
edge_types(cg)
Arguments
cg |
A |
Value
A character vector of edge types.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %--o% C,
C %<->% D,
D %---% E,
A %o-o% E,
class = "UNKNOWN"
)
edge_types(cg) # returns c("-->", "o-o", "--o", "<->", "---")
Get edges of a caugi.
Description
Get edges of a caugi.
Usage
edges(cg)
E(cg)
Arguments
cg |
A |
Value
A data.table with columns from, edge, and to.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
D,
class = "DAG"
)
edges(cg) # returns the data.table with columns from, edge, to
Exogenize a graph
Description
Exogenize a graph by removing all ingoing edges to the set of nodes specified (i.e., make the nodes exogenous), as well as joining the parents of the nodes specified to the children of the nodes specified.
Usage
exogenize(cg, nodes)
Arguments
cg |
A |
nodes |
A character vector of node names to exogenize. Must be a subset of the nodes in the graph. |
Value
A caugi object representing the exogenized graph.
See Also
Other operations:
condition_marginalize(),
latent_project(),
moralize(),
mutate_caugi(),
skeleton()
Examples
cg <- caugi(A %-->% B, class = "DAG")
exogenize(cg, nodes = "B") # A, B
Get all exogenous nodes in a caugi
Description
Get all exogenous nodes (nodes with no parents) in a
caugi.
Usage
exogenous(cg, undirected_as_parents = FALSE)
Arguments
cg |
A |
undirected_as_parents |
Logical; if |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
exogenous(cg) # "A"
Export Format Classes
Description
S7 classes for representing caugi graphs in various export formats. These classes provide a common interface for serializing graphs to different text formats like DOT, GraphML, JSON, etc.
Base Class
caugi_export is the base class for all export formats. It provides:
-
contentproperty: Character string containing the serialized graph -
formatproperty: Character string indicating the format type Common methods:
print(),as.character(),knit_print()
Subclasses
-
caugi_dot: DOT format for Graphviz visualization -
caugi_mermaid: Mermaid format for web-based visualization
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Caugi Native Format Serialization
Description
Functions for converting caugi graphs to and from the native caugi JSON format. This format provides efficient, reproducible serialization for saving and sharing caugi graphs.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
DOT Format Export and Import
Description
Functions for converting caugi graphs to and from Graphviz DOT format. The DOT format is a plain text graph description language used by Graphviz tools for visualization.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
GraphML Format Export and Import
Description
Functions for converting caugi graphs to and from GraphML format. GraphML is an XML-based file format for graphs supported by many graph tools and libraries.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Mermaid Format Export
Description
Functions for converting caugi graphs to Mermaid flowchart format. Mermaid is a JavaScript-based diagramming tool that renders in web browsers and is natively supported by Quarto, GitHub, and many other platforms.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Generate a caugi using Erdős-Rényi.
Description
Sample a random DAG or CPDAG using Erdős-Rényi for random graph generation.
Usage
generate_graph(n, m = NULL, p = NULL, class = c("DAG", "CPDAG"))
Arguments
n |
Integer >= 0. Number of nodes in the graph. |
m |
Integer in |
p |
Numeric in |
class |
"DAG" or "CPDAG". |
Value
The sampled caugi object.
See Also
Other simulation functions:
simulate_data()
Examples
# generate a random DAG with 5 nodes and 4 edges
dag <- generate_graph(n = 5, m = 4, class = "DAG")
# generate a random CPDAG with 5 nodes and edge probability 0.3
cpdag <- generate_graph(n = 5, p = 0.3, class = "CPDAG")
Hamming Distance
Description
Compute the Hamming Distance between two graphs.
Usage
hd(cg1, cg2, normalized = FALSE)
Arguments
cg1 |
A |
cg2 |
A |
normalized |
Logical; if |
Value
An integer representing the Hamming Distance between the two graphs,
if normalized = FALSE, or a numeric between 0 and 1 if normalized = TRUE.
See Also
Examples
cg1 <- caugi(A %-->% B %-->% C, D %-->% C, class = "DAG")
cg2 <- caugi(A %-->% B %-->% C, D %---% C, class = "PDAG")
hd(cg1, cg2) # 0
Is the caugi acyclic?
Description
Checks if the given caugi graph is acyclic.
Usage
is_acyclic(cg, force_check = FALSE)
Arguments
cg |
A |
force_check |
Logical; if |
Details
Logically, it should not be possible to have a graph class of "DAG" or "PDAG" that has cycles, but in case the user modified the graph after creation in some unforeseen way that could have introduced cycles, this function allows to force a check of acyclicity, if needed.
Value
A logical value indicating whether the graph is acyclic.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_acyclic <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
is_acyclic(cg_acyclic) # TRUE
cg_cyclic <- caugi(
A %-->% B,
B %-->% C,
C %-->% A,
class = "UNKNOWN"
)
is_acyclic(cg_cyclic) # FALSE
Is the caugi graph an ADMG?
Description
Checks if the given caugi graph is an
Acyclic Directed Mixed Graph (ADMG).
An ADMG contains only directed (-->) and bidirected (<->) edges,
and the directed part must be acyclic.
Usage
is_admg(cg, force_check = FALSE)
Arguments
cg |
A |
force_check |
Logical; if |
Value
A logical value indicating whether the graph is an ADMG.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_admg <- caugi(
A %-->% B,
A %<->% C,
class = "ADMG"
)
is_admg(cg_admg) # TRUE
cg_dag <- caugi(
A %-->% B,
class = "DAG"
)
is_admg(cg_dag) # TRUE (DAGs are valid ADMGs)
Is the caugi graph an AG?
Description
Checks if the given caugi graph is an
Ancestral Graph (AG).
An AG contains directed (-->), bidirected (<->), and undirected (---)
edges, and must satisfy ancestral graph constraints (no directed cycles,
anterior constraint, and undirected constraint).
Usage
is_ag(cg, force_check = FALSE)
Arguments
cg |
A |
force_check |
Logical; if |
Value
A logical value indicating whether the graph is an AG.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_ag <- caugi(
A %-->% B,
C %<->% D,
E %---% F,
class = "AG"
)
is_ag(cg_ag) # TRUE
cg_ug <- caugi(
A %---% B,
class = "UG"
)
is_ag(cg_ug) # TRUE (UGs are valid AGs)
Is it a caugi graph?
Description
Checks if the given object is a caugi. Mostly used
internally to validate inputs.
Usage
is_caugi(x, throw_error = FALSE)
Arguments
x |
An object to check. |
throw_error |
Logical; if |
Value
A logical value indicating whether the object is a caugi.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
class = "DAG"
)
is_caugi(cg) # TRUE
Is the caugi graph a CPDAG?
Description
Checks if the given caugi graph is a
Complete Partially Directed Acyclic Graph (CPDAG).
Usage
is_cpdag(cg)
Arguments
cg |
A |
Value
A logical value indicating whether the graph is a CPDAG.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_cpdag <- caugi(
A %---% B,
A %-->% C,
B %-->% C,
class = "PDAG"
)
is_cpdag(cg_cpdag) # TRUE
cg_not_cpdag <- caugi(
A %---% B,
A %---% C,
B %-->% C,
class = "PDAG"
)
is_cpdag(cg_not_cpdag) # FALSE
Is the caugi graph a DAG?
Description
Checks if the given caugi graph is a
Directed Acyclic Graph (DAG).
Usage
is_dag(cg, force_check = FALSE)
Arguments
cg |
A |
force_check |
Logical; if |
Value
A logical value indicating whether the graph is a DAG.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_dag_class <- caugi(
A %-->% B,
class = "DAG"
)
is_dag(cg_dag_class) # TRUE
cg_dag_but_pdag_class <- caugi(
A %-->% B,
class = "PDAG"
)
is_dag(cg_dag_but_pdag_class) # TRUE
cg_cyclic <- caugi(
A %-->% B,
B %-->% C,
C %-->% A,
class = "UNKNOWN",
simple = FALSE
)
is_dag(cg_cyclic) # FALSE
cg_undirected <- caugi(
A %---% B,
class = "UNKNOWN"
)
is_dag(cg_undirected) # FALSE
Is the edge symmetric?
Description
Check if the given edge glyph is symmetric in the edge registry.
Usage
is_edge_symmetric(glyph)
Arguments
glyph |
A string representing the edge glyph (e.g., |
Value
Logical, TRUE if the edge is symmetric, otherwise throws error.
Is the caugi graph empty?
Description
Checks if the given caugi graph is empty (has no nodes).
Usage
is_empty_caugi(cg)
Arguments
cg |
A |
Value
A logical value indicating whether the graph is empty.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_empty <- caugi(class = "DAG")
is_empty_caugi(cg_empty) # TRUE
cg_non_empty <- caugi(
A %-->% B,
class = "DAG"
)
is_empty_caugi(cg_non_empty) # FALSE
cg_no_edges_but_has_nodes <- caugi(
A, B,
class = "DAG"
)
is_empty_caugi(cg_no_edges_but_has_nodes) # FALSE
Is the caugi graph a MAG?
Description
Checks if the given caugi graph is a
Maximal Ancestral Graph (MAG).
A MAG is an ancestral graph where no additional edge can be added without violating the ancestral graph constraints or changing the encoded independence model.
Usage
is_mag(cg, force_check = FALSE)
Arguments
cg |
A |
force_check |
Logical; if |
Value
A logical value indicating whether the graph is a MAG.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_ag <- caugi(
A %-->% B,
B %-->% C,
class = "AG"
)
is_mag(cg_ag) # TRUE (0 and 2 are m-separated by {B})
Is the caugi graph a PDAG?
Description
Checks if the given caugi graph is a
Partially Directed Acyclic Graph (PDAG).
Usage
is_pdag(cg, force_check = FALSE)
Arguments
cg |
A |
force_check |
Logical; if |
Value
A logical value indicating whether the graph is a PDAG.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_dag_class <- caugi(
A %-->% B,
class = "DAG"
)
is_pdag(cg_dag_class) # TRUE
cg_dag_but_pdag_class <- caugi(
A %-->% B,
class = "PDAG"
)
is_pdag(cg_dag_but_pdag_class) # TRUE
cg_cyclic <- caugi(
A %-->% B,
B %-->% C,
C %-->% A,
D %---% A,
class = "UNKNOWN",
simple = FALSE
)
is_pdag(cg_cyclic) # FALSE
cg_undirected <- caugi(
A %---% B,
class = "UNKNOWN"
)
is_pdag(cg_undirected) # TRUE
cg_pag <- caugi(
A %o->% B,
class = "UNKNOWN"
)
is_pdag(cg_pag) # FALSE
Is the caugi graph an UG?
Description
Checks if the given caugi graph is an undirected graph (UG).
Usage
is_ug(cg, force_check = FALSE)
Arguments
cg |
A |
force_check |
Logical; if |
Value
A logical value indicating whether the graph is an UG.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg_ug_class <- caugi(
A %---% B,
class = "UG"
)
is_ug(cg_ug_class) # TRUE
cg_not_ug <- caugi(
A %-->% B,
class = "DAG"
)
is_ug(cg_not_ug) # FALSE
Is a set a valid adjustment set in an ADMG?
Description
Checks whether Z is a valid adjustment set for estimating
the causal effect of X on Y in an ADMG using the generalized adjustment
criterion.
Usage
is_valid_adjustment_admg(
cg,
X = NULL,
Y = NULL,
Z = NULL,
X_index = NULL,
Y_index = NULL,
Z_index = NULL
)
Arguments
cg |
A |
X, Y |
Node names (can be vectors for multiple treatments/outcomes). |
Z |
Conditioning set (character vector of node names). |
X_index, Y_index, Z_index |
Optional 1-based indices. |
Value
Logical value indicating if the adjustment set is valid.
See Also
Other adjustment:
adjustment_set(),
all_adjustment_sets_admg(),
all_backdoor_sets(),
d_separated(),
is_valid_backdoor()
Examples
# Classic confounding
cg <- caugi(
L %-->% X,
X %-->% Y,
L %-->% Y,
class = "ADMG"
)
is_valid_adjustment_admg(cg, X = "X", Y = "Y", Z = NULL) # FALSE
is_valid_adjustment_admg(cg, X = "X", Y = "Y", Z = "L") # TRUE
Is a backdoor set valid?
Description
Checks whether Z is a valid backdoor adjustment set for
X --> Y.
Usage
is_valid_backdoor(
cg,
X = NULL,
Y = NULL,
Z = NULL,
X_index = NULL,
Y_index = NULL,
Z_index = NULL
)
Arguments
cg |
A |
X, Y |
Single node names. |
Z |
Optional node set for conditioning |
X_index, Y_index, Z_index |
Optional 1-based indices. |
Value
Logical value indicating if backdoor is valid or not.
See Also
Other adjustment:
adjustment_set(),
all_adjustment_sets_admg(),
all_backdoor_sets(),
d_separated(),
is_valid_adjustment_admg()
Examples
cg <- caugi(
C %-->% X,
X %-->% F,
X %-->% D,
A %-->% X,
A %-->% K,
K %-->% Y,
D %-->% Y,
D %-->% G,
Y %-->% H,
class = "DAG"
)
is_valid_backdoor(cg, X = "X", Y = "Y", Z = NULL) # FALSE
is_valid_backdoor(cg, X = "X", Y = "Y", Z = "K") # TRUE
is_valid_backdoor(cg, X = "X", Y = "Y", Z = c("A", "C")) # TRUE
Knit Print Method for caugi_export
Description
Renders caugi export objects as code blocks in Quarto/R Markdown documents. This method is automatically invoked when an export object is the last expression in a code chunk.
Arguments
x |
A |
... |
Additional arguments (currently unused). |
Details
This method enables seamless rendering of caugi graphs in Quarto and
R Markdown. The code block type is determined by the export format.
Simply use an export function (e.g., to_dot(cg)) as the last expression
in a chunk with output: asis:
#| output: asis to_dot(cg)
Value
A knit_asis object for rendering by knitr.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Project latent variables from a DAG to an ADMG
Description
Projects out latent (unobserved) variables from a DAG to produce an Acyclic Directed Mixed Graph (ADMG) over the observed variables.
Usage
latent_project(cg, latents)
Arguments
cg |
A |
latents |
Character vector of latent variable names to project out. |
Value
A caugi object of class "ADMG" containing only the observed
variables.
See Also
Other operations:
condition_marginalize(),
exogenize(),
moralize(),
mutate_caugi(),
skeleton()
Examples
# DAG with latent confounder U
dag <- caugi(
U %-->% X,
U %-->% Y,
X %-->% Y,
class = "DAG"
)
# Project out the latent variable
admg <- latent_project(dag, latents = "U")
# Result: X -> Y, X <-> Y (children of U become bidirected-connected)
edges(admg)
# DAG with directed path through latent
dag2 <- caugi(
X %-->% L,
L %-->% Y,
class = "DAG"
)
# Project out the latent variable
admg2 <- latent_project(dag2, latents = "L")
# Result: X -> Y (directed path X -> L -> Y becomes X -> Y)
edges(admg2)
Length of a caugi
Description
Returns the number of nodes in the graph.
Arguments
x |
A |
Value
An integer representing the number of nodes.
See Also
Other caugi methods:
print()
Examples
cg <- caugi(
A %-->% B,
class = "DAG"
)
length(cg) # 2
cg2 <- caugi(
A %-->% B + C,
nodes = LETTERS[1:5],
class = "DAG"
)
length(cg2) # 5
M-separation test for AGs and ADMGs
Description
Test whether two sets of nodes are m-separated given a conditioning set in an ancestral graph (AG) or an ADMG.
M-separation generalizes d-separation to AGs/ADMGs and applies to DAGs.
Usage
m_separated(
cg,
X = NULL,
Y = NULL,
Z = NULL,
X_index = NULL,
Y_index = NULL,
Z_index = NULL
)
Arguments
cg |
A |
X, Y, Z |
Node selectors: character vector of names, unquoted expression
(supports |
X_index, Y_index, Z_index |
Optional numeric 1-based indices (exclusive
with |
Value
A logical value; TRUE if X and Y are m-separated given Z.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
# Classic confounding example
cg <- caugi(
L %-->% X,
X %-->% Y,
L %-->% Y,
class = "ADMG"
)
m_separated(cg, X = "X", Y = "Y") # FALSE (connected via L)
m_separated(cg, X = "X", Y = "Y", Z = "L") # TRUE (L blocks the path)
Make Content for Custom Edge Grob
Description
This S3 method for grid::makeContent handles dynamic edge endpoint calculation at draw time. It converts edge direction to absolute coordinates (mm) to properly handle aspect ratio, then applies node radius offsets before converting back to native coordinates.
Usage
## S3 method for class 'caugi_edge_grob'
makeContent(x)
Arguments
x |
A caugi_edge_grob object |
Value
The modified grob with children set to the adjusted line
Get Markov blanket of nodes in a caugi
Description
Get Markov blanket of nodes in a caugi
Usage
markov_blanket(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
markov_blanket(cg, "A") # "B"
markov_blanket(cg, index = 2) # "A" "C"
markov_blanket(cg, "B") # "A" "C"
markov_blanket(cg, c("B", "C"))
#> $B
#> [1] "A" "C"
#>
#> $C
#> [1] "B"
Moralize a DAG
Description
Moralizing a DAG involves connecting all parents of each node and then converting all directed edges into undirected edges.
Usage
moralize(cg)
Arguments
cg |
A |
Details
This changes the graph from a Directed Acyclic Graph (DAG) to an Undirected Graph (UG), also known as a Markov Graph.
Value
A caugi object representing the moralized graph (UG).
See Also
Other operations:
condition_marginalize(),
exogenize(),
latent_project(),
mutate_caugi(),
skeleton()
Examples
cg <- caugi(A %-->% C, B %-->% C, class = "DAG")
moralize(cg) # A -- B, A -- C, B -- C
Mutate caugi class
Description
Mutate the caugi class from one graph class to another, if possible.
For example, convert a DAG to a PDAG, or a fully directed caugi of
class UNKNOWN to a DAG. Throws an error if not possible.
Usage
mutate_caugi(cg, class)
Arguments
cg |
A |
class |
A character string specifying the new class. |
Details
This function returns a copy of the object, and the original remains unchanged.
Value
A caugi object of the specified class.
See Also
Other operations:
condition_marginalize(),
exogenize(),
latent_project(),
moralize(),
skeleton()
Examples
cg <- caugi(A %-->% B, class = "UNKNOWN")
cg_dag <- mutate_caugi(cg, "DAG")
Get neighbors of nodes in a caugi
Description
Get neighbors of a node in the graph, optionally filtered by edge direction
or type. This function works for all graph classes including UNKNOWN.
Usage
neighbors(
cg,
nodes = NULL,
index = NULL,
mode = c("all", "in", "out", "undirected", "bidirected", "partial")
)
neighbours(
cg,
nodes = NULL,
index = NULL,
mode = c("all", "in", "out", "undirected", "bidirected", "partial")
)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
mode |
Character; specifies which types of neighbors to return:
Not all modes are valid for all graph classes:
|
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
neighbors(cg, "A") # "B"
neighbors(cg, index = 2) # "A" "C"
neighbors(cg, "B") # "A" "C"
neighbors(cg, c("B", "C"))
#> $B
#> [1] "A" "C"
#>
#> $C
#> [1] "B"
# Using mode to filter by edge direction
neighbors(cg, "B", mode = "in") # "A" (parents)
neighbors(cg, "B", mode = "out") # "C" (children)
# Works for UNKNOWN graphs too
cg_unknown <- caugi(
A %-->% B,
B %---% C,
C %o->% D,
class = "UNKNOWN"
)
neighbors(cg_unknown, "B", mode = "in") # "A"
neighbors(cg_unknown, "B", mode = "undirected") # "C"
neighbors(cg_unknown, "C", mode = "partial") # "D"
Get nodes or edges of a caugi
Description
Get nodes or edges of a caugi
Usage
nodes(cg)
vertices(cg)
V(cg)
Arguments
cg |
A |
Value
A data.table with a name column.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
parents(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
D,
class = "DAG"
)
nodes(cg) # returns the data.table with nodes A, B, C, D
Get parents of nodes in a caugi
Description
Get parents of nodes in a graph (nodes with directed edges pointing INTO
the target node). This is equivalent to neighbors(cg, nodes, mode = "in").
Note that not both nodes and index can be given.
Usage
parents(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
same_nodes(),
spouses(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
parents(cg, "A") # NULL
parents(cg, index = 2) # "A"
parents(cg, "B") # "A"
parents(cg, c("B", "C"))
#> $B
#> [1] "A"
#>
#> $C
#> [1] "B"
Create a caugi Graph Plot Object
Description
Creates a grid graphics object (gTree) representing a caugi graph.
If the graph has not been built yet, it will be built automatically before
plotting. This implementation uses idiomatic grid graphics with viewports
for proper coordinate handling.
Arguments
x |
A |
layout |
Specifies the graph layout method. Can be:
|
... |
Additional arguments passed to |
node_style |
List of node styling parameters. Supports:
|
edge_style |
List of edge styling parameters. Can specify global options
or per-type options via
|
label_style |
List of label styling parameters. Supports:
|
tier_style |
List of tier box styling parameters. Tier boxes are shown
when
|
main |
Optional character string for plot title. If |
title_style |
List of title styling parameters. Supports:
|
outer_margin |
Grid unit specifying outer margin around the plot.
Default is |
title_gap |
Grid unit specifying gap between title and graph.
Default is |
Value
A caugi_plot object that wraps a gTree for grid graphics
display. The plot is automatically drawn when printed or explicitly
plotted.
See Also
Other plotting:
add-caugi_plot-caugi_plot,
caugi_layout(),
caugi_layout_bipartite(),
caugi_layout_fruchterman_reingold(),
caugi_layout_kamada_kawai(),
caugi_layout_sugiyama(),
caugi_layout_tiered(),
caugi_plot(),
divide-caugi_plot-caugi_plot
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
plot(cg)
# Use a specific layout method (as string)
plot(cg, layout = "kamada-kawai")
# Use a layout function
plot(cg, layout = caugi_layout_sugiyama)
# Pre-compute layout and use it
coords <- caugi_layout_fruchterman_reingold(cg)
plot(cg, layout = coords)
# Bipartite layout with a function
cg_bp <- caugi(A %-->% X, B %-->% X, C %-->% Y)
partition <- c(TRUE, TRUE, TRUE, FALSE, FALSE)
plot(cg_bp, layout = caugi_layout_bipartite, partition = partition)
# Customize nodes
plot(cg, node_style = list(fill = "lightgreen", padding = 0.8))
# Customize edges by type
plot(
cg,
edge_style = list(
directed = list(col = "blue", arrow_size = 4),
undirected = list(col = "red")
)
)
# Add a title
plot(cg, main = "Causal Graph")
# Customize title
plot(
cg,
main = "My Graph",
title_style = list(fontsize = 18, col = "blue", fontface = "italic")
)
Print a caugi
Description
Print a caugi
Arguments
x |
A |
max_nodes |
Optional numeric; maximum number of node names to consider.
If |
max_edges |
Optional numeric; maximum number of edges to consider.
If |
... |
Not used. |
Value
The input caugi object, invisibly.
See Also
Other caugi methods:
length()
Examples
cg <- caugi(A %-->% B, class = "DAG")
print(cg)
Read caugi Graph from File
Description
Reads a caugi graph from a file in the native caugi JSON format.
Usage
read_caugi(path, lazy = FALSE)
Arguments
path |
Character string specifying the file path. |
lazy |
Logical; if |
Details
The function validates the file format and version, ensuring compatibility with the current version of the caugi package.
Value
A caugi object.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(
A %-->% B + C,
class = "DAG"
)
# Write and read
tmp <- tempfile(fileext = ".caugi.json")
write_caugi(cg, tmp)
cg2 <- read_caugi(tmp)
# Clean up
unlink(tmp)
Read GraphML File to caugi Graph
Description
Imports a GraphML file as a caugi graph. Supports GraphML files exported from caugi with full edge type information.
Usage
read_graphml(path, class = NULL)
Arguments
path |
File path to the GraphML file. |
class |
Graph class to assign. If |
Details
This function provides basic GraphML import support. It reads:
Nodes and their IDs
Edges with source and target
Edge types (if present in
edge_typeattribute)Graph class (if present in graph data)
For GraphML files not created by caugi, edge types default to "–>" for directed graphs and "—" for undirected graphs.
Value
A caugi object.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
# Create and export a graph
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
tmp <- tempfile(fileext = ".graphml")
write_graphml(cg, tmp)
# Read it back
cg2 <- read_graphml(tmp)
# Clean up
unlink(tmp)
Register a new edge type in the global registry.
Description
Register a new edge type in the global registry.
Usage
register_caugi_edge(glyph, tail_mark, head_mark, class, symmetric = FALSE)
Arguments
glyph |
A string representing the edge glyph (e.g., |
tail_mark |
One of "arrow", "tail", "circle", "other". |
head_mark |
One of "arrow", "tail", "circle", "other". |
class |
One of "directed","undirected","bidirected","partial". |
symmetric |
Logical. |
Value
TRUE, invisibly.
See Also
Other registry:
registry
Examples
# first, for reproducability, we reset the registry to default
reset_caugi_registry()
# create a new registry
reg <- caugi_registry()
# register an edge
register_caugi_edge(
glyph = "<--",
tail_mark = "arrow",
head_mark = "tail",
class = "directed",
symmetric = FALSE
)
# now, this edge is available for caugi graphs:
cg <- caugi(A %-->% B, B %<--% C, class = "DAG")
# reset the registry to default
reset_caugi_registry()
caugi edge registry
Description
The caugi edge registry stores information about the different edge types
that can be used in caugi graphs. It maps edge glyphs (e.g., "-->",
"<->", "o->", etc.) to their specifications, including tail and head
marks, class, and symmetry. The registry allows for dynamic registration of
new edge types, enabling users to extend the set of supported edges in
caugi. It is implemented as a singleton, ensuring that there is a single
global instance of the registry throughout the R session.
Usage
caugi_registry()
reset_caugi_registry()
seal_caugi_registry()
Details
The intended use of the caugi registry is mostly for advanced users and
developers. The registry enables users who need to define their own custom
edge types in caugi directly. . It currently mostly supports the
representation of new edges, but for users that might want to represent
reverse edges, this preserves correctness of reason over these edges.
Value
An edge_registry external pointer.
Functions
-
caugi_registry(): Access the global edge registry, creating it if needed. -
reset_caugi_registry(): Reset the global edge registry to its default state. -
seal_caugi_registry(): Seal the global edge registry to prevent further modifications.
See Also
Other registry:
register_caugi_edge()
Examples
# first, for reproducability, we reset the registry to default
reset_caugi_registry()
# create a new registry
reg <- caugi_registry()
# register an edge
register_caugi_edge(
glyph = "<--",
tail_mark = "arrow",
head_mark = "tail",
class = "directed",
symmetric = FALSE
)
# now, this edge is available for caugi graphs:
cg <- caugi(A %-->% B, B %<--% C, class = "DAG")
# reset the registry to default
reset_caugi_registry()
Same nodes?
Description
Check if two caugi objects have the same nodes.
Usage
same_nodes(cg1, cg2, throw_error = FALSE)
Arguments
cg1 |
A |
cg2 |
A |
throw_error |
Logical; if |
Value
A logical indicating if the two graphs have the same nodes.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
spouses(),
subgraph(),
topological_sort()
Examples
cg1 <- caugi(
A %-->% B,
class = "DAG"
)
cg2 <- caugi(
A %-->% B + C,
class = "DAG"
)
same_nodes(cg1, cg2) # FALSE
Structural Hamming Distance
Description
Compute the Structural Hamming Distance (SHD) between two graphs.
Usage
shd(cg1, cg2, normalized = FALSE)
Arguments
cg1 |
A |
cg2 |
A |
normalized |
Logical; if |
Value
An integer representing the Hamming Distance between the two graphs,
if normalized = FALSE, or a numeric between 0 and 1 if normalized = TRUE.
See Also
Examples
cg1 <- caugi(A %-->% B %-->% C, D %-->% C, class = "DAG")
cg2 <- caugi(A %-->% B %-->% C, D %---% C, class = "PDAG")
shd(cg1, cg2) # 1
Simulate data from a caugi DAG.
Description
Simulate data from a caugi object of class DAG using a
linear structural equation model (SEM). As standard, the data is
simulated from a DAG, where each node is generated as a linear combination
of its parents plus Gaussian noise, following the topological order of the
graph. Nodes without custom equations are simulated using auto-generated
linear Gaussian relationships.
Usage
simulate_data(
cg,
n,
...,
standardize = TRUE,
coef_range = c(0.1, 0.9),
error_sd = 1,
seed = NULL
)
Arguments
cg |
A |
n |
Integer; number of observations to simulate. |
... |
Named expressions for custom structural equations. Names must
match node names in the graph. Expressions can reference parent node names
and the variable |
standardize |
Logical; if |
coef_range |
Numeric vector of length 2; range for random edge
coefficients that will be sampled uniformly. Default is |
error_sd |
Numeric; standard deviation for error terms in
auto-generated equations. Default is |
seed |
Optional integer; random seed for reproducibility. |
Value
A data.frame with n rows and one column per node, ordered
according to the node order in the graph.
See Also
Other simulation functions:
generate_graph()
Examples
cg <- caugi(A %-->% B, B %-->% C, A %-->% C, class = "DAG")
# Fully automatic simulation
df <- simulate_data(cg, n = 100)
# With standardization
df <- simulate_data(cg, n = 100, standardize = TRUE)
# Custom equations for some nodes
df <- simulate_data(cg, n = 100,
A = rnorm(n, mean = 10, sd = 2),
B = 0.5 * A + rnorm(n, sd = 0.5)
)
# Reproducible simulation
df <- simulate_data(cg, n = 100, seed = 42)
Get the skeleton of a graph
Description
The skeleton of a graph is obtained by replacing all directed edges with undirected edges.
Usage
skeleton(cg)
Arguments
cg |
A |
Details
This changes the graph from any class to an Undirected Graph (UG), also known as a Markov Graph.
Value
A caugi object representing the skeleton of the graph (UG).
See Also
Other operations:
condition_marginalize(),
exogenize(),
latent_project(),
moralize(),
mutate_caugi()
Examples
cg <- caugi(A %-->% B, class = "DAG")
skeleton(cg) # A --- B
Get spouses (bidirected neighbors) of nodes in an ADMG
Description
Get nodes connected via bidirected edges in an ADMG.
Usage
spouses(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names. |
index |
A vector of node indexes. |
Value
Either a character vector of node names (if a single node is requested) or a list of character vectors (if multiple nodes are requested).
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
subgraph(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
A %<->% C,
B %<->% C,
class = "ADMG"
)
spouses(cg, "A") # "C"
spouses(cg, "C") # c("A", "B")
Get the induced subgraph
Description
Get the induced subgraph
Usage
subgraph(cg, nodes = NULL, index = NULL)
Arguments
cg |
A |
nodes |
A vector of node names, a vector of unquoted
node names, or an expression combining these with |
index |
A vector of node indexes. |
Value
A new caugi that is a subgraph of the selected nodes.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
topological_sort()
Examples
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
sub_cg <- subgraph(cg, c("B", "C"))
cg2 <- caugi(B %-->% C, class = "DAG")
all(nodes(sub_cg) == nodes(cg2)) # TRUE
all(edges(sub_cg) == edges(cg2)) # TRUE
Export caugi Graph to DOT Format
Description
Converts a caugi graph to the Graphviz DOT format as a string. The DOT format can be used with Graphviz tools for visualization and analysis.
Usage
to_dot(x, graph_attrs = list(), node_attrs = list(), edge_attrs = list())
Arguments
x |
A |
graph_attrs |
Named list of graph attributes (e.g.,
|
node_attrs |
Named list of default node attributes. |
edge_attrs |
Named list of default edge attributes. |
Details
The function handles different edge types:
Directed edges (
-->) use->in DOTUndirected edges (
---) use--in DOT (or->withdir=nonein digraphs)Bidirected edges (
<->) use->with[dir=both]attributePartial edges (
o->) use->with[arrowtail=odot, dir=both]attribute
Value
A caugi_dot object containing the DOT representation.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
# Get DOT string
dot <- to_dot(cg)
dot@content
# With custom attributes
dot <- to_dot(
cg,
graph_attrs = list(rankdir = "LR"),
node_attrs = list(shape = "box")
)
Export caugi Graph to GraphML Format
Description
Converts a caugi graph to the GraphML XML format as a string. GraphML is widely supported by graph analysis tools and libraries.
Usage
to_graphml(x)
Arguments
x |
A |
Details
The GraphML export includes:
Node IDs and labels
Edge types stored as a custom
edge_typeattributeGraph class stored as a graph-level attribute
Edge types are encoded using the caugi DSL operators (e.g., "–>", "<->"). This allows for perfect round-trip conversion back to caugi.
Value
A caugi_graphml object containing the GraphML representation.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
# Get GraphML string
graphml <- to_graphml(cg)
cat(graphml@content)
# Write to file
## Not run:
write_graphml(cg, "graph.graphml")
## End(Not run)
Export caugi Graph to Mermaid Format
Description
Converts a caugi graph to the Mermaid flowchart format as a string. Mermaid diagrams can be rendered in Quarto, R Markdown, GitHub, and many other platforms.
Usage
to_mermaid(x, direction = "TD")
Arguments
x |
A |
direction |
Graph direction: "TB" (top-bottom), "TD" (top-down), "BT" (bottom-top), "LR" (left-right), or "RL" (right-left). Default is "TD". |
Details
The function handles different edge types:
Directed edges (
-->) use-->in MermaidUndirected edges (
---) use---in MermaidBidirected edges (
<->) use<-->in MermaidPartial edges (
o->) useo-->in Mermaid (circle end)
Node names are automatically escaped if they contain special characters.
Value
A caugi_mermaid object containing the Mermaid representation.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
write_caugi(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
# Get Mermaid string
mmd <- to_mermaid(cg)
mmd@content
# With custom direction
mmd <- to_mermaid(cg, direction = "LR")
Get a topological ordering of a DAG
Description
Returns a topological ordering of the nodes in a DAG. For every directed edge u -> v in the graph, u will appear before v in the returned ordering.
Usage
topological_sort(cg)
Arguments
cg |
A |
Value
A character vector of node names in topological order.
See Also
Other queries:
ancestors(),
anteriors(),
children(),
descendants(),
districts(),
edge_types(),
edges(),
exogenous(),
is_acyclic(),
is_admg(),
is_ag(),
is_caugi(),
is_cpdag(),
is_dag(),
is_empty_caugi(),
is_mag(),
is_pdag(),
is_ug(),
m_separated(),
markov_blanket(),
neighbors(),
nodes(),
parents(),
same_nodes(),
spouses(),
subgraph()
Examples
# Simple DAG: A -> B -> C
cg <- caugi(
A %-->% B,
B %-->% C,
class = "DAG"
)
topological_sort(cg) # Returns c("A", "B", "C") or equivalent valid ordering
# DAG with multiple valid orderings
cg2 <- caugi(
A %-->% C,
B %-->% C,
class = "DAG"
)
# Could return c("A", "B", "C") or c("B", "A", "C")
topological_sort(cg2)
Write caugi Graph to File
Description
Writes a caugi graph to a file in the native caugi JSON format. This format is designed for reproducibility, caching, and sharing caugi graphs across R sessions.
Usage
write_caugi(x, path, comment = NULL, tags = NULL)
Arguments
x |
A |
path |
Character string specifying the file path. |
comment |
Optional character string with a comment about the graph. |
tags |
Optional character vector of tags for categorizing the graph. |
Details
The caugi format is a versioned JSON schema that captures:
Graph structure (nodes and edges with their types)
Graph class (DAG, PDAG, ADMG, UG, etc.)
Optional metadata (comments and tags)
Edge types are encoded using their DSL operators (e.g., "-->", "<->", "--").
For a complete guide to the format, see vignette("serialization", package = "caugi").
The formal JSON Schema is available at:
https://caugi.org/schemas/caugi-v1.schema.json
Value
Invisibly returns the input x.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_dot(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
# Write to file
tmp <- tempfile(fileext = ".caugi.json")
write_caugi(cg, tmp, comment = "Example DAG")
# Read back
cg2 <- read_caugi(tmp)
identical(edges(cg), edges(cg2))
# Clean up
unlink(tmp)
Write caugi Graph to DOT File
Description
Writes a caugi graph to a file in Graphviz DOT format.
Usage
write_dot(x, file, ...)
Arguments
x |
A |
file |
Path to output file. |
... |
Additional arguments passed to |
Value
Invisibly returns the path to the file.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_graphml(),
write_mermaid()
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
## Not run:
# Write to file
write_dot(cg, "graph.dot")
# With custom attributes
write_dot(
cg,
"graph.dot",
graph_attrs = list(rankdir = "LR")
)
## End(Not run)
Write caugi Graph to GraphML File
Description
Exports a caugi graph to a GraphML file.
Usage
write_graphml(x, path)
Arguments
x |
A |
path |
File path for the output GraphML file. |
Value
Invisibly returns NULL. Called for side effects.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_mermaid()
Examples
cg <- caugi(A %-->% B + C, class = "DAG")
tmp <- tempfile(fileext = ".graphml")
write_graphml(cg, tmp)
# Read it back
cg2 <- read_graphml(tmp)
# Clean up
unlink(tmp)
Write caugi Graph to Mermaid File
Description
Writes a caugi graph to a file in Mermaid format.
Usage
write_mermaid(x, file, ...)
Arguments
x |
A |
file |
Path to output file. |
... |
Additional arguments passed to |
Value
Invisibly returns the path to the file.
See Also
Other export:
caugi_deserialize(),
caugi_dot(),
caugi_export(),
caugi_graphml(),
caugi_mermaid(),
caugi_serialize(),
export-classes,
format-caugi,
format-dot,
format-graphml,
format-mermaid,
knit_print.caugi_export,
read_caugi(),
read_graphml(),
to_dot(),
to_graphml(),
to_mermaid(),
write_caugi(),
write_dot(),
write_graphml()
Examples
cg <- caugi(
A %-->% B + C,
B %-->% D,
C %-->% D,
class = "DAG"
)
## Not run:
# Write to file
write_mermaid(cg, "graph.mmd")
# With custom direction
write_mermaid(cg, "graph.mmd", direction = "LR")
## End(Not run)