Skip to content

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.

Advanced ~15 min10 steps

What runs in CodeSplash

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

Read first

01

Graphs from observational data

Read

A 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.

02

NOTEARS: no cycles as a smooth constraint

Read

Searching 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 WW (entry WijW_{ij} means i→ji\to j) by least squares with an L1 penalty, subject to one smooth equation:

min⁡W12n∥X−XW∥F2+λ∥W∥1s.t.h(W)=tr⁡(eW⊙W)−d=0.\min_W\tfrac{1}{2n}\lVert X-XW\rVert_F^2+\lambda\lVert W\rVert_1\quad\text{s.t.}\quad h(W)=\operatorname{tr}\big(e^{W\odot W}\big)-d=0.

h(W)h(W) is zero exactly when the graph has no cycles: the matrix exponential counts weighted closed walks. In the reference's example, hh 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?

How sure?
0.05

Pushes weak edges to zero. Edges under 0.3 in size are dropped after fitting.

300

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.

Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Change the units, change the arrows

Predict

Predict first

You refit NOTEARS on the same data after standardizing every variable (or after undoing a standardization). What happens to the graph?

The same graphSome arrows can change
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.

Suggest causal structure (PC, NOTEARS)Recorded · Python and R agreeRecorded 2026-11-25 · 48 values compared
R

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

Weight of each suggested arrowWhat do the values of a square or rectangular result matrix look like at a glance?
View data
ToFromWeight
sunsun0
watersun0
fertilizersun0
pestssun0
temperaturesun0.7805
moisturesun0
growthsun0
harvestsun0
sunwater0
waterwater0
fertilizerwater0
pestswater0
temperaturewater0
moisturewater0
growthwater0
harvestwater0
sunfertilizer0
waterfertilizer0
fertilizerfertilizer0
pestsfertilizer0
temperaturefertilizer0
moisturefertilizer0
growthfertilizer0
harvestfertilizer0
sunpests0
waterpests0
fertilizerpests0
pestspests0
temperaturepests0
moisturepests0
growthpests0
harvestpests0
suntemperature0
watertemperature0
fertilizertemperature0
peststemperature0
temperaturetemperature0
moisturetemperature0
growthtemperature0
harvesttemperature0
sunmoisture0
watermoisture0.8681
fertilizermoisture−0.4617
pestsmoisture0
temperaturemoisture0
moisturemoisture0
growthmoisture0
harvestmoisture0
sungrowth0.5389
watergrowth0
fertilizergrowth0.6705
pestsgrowth1.204
temperaturegrowth0
moisturegrowth0.5894
growthgrowth0
harvestgrowth0.8526
sunharvest0
waterharvest0
fertilizerharvest0
pestsharvest−1.491

First 60 of 64 rows.

Suggested links

FromLinkToWeight (least squares)In resamplesThis direction
sun→temperature0.7805——
growth→sun0.5389——
moisture→water0.8681——
moisture→fertilizer−0.4617——
growth→fertilizer0.6705——
growth→pests1.204——
harvest→pests−1.491——
growth→moisture0.5894——
growth→harvest0.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 "")))
))
Python

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

FromLinkToWeight (least squares)In resamplesThis direction
sun→temperature0.7805——
growth→sun0.5389——
moisture→water0.8681——
moisture→fertilizer−0.4617——
growth→fertilizer0.6705——
growth→pests1.204——
harvest→pests−1.491——
growth→moisture0.5894——
growth→harvest0.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 []),
})
04

What acyclicity doesn't certify

Read

h(W)=0h(W)=0 certifies 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:

Suggest causal structure (PC, NOTEARS)Recorded · Python and R agreeRecorded 2026-11-25 · 151 values compared
R

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

How often each arrow came back in 20 resamplesWhat do the values of a square or rectangular result matrix look like at a glance?

Row → column: the share of refits with that arrow, or with an undirected link between the two.

View data
ToShareFromShare of resamples
sunsun0
watersun0
fertilizersun0
pestssun0
temperature90%sun0.9000
moisturesun0
growth100%sun1
harvestsun0
sunwater0
waterwater0
fertilizerwater0
pestswater0
temperaturewater0
moisture100%water1
growthwater0
harvestwater0
sun10%fertilizer0.1000
waterfertilizer0
fertilizerfertilizer0
pestsfertilizer0
temperaturefertilizer0
moisture5%fertilizer0.0500
growth100%fertilizer1
harvest5%fertilizer0.0500
sunpests0
waterpests0
fertilizerpests0
pestspests0
temperaturepests0
moisturepests0
growthpests0
harvest100%pests1
sun100%temperature1
watertemperature0
fertilizertemperature0
peststemperature0
temperaturetemperature0
moisturetemperature0
growthtemperature0
harvesttemperature0
sunmoisture0
water100%moisture1
fertilizer5%moisture0.0500
pestsmoisture0
temperaturemoisture0
moisturemoisture0
growth100%moisture1
harvestmoisture0
sungrowth0
watergrowth0
fertilizergrowth0
pestsgrowth0
temperaturegrowth0
moisturegrowth0
growthgrowth0
harvest100%growth1
sunharvest0
waterharvest0
fertilizerharvest0
pestsharvest0

First 60 of 64 rows.

Suggested links

FromLinkToLargest p-valueIn resamplesThis direction
sun—temperature2.975e-91100.0%—
sun→growth1.765e-12100.0%100.0%
water—moisture4.095e-145100.0%—
fertilizer→growth1.183e-8100.0%100.0%
pests→harvest3.984e-29100.0%100.0%
moisture→growth2.606e-16100.0%100.0%
growth→harvest2.455e-50100.0%100.0%

Pairs with no link: what made them independent

VariableAndIndependent givenLargest p-value
sunwaternothing0.4883
sunfertilizernothing0.9599
sunpestsnothing0.1020
sunmoisturenothing0.5393
sunharvestgrowth0.7482
waterfertilizernothing0.2369
waterpestsnothing0.7263
watertemperaturenothing0.9528
watergrowthmoisture0.6797
waterharvestmoisture0.2448
fertilizerpestsnothing0.2310
fertilizertemperaturenothing0.2373
fertilizermoisturenothing0.1373
fertilizerharvestgrowth0.4069
peststemperaturenothing0.1001
pestsmoisturenothing0.7865
pestsgrowthnothing0.1352
temperaturemoisturenothing0.7855
temperaturegrowthsun0.6370
temperatureharvestsun0.6420
moistureharvestgrowth0.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 "")))
))
Python

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

FromLinkToLargest p-valueIn resamplesThis direction
sun—temperature2.975e-91100.0%—
sun→growth1.765e-12100.0%100.0%
water—moisture4.095e-145100.0%—
fertilizer→growth1.183e-8100.0%100.0%
pests→harvest3.984e-29100.0%100.0%
moisture→growth2.606e-16100.0%100.0%
growth→harvest2.455e-50100.0%100.0%

Pairs with no link: what made them independent

VariableAndIndependent givenLargest p-value
sunwaternothing0.4883
sunfertilizernothing0.9599
sunpestsnothing0.1020
sunmoisturenothing0.5393
sunharvestgrowth0.7482
waterfertilizernothing0.2369
waterpestsnothing0.7263
watertemperaturenothing0.9528
watergrowthmoisture0.6797
waterharvestmoisture0.2448
fertilizerpestsnothing0.2310
fertilizertemperaturenothing0.2373
fertilizermoisturenothing0.1373
fertilizerharvestgrowth0.4069
peststemperaturenothing0.1001
pestsmoisturenothing0.7865
pestsgrowthnothing0.1352
temperaturemoisturenothing0.7855
temperaturegrowthsun0.6370
temperatureharvestsun0.6420
moistureharvestgrowth0.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.

05

DAG-GNN: neural mechanisms

Read

DAG-GNN replaces the linear model with a variational autoencoder whose decoder passes latent noise through the graph: X=f2((I−A⊤)−1f1(Z))X=f_2\big((I-A^\top)^{-1}f_1(Z)\big). It keeps an acyclicity penalty, here h(A)=tr⁡[(I+αA⊙A)d]−dh(A)=\operatorname{tr}[(I+\alpha A\odot A)^d]-d, 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 AA, or every arrow is reversed. Compare against linear NOTEARS and a graph-free VAE.

06

IRM: features that hold everywhere

Read

Invariant risk minimization takes a different route. With data from several environments (hospitals, years, regions), find a representation Φ\Phi whose best predictor ww 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:

∑e[Re(Φ)+λ ∥∇wRe(w⋅Φ)∣w=1∥2].\sum_e\Big[R^e(\Phi)+\lambda\,\big\lVert\nabla_{w}R^e(w\cdot\Phi)\big\rvert_{w=1}\big\rVert^2\Big].

In the reference's two-environment example, the penalties are 0.0414 and 0.000493: the first environment wants the predictor rescaled far more.

07

When IRM fails

Read

IRMv1 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 λ\lambda, 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.

08

Where each idea stands in CodeSplash

Read
EntryIn 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
Reference · UNC012 · Explained hereDAG-GNNLearn a directed acyclic dependency structure inside a variational generative neural model. DAG-GNN extends continuous structural learning with nonlinear transformations and support for vector-valued or discrete… Reference · UNC013 · Runs as a notebookInvariant risk minimization (IRM / IRMv1)Learn representations for which a common predictor is simultaneously suitable across several training environments. The aim is to reduce reliance on environment-specific correlations.
09

Check your understanding

Checkpoint

Check yourself

What does h(W)=tr⁡(eW⊙W)−d=0h(W)=\operatorname{tr}(e^{W\odot W})-d=0 guarantee?

Show the answer

Answer: a

The matrix exponential counts weighted closed walks; h=0h=0 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 h(W)h(W) 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

(I−A⊤)−1(I-A^\top)^{-1} 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.

10

Do it on your own data

In the app

Under 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