Skip to content

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.

Applied ~14 min8 steps

What runs in CodeSplash

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

Read first

01

From correlations to a graph

Read

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

02

PC-stable: remove what other variables explain

Read

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

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 []),
})
03

Which arrows the data can fix

Read

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

05

Categories: the G² test

Read

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

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

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

How often each arrow came back in 10 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
seasonseason0
rain90%season0.9000
sprinkler90%season0.9000
wetseason0
slippery10%season0.1000
weekday10%season0.1000
season20%rain0.2000
rainrain0
sprinkler20%rain0.2000
wet90%rain0.9000
slipperyrain0
weekdayrain0
season10%sprinkler0.1000
rainsprinkler0
sprinklersprinkler0
wet80%sprinkler0.8000
slipperysprinkler0
weekday20%sprinkler0.2000
seasonwet0
rain20%wet0.2000
sprinkler20%wet0.2000
wetwet0
slippery80%wet0.8000
weekday10%wet0.1000
seasonslippery0
rain10%slippery0.1000
sprinkler10%slippery0.1000
wet30%slippery0.3000
slipperyslippery0
weekdayslippery0
season10%weekday0.1000
rainweekday0
sprinkler50%weekday0.5000
wet20%weekday0.2000
slipperyweekday0
weekdayweekday0

Suggested links

FromLinkToLargest p-valueIn resamplesThis direction
season→rain9.052e-90100.0%90.0%
season→sprinkler5.499e-109100.0%90.0%
rain→wet1.042e-125100.0%90.0%
sprinkler→wet4.695e-65100.0%80.0%
wet→slippery5.700e-124100.0%80.0%

Pairs with no link: what made them independent

VariableAndIndependent givenLargest p-value
seasonwetnothing0.1180
seasonslipperynothing0.1417
seasonweekdaynothing0.5989
rainsprinklerseason0.3694
rainslipperywet0.8854
rainweekdaynothing0.6545
sprinklerslipperywet0.8004
sprinklerweekdaynothing0.2307
wetweekdaynothing0.0589
slipperyweekdaynothing0.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 "")))
))
Python

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

FromLinkToLargest p-valueIn resamplesThis direction
season→rain9.052e-90100.0%90.0%
season→sprinkler5.499e-109100.0%90.0%
rain→wet1.042e-125100.0%90.0%
sprinkler→wet4.695e-65100.0%80.0%
wet→slippery5.700e-124100.0%80.0%

Pairs with no link: what made them independent

VariableAndIndependent givenLargest p-value
seasonwetnothing0.1180
seasonslipperynothing0.1417
seasonweekdaynothing0.5989
rainsprinklerseason0.3694
rainslipperywet0.8854
rainweekdaynothing0.6545
sprinklerslipperywet0.8004
sprinklerweekdaynothing0.2307
wetweekdaynothing0.0589
slipperyweekdaynothing0.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 []),
})
06

NOTEARS: a linear model with no loops

Read

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

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 []),
})
07

Hypotheses, not a DAG you can claim

Read

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

08

Check your understanding

Checkpoint

Check 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