CDiscover · discover.structure
Suggest causal structure (PC, NOTEARS)
Which variables could depend on which, and which arrows do the data allow?
Suggests a causal graph from the data: PC-stable removes the link between two variables when some set of the others makes them independent, then orients the arrows the independences fix (colliders and Meek's rules), leaving the rest undirected; NOTEARS fits a linear model whose arrows must form a graph with no loops. Resampling the rows shows how often each link and arrow comes back. The result is a set of hypotheses, never a DAG you can claim: hidden common causes, the test's power and the variables you chose all shape it, so draw your own DAG from what you know and use these suggestions to question it.
A real result
Example “Garden pc”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
PC-stable suggests 7 links among 8 variables (5 with a direction, 2 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 7
- With a direction
- 5
- Undirected
- 2
Plots
Row → column: the share of refits with that arrow, or with an undirected link between the two.
View data
| To | Share | From | Share of resamples |
|---|---|---|---|
| sun | sun | 0 | |
| water | sun | 0 | |
| fertilizer | sun | 0 | |
| pests | sun | 0 | |
| temperature | 90% | sun | 0.9000 |
| moisture | sun | 0 | |
| growth | 100% | sun | 1 |
| harvest | sun | 0 | |
| sun | water | 0 | |
| water | water | 0 | |
| fertilizer | water | 0 | |
| pests | water | 0 | |
| temperature | water | 0 | |
| moisture | 100% | water | 1 |
| growth | water | 0 | |
| harvest | water | 0 | |
| sun | 10% | fertilizer | 0.1000 |
| water | fertilizer | 0 | |
| fertilizer | fertilizer | 0 | |
| pests | fertilizer | 0 | |
| temperature | fertilizer | 0 | |
| moisture | 5% | fertilizer | 0.0500 |
| growth | 100% | fertilizer | 1 |
| harvest | 5% | fertilizer | 0.0500 |
| sun | pests | 0 | |
| water | pests | 0 | |
| fertilizer | pests | 0 | |
| pests | pests | 0 | |
| temperature | pests | 0 | |
| moisture | pests | 0 | |
| growth | pests | 0 | |
| harvest | 100% | pests | 1 |
| sun | 100% | temperature | 1 |
| water | temperature | 0 | |
| fertilizer | temperature | 0 | |
| pests | temperature | 0 | |
| temperature | temperature | 0 | |
| moisture | temperature | 0 | |
| growth | temperature | 0 | |
| harvest | temperature | 0 | |
| sun | moisture | 0 | |
| water | 100% | moisture | 1 |
| fertilizer | 5% | moisture | 0.0500 |
| pests | moisture | 0 | |
| temperature | moisture | 0 | |
| moisture | moisture | 0 | |
| growth | 100% | moisture | 1 |
| harvest | moisture | 0 | |
| sun | growth | 0 | |
| water | growth | 0 | |
| fertilizer | growth | 0 | |
| pests | growth | 0 | |
| temperature | growth | 0 | |
| moisture | growth | 0 | |
| growth | growth | 0 | |
| harvest | 100% | growth | 1 |
| sun | harvest | 0 | |
| water | harvest | 0 | |
| fertilizer | harvest | 0 | |
| pests | harvest | 0 |
First 60 of 64 rows.
Suggested links
| From | Link | To | Largest p-value | In resamples | This direction |
|---|---|---|---|---|---|
| sun | — | temperature | 2.975e-91 | 100.0% | — |
| sun | → | growth | 1.765e-12 | 100.0% | 100.0% |
| water | — | moisture | 4.095e-145 | 100.0% | — |
| fertilizer | → | growth | 1.183e-8 | 100.0% | 100.0% |
| pests | → | harvest | 3.984e-29 | 100.0% | 100.0% |
| moisture | → | growth | 2.606e-16 | 100.0% | 100.0% |
| growth | → | harvest | 2.455e-50 | 100.0% | 100.0% |
Pairs with no link: what made them independent
| Variable | And | Independent given | Largest p-value |
|---|---|---|---|
| sun | water | nothing | 0.4883 |
| sun | fertilizer | nothing | 0.9599 |
| sun | pests | nothing | 0.1020 |
| sun | moisture | nothing | 0.5393 |
| sun | harvest | growth | 0.7482 |
| water | fertilizer | nothing | 0.2369 |
| water | pests | nothing | 0.7263 |
| water | temperature | nothing | 0.9528 |
| water | growth | moisture | 0.6797 |
| water | harvest | moisture | 0.2448 |
| fertilizer | pests | nothing | 0.2310 |
| fertilizer | temperature | nothing | 0.2373 |
| fertilizer | moisture | nothing | 0.1373 |
| fertilizer | harvest | growth | 0.4069 |
| pests | temperature | nothing | 0.1001 |
| pests | moisture | nothing | 0.7865 |
| pests | growth | nothing | 0.1352 |
| temperature | moisture | nothing | 0.7855 |
| temperature | growth | sun | 0.6370 |
| temperature | harvest | sun | 0.6420 |
| moisture | harvest | growth | 0.8946 |
- Independence test: Fisher z (partial correlation), α = 0.05, conditioning sets up to 4 variables.
- A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.
PC-stable suggests 7 links among 8 variables (5 with a direction, 2 without). These are hypotheses to check against what you know, not causal conclusions.
- Links
- 7
- With a direction
- 5
- Undirected
- 2
To keep this page light, the plots are shown once, under the R tab.
Suggested links
| From | Link | To | Largest p-value | In resamples | This direction |
|---|---|---|---|---|---|
| sun | — | temperature | 2.975e-91 | 100.0% | — |
| sun | → | growth | 1.765e-12 | 100.0% | 100.0% |
| water | — | moisture | 4.095e-145 | 100.0% | — |
| fertilizer | → | growth | 1.183e-8 | 100.0% | 100.0% |
| pests | → | harvest | 3.984e-29 | 100.0% | 100.0% |
| moisture | → | growth | 2.606e-16 | 100.0% | 100.0% |
| growth | → | harvest | 2.455e-50 | 100.0% | 100.0% |
Pairs with no link: what made them independent
| Variable | And | Independent given | Largest p-value |
|---|---|---|---|
| sun | water | nothing | 0.4883 |
| sun | fertilizer | nothing | 0.9599 |
| sun | pests | nothing | 0.1020 |
| sun | moisture | nothing | 0.5393 |
| sun | harvest | growth | 0.7482 |
| water | fertilizer | nothing | 0.2369 |
| water | pests | nothing | 0.7263 |
| water | temperature | nothing | 0.9528 |
| water | growth | moisture | 0.6797 |
| water | harvest | moisture | 0.2448 |
| fertilizer | pests | nothing | 0.2310 |
| fertilizer | temperature | nothing | 0.2373 |
| fertilizer | moisture | nothing | 0.1373 |
| fertilizer | harvest | growth | 0.4069 |
| pests | temperature | nothing | 0.1001 |
| pests | moisture | nothing | 0.7865 |
| pests | growth | nothing | 0.1352 |
| temperature | moisture | nothing | 0.7855 |
| temperature | growth | sun | 0.6370 |
| temperature | harvest | sun | 0.6420 |
| moisture | harvest | growth | 0.8946 |
- Independence test: Fisher z (partial correlation), α = 0.05, conditioning sets up to 4 variables.
- A suggested graph is never a DAG you can claim: a hidden common cause, too few rows or a curved relation can each add, remove or flip an arrow.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Garden pccsl_garden · variables: sun, water, fertilizer, pests, temperature, moisture, growth, harvest
- Garden pc alpha maxcondcsl_garden · variables: sun, water, fertilizer, pests, temperature, moisture, growth, harvest
- Garden pc yes nocsl_garden · variables: sun, temperature, frost, growth
- Sprinkler pc g2csl_sprinkler · variables: season, rain, sprinkler, wet, slippery, weekday
- Garden notearscsl_garden · variables: sun, water, fertilizer, pests, temperature, moisture, growth, harvest
- Garden notears center bootcsl_garden · variables: sun, water, fertilizer, growth, harvest
- Degenerate constantcsl_garden · variables: sun, water, growth
- Degenerate all nacsl_garden · variables: sun, water, growth
In the guides
Where it sits in the decision guides
- Causal structure suggestions (PC-stable, NOTEARS) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Variablesnumeric / boolean / categorical · 2–30 columns
- The variables to place in the graph. Leave out IDs and anything measured after the outcome you care about; a variable left out can still be a hidden common cause.
Choices you make
model
- Algorithmdefault pc
PC tests conditional independence and works on numbers or categories; NOTEARS fits a linear model and needs numbers.
- PC-stable(default) — Removes links that some set of other variables explains away, then orients only the arrows the independences fix. The result does not depend on the column order.
- NOTEARS (linear) — Fits a sparse linear model whose arrows can't form a loop. Every link gets a direction, but directions are fragile: they can change when variables are rescaled.
- Independence testdefault auto
How PC decides that two variables are independent given others.
- Automatic(default) — Fisher z when every variable is a number or yes/no; G² when every variable is a category or yes/no.
- Fisher z (partial correlation) — For numbers: tests whether the partial correlation is 0, assuming roughly linear, Gaussian relations.
- G² (categories) — For categories: a likelihood-ratio test of the counts in each stratum; skipped (treated as independent) when there are fewer than 10 rows per degree of freedom.
- Significance leveldefault 0.05
A link is removed when a test's p-value is at least this. Smaller keeps more links (only clear independences remove one).
- Largest conditioning setdefault 4
The most variables PC conditions on at once. Larger sets need many rows per test; 4 keeps tests meaningful and runs fast.
- Sparsity penalty (λ)default 0.1
L1 penalty on the weights; larger gives fewer arrows.
- Weight thresholddefault 0.3
Weights smaller than this in absolute value are dropped after the fit (the reference default is 0.3).
- Scalingdefault standardize
NOTEARS depends on the variables' units; the result also reports how many links change under the other choice.
- Standardize(default) — Gives every variable unit SD first, so units don't decide the arrows.
- Center only — Keeps the variables' own scales, as the original NOTEARS code does.
- Resamplesdefault 50
Refits on rows drawn with replacement to show how often each link and arrow comes back. 0 skips it.
- Required linksdefault —
Links you know exist, separated by commas: a -> b for an arrow, a -- b for a link either way. They are always in the graph, and an arrow keeps your direction.
- Forbidden linksdefault —
Links you know don't exist, separated by commas: a -> b means a doesn't cause b directly; a -- b means no direct link at all.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
No hidden common causesNot checked from data: state why it holds
Both algorithms assume every common cause of two variables is among the variables. A hidden one can create a link, or an arrow, that isn't a direct effect.
Independences come from the graphNot checked from data: state why it holds
PC assumes the independences in the data are exactly those the true graph implies; effects that cancel out can hide a real link.
No feedback loopsNot checked from data: state why it holds
The graph has no cycles, and each row is an independent draw from one causal system.
Linear relations (Fisher z, NOTEARS)Not checked from data: state why it holds
Fisher z and NOTEARS see only linear dependence; a curved relation can be missed. G² makes no such assumption but needs many rows per category combination.
What it reports
- algorithm_label
- A graph of possible causes learned from data: hypotheses to question a DAG with, never a DAG to base a causal claim on.
- n
- Complete rows and variables in the graph. PC's tests need many rows per conditioning variable.
- p
- Complete rows and variables in the graph. PC's tests need many rows per conditioning variable.
- n_edges
- Links in the suggested graph, split into arrows (a direction the data fix) and undirected links (direction unknown).
- n_directed
- Links in the suggested graph, split into arrows (a direction the data fix) and undirected links (direction unknown).
- n_undirected
- DAGs that imply exactly the same independences. Data like these can't choose between them, so PC leaves such links undirected.
- bootstrap
- How often a link (any form) or an arrow came back when the rows were resampled and the graph refit; steadier links are surer.
- n_tests
- Removes the link between two variables when some set of others makes them independent, then orients the arrows those tests fix.
- max_order
- Removes the link between two variables when some set of others makes them independent, then orients the arrows those tests fix.
- h_converged
- 1 when the fit's acyclicity measure h(W) fell to 10⁻⁸ or below, so the arrows form no loop; 0 means read them with care.
- shd_other_scale
- Pairs whose link differs when the variables are standardized instead of centered (or the reverse); above 0, units shaped arrows.
Per group, level or term: edge[<a>|<b>], pmax[<a>|<b>], weight[<from>-><to>], freq[<a>|<b>], freq_dir[<from>-><to>], n_required, n_forbidden, n_conflicts (with background knowledge), n_dropped (NOTEARS with background knowledge)
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses numpy, scipy, codesplash; R uses codesplashr.
Default traps between the two languages
- PC-stable: both engines run the same written-out search (pcalg 2.7's stable skeleton and relaxed orientation, the same test order and the same Fisher z or G² p-values), so the links, arrows, separating sets and largest p-values match; pcalg itself gives the same graph and pMax on the fixtures (tests/crosscheck/w7_csl_structure.R).
- NOTEARS: both engines run the same augmented Lagrangian with the same OWL-QN inner solver. Its last rounds are badly conditioned, so the raw weights differ between engines by about 10⁻⁴; they only decide the arrows (|w| ≥ the threshold), and each arrow's reported weight is a least-squares refit on its parents, which matches. The reference code's L-BFGS-B gives the same graph on simulated data (tests/crosscheck/w7_csl_structure.py).
- Resamples come from the shared Wichmann–Hill stream, so both engines refit the same rows.
- Background knowledge: both engines parse the links, settle the pairs and add the arrows in the same order (pcalg's fixedEdges/fixedGaps and addBgKnowledge with Meek's rules 1–4; tests/crosscheck/w8_fup2_structure_knowledge.R). Unlike pcalg, a pair with no link only because it is forbidden orients no collider (it has no separating set), and an arrow the data orient the other way is kept as the data have it and reported, where pcalg refuses the whole graph. NOTEARS holds forbidden weights at 0, leaves required ones unpenalized and above the threshold, and drops the weakest other arrow on any loop that forcing required arrows closes.
The exact script CodeSplash ran for example “Garden pc” · 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 []),
})
The exact script CodeSplash ran for example “Garden pc” · 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 "")))
))
Sources
- Spirtes P, Glymour C, Scheines R (2000). Causation, Prediction, and Search, 2nd ed. MIT Press.
- Colombo D, Maathuis MH (2014). Order-independent constraint-based causal structure learning. JMLR 15:3741–3782.
- Meek C (1995). Causal inference and causal explanation with background knowledge. UAI 1995, 403–410.
- Kalisch M, Mächler M, Colombo D, Maathuis MH, Bühlmann P (2012). Causal inference using graphical models with the R package pcalg. J Stat Softw 47(11).
- Zheng X, Aragam B, Ravikumar P, Xing EP (2018). DAGs with NO TEARS: continuous optimization for structure learning. NeurIPS 2018.
- Andrew G, Gao J (2007). Scalable training of L1-regularized log-linear models. ICML 2007, 33–40.
- Reisach AG, Seiler C, Weichwald S (2021). Beware of the simulated DAG! Causal discovery benchmarks may be easy to game. NeurIPS 2021.
From the CodeSplash method registry · discover.structure v1.1.0.