Learning causal structure: NOTEARS, DAG-GNN and invariant risk
NOTEARS makes "no cycles" a smooth constraint so a graph can be fit by gradients; DAG-GNN adds neural mechanisms; IRM seeks features whose link to the outcome holds in every environment.
What runs in CodeSplash
- UNC011NOTEARS continuous directed-acyclic-graph learning Runs in CodeSplash
- UNC012DAG-GNN Explained here
- UNC013Invariant risk minimization (IRM / IRMv1) Runs as a notebook
- Suggest causal structure (PC, NOTEARS) Verified in Python and R
You will be able to
- Write the NOTEARS objective and explain the acyclicity function h(W)
- Explain why a variable's scale can change NOTEARS' arrows, and check for it
- Say why a DAG-GNN's good reconstruction doesn't validate its graph
- State IRM's goal, its practical surrogate, and why invariant features aren't proven causes
Graphs from observational data
ReadA causal graph says which variables affect which. Learning one from observational data is possible only under strong assumptions: no hidden common causes, no feedback loops, no selection, and a model family that matches the mechanisms. Even then, several graphs often fit the data equally well (a Markov equivalenceMarkov equivalence classDAGs that imply exactly the same independences. Data like these can't choose between them, so PC leaves such links undirected. class), so some arrows can't be oriented at all.
The methods here are fast, flexible ways to propose graphs. Treat their output as hypotheses to test with interventions or domain knowledge, never as a DAG you can claim.
NOTEARS: no cycles as a smooth constraint
ReadSearching over all acyclic graphs is combinatorial. NOTEARSNOTEARSFits a sparse linear model whose arrows can't form a loop (tr exp(W∘W) = d). Directions can change when units change. fits a weighted adjacency matrix (entry means ) by least squares with an L1 penalty, subject to one smooth equation:
is zero exactly when the graph has no cycles: the matrix exponential counts weighted closed walks. In the reference's example, is 0 for an acyclic graph and 0.00980 once a small cycle is added.
Fit NOTEARS to a four-variable chain, then standardize the columns and compare the arrows.
CExplorable · Learning a causal graph by optimization (NOTEARS)
Can a smooth penalty keep a learned graph free of cycles, and what else is the fit quietly relying on?
Standardizing a column doesn't change which variable causes which. Will it change the graph NOTEARS finds?
Pushes weak edges to zero. Edges under 0.3 in size are dropped after fitting.
Rows drawn from the true graph X₁ → X₂ → X₃, X₁ → X₄ (all noise SD 1).
Rescale every variable to SD 1 before fitting, as many pipelines do.
Commit your prediction above to see the result
Make your prediction to see the result.
Change the units, change the arrows
PredictPredict first
You refit NOTEARS on the same data after standardizing every variable (or after undoing a standardization). What happens to the graph?
Reveal
Some arrows can change. Least-squares NOTEARS tends to point arrows toward variables with larger variance, so rescaling can reorient edges. On the garden data, 4 links changed between the two scalings. Report the scaling you chose and how sensitive the graph is to it.
NOTEARS suggests 9 links among 8 variables (9 with a direction, 0 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 9
- With a direction
- 9
- Undirected
- 0
Plots
View data
| To | From | Weight |
|---|---|---|
| sun | sun | 0 |
| water | sun | 0 |
| fertilizer | sun | 0 |
| pests | sun | 0 |
| temperature | sun | 0.7805 |
| moisture | sun | 0 |
| growth | sun | 0 |
| harvest | sun | 0 |
| sun | water | 0 |
| water | water | 0 |
| fertilizer | water | 0 |
| pests | water | 0 |
| temperature | water | 0 |
| moisture | water | 0 |
| growth | water | 0 |
| harvest | water | 0 |
| sun | fertilizer | 0 |
| water | fertilizer | 0 |
| fertilizer | fertilizer | 0 |
| pests | fertilizer | 0 |
| temperature | fertilizer | 0 |
| moisture | fertilizer | 0 |
| growth | fertilizer | 0 |
| harvest | fertilizer | 0 |
| sun | pests | 0 |
| water | pests | 0 |
| fertilizer | pests | 0 |
| pests | pests | 0 |
| temperature | pests | 0 |
| moisture | pests | 0 |
| growth | pests | 0 |
| harvest | pests | 0 |
| sun | temperature | 0 |
| water | temperature | 0 |
| fertilizer | temperature | 0 |
| pests | temperature | 0 |
| temperature | temperature | 0 |
| moisture | temperature | 0 |
| growth | temperature | 0 |
| harvest | temperature | 0 |
| sun | moisture | 0 |
| water | moisture | 0.8681 |
| fertilizer | moisture | −0.4617 |
| pests | moisture | 0 |
| temperature | moisture | 0 |
| moisture | moisture | 0 |
| growth | moisture | 0 |
| harvest | moisture | 0 |
| sun | growth | 0.5389 |
| water | growth | 0 |
| fertilizer | growth | 0.6705 |
| pests | growth | 1.204 |
| temperature | growth | 0 |
| moisture | growth | 0.5894 |
| growth | growth | 0 |
| harvest | growth | 0.8526 |
| sun | harvest | 0 |
| water | harvest | 0 |
| fertilizer | harvest | 0 |
| pests | harvest | −1.491 |
First 60 of 64 rows.
Suggested links
| From | Link | To | Weight (least squares) | In resamples | This direction |
|---|---|---|---|---|---|
| sun | → | temperature | 0.7805 | — | — |
| growth | → | sun | 0.5389 | — | — |
| moisture | → | water | 0.8681 | — | — |
| moisture | → | fertilizer | −0.4617 | — | — |
| growth | → | fertilizer | 0.6705 | — | — |
| growth | → | pests | 1.204 | — | — |
| harvest | → | pests | −1.491 | — | — |
| growth | → | moisture | 0.5894 | — | — |
| growth | → | harvest | 0.8526 | — | — |
- 4 links change when the variables are centered only instead, so these arrows partly reflect the units.
- NOTEARS on standardized variables, λ = 0.1, weights below 0.3 dropped; reported weights are least-squares refits on each variable's suggested parents.
- A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.
The exact R script · R R version 4.5.1 (2025-06-13)
# Suggest causal structure (PC, NOTEARS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.structure 1.1.0 · spec 340508c83665c287
# Dataset: csl_garden (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
VARIABLES <- c("sun", "water", "fertilizer", "pests", "temperature", "moisture", "growth", "harvest")
ALGORITHM <- "notears" # pc | notears
TEST <- "auto" # auto | fisher_z | g2 (PC)
ALPHA <- 0.05
MAX_COND <- 4
LAMBDA1 <- 0.1
W_THRESHOLD <- 0.3
SCALE <- "standardize" # standardize | center (NOTEARS)
BOOTSTRAP <- 0
REQUIRED <- "" # background knowledge: links you know exist ("a -> b, c -- d")
FORBIDDEN <- "" # and links you know don't
SEED <- 42
MAX_LEVELS <- 20 # G²: categories per variable
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/csl_garden.parquet", col_select = VARIABLES))
n_input <- nrow(df)
cs_check_finite_columns(df, VARIABLES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, VARIABLES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 10, "Causal structure suggestions")
p <- length(VARIABLES)
kind_of <- function(v) if (is.logical(v)) "boolean" else if (is.numeric(v)) "numeric" else "categorical"
kinds <- vapply(VARIABLES, function(c) kind_of(df[[c]]), character(1), USE.NAMES = FALSE)
labels <- lapply(VARIABLES, function(c) cs_ml_label_text(df[[c]][rows + 1L]))
for (k in seq_len(p)) if (length(unique(labels[[k]])) < 2) cs_error("CS_E_CONSTANT", column = VARIABLES[k])
if (ALGORITHM == "notears") {
if ("categorical" %in% kinds) cs_error("CS_E_INVALID_OPTION", option = "Algorithm", allowed = "PC-stable when a variable is a category (NOTEARS needs numbers)", value = "NOTEARS")
test_used <- "none"
} else if (TEST == "auto") {
if (!("categorical" %in% kinds)) {
test_used <- "fisher_z"
} else if (!("numeric" %in% kinds)) {
test_used <- "g2"
} else {
cs_error("CS_E_INVALID_OPTION", option = "Independence test", allowed = "Fisher z or G² chosen by hand when numbers and categories are mixed", value = "Automatic")
}
} else {
test_used <- TEST
if (test_used == "fisher_z" && "categorical" %in% kinds) cs_error("CS_E_INVALID_OPTION", option = "Independence test", allowed = "G² when a variable is a category", value = "Fisher z")
}
if (test_used == "g2") {
X <- matrix(0, length(rows), p)
for (k in seq_len(p)) {
levels <- sort(unique(labels[[k]]), method = "radix")
if (length(levels) > MAX_LEVELS) cs_error("CS_E_TOO_MANY_LEVELS", column = VARIABLES[k], k = length(levels), max = MAX_LEVELS)
X[, k] <- match(labels[[k]], levels) - 1
}
} else {
X <- matrix(vapply(VARIABLES, function(c) as.numeric(df[[c]][rows + 1L]), numeric(length(rows))), ncol = p) # yes/no as 1/0
}
n <- nrow(X)
# NULL without knowledge, so the fit below is exactly the plain one.
kn <- cs_ml_structure_knowledge(p, cs_ml_structure_knowledge_parse(REQUIRED, VARIABLES, "Required links"),
cs_ml_structure_knowledge_parse(FORBIDDEN, VARIABLES, "Forbidden links"), VARIABLES)
# %% Fit
fit_args <- list(algorithm = ALGORITHM, test = test_used, alpha = ALPHA, max_cond = MAX_COND, lambda1 = LAMBDA1,
w_threshold = W_THRESHOLD, standardize = SCALE == "standardize", max_iter = 100)
fit <- do.call(cs_ml_structure_fit_knowledge, c(list(data = X, kn = kn), fit_args))
pdag <- fit$pdag
edges <- cs_ml_structure_edges(pdag)
boot <- do.call(cs_ml_structure_bootstrap_knowledge, c(list(data = X, B = BOOTSTRAP, seed = SEED, kn = kn), fit_args))
freq <- boot$freq
freq_dir <- boot$freq_dir
weights <- NULL
shd_other <- NULL
if (ALGORITHM == "notears") {
weights <- cs_ml_structure_refit(cs_ml_structure_scaled(X, SCALE == "standardize"), pdag)
other_args <- fit_args
other_args$standardize <- SCALE != "standardize"
other <- do.call(cs_ml_structure_fit_knowledge, c(list(data = X, kn = kn), other_args))
shd_other <- cs_ml_structure_shd(pdag, other$pdag)
if (fit$h > 1e-8) warnings <- c(warnings, "The fit stopped before its graph was fully free of loops; read the arrows with extra care.")
if (shd_other > 0) {
warnings <- c(warnings, sprintf("%d %s when the variables are %s instead, so these arrows partly reflect the units.", shd_other,
if (shd_other == 1) "link changes" else "links change", if (SCALE == "standardize") "centered only" else "standardized"))
}
}
if (!is.null(kn)) {
for (e in fit$conflicts) {
a <- e[1]
b <- e[2]
required <- any(vapply(kn$req_dir, function(r) r[1] == a && r[2] == b, logical(1)))
warnings <- c(warnings, if (required) {
sprintf("The data orient %s → %s, against your required arrow %s → %s; the graph shows the data's direction.", VARIABLES[b], VARIABLES[a], VARIABLES[a], VARIABLES[b])
} else {
sprintf("The data orient %s → %s, which you forbade; the graph shows the data's direction.", VARIABLES[b], VARIABLES[a])
})
}
if (length(fit$dropped)) {
nd <- length(fit$dropped)
warnings <- c(warnings, sprintf("Keeping your required arrows closed a loop, so the weakest suggested arrow%s on it %s dropped: %s.",
if (nd != 1) "s" else "", if (nd != 1) "were" else "was",
paste(vapply(fit$dropped, function(e) sprintf("%s → %s", VARIABLES[e[1]], VARIABLES[e[2]]), ""), collapse = ", ")))
}
}
# %% Values
algorithm_label <- if (ALGORITHM == "pc") "PC-stable" else "NOTEARS"
etype <- vapply(edges, function(e) e$type, character(1))
values <- list(
algorithm_label = algorithm_label,
n = n,
p = p,
n_edges = length(edges),
n_directed = sum(etype == "directed"),
n_undirected = sum(etype == "undirected"),
bootstrap = BOOTSTRAP,
n_tests = if (ALGORITHM == "pc") fit$n_tests else NA,
max_order = if (ALGORITHM == "pc") fit$max_order else NA,
h_converged = if (ALGORITHM == "notears") (if (fit$h <= 1e-8) 1L else 0L) else NA,
shd_other_scale = if (is.null(shd_other)) NA else shd_other
)
if (!is.null(kn)) {
values$n_required <- kn$n_required
values$n_forbidden <- kn$n_forbidden
values$n_conflicts <- length(fit$conflicts)
if (ALGORITHM == "notears") values$n_dropped <- length(fit$dropped)
}
for (i in seq_len(p - 1)) {
for (j in (i + 1):p) {
a <- VARIABLES[i]
b <- VARIABLES[j]
code <- if (pdag[i, j] == 1 && pdag[j, i] == 1) 2L else if (pdag[i, j] == 1) 1L else if (pdag[j, i] == 1) -1L else 0L
values[[sprintf("edge[%s|%s]", a, b)]] <- code
if (ALGORITHM == "pc" && (is.null(kn) || is.finite(fit$pmax[i, j]))) values[[sprintf("pmax[%s|%s]", a, b)]] <- fit$pmax[i, j] # knowledge-settled pairs aren't tested
if (BOOTSTRAP > 0) values[[sprintf("freq[%s|%s]", a, b)]] <- freq[i, j]
}
}
if (ALGORITHM == "notears") for (e in edges) values[[sprintf("weight[%s->%s]", VARIABLES[e$from], VARIABLES[e$to])]] <- weights[e$from, e$to]
if (BOOTSTRAP > 0) {
for (i in seq_len(p)) for (j in seq_len(p)) if (i != j) values[[sprintf("freq_dir[%s->%s]", VARIABLES[i], VARIABLES[j])]] <- freq_dir[i, j]
}
# %% Tables
strength_label <- if (ALGORITHM == "pc") "Largest p-value" else "Weight (least squares)"
edge_rows <- lapply(edges, function(e) {
row <- list(
from = VARIABLES[e$from], to = VARIABLES[e$to], type = if (e$type == "directed") "→" else "—",
strength = if (ALGORITHM == "pc") (if (is.finite(fit$pmax[e$from, e$to])) fit$pmax[e$from, e$to] else NULL) else weights[e$from, e$to],
share = if (BOOTSTRAP > 0) freq[e$from, e$to] else NULL,
share_dir = if (BOOTSTRAP > 0 && e$type == "directed") freq_dir[e$from, e$to] else NULL
)
if (!is.null(kn)) row$knowledge <- if (kn$fixed[e$from, e$to]) "required" else ""
row
})
edge_columns <- list(list(key = "from", label = "From"), list(key = "type", label = "Link"), list(key = "to", label = "To"),
list(key = "strength", label = strength_label, type = if (ALGORITHM == "pc") "p" else "number"),
list(key = "share", label = "In resamples", type = "percent"),
list(key = "share_dir", label = "This direction", type = "percent"))
if (!is.null(kn)) edge_columns[[length(edge_columns) + 1]] <- list(key = "knowledge", label = "Your knowledge")
tables <- list(list(
key = "edges",
title = "Suggested links",
columns = edge_columns,
rows = edge_rows
))
if (ALGORITHM == "pc") {
sep_rows <- list()
for (i in seq_len(p - 1)) {
for (j in (i + 1):p) {
if (!fit$adj[i, j] && !is.null(kn) && kn$gaps[i, j]) {
sep_rows[[length(sep_rows) + 1]] <- list(a = VARIABLES[i], b = VARIABLES[j], given = "forbidden by you (not tested)", p = NULL)
} else if (!fit$adj[i, j]) {
S <- fit$sepset[[paste(i, j)]]
if (is.null(S)) S <- fit$sepset[[paste(j, i)]]
sep_rows[[length(sep_rows) + 1]] <- list(a = VARIABLES[i], b = VARIABLES[j],
given = if (length(S)) paste(VARIABLES[S], collapse = ", ") else "nothing", p = fit$pmax[i, j])
}
}
}
tables[[2]] <- list(
key = "separations",
title = "Pairs with no link: what made them independent",
columns = list(list(key = "a", label = "Variable"), list(key = "b", label = "And"), list(key = "given", label = "Independent given"),
list(key = "p", label = "Largest p-value", type = "p")),
rows = sep_rows
)
}
# %% Charts
charts <- list()
rowv <- rep(VARIABLES, each = p)
colv <- rep(VARIABLES, times = p)
fd <- as.vector(t(freq_dir))
diag_cell <- rep(seq_len(p), each = p) == rep(seq_len(p), times = p)
if (BOOTSTRAP > 0) {
charts[[1]] <- cs_chart("frequencies", "matrix-heatmap", sprintf("How often each arrow came back in %d resamples", BOOTSTRAP), list(
row = cs_col("From", rowv, "categorical", levels = VARIABLES),
col = cs_col("To", colv, "categorical", levels = VARIABLES),
value = cs_col("Share of resamples", ifelse(diag_cell, 0, fd), "numeric"),
label = cs_col("Share", ifelse(!diag_cell & fd > 0, sprintf("%.0f%%", 100 * fd), ""), "categorical")
), controls = list(scale = "sequential", min = 0, max = 1),
note = "Row → column: the share of refits with that arrow, or with an undirected link between the two.")
} else if (ALGORITHM == "notears") {
charts[[1]] <- cs_chart("weights", "matrix-heatmap", "Weight of each suggested arrow", list(
row = cs_col("From", rowv, "categorical", levels = VARIABLES),
col = cs_col("To", colv, "categorical", levels = VARIABLES),
value = cs_col("Weight", as.vector(t(weights)), "numeric")
), controls = list(scale = "diverging"))
}
# %% Result
directed <- values$n_directed
undirected <- values$n_undirected
cs_publish(list(
title = "Suggest causal structure (PC, NOTEARS)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = sprintf("%s suggests %d %s among %d variables (%d with a direction, %d without). These are hypotheses to check against what you know, not causal conclusions.",
algorithm_label, length(edges), if (length(edges) == 1) "link" else "links", p, directed, undirected),
statistics = list(list(key = "n_edges", label = "Links", value = length(edges), format = "integer"),
list(key = "n_directed", label = "With a direction", value = directed, format = "integer"),
list(key = "n_undirected", label = "Undirected", value = undirected, format = "integer")),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
notes = c(list(
if (ALGORITHM == "pc") sprintf("Independence test: %s, α = %g, conditioning sets up to %d variables.",
if (test_used == "fisher_z") "Fisher z (partial correlation)" else "G² on category counts", ALPHA, MAX_COND)
else sprintf("NOTEARS on %s variables, λ = %g, weights below %g dropped; reported weights are least-squares refits on each variable's suggested parents.",
if (SCALE == "standardize") "standardized" else "centered", LAMBDA1, W_THRESHOLD),
"A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow."
), if (!is.null(kn)) list(sprintf("Background knowledge: %d required and %d forbidden link%s; resamples use it too.", kn$n_required,
kn$n_forbidden, if (kn$n_forbidden != 1) "s" else "")))
))
NOTEARS suggests 9 links among 8 variables (9 with a direction, 0 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 9
- With a direction
- 9
- Undirected
- 0
To keep this page light, the plots are shown once, under the R tab.
Suggested links
| From | Link | To | Weight (least squares) | In resamples | This direction |
|---|---|---|---|---|---|
| sun | → | temperature | 0.7805 | — | — |
| growth | → | sun | 0.5389 | — | — |
| moisture | → | water | 0.8681 | — | — |
| moisture | → | fertilizer | −0.4617 | — | — |
| growth | → | fertilizer | 0.6705 | — | — |
| growth | → | pests | 1.204 | — | — |
| harvest | → | pests | −1.491 | — | — |
| growth | → | moisture | 0.5894 | — | — |
| growth | → | harvest | 0.8526 | — | — |
- 4 links change when the variables are centered only instead, so these arrows partly reflect the units.
- NOTEARS on standardized variables, λ = 0.1, weights below 0.3 dropped; reported weights are least-squares refits on each variable's suggested parents.
- A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Suggest causal structure (PC, NOTEARS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.structure 1.1.0 · spec 340508c83665c287
# Dataset: csl_garden (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.ml import structure as st
from codesplash.ml import structure_knowledge as sk
# %% Data
VARIABLES = ["sun", "water", "fertilizer", "pests", "temperature", "moisture", "growth", "harvest"]
ALGORITHM = "notears" # pc | notears
TEST = "auto" # auto | fisher_z | g2 (PC)
ALPHA = 0.05
MAX_COND = 4
LAMBDA1 = 0.1
W_THRESHOLD = 0.3
SCALE = "standardize" # standardize | center (NOTEARS)
BOOTSTRAP = 0
REQUIRED = "" # background knowledge: links you know exist ("a -> b, c -- d")
FORBIDDEN = "" # and links you know don't
SEED = 42
MAX_LEVELS = 20 # G²: categories per variable
df = pd.read_parquet("tests/parity/fixtures/csl_garden.parquet", columns=VARIABLES)
n_input = len(df)
cs.check_finite_columns(df, VARIABLES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, VARIABLES)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 10, "Causal structure suggestions")
p = len(VARIABLES)
def kind_of(col):
s = df[col]
if pd.api.types.is_bool_dtype(s):
return "boolean"
return "numeric" if pd.api.types.is_numeric_dtype(s) else "categorical"
kinds = [kind_of(c) for c in VARIABLES]
labels = [cc.label_text(df[c].iloc[rows].tolist()) for c in VARIABLES]
for c, lab in zip(VARIABLES, labels):
if len(set(lab.tolist())) < 2:
cs.cs_error("CS_E_CONSTANT", column=c)
if ALGORITHM == "notears":
if "categorical" in kinds:
cs.cs_error("CS_E_INVALID_OPTION", option="Algorithm", allowed="PC-stable when a variable is a category (NOTEARS needs numbers)", value="NOTEARS")
test_used = "none"
elif TEST == "auto":
if "categorical" not in kinds:
test_used = "fisher_z"
elif "numeric" not in kinds:
test_used = "g2"
else:
cs.cs_error("CS_E_INVALID_OPTION", option="Independence test", allowed="Fisher z or G² chosen by hand when numbers and categories are mixed", value="Automatic")
else:
test_used = TEST
if test_used == "fisher_z" and "categorical" in kinds:
cs.cs_error("CS_E_INVALID_OPTION", option="Independence test", allowed="G² when a variable is a category", value="Fisher z")
if test_used == "g2":
cols = []
for c, lab in zip(VARIABLES, labels):
levels = sorted(set(lab.tolist()))
if len(levels) > MAX_LEVELS:
cs.cs_error("CS_E_TOO_MANY_LEVELS", column=c, k=len(levels), max=MAX_LEVELS)
pos = {v: i for i, v in enumerate(levels)}
cols.append([pos[v] for v in lab.tolist()])
X = np.array(cols, dtype=np.float64).T
else:
X = np.column_stack([df[c].iloc[rows].to_numpy(dtype=np.float64) for c in VARIABLES]) # yes/no as 1/0
n = X.shape[0]
# None without knowledge, so the fit below is exactly the plain one.
kn = sk.knowledge(p, sk.parse(REQUIRED, VARIABLES, "Required links"), sk.parse(FORBIDDEN, VARIABLES, "Forbidden links"), VARIABLES)
# %% Fit
kw = dict(algorithm=ALGORITHM, test=test_used, alpha=ALPHA, max_cond=MAX_COND, lambda1=LAMBDA1, w_threshold=W_THRESHOLD,
standardize=SCALE == "standardize", max_iter=100)
fit = sk.fit(X, kn, **kw)
pdag = fit["pdag"]
edges = st.edge_list(pdag)
freq, freq_dir = sk.bootstrap(X, BOOTSTRAP, SEED, kn, **kw)
weights = None
shd_other = None
if ALGORITHM == "notears":
weights = st.refit_weights(st.scaled(X, SCALE == "standardize"), pdag)
other = sk.fit(X, kn, **dict(kw, standardize=SCALE != "standardize"))
shd_other = st.shd(pdag, other["pdag"])
if fit["h"] > 1e-8:
warnings.append("The fit stopped before its graph was fully free of loops; read the arrows with extra care.")
if shd_other:
warnings.append(f"{shd_other} link{' changes' if shd_other == 1 else 's change'} when the variables are "
f"{'centered only' if SCALE == 'standardize' else 'standardized'} instead, so these arrows partly reflect the units.")
if kn is not None:
req_set = set(kn["req_dir"])
for a, b in fit["conflicts"]:
if (a, b) in req_set:
warnings.append(f"The data orient {VARIABLES[b]} → {VARIABLES[a]}, against your required arrow {VARIABLES[a]} → {VARIABLES[b]}; the graph shows the data's direction.")
else:
warnings.append(f"The data orient {VARIABLES[b]} → {VARIABLES[a]}, which you forbade; the graph shows the data's direction.")
if fit.get("dropped"):
dropped_text = ", ".join(f"{VARIABLES[a]} → {VARIABLES[b]}" for a, b in fit["dropped"])
warnings.append(f"Keeping your required arrows closed a loop, so the weakest suggested arrow{'s' if len(fit['dropped']) != 1 else ''} on it {'were' if len(fit['dropped']) != 1 else 'was'} dropped: {dropped_text}.")
# %% Values
algorithm_label = "PC-stable" if ALGORITHM == "pc" else "NOTEARS"
values = {
"algorithm_label": algorithm_label,
"n": n,
"p": p,
"n_edges": len(edges),
"n_directed": sum(1 for e in edges if e[2] == "directed"),
"n_undirected": sum(1 for e in edges if e[2] == "undirected"),
"bootstrap": BOOTSTRAP,
"n_tests": fit["n_tests"] if ALGORITHM == "pc" else None,
"max_order": fit["max_order"] if ALGORITHM == "pc" else None,
"h_converged": (1 if fit["h"] <= 1e-8 else 0) if ALGORITHM == "notears" else None,
"shd_other_scale": shd_other,
}
if kn is not None:
values["n_required"] = kn["n_required"]
values["n_forbidden"] = kn["n_forbidden"]
values["n_conflicts"] = len(fit["conflicts"])
if ALGORITHM == "notears":
values["n_dropped"] = len(fit["dropped"])
for i in range(p):
for j in range(i + 1, p):
a, b = VARIABLES[i], VARIABLES[j]
code = 2 if (pdag[i, j] == 1 and pdag[j, i] == 1) else 1 if pdag[i, j] == 1 else -1 if pdag[j, i] == 1 else 0
values[f"edge[{a}|{b}]"] = code
if ALGORITHM == "pc" and (kn is None or np.isfinite(fit["pmax"][i, j])): # knowledge-settled pairs aren't tested
values[f"pmax[{a}|{b}]"] = float(fit["pmax"][i, j])
if BOOTSTRAP > 0:
values[f"freq[{a}|{b}]"] = float(freq[i, j])
if ALGORITHM == "notears":
for i, j, _ in edges:
values[f"weight[{VARIABLES[i]}->{VARIABLES[j]}]"] = float(weights[i, j])
if BOOTSTRAP > 0:
for i in range(p):
for j in range(p):
if i != j:
values[f"freq_dir[{VARIABLES[i]}->{VARIABLES[j]}]"] = float(freq_dir[i, j])
# %% Tables
strength_label = "Largest p-value" if ALGORITHM == "pc" else "Weight (least squares)"
edge_rows = []
for i, j, kind in edges:
row = {
"from": VARIABLES[i], "to": VARIABLES[j], "type": "→" if kind == "directed" else "—",
"strength": (float(fit["pmax"][i, j]) if np.isfinite(fit["pmax"][i, j]) else None) if ALGORITHM == "pc" else float(weights[i, j]),
"share": float(freq[i, j]) if BOOTSTRAP > 0 else None,
"share_dir": float(freq_dir[i, j]) if BOOTSTRAP > 0 and kind == "directed" else None,
}
if kn is not None:
row["knowledge"] = "required" if kn["fixed"][i, j] else ""
edge_rows.append(row)
edge_columns = [{"key": "from", "label": "From"}, {"key": "type", "label": "Link"}, {"key": "to", "label": "To"},
{"key": "strength", "label": strength_label, "type": "p" if ALGORITHM == "pc" else "number"},
{"key": "share", "label": "In resamples", "type": "percent"},
{"key": "share_dir", "label": "This direction", "type": "percent"}]
if kn is not None:
edge_columns.append({"key": "knowledge", "label": "Your knowledge"})
tables = [{
"key": "edges",
"title": "Suggested links",
"columns": edge_columns,
"rows": edge_rows,
}]
if ALGORITHM == "pc":
sep_rows = []
for i in range(p):
for j in range(i + 1, p):
if not fit["adj"][i, j]:
if kn is not None and kn["gaps"][i, j]:
sep_rows.append({"a": VARIABLES[i], "b": VARIABLES[j], "given": "forbidden by you (not tested)", "p": None})
continue
S = fit["sepset"].get((i, j), fit["sepset"].get((j, i), []))
sep_rows.append({"a": VARIABLES[i], "b": VARIABLES[j], "given": ", ".join(VARIABLES[k] for k in S) if S else "nothing",
"p": float(fit["pmax"][i, j])})
tables.append({
"key": "separations",
"title": "Pairs with no link: what made them independent",
"columns": [{"key": "a", "label": "Variable"}, {"key": "b", "label": "And"}, {"key": "given", "label": "Independent given"},
{"key": "p", "label": "Largest p-value", "type": "p"}],
"rows": sep_rows,
})
# %% Charts
charts = []
if BOOTSTRAP > 0:
charts.append(cs.chart("frequencies", "matrix-heatmap", f"How often each arrow came back in {BOOTSTRAP} resamples", {
"row": cs.col("From", [a for a in VARIABLES for _ in VARIABLES], "categorical", levels=VARIABLES),
"col": cs.col("To", [b for _ in VARIABLES for b in VARIABLES], "categorical", levels=VARIABLES),
"value": cs.col("Share of resamples", [float(freq_dir[i, j]) if i != j else 0.0 for i in range(p) for j in range(p)], "numeric"),
"label": cs.col("Share", [f"{freq_dir[i, j]:.0%}" if i != j and freq_dir[i, j] > 0 else "" for i in range(p) for j in range(p)], "categorical"),
}, controls={"scale": "sequential", "min": 0, "max": 1},
note="Row → column: the share of refits with that arrow, or with an undirected link between the two."))
elif ALGORITHM == "notears":
charts.append(cs.chart("weights", "matrix-heatmap", "Weight of each suggested arrow", {
"row": cs.col("From", [a for a in VARIABLES for _ in VARIABLES], "categorical", levels=VARIABLES),
"col": cs.col("To", [b for _ in VARIABLES for b in VARIABLES], "categorical", levels=VARIABLES),
"value": cs.col("Weight", [float(weights[i, j]) for i in range(p) for j in range(p)], "numeric"),
}, controls={"scale": "diverging"}))
# %% Result
directed = values["n_directed"]
undirected = values["n_undirected"]
cs.publish({
"title": "Suggest causal structure (PC, NOTEARS)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": n,
"summary": f"{algorithm_label} suggests {len(edges)} link{'' if len(edges) == 1 else 's'} among {p} variables "
f"({directed} with a direction, {undirected} without). These are hypotheses to check against what you know, not causal conclusions.",
"statistics": [
{"key": "n_edges", "label": "Links", "value": len(edges), "format": "integer"},
{"key": "n_directed", "label": "With a direction", "value": directed, "format": "integer"},
{"key": "n_undirected", "label": "Undirected", "value": undirected, "format": "integer"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"notes": [
f"Independence test: {'Fisher z (partial correlation)' if test_used == 'fisher_z' else 'G² on category counts'}, α = {ALPHA:g}, conditioning sets up to {MAX_COND} variables."
if ALGORITHM == "pc" else
f"NOTEARS on {'standardized' if SCALE == 'standardize' else 'centered'} variables, λ = {LAMBDA1:g}, weights below {W_THRESHOLD:g} dropped; reported weights are least-squares refits on each variable's suggested parents.",
"A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.",
] + ([f"Background knowledge: {kn['n_required']} required and {kn['n_forbidden']} forbidden link{'s' if kn['n_forbidden'] != 1 else ''}; resamples use it too."] if kn is not None else []),
})
What acyclicity doesn't certify
Readcertifies a combinatorial property, no cycles, not causality. In practice the solver stops near zero and small weights are thresholded, so check the final graph for cycles discretely. Compare NOTEARS with PC-stable, which leaves arrows it can't orient undirected:
PC-stable suggests 7 links among 8 variables (5 with a direction, 2 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 7
- With a direction
- 5
- Undirected
- 2
Plots
Row → column: the share of refits with that arrow, or with an undirected link between the two.
View data
| To | Share | From | Share of resamples |
|---|---|---|---|
| sun | sun | 0 | |
| water | sun | 0 | |
| fertilizer | sun | 0 | |
| pests | sun | 0 | |
| temperature | 90% | sun | 0.9000 |
| moisture | sun | 0 | |
| growth | 100% | sun | 1 |
| harvest | sun | 0 | |
| sun | water | 0 | |
| water | water | 0 | |
| fertilizer | water | 0 | |
| pests | water | 0 | |
| temperature | water | 0 | |
| moisture | 100% | water | 1 |
| growth | water | 0 | |
| harvest | water | 0 | |
| sun | 10% | fertilizer | 0.1000 |
| water | fertilizer | 0 | |
| fertilizer | fertilizer | 0 | |
| pests | fertilizer | 0 | |
| temperature | fertilizer | 0 | |
| moisture | 5% | fertilizer | 0.0500 |
| growth | 100% | fertilizer | 1 |
| harvest | 5% | fertilizer | 0.0500 |
| sun | pests | 0 | |
| water | pests | 0 | |
| fertilizer | pests | 0 | |
| pests | pests | 0 | |
| temperature | pests | 0 | |
| moisture | pests | 0 | |
| growth | pests | 0 | |
| harvest | 100% | pests | 1 |
| sun | 100% | temperature | 1 |
| water | temperature | 0 | |
| fertilizer | temperature | 0 | |
| pests | temperature | 0 | |
| temperature | temperature | 0 | |
| moisture | temperature | 0 | |
| growth | temperature | 0 | |
| harvest | temperature | 0 | |
| sun | moisture | 0 | |
| water | 100% | moisture | 1 |
| fertilizer | 5% | moisture | 0.0500 |
| pests | moisture | 0 | |
| temperature | moisture | 0 | |
| moisture | moisture | 0 | |
| growth | 100% | moisture | 1 |
| harvest | moisture | 0 | |
| sun | growth | 0 | |
| water | growth | 0 | |
| fertilizer | growth | 0 | |
| pests | growth | 0 | |
| temperature | growth | 0 | |
| moisture | growth | 0 | |
| growth | growth | 0 | |
| harvest | 100% | growth | 1 |
| sun | harvest | 0 | |
| water | harvest | 0 | |
| fertilizer | harvest | 0 | |
| pests | harvest | 0 |
First 60 of 64 rows.
Suggested links
| From | Link | To | Largest p-value | In resamples | This direction |
|---|---|---|---|---|---|
| sun | — | temperature | 2.975e-91 | 100.0% | — |
| sun | → | growth | 1.765e-12 | 100.0% | 100.0% |
| water | — | moisture | 4.095e-145 | 100.0% | — |
| fertilizer | → | growth | 1.183e-8 | 100.0% | 100.0% |
| pests | → | harvest | 3.984e-29 | 100.0% | 100.0% |
| moisture | → | growth | 2.606e-16 | 100.0% | 100.0% |
| growth | → | harvest | 2.455e-50 | 100.0% | 100.0% |
Pairs with no link: what made them independent
| Variable | And | Independent given | Largest p-value |
|---|---|---|---|
| sun | water | nothing | 0.4883 |
| sun | fertilizer | nothing | 0.9599 |
| sun | pests | nothing | 0.1020 |
| sun | moisture | nothing | 0.5393 |
| sun | harvest | growth | 0.7482 |
| water | fertilizer | nothing | 0.2369 |
| water | pests | nothing | 0.7263 |
| water | temperature | nothing | 0.9528 |
| water | growth | moisture | 0.6797 |
| water | harvest | moisture | 0.2448 |
| fertilizer | pests | nothing | 0.2310 |
| fertilizer | temperature | nothing | 0.2373 |
| fertilizer | moisture | nothing | 0.1373 |
| fertilizer | harvest | growth | 0.4069 |
| pests | temperature | nothing | 0.1001 |
| pests | moisture | nothing | 0.7865 |
| pests | growth | nothing | 0.1352 |
| temperature | moisture | nothing | 0.7855 |
| temperature | growth | sun | 0.6370 |
| temperature | harvest | sun | 0.6420 |
| moisture | harvest | growth | 0.8946 |
- Independence test: Fisher z (partial correlation), α = 0.05, conditioning sets up to 4 variables.
- A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.
The exact R script · R R version 4.5.1 (2025-06-13)
# Suggest causal structure (PC, NOTEARS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.structure 1.1.0 · spec 707a7b65e7b08e7d
# Dataset: csl_garden (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
VARIABLES <- c("sun", "water", "fertilizer", "pests", "temperature", "moisture", "growth", "harvest")
ALGORITHM <- "pc" # pc | notears
TEST <- "auto" # auto | fisher_z | g2 (PC)
ALPHA <- 0.05
MAX_COND <- 4
LAMBDA1 <- 0.1
W_THRESHOLD <- 0.3
SCALE <- "standardize" # standardize | center (NOTEARS)
BOOTSTRAP <- 20
REQUIRED <- "" # background knowledge: links you know exist ("a -> b, c -- d")
FORBIDDEN <- "" # and links you know don't
SEED <- 42
MAX_LEVELS <- 20 # G²: categories per variable
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/csl_garden.parquet", col_select = VARIABLES))
n_input <- nrow(df)
cs_check_finite_columns(df, VARIABLES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows <- cs_ml_complete_rows(df, VARIABLES)
warnings <- list()
if (length(rows) < n_input) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
cs_check_rows(length(rows), 10, "Causal structure suggestions")
p <- length(VARIABLES)
kind_of <- function(v) if (is.logical(v)) "boolean" else if (is.numeric(v)) "numeric" else "categorical"
kinds <- vapply(VARIABLES, function(c) kind_of(df[[c]]), character(1), USE.NAMES = FALSE)
labels <- lapply(VARIABLES, function(c) cs_ml_label_text(df[[c]][rows + 1L]))
for (k in seq_len(p)) if (length(unique(labels[[k]])) < 2) cs_error("CS_E_CONSTANT", column = VARIABLES[k])
if (ALGORITHM == "notears") {
if ("categorical" %in% kinds) cs_error("CS_E_INVALID_OPTION", option = "Algorithm", allowed = "PC-stable when a variable is a category (NOTEARS needs numbers)", value = "NOTEARS")
test_used <- "none"
} else if (TEST == "auto") {
if (!("categorical" %in% kinds)) {
test_used <- "fisher_z"
} else if (!("numeric" %in% kinds)) {
test_used <- "g2"
} else {
cs_error("CS_E_INVALID_OPTION", option = "Independence test", allowed = "Fisher z or G² chosen by hand when numbers and categories are mixed", value = "Automatic")
}
} else {
test_used <- TEST
if (test_used == "fisher_z" && "categorical" %in% kinds) cs_error("CS_E_INVALID_OPTION", option = "Independence test", allowed = "G² when a variable is a category", value = "Fisher z")
}
if (test_used == "g2") {
X <- matrix(0, length(rows), p)
for (k in seq_len(p)) {
levels <- sort(unique(labels[[k]]), method = "radix")
if (length(levels) > MAX_LEVELS) cs_error("CS_E_TOO_MANY_LEVELS", column = VARIABLES[k], k = length(levels), max = MAX_LEVELS)
X[, k] <- match(labels[[k]], levels) - 1
}
} else {
X <- matrix(vapply(VARIABLES, function(c) as.numeric(df[[c]][rows + 1L]), numeric(length(rows))), ncol = p) # yes/no as 1/0
}
n <- nrow(X)
# NULL without knowledge, so the fit below is exactly the plain one.
kn <- cs_ml_structure_knowledge(p, cs_ml_structure_knowledge_parse(REQUIRED, VARIABLES, "Required links"),
cs_ml_structure_knowledge_parse(FORBIDDEN, VARIABLES, "Forbidden links"), VARIABLES)
# %% Fit
fit_args <- list(algorithm = ALGORITHM, test = test_used, alpha = ALPHA, max_cond = MAX_COND, lambda1 = LAMBDA1,
w_threshold = W_THRESHOLD, standardize = SCALE == "standardize", max_iter = 100)
fit <- do.call(cs_ml_structure_fit_knowledge, c(list(data = X, kn = kn), fit_args))
pdag <- fit$pdag
edges <- cs_ml_structure_edges(pdag)
boot <- do.call(cs_ml_structure_bootstrap_knowledge, c(list(data = X, B = BOOTSTRAP, seed = SEED, kn = kn), fit_args))
freq <- boot$freq
freq_dir <- boot$freq_dir
weights <- NULL
shd_other <- NULL
if (ALGORITHM == "notears") {
weights <- cs_ml_structure_refit(cs_ml_structure_scaled(X, SCALE == "standardize"), pdag)
other_args <- fit_args
other_args$standardize <- SCALE != "standardize"
other <- do.call(cs_ml_structure_fit_knowledge, c(list(data = X, kn = kn), other_args))
shd_other <- cs_ml_structure_shd(pdag, other$pdag)
if (fit$h > 1e-8) warnings <- c(warnings, "The fit stopped before its graph was fully free of loops; read the arrows with extra care.")
if (shd_other > 0) {
warnings <- c(warnings, sprintf("%d %s when the variables are %s instead, so these arrows partly reflect the units.", shd_other,
if (shd_other == 1) "link changes" else "links change", if (SCALE == "standardize") "centered only" else "standardized"))
}
}
if (!is.null(kn)) {
for (e in fit$conflicts) {
a <- e[1]
b <- e[2]
required <- any(vapply(kn$req_dir, function(r) r[1] == a && r[2] == b, logical(1)))
warnings <- c(warnings, if (required) {
sprintf("The data orient %s → %s, against your required arrow %s → %s; the graph shows the data's direction.", VARIABLES[b], VARIABLES[a], VARIABLES[a], VARIABLES[b])
} else {
sprintf("The data orient %s → %s, which you forbade; the graph shows the data's direction.", VARIABLES[b], VARIABLES[a])
})
}
if (length(fit$dropped)) {
nd <- length(fit$dropped)
warnings <- c(warnings, sprintf("Keeping your required arrows closed a loop, so the weakest suggested arrow%s on it %s dropped: %s.",
if (nd != 1) "s" else "", if (nd != 1) "were" else "was",
paste(vapply(fit$dropped, function(e) sprintf("%s → %s", VARIABLES[e[1]], VARIABLES[e[2]]), ""), collapse = ", ")))
}
}
# %% Values
algorithm_label <- if (ALGORITHM == "pc") "PC-stable" else "NOTEARS"
etype <- vapply(edges, function(e) e$type, character(1))
values <- list(
algorithm_label = algorithm_label,
n = n,
p = p,
n_edges = length(edges),
n_directed = sum(etype == "directed"),
n_undirected = sum(etype == "undirected"),
bootstrap = BOOTSTRAP,
n_tests = if (ALGORITHM == "pc") fit$n_tests else NA,
max_order = if (ALGORITHM == "pc") fit$max_order else NA,
h_converged = if (ALGORITHM == "notears") (if (fit$h <= 1e-8) 1L else 0L) else NA,
shd_other_scale = if (is.null(shd_other)) NA else shd_other
)
if (!is.null(kn)) {
values$n_required <- kn$n_required
values$n_forbidden <- kn$n_forbidden
values$n_conflicts <- length(fit$conflicts)
if (ALGORITHM == "notears") values$n_dropped <- length(fit$dropped)
}
for (i in seq_len(p - 1)) {
for (j in (i + 1):p) {
a <- VARIABLES[i]
b <- VARIABLES[j]
code <- if (pdag[i, j] == 1 && pdag[j, i] == 1) 2L else if (pdag[i, j] == 1) 1L else if (pdag[j, i] == 1) -1L else 0L
values[[sprintf("edge[%s|%s]", a, b)]] <- code
if (ALGORITHM == "pc" && (is.null(kn) || is.finite(fit$pmax[i, j]))) values[[sprintf("pmax[%s|%s]", a, b)]] <- fit$pmax[i, j] # knowledge-settled pairs aren't tested
if (BOOTSTRAP > 0) values[[sprintf("freq[%s|%s]", a, b)]] <- freq[i, j]
}
}
if (ALGORITHM == "notears") for (e in edges) values[[sprintf("weight[%s->%s]", VARIABLES[e$from], VARIABLES[e$to])]] <- weights[e$from, e$to]
if (BOOTSTRAP > 0) {
for (i in seq_len(p)) for (j in seq_len(p)) if (i != j) values[[sprintf("freq_dir[%s->%s]", VARIABLES[i], VARIABLES[j])]] <- freq_dir[i, j]
}
# %% Tables
strength_label <- if (ALGORITHM == "pc") "Largest p-value" else "Weight (least squares)"
edge_rows <- lapply(edges, function(e) {
row <- list(
from = VARIABLES[e$from], to = VARIABLES[e$to], type = if (e$type == "directed") "→" else "—",
strength = if (ALGORITHM == "pc") (if (is.finite(fit$pmax[e$from, e$to])) fit$pmax[e$from, e$to] else NULL) else weights[e$from, e$to],
share = if (BOOTSTRAP > 0) freq[e$from, e$to] else NULL,
share_dir = if (BOOTSTRAP > 0 && e$type == "directed") freq_dir[e$from, e$to] else NULL
)
if (!is.null(kn)) row$knowledge <- if (kn$fixed[e$from, e$to]) "required" else ""
row
})
edge_columns <- list(list(key = "from", label = "From"), list(key = "type", label = "Link"), list(key = "to", label = "To"),
list(key = "strength", label = strength_label, type = if (ALGORITHM == "pc") "p" else "number"),
list(key = "share", label = "In resamples", type = "percent"),
list(key = "share_dir", label = "This direction", type = "percent"))
if (!is.null(kn)) edge_columns[[length(edge_columns) + 1]] <- list(key = "knowledge", label = "Your knowledge")
tables <- list(list(
key = "edges",
title = "Suggested links",
columns = edge_columns,
rows = edge_rows
))
if (ALGORITHM == "pc") {
sep_rows <- list()
for (i in seq_len(p - 1)) {
for (j in (i + 1):p) {
if (!fit$adj[i, j] && !is.null(kn) && kn$gaps[i, j]) {
sep_rows[[length(sep_rows) + 1]] <- list(a = VARIABLES[i], b = VARIABLES[j], given = "forbidden by you (not tested)", p = NULL)
} else if (!fit$adj[i, j]) {
S <- fit$sepset[[paste(i, j)]]
if (is.null(S)) S <- fit$sepset[[paste(j, i)]]
sep_rows[[length(sep_rows) + 1]] <- list(a = VARIABLES[i], b = VARIABLES[j],
given = if (length(S)) paste(VARIABLES[S], collapse = ", ") else "nothing", p = fit$pmax[i, j])
}
}
}
tables[[2]] <- list(
key = "separations",
title = "Pairs with no link: what made them independent",
columns = list(list(key = "a", label = "Variable"), list(key = "b", label = "And"), list(key = "given", label = "Independent given"),
list(key = "p", label = "Largest p-value", type = "p")),
rows = sep_rows
)
}
# %% Charts
charts <- list()
rowv <- rep(VARIABLES, each = p)
colv <- rep(VARIABLES, times = p)
fd <- as.vector(t(freq_dir))
diag_cell <- rep(seq_len(p), each = p) == rep(seq_len(p), times = p)
if (BOOTSTRAP > 0) {
charts[[1]] <- cs_chart("frequencies", "matrix-heatmap", sprintf("How often each arrow came back in %d resamples", BOOTSTRAP), list(
row = cs_col("From", rowv, "categorical", levels = VARIABLES),
col = cs_col("To", colv, "categorical", levels = VARIABLES),
value = cs_col("Share of resamples", ifelse(diag_cell, 0, fd), "numeric"),
label = cs_col("Share", ifelse(!diag_cell & fd > 0, sprintf("%.0f%%", 100 * fd), ""), "categorical")
), controls = list(scale = "sequential", min = 0, max = 1),
note = "Row → column: the share of refits with that arrow, or with an undirected link between the two.")
} else if (ALGORITHM == "notears") {
charts[[1]] <- cs_chart("weights", "matrix-heatmap", "Weight of each suggested arrow", list(
row = cs_col("From", rowv, "categorical", levels = VARIABLES),
col = cs_col("To", colv, "categorical", levels = VARIABLES),
value = cs_col("Weight", as.vector(t(weights)), "numeric")
), controls = list(scale = "diverging"))
}
# %% Result
directed <- values$n_directed
undirected <- values$n_undirected
cs_publish(list(
title = "Suggest causal structure (PC, NOTEARS)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = sprintf("%s suggests %d %s among %d variables (%d with a direction, %d without). These are hypotheses to check against what you know, not causal conclusions.",
algorithm_label, length(edges), if (length(edges) == 1) "link" else "links", p, directed, undirected),
statistics = list(list(key = "n_edges", label = "Links", value = length(edges), format = "integer"),
list(key = "n_directed", label = "With a direction", value = directed, format = "integer"),
list(key = "n_undirected", label = "Undirected", value = undirected, format = "integer")),
tables = tables,
values = values,
charts = charts,
warnings = warnings,
notes = c(list(
if (ALGORITHM == "pc") sprintf("Independence test: %s, α = %g, conditioning sets up to %d variables.",
if (test_used == "fisher_z") "Fisher z (partial correlation)" else "G² on category counts", ALPHA, MAX_COND)
else sprintf("NOTEARS on %s variables, λ = %g, weights below %g dropped; reported weights are least-squares refits on each variable's suggested parents.",
if (SCALE == "standardize") "standardized" else "centered", LAMBDA1, W_THRESHOLD),
"A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow."
), if (!is.null(kn)) list(sprintf("Background knowledge: %d required and %d forbidden link%s; resamples use it too.", kn$n_required,
kn$n_forbidden, if (kn$n_forbidden != 1) "s" else "")))
))
PC-stable suggests 7 links among 8 variables (5 with a direction, 2 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 7
- With a direction
- 5
- Undirected
- 2
To keep this page light, the plots are shown once, under the R tab.
Suggested links
| From | Link | To | Largest p-value | In resamples | This direction |
|---|---|---|---|---|---|
| sun | — | temperature | 2.975e-91 | 100.0% | — |
| sun | → | growth | 1.765e-12 | 100.0% | 100.0% |
| water | — | moisture | 4.095e-145 | 100.0% | — |
| fertilizer | → | growth | 1.183e-8 | 100.0% | 100.0% |
| pests | → | harvest | 3.984e-29 | 100.0% | 100.0% |
| moisture | → | growth | 2.606e-16 | 100.0% | 100.0% |
| growth | → | harvest | 2.455e-50 | 100.0% | 100.0% |
Pairs with no link: what made them independent
| Variable | And | Independent given | Largest p-value |
|---|---|---|---|
| sun | water | nothing | 0.4883 |
| sun | fertilizer | nothing | 0.9599 |
| sun | pests | nothing | 0.1020 |
| sun | moisture | nothing | 0.5393 |
| sun | harvest | growth | 0.7482 |
| water | fertilizer | nothing | 0.2369 |
| water | pests | nothing | 0.7263 |
| water | temperature | nothing | 0.9528 |
| water | growth | moisture | 0.6797 |
| water | harvest | moisture | 0.2448 |
| fertilizer | pests | nothing | 0.2310 |
| fertilizer | temperature | nothing | 0.2373 |
| fertilizer | moisture | nothing | 0.1373 |
| fertilizer | harvest | growth | 0.4069 |
| pests | temperature | nothing | 0.1001 |
| pests | moisture | nothing | 0.7865 |
| pests | growth | nothing | 0.1352 |
| temperature | moisture | nothing | 0.7855 |
| temperature | growth | sun | 0.6370 |
| temperature | harvest | sun | 0.6420 |
| moisture | harvest | growth | 0.8946 |
- Independence test: Fisher z (partial correlation), α = 0.05, conditioning sets up to 4 variables.
- A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Suggest causal structure (PC, NOTEARS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.structure 1.1.0 · spec 707a7b65e7b08e7d
# Dataset: csl_garden (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.ml import cluster_compare as cc
from codesplash.ml import embed as csembed
from codesplash.ml import structure as st
from codesplash.ml import structure_knowledge as sk
# %% Data
VARIABLES = ["sun", "water", "fertilizer", "pests", "temperature", "moisture", "growth", "harvest"]
ALGORITHM = "pc" # pc | notears
TEST = "auto" # auto | fisher_z | g2 (PC)
ALPHA = 0.05
MAX_COND = 4
LAMBDA1 = 0.1
W_THRESHOLD = 0.3
SCALE = "standardize" # standardize | center (NOTEARS)
BOOTSTRAP = 20
REQUIRED = "" # background knowledge: links you know exist ("a -> b, c -- d")
FORBIDDEN = "" # and links you know don't
SEED = 42
MAX_LEVELS = 20 # G²: categories per variable
df = pd.read_parquet("tests/parity/fixtures/csl_garden.parquet", columns=VARIABLES)
n_input = len(df)
cs.check_finite_columns(df, VARIABLES) # ±Inf stops with CS_E_NOT_FINITE in both engines
rows = csembed.complete_rows(df, VARIABLES)
warnings = []
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 10, "Causal structure suggestions")
p = len(VARIABLES)
def kind_of(col):
s = df[col]
if pd.api.types.is_bool_dtype(s):
return "boolean"
return "numeric" if pd.api.types.is_numeric_dtype(s) else "categorical"
kinds = [kind_of(c) for c in VARIABLES]
labels = [cc.label_text(df[c].iloc[rows].tolist()) for c in VARIABLES]
for c, lab in zip(VARIABLES, labels):
if len(set(lab.tolist())) < 2:
cs.cs_error("CS_E_CONSTANT", column=c)
if ALGORITHM == "notears":
if "categorical" in kinds:
cs.cs_error("CS_E_INVALID_OPTION", option="Algorithm", allowed="PC-stable when a variable is a category (NOTEARS needs numbers)", value="NOTEARS")
test_used = "none"
elif TEST == "auto":
if "categorical" not in kinds:
test_used = "fisher_z"
elif "numeric" not in kinds:
test_used = "g2"
else:
cs.cs_error("CS_E_INVALID_OPTION", option="Independence test", allowed="Fisher z or G² chosen by hand when numbers and categories are mixed", value="Automatic")
else:
test_used = TEST
if test_used == "fisher_z" and "categorical" in kinds:
cs.cs_error("CS_E_INVALID_OPTION", option="Independence test", allowed="G² when a variable is a category", value="Fisher z")
if test_used == "g2":
cols = []
for c, lab in zip(VARIABLES, labels):
levels = sorted(set(lab.tolist()))
if len(levels) > MAX_LEVELS:
cs.cs_error("CS_E_TOO_MANY_LEVELS", column=c, k=len(levels), max=MAX_LEVELS)
pos = {v: i for i, v in enumerate(levels)}
cols.append([pos[v] for v in lab.tolist()])
X = np.array(cols, dtype=np.float64).T
else:
X = np.column_stack([df[c].iloc[rows].to_numpy(dtype=np.float64) for c in VARIABLES]) # yes/no as 1/0
n = X.shape[0]
# None without knowledge, so the fit below is exactly the plain one.
kn = sk.knowledge(p, sk.parse(REQUIRED, VARIABLES, "Required links"), sk.parse(FORBIDDEN, VARIABLES, "Forbidden links"), VARIABLES)
# %% Fit
kw = dict(algorithm=ALGORITHM, test=test_used, alpha=ALPHA, max_cond=MAX_COND, lambda1=LAMBDA1, w_threshold=W_THRESHOLD,
standardize=SCALE == "standardize", max_iter=100)
fit = sk.fit(X, kn, **kw)
pdag = fit["pdag"]
edges = st.edge_list(pdag)
freq, freq_dir = sk.bootstrap(X, BOOTSTRAP, SEED, kn, **kw)
weights = None
shd_other = None
if ALGORITHM == "notears":
weights = st.refit_weights(st.scaled(X, SCALE == "standardize"), pdag)
other = sk.fit(X, kn, **dict(kw, standardize=SCALE != "standardize"))
shd_other = st.shd(pdag, other["pdag"])
if fit["h"] > 1e-8:
warnings.append("The fit stopped before its graph was fully free of loops; read the arrows with extra care.")
if shd_other:
warnings.append(f"{shd_other} link{' changes' if shd_other == 1 else 's change'} when the variables are "
f"{'centered only' if SCALE == 'standardize' else 'standardized'} instead, so these arrows partly reflect the units.")
if kn is not None:
req_set = set(kn["req_dir"])
for a, b in fit["conflicts"]:
if (a, b) in req_set:
warnings.append(f"The data orient {VARIABLES[b]} → {VARIABLES[a]}, against your required arrow {VARIABLES[a]} → {VARIABLES[b]}; the graph shows the data's direction.")
else:
warnings.append(f"The data orient {VARIABLES[b]} → {VARIABLES[a]}, which you forbade; the graph shows the data's direction.")
if fit.get("dropped"):
dropped_text = ", ".join(f"{VARIABLES[a]} → {VARIABLES[b]}" for a, b in fit["dropped"])
warnings.append(f"Keeping your required arrows closed a loop, so the weakest suggested arrow{'s' if len(fit['dropped']) != 1 else ''} on it {'were' if len(fit['dropped']) != 1 else 'was'} dropped: {dropped_text}.")
# %% Values
algorithm_label = "PC-stable" if ALGORITHM == "pc" else "NOTEARS"
values = {
"algorithm_label": algorithm_label,
"n": n,
"p": p,
"n_edges": len(edges),
"n_directed": sum(1 for e in edges if e[2] == "directed"),
"n_undirected": sum(1 for e in edges if e[2] == "undirected"),
"bootstrap": BOOTSTRAP,
"n_tests": fit["n_tests"] if ALGORITHM == "pc" else None,
"max_order": fit["max_order"] if ALGORITHM == "pc" else None,
"h_converged": (1 if fit["h"] <= 1e-8 else 0) if ALGORITHM == "notears" else None,
"shd_other_scale": shd_other,
}
if kn is not None:
values["n_required"] = kn["n_required"]
values["n_forbidden"] = kn["n_forbidden"]
values["n_conflicts"] = len(fit["conflicts"])
if ALGORITHM == "notears":
values["n_dropped"] = len(fit["dropped"])
for i in range(p):
for j in range(i + 1, p):
a, b = VARIABLES[i], VARIABLES[j]
code = 2 if (pdag[i, j] == 1 and pdag[j, i] == 1) else 1 if pdag[i, j] == 1 else -1 if pdag[j, i] == 1 else 0
values[f"edge[{a}|{b}]"] = code
if ALGORITHM == "pc" and (kn is None or np.isfinite(fit["pmax"][i, j])): # knowledge-settled pairs aren't tested
values[f"pmax[{a}|{b}]"] = float(fit["pmax"][i, j])
if BOOTSTRAP > 0:
values[f"freq[{a}|{b}]"] = float(freq[i, j])
if ALGORITHM == "notears":
for i, j, _ in edges:
values[f"weight[{VARIABLES[i]}->{VARIABLES[j]}]"] = float(weights[i, j])
if BOOTSTRAP > 0:
for i in range(p):
for j in range(p):
if i != j:
values[f"freq_dir[{VARIABLES[i]}->{VARIABLES[j]}]"] = float(freq_dir[i, j])
# %% Tables
strength_label = "Largest p-value" if ALGORITHM == "pc" else "Weight (least squares)"
edge_rows = []
for i, j, kind in edges:
row = {
"from": VARIABLES[i], "to": VARIABLES[j], "type": "→" if kind == "directed" else "—",
"strength": (float(fit["pmax"][i, j]) if np.isfinite(fit["pmax"][i, j]) else None) if ALGORITHM == "pc" else float(weights[i, j]),
"share": float(freq[i, j]) if BOOTSTRAP > 0 else None,
"share_dir": float(freq_dir[i, j]) if BOOTSTRAP > 0 and kind == "directed" else None,
}
if kn is not None:
row["knowledge"] = "required" if kn["fixed"][i, j] else ""
edge_rows.append(row)
edge_columns = [{"key": "from", "label": "From"}, {"key": "type", "label": "Link"}, {"key": "to", "label": "To"},
{"key": "strength", "label": strength_label, "type": "p" if ALGORITHM == "pc" else "number"},
{"key": "share", "label": "In resamples", "type": "percent"},
{"key": "share_dir", "label": "This direction", "type": "percent"}]
if kn is not None:
edge_columns.append({"key": "knowledge", "label": "Your knowledge"})
tables = [{
"key": "edges",
"title": "Suggested links",
"columns": edge_columns,
"rows": edge_rows,
}]
if ALGORITHM == "pc":
sep_rows = []
for i in range(p):
for j in range(i + 1, p):
if not fit["adj"][i, j]:
if kn is not None and kn["gaps"][i, j]:
sep_rows.append({"a": VARIABLES[i], "b": VARIABLES[j], "given": "forbidden by you (not tested)", "p": None})
continue
S = fit["sepset"].get((i, j), fit["sepset"].get((j, i), []))
sep_rows.append({"a": VARIABLES[i], "b": VARIABLES[j], "given": ", ".join(VARIABLES[k] for k in S) if S else "nothing",
"p": float(fit["pmax"][i, j])})
tables.append({
"key": "separations",
"title": "Pairs with no link: what made them independent",
"columns": [{"key": "a", "label": "Variable"}, {"key": "b", "label": "And"}, {"key": "given", "label": "Independent given"},
{"key": "p", "label": "Largest p-value", "type": "p"}],
"rows": sep_rows,
})
# %% Charts
charts = []
if BOOTSTRAP > 0:
charts.append(cs.chart("frequencies", "matrix-heatmap", f"How often each arrow came back in {BOOTSTRAP} resamples", {
"row": cs.col("From", [a for a in VARIABLES for _ in VARIABLES], "categorical", levels=VARIABLES),
"col": cs.col("To", [b for _ in VARIABLES for b in VARIABLES], "categorical", levels=VARIABLES),
"value": cs.col("Share of resamples", [float(freq_dir[i, j]) if i != j else 0.0 for i in range(p) for j in range(p)], "numeric"),
"label": cs.col("Share", [f"{freq_dir[i, j]:.0%}" if i != j and freq_dir[i, j] > 0 else "" for i in range(p) for j in range(p)], "categorical"),
}, controls={"scale": "sequential", "min": 0, "max": 1},
note="Row → column: the share of refits with that arrow, or with an undirected link between the two."))
elif ALGORITHM == "notears":
charts.append(cs.chart("weights", "matrix-heatmap", "Weight of each suggested arrow", {
"row": cs.col("From", [a for a in VARIABLES for _ in VARIABLES], "categorical", levels=VARIABLES),
"col": cs.col("To", [b for _ in VARIABLES for b in VARIABLES], "categorical", levels=VARIABLES),
"value": cs.col("Weight", [float(weights[i, j]) for i in range(p) for j in range(p)], "numeric"),
}, controls={"scale": "diverging"}))
# %% Result
directed = values["n_directed"]
undirected = values["n_undirected"]
cs.publish({
"title": "Suggest causal structure (PC, NOTEARS)",
"engine": cs.engine_info("numpy", "scipy", "pandas"),
"n": n,
"summary": f"{algorithm_label} suggests {len(edges)} link{'' if len(edges) == 1 else 's'} among {p} variables "
f"({directed} with a direction, {undirected} without). These are hypotheses to check against what you know, not causal conclusions.",
"statistics": [
{"key": "n_edges", "label": "Links", "value": len(edges), "format": "integer"},
{"key": "n_directed", "label": "With a direction", "value": directed, "format": "integer"},
{"key": "n_undirected", "label": "Undirected", "value": undirected, "format": "integer"},
],
"tables": tables,
"values": values,
"charts": charts,
"warnings": warnings,
"notes": [
f"Independence test: {'Fisher z (partial correlation)' if test_used == 'fisher_z' else 'G² on category counts'}, α = {ALPHA:g}, conditioning sets up to {MAX_COND} variables."
if ALGORITHM == "pc" else
f"NOTEARS on {'standardized' if SCALE == 'standardize' else 'centered'} variables, λ = {LAMBDA1:g}, weights below {W_THRESHOLD:g} dropped; reported weights are least-squares refits on each variable's suggested parents.",
"A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.",
] + ([f"Background knowledge: {kn['n_required']} required and {kn['n_forbidden']} forbidden link{'s' if kn['n_forbidden'] != 1 else ''}; resamples use it too."] if kn is not None else []),
})
Here PC-stable left 2 links undirected. NOTEARS orients every link it keeps; that confidence comes from its linear-Gaussian least-squares assumptions, not from the data. On real data, assess stability across bootstrap resamples; edge accuracy needs a known ground truth.
DAG-GNN: neural mechanisms
ReadDAG-GNN replaces the linear model with a variational autoencoder whose decoder passes latent noise through the graph: . It keeps an acyclicity penalty, here , inside an augmented Lagrangian on the ELBO.
Flexible decoders bring a risk: neural reconstruction can compensate for a wrong graph, so a good fit doesn't validate the arrows. The transpose convention must match the meaning of , or every arrow is reversed. Compare against linear NOTEARS and a graph-free VAE.
IRM: features that hold everywhere
ReadInvariant risk minimization takes a different route. With data from several environments (hospitals, years, regions), find a representation whose best predictor is the same in every environment, hoping stable relations are causal and unstable ones spurious. The practical IRMv1 surrogate adds a penalty for how much each environment would like to rescale the predictor:
In the reference's two-environment example, the penalties are 0.0414 and 0.000493: the first environment wants the predictor rescaled far more.
When IRM fails
ReadIRMv1 can fail even in simple settings its intuition covers. It needs environments that really differ in the spurious relation; identical environments identify nothing. Gradient and representation scale interact with , and a tiny penalty with poor prediction may mean a degenerate representation.
Report worst-environment and average risk on held-out environments, against plain empirical risk minimization and group-robust baselines, over several seeds. And don't equate invariant features with proven causes.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| NOTEARS (UNC011) | Runs in CodeSplash: Suggest causal structure (PC, NOTEARS), Algorithm NOTEARS, with bootstrap edge frequencies and a scaling check |
| DAG-GNN (UNC012) | Explained here |
| IRM (UNC013) | Runs as a notebook: the reference's program runs in Python and R; there's no method |
Check your understanding
CheckpointCheck yourself
What does guarantee?
Show the answer
Answer: a
The matrix exponential counts weighted closed walks; means there are none. Causality needs assumptions the constraint doesn't supply.
Check yourself
Why can rescaling a variable reverse some NOTEARS arrows?
Show the answer
Answer: b
Variance ordering can drive orientation. Report the scaling and check how many links change under the other one.
Check yourself
NOTEARS stops with tiny but not zero, then small weights are thresholded. What should you check?
Show the answer
Answer: b
A near-zero continuous constraint doesn't guarantee an acyclic graph after thresholding.
Check yourself
A DAG-GNN reconstructs the data very well. Does that validate its graph?
Show the answer
Answer: b
Report predictive performance separately from edge recovery, and compare with linear NOTEARS and a graph-free VAE.
Check yourself
What goes wrong if a DAG-GNN implementation uses the opposite transpose convention for A?
Show the answer
Answer: b
fixes which index is parent and which is child. Check the convention before interpreting arrows.
Check yourself
What does invariant risk minimization look for?
Show the answer
Answer: a
The hope is that stable relations are causal and unstable ones spurious, which is an assumption, not a guarantee.
Check yourself
All your training environments have the same spurious correlation. What can IRM do?
Show the answer
Answer: b
IRM needs environments that differ in the spurious relation. Evaluate on held-out environments against plain ERM.
Do it on your own data
In the appUnder Dependencies in Discover, open Suggest causal structure (PC, NOTEARS), run PC-stable and NOTEARS on the same columns with bootstrap edge frequencies, and read the scaling warning. Then take the candidate graph to the Causal Studio's DAG step as a hypothesis, adding required and forbidden edges from what you know.
Concepts in this lesson