Suggesting causal structure: PC-stable and NOTEARS
Structure learning proposes which variables could cause which. PC-stable removes links other variables explain away; NOTEARS fits a linear model with no loops. Both give hypotheses to question your DAG, never a DAG to claim.
What runs in CodeSplash
- Suggest causal structure (PC, NOTEARS) Verified in Python and R
You will be able to
- Explain how PC-stable decides that two variables have no direct link
- Read colliders, undirected links and the share of resamples behind each link
- Say why a suggested graph can't justify a causal claim, and how the Causal studio keeps it out of the claim ladder
From correlations to a graph
ReadA garden study measures sunshine, water, fertilizer, pests, temperature, soil moisture, plant growth and the harvest. Almost everything correlates with the harvest. Which links are direct, and which run through something else?
Structure learningSuggested causal structureA graph of possible causes learned from data: hypotheses to question a DAG with, never a DAG to base a causal claim on. turns the pattern of dependence into a graph. It can't see causes; it sees which variables stay dependent when you hold others fixed, and some patterns of that fix a direction.
PC-stable: remove what other variables explain
ReadPC starts with every pair linked. It then tests each pair for conditional independenceConditional independenceTwo variables are unrelated within each level of a third, though they may look related when pooled over it.: first on its own, then given one other variable, then two, and so on. As soon as some set of variables makes the pair independent (p ≥ α), the link goes and that set is remembered as the pair's separating set. Water and growth are related, but given soil moisture they are not, so their link goes: water reaches growth only through moisture.
The stable version fixes each variable's neighbors at the start of each round, so the result doesn't depend on the column order.
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 []),
})
Which arrows the data can fix
ReadTwo variables with no link can still share a neighbor. If sunshine and moisture are unlinked, both linked to growth, and growth was not in the set that separated them, the only explanation is sunshine → growth ← moisture: a colliderColliderA variable caused by both treatment and outcome; adjusting for it creates a false association.. Meek's rules then orient any arrow that would otherwise create a new collider or a loop.
Links the data can't orient
ReadEverything else stays an undirected line. Sunshine — temperature is one: "sunshine causes temperature" and "temperature causes sunshine" imply exactly the same independences, so no amount of this kind of data can tell them apart. These graphs form a Markov equivalence classMarkov equivalence classDAGs that imply exactly the same independences. Data like these can't choose between them, so PC leaves such links undirected., and PC returns the class, not one member.
View data
| variable | with | r |
|---|---|---|
| age | age | 1 |
| age | BMI | 0.1207 |
| age | systolic BP | 0.1471 |
| age | cholesterol | 0.1467 |
| age | glucose | 0.1912 |
| age | activity | −0.1247 |
| BMI | age | 0.1207 |
| BMI | BMI | 1 |
| BMI | systolic BP | 0.3132 |
| BMI | cholesterol | 0.3194 |
| BMI | glucose | 0.3629 |
| BMI | activity | −0.1770 |
| systolic BP | age | 0.1471 |
| systolic BP | BMI | 0.3132 |
| systolic BP | systolic BP | 1 |
| systolic BP | cholesterol | 0.4537 |
| systolic BP | glucose | 0.5647 |
| systolic BP | activity | −0.3672 |
| cholesterol | age | 0.1467 |
| cholesterol | BMI | 0.3194 |
| cholesterol | systolic BP | 0.4537 |
| cholesterol | cholesterol | 1 |
| cholesterol | glucose | 0.6006 |
| cholesterol | activity | −0.3861 |
| glucose | age | 0.1912 |
| glucose | BMI | 0.3629 |
| glucose | systolic BP | 0.5647 |
| glucose | cholesterol | 0.6006 |
| glucose | glucose | 1 |
| glucose | activity | −0.4105 |
| activity | age | −0.1247 |
| activity | BMI | −0.1770 |
| activity | systolic BP | −0.3672 |
| activity | cholesterol | −0.3861 |
| activity | glucose | −0.4105 |
| activity | activity | 1 |
The heatmap shows how often each arrow came back when the rows were resampled. A link that appears in 95% of resamples is a steadier hypothesis than one at 40%.
Categories: the G² test
ReadFor category columns, PC uses a G² testG² test of independenceTests whether two categories are independent within each combination of others from the counts; needs about 10 rows per df. on the counts in each combination of the conditioning variables. It needs many rows per combination, so with too few (under 10 per degree of freedom) a test is skipped and the pair treated as independent.
PC-stable suggests 5 links among 6 variables (5 with a direction, 0 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 5
- With a direction
- 5
- Undirected
- 0
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 |
|---|---|---|---|
| season | season | 0 | |
| rain | 90% | season | 0.9000 |
| sprinkler | 90% | season | 0.9000 |
| wet | season | 0 | |
| slippery | 10% | season | 0.1000 |
| weekday | 10% | season | 0.1000 |
| season | 20% | rain | 0.2000 |
| rain | rain | 0 | |
| sprinkler | 20% | rain | 0.2000 |
| wet | 90% | rain | 0.9000 |
| slippery | rain | 0 | |
| weekday | rain | 0 | |
| season | 10% | sprinkler | 0.1000 |
| rain | sprinkler | 0 | |
| sprinkler | sprinkler | 0 | |
| wet | 80% | sprinkler | 0.8000 |
| slippery | sprinkler | 0 | |
| weekday | 20% | sprinkler | 0.2000 |
| season | wet | 0 | |
| rain | 20% | wet | 0.2000 |
| sprinkler | 20% | wet | 0.2000 |
| wet | wet | 0 | |
| slippery | 80% | wet | 0.8000 |
| weekday | 10% | wet | 0.1000 |
| season | slippery | 0 | |
| rain | 10% | slippery | 0.1000 |
| sprinkler | 10% | slippery | 0.1000 |
| wet | 30% | slippery | 0.3000 |
| slippery | slippery | 0 | |
| weekday | slippery | 0 | |
| season | 10% | weekday | 0.1000 |
| rain | weekday | 0 | |
| sprinkler | 50% | weekday | 0.5000 |
| wet | 20% | weekday | 0.2000 |
| slippery | weekday | 0 | |
| weekday | weekday | 0 |
Suggested links
| From | Link | To | Largest p-value | In resamples | This direction |
|---|---|---|---|---|---|
| season | → | rain | 9.052e-90 | 100.0% | 90.0% |
| season | → | sprinkler | 5.499e-109 | 100.0% | 90.0% |
| rain | → | wet | 1.042e-125 | 100.0% | 90.0% |
| sprinkler | → | wet | 4.695e-65 | 100.0% | 80.0% |
| wet | → | slippery | 5.700e-124 | 100.0% | 80.0% |
Pairs with no link: what made them independent
| Variable | And | Independent given | Largest p-value |
|---|---|---|---|
| season | wet | nothing | 0.1180 |
| season | slippery | nothing | 0.1417 |
| season | weekday | nothing | 0.5989 |
| rain | sprinkler | season | 0.3694 |
| rain | slippery | wet | 0.8854 |
| rain | weekday | nothing | 0.6545 |
| sprinkler | slippery | wet | 0.8004 |
| sprinkler | weekday | nothing | 0.2307 |
| wet | weekday | nothing | 0.0589 |
| slippery | weekday | nothing | 0.3292 |
- Independence test: G² on category counts, α = 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 9c16f2a1d10474e5
# Dataset: csl_sprinkler (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("season", "rain", "sprinkler", "wet", "slippery", "weekday")
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 <- 10
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_sprinkler.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 5 links among 6 variables (5 with a direction, 0 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 5
- With a direction
- 5
- Undirected
- 0
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 |
|---|---|---|---|---|---|
| season | → | rain | 9.052e-90 | 100.0% | 90.0% |
| season | → | sprinkler | 5.499e-109 | 100.0% | 90.0% |
| rain | → | wet | 1.042e-125 | 100.0% | 90.0% |
| sprinkler | → | wet | 4.695e-65 | 100.0% | 80.0% |
| wet | → | slippery | 5.700e-124 | 100.0% | 80.0% |
Pairs with no link: what made them independent
| Variable | And | Independent given | Largest p-value |
|---|---|---|---|
| season | wet | nothing | 0.1180 |
| season | slippery | nothing | 0.1417 |
| season | weekday | nothing | 0.5989 |
| rain | sprinkler | season | 0.3694 |
| rain | slippery | wet | 0.8854 |
| rain | weekday | nothing | 0.6545 |
| sprinkler | slippery | wet | 0.8004 |
| sprinkler | weekday | nothing | 0.2307 |
| wet | weekday | nothing | 0.0589 |
| slippery | weekday | nothing | 0.3292 |
- Independence test: G² on category counts, α = 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 9c16f2a1d10474e5
# Dataset: csl_sprinkler (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 = ["season", "rain", "sprinkler", "wet", "slippery", "weekday"]
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 = 10
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_sprinkler.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 []),
})
NOTEARS: a linear model with no loops
ReadNOTEARSNOTEARSFits a sparse linear model whose arrows can't form a loop (tr exp(W∘W) = d). Directions can change when units change. fits every variable as a linear function of the others, with a penalty that is zero only when the arrows form no loop, and drops small weights. Every link gets a direction, but those directions are fragile: they change when variables are rescaled, which is why the result reports how many links move under the other scaling.
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 []),
})
Hypotheses, not a DAG you can claim
ReadThese graphs rest on assumptions the data can't check: no hidden common causes, independences that come only from the graph, no feedback, and (for Fisher z and NOTEARS) linear relations. A hidden common cause of two variables produces exactly the dependence a direct arrow would.
So use suggestions to question your DAG: an arrow you drew that the data separate, or a link you left out that keeps coming back. In the Causal studio, the DAG step's Suggest edges tab lists each suggestion to accept or reject. Accepted ones stay marked "suggested" and never count toward the claim levelClaim levelHow strong a causal statement the design supports, from association up to a causal effect.; make one your own assumption only if you'd draw it from what you know.
Check your understanding
CheckpointCheck yourself
PC removes the link between water and growth after conditioning on soil moisture. What does that say?
Show the answer
Answer: b
The link is removed because the dependence disappears given moisture. Water can still matter, through moisture.
Check yourself
PC leaves sunshine — temperature undirected. Why?
Show the answer
Answer: c
Graphs in the same Markov equivalence class fit the data equally well. PC returns the class and leaves such links undirected.
Check yourself
You accept a suggested arrow into your study's DAG. Why doesn't it raise the claim level?
Show the answer
Answer: b
The ladder needs a DAG you assert from what you know. Make a suggested arrow your own assumption only if you'd draw it anyway.
Concepts in this lesson