Module contents
Stage 8 of 9Research 110 min

Sensitivity, refutation and causal discovery

Ask how much unobserved confounding would be needed to nullify project estimates using the Cinelli-Hazlett robustness value and E-value, and subject estimates to refutation tests. Then reverse the problem: learn the graph from data with PC and NOTEARS, first on simulated data with a known graph and then on a real dataset, measuring their errors.

After this lesson you can

  • Calculate robustness values and sensitivity contours for estimates from earlier stages.
  • Apply placebo treatments, random common causes, and subsampling as refutation tests.
  • Implement the PC algorithm and apply NOTEARS to data with a known graph.
  • Measure structural Hamming distance and its sensitivity to sample size and noise.

Before you start

How much would change a conclusion

Adjustment for observed covariates does not by itself eliminate unmeasured confounding. Sensitivity analysis asks how much an omitted variable would need to explain to change a conclusion. Causal discovery asks another question: which structures are compatible with observed independences and assumptions about how data are generated. Neither replaces knowledge of the treatment mechanism.

In a linear regression of YY on treatment DD and covariates XX, imagine adding an omitted variable UU. After removing from DD and UU the linear part explained by XX, the Frisch-Waugh-Lovell theorem gives

β^corto−β^largo=γ^D~⊤U~D~⊤D~.\hat\beta_{\mathrm{corto}}-\hat\beta_{\mathrm{largo}}=\hat\gamma\frac{\tilde D^\top\tilde U}{\tilde D^\top\tilde D}.

The difference vanishes if UU‘s contribution to the outcome or its residual association with DD is zero. Define rD=RD∼U∣X2r_D=R^2_{D\sim U\mid X} and rY=RY∼U∣D,X2r_Y=R^2_{Y\sim U\mid D,X}. Under the classical OLS standard error and residual degrees of freedom ν\nu, the magnitude of bias due to UU can be written se⁡(β^)νrDrY/(1−rD)\operatorname{se}(\hat\beta)\sqrt{\nu r_Dr_Y/(1-r_D)}. Direction depends on the sign of associations; the figure uses the sign moving the coefficient toward zero. See Cinelli and Hazlett for the identities and their conditions.

The robustness value to the null point is the smallest common value rD=rYr_D=r_Y capable of bringing the estimated coefficient to zero. If f=∣t∣/νf=|t|/\sqrt{\nu}, it is (f4+4f2−f2)/2(\sqrt{f^4+4f^2}-f^2)/2. It concerns the point, not whether an interval includes zero. The calculation uses homoscedastic errors and neither evaluates uncertainty in the hypothetical adjustment nor proves such a variable exists. The square in the figure represents an observed covariate as a descriptive reference, not a proven bound for all omitted confounding.

InteractiveTwo forces of confounding
000.10.10.20.20.30.3Partial R² with treatmentPartial R² with outcome

Blue: adjusted coefficient remains positive; orange: it reaches zero or changes sign. The line is the zero contour, the circle the chosen scenario, and the square the observed reference: 1975 earnings.

0.02
0.02
Observed coefficient751.9
Hypothetically adjusted-202.6
RV to reduce to zero1.58 %
Regions by hypothetically adjusted OLS coefficient; circle: reader's choice; square: observed covariate.

With 185 NSW participants and 2,490 PSID controls, OLS adjusts for age, education, demographic indicators, and 1974 and 1975 earnings: coefficient 751.95 dollars, classical error 915.26, ν=2665\nu=2665, and robustness value 1.58%. Prior 1975 earnings have rD=0,29%r_D=0,29\% and rY=13,75%r_Y=13,75\% when compared conditional on the other covariates. In Card’s data, a regression of log wages on education and controls gives 0.03747 per year of education, classical error 0.00274, and value 22.07%; the age reference has 0.46% and 0.45%. These are particular descriptive models, not newly guaranteed causal estimates. The OLS value does not automatically apply to AIPW ATT, IV, RD, DiD, or synthetic control: their threats and estimands require design-appropriate analyses.

For a risk ratio, the point E-value for RR≥1RR\ge1 is RR+RR(RR−1)RR+\sqrt{RR(RR-1)}; for a protective effect first use its reciprocal. If RR=1,8RR=1,8, the result is 3: under the measure’s assumptions, if both covariate-conditional associations had equal strength, each would need to reach risk ratio 3 to explain the point; with unequal strengths, at least one must reach 3 and the other may be smaller. The measure for the interval limit closest to the null differs; if the interval includes one, its E-value is 1. Do not apply this formula directly to wage differences or linear coefficients. The formulation and limits appear in VanderWeele and Ding.

Trying to refute an estimate

Using the same NSW/PSID regression, DoWhy’s refutation tests ran 20 simulations per diagnostic with seed 801. Permuting treatment gives mean placebo estimate -441.67 and p=0,255p=0,255; adding a random common cause gives 754.67 versus the original 751.95 (p=0,470p=0,470); using 80% subsets gives 815.10 (p=0,438p=0,438). Values depend on the procedure and are imprecise with 20 repetitions. A random covariate does not necessarily represent a real confounder, and resampling stability does not establish ignorability. A diagnostic compatible with the model does not prove absence of bias.

Searching for compatible structures

The PC algorithm starts with every pair connected and removes an edge when a test does not reject conditional independence for some set of neighbors. It records the separating set. It then orients colliders X→Z←YX\to Z\leftarrow Y when XX and YY are not adjacent and ZZ is not in their separator, and applies propagation rules. A line without an arrow represents an unidentified orientation in the equivalence class, not a necessarily bidirectional relationship. The demonstration uses partial correlation and Fisher transformation; validity requires, among other conditions, approximately Gaussian data, causal sufficiency, absence of problematic selection, and faithfulness. Sample size and test level affect both types of error; accepting independence for lack of rejection is an algorithmic rule, not proof of exact equality.

InteractivePC step by step
X1X2X3X4

The algorithm starts with all pairs connected.

The generating DAG has X1→X3, X2→X3, X3→X4, and X1→X4. SHD uses its equivalence class and does not require orienting edges the data do not identify.

0
Current edges6
Final SHD to true CPDAG0
StageComplete graph
Four-variable simulation; the last stage shows orientations compatible with the tests.

Applying PC to age, education, and 1974, 1975, and 1978 earnings in NSW/PSID produces, among other edges, education→age and 1975 earnings→education. These arrows are not causal claims: they contradict plausible temporal order and indicate that the procedure’s assumptions and observational mixture of groups need examination. The true graph is unknown here and SHD is not calculated. The learned structure helps formulate questions and check them against temporal knowledge; it does not identify an effect by itself.

NOTEARS optimizes a weight matrix WW with least-squares loss and sparse penalty, imposing acyclicity through h(W)=tr⁡(eW∘W)−d=0h(W)=\operatorname{tr}(e^{W\circ W})-d=0. Our laboratory uses augmented multipliers, penalty L1=0,05L_1=0,05, and threshold 0.3. Due to numerical tolerance, a long cycle may remain after thresholding: the lowest-magnitude edge of each cycle is iteratively removed and the count reported. Across 24 runs six were removed in total; maximum hh before thresholding was 7,55⋅10−97,55\cdot10^{-9}. Data are linear Gaussian with independent errors and no latent confounders; unequal variances and observational equivalence limit interpretation of directions.

On the same five standardized real columns, NOTEARS retains 1974 earnings→1975 and 1975 earnings→1978, with weights 0.806 and 0.504. This output depends on scale, penalty, and threshold and also does not establish causality; the true graph is unknown. In this sample earnings have a non-Gaussian distribution and many zeros, and both group selection and unmeasured variables can alter relationships. The difference between the two learned graphs calls for investigation, not automatic selection of which represents the world.

Comparing when we do know the truth

In this validated causal discovery example, we generate graphs of 10 or 20 nodes, expected average degree two, and coefficients of magnitude 0.5 to 1.2. For each size we use three seeds, 200 or 1,000 observations, and noise standard deviation 0.5 or 1 at nodes after the first; we then standardize columns. The same seed pairs conditions. Structural Hamming distance (SHD) counts one discrepancy per pair: absence, undirected line, or different direction. We compare the true CPDAG with PC and with the CPDAG of NOTEARS’ DAG, so as not to penalize an orientation unidentifiable within its class.

NodesSampleNoiseMean PC SHDMean NOTEARS SHD
102000.53.678.67
1020012.678.00
101,0000.51.678.33
101,00012.009.00
202000.511.6723.67
20200110.0022.33
201,0000.58.3323.67
201,00019.3322.33

These are averages of only three graphs per row, not a general method ranking. Our PC skeleton matches causal-learn in all 24 cases; some orientations differ, so that check does not verify complete equivalence. Hyperparameter selection, edge strength, nonlinearity, and latent confounding can change results.

Laboratory

In Python 3.12 install python -m pip install "numpy==2.2.6" "pandas==2.3.3" "scipy==1.15.3" "scikit-learn==1.6.1" "statsmodels==0.15.0" "linearmodels==7.0" "dowhy==0.14" "causal-learn==0.1.4.8" "pysensemakr==0.0.8". Download into one folder sensitivity.py, discovery.py, graph_eval.py, refutations.py, experiment.py, test_discovery.py, and nsw_data.py. The reference results include seeds, diagnostics, and graphs. Run python test_discovery.py and python experiment.py --project causal_project --out results_new.json --repetitions 3. The loader downloads original Dehejia and Wahba data, verifies hashes, and retains existing files; the experiment does not overwrite results. The next cell combines definitions and runs the same analysis in a local session.

[ ]Sensitivity and causal discoveryLocal GPU
"""Descarga verificable de NSW y PSID de la página de Dehejia y Wahba."""
from pathlib import Path
import hashlib
import urllib.request
import pandas as pd

FILES = {
    'nswre74_treated.txt':'e7b742fe0ff07a0f45e129b4ff108bb9611cd83d53604732c48a8a0a3e20eda3',
    'nswre74_control.txt':'a1364cea459d953dc691a667d99194b4ad335d6d550354fe23a5d2dc58d729b5',
    'psid_controls.txt':'73ffcdd8feb7f965f8e1de9bfdb80a095542c7a95ce7f56b2e2b2a9716e858cc',
}
BASE = 'https://users.nber.org/~rdehejia/data/'
COLUMNS = ['treat','age','education','black','hispanic','married','nodegree','re74','re75','re78']


def fetch_data(directory):
    directory = Path(directory)
    directory.mkdir(parents=True, exist_ok=True)
    for name, expected in FILES.items():
        path = directory / name
        if not path.exists():
            with urllib.request.urlopen(BASE+name, timeout=60) as response:
                data = response.read()
            if hashlib.sha256(data).hexdigest() != expected:
                raise ValueError(f'Hash inesperado: {name}')
            path.write_bytes(data)
        if hashlib.sha256(path.read_bytes()).hexdigest() != expected:
            raise ValueError(f'Archivo local modificado: {name}')
    return directory


def load_data(directory):
    directory = fetch_data(directory)
    treated, controls, psid = [pd.read_csv(directory / n, sep=r'\s+', header=None, names=COLUMNS)
                               for n in ('nswre74_treated.txt','nswre74_control.txt','psid_controls.txt')]
    if (len(treated),len(controls),len(psid)) != (185,260,2490):
        raise ValueError('El número de filas no coincide con la documentación')
    if not (treated.treat.eq(1).all() and controls.treat.eq(0).all() and psid.treat.eq(0).all()):
        raise ValueError('Indicadores de tratamiento inesperados')
    return pd.concat([treated,controls], ignore_index=True), pd.concat([treated,psid], ignore_index=True)

"""Sensibilidad a confusión omitida para OLS con error estándar clásico."""
import numpy as np
import statsmodels.api as sm

def robustness_value(t,df):
    if df<=0 or not np.isfinite(t):raise ValueError('t o grados de libertad inválidos')
    f=abs(t)/np.sqrt(df)
    return float((np.sqrt(f**4+4*f*f)-f*f)/2)

def adjusted_estimate(beta,se,df,r_t,r_y):
    if df<=0 or se<0 or not 0<=r_t<1 or not 0<=r_y<=1:raise ValueError('Parámetros inválidos')
    bias=se*np.sqrt(df)*np.sqrt(r_t*r_y/(1-r_t))
    return float(beta-np.sign(beta)*bias)

def evalue(rr):
    if not np.isfinite(rr) or rr<=0:raise ValueError('Se requiere riesgo relativo positivo')
    q=max(rr,1/rr)
    return float(q+np.sqrt(q*(q-1)))

def partial_r2(target,candidate,controls):
    x=sm.add_constant(np.asarray(controls,float),has_constant='add')
    a=sm.OLS(target,x).fit().resid;b=sm.OLS(candidate,x).fit().resid
    return float(np.corrcoef(a,b)[0,1]**2)

def ols_summary(frame,outcome,treatment,controls,benchmark):
    cols=[treatment]+controls
    fit=sm.OLS(frame[outcome],sm.add_constant(frame[cols],has_constant='add')).fit()
    t=float(fit.tvalues[treatment]);df=float(fit.df_resid);beta=float(fit.params[treatment]);se=float(fit.bse[treatment])
    rest=[c for c in controls if c!=benchmark]
    rt=partial_r2(frame[treatment],frame[benchmark],frame[rest])
    ry=partial_r2(frame[outcome],frame[benchmark],frame[[treatment]+rest])
    return {'beta':beta,'se_classical':se,'t':t,'df':df,'rv_point_null':robustness_value(t,df),
            'benchmark':benchmark,'benchmark_r_t':rt,'benchmark_r_y':ry}

"""PC estable para gaussianas y NOTEARS lineal con datos estandarizados."""
from itertools import combinations
import numpy as np
import networkx as nx
from scipy.linalg import expm
from scipy.optimize import minimize
from scipy.stats import norm

def partial_pvalue(data,i,j,cond):
    n=len(data);cols=[i,j,*cond]
    if n-len(cond)-3<=0:return 1.
    cov=np.corrcoef(data[:,cols],rowvar=False)
    precision=np.linalg.pinv(cov);r=-precision[0,1]/np.sqrt(precision[0,0]*precision[1,1])
    r=np.clip(r,-1+1e-12,1-1e-12)
    stat=np.sqrt(n-len(cond)-3)*abs(np.arctanh(r))
    return float(2*norm.sf(stat))

def pc_skeleton(data,alpha=.05,max_cond=None,trace=None):
    X=np.asarray(data,float)
    if X.ndim!=2 or not np.isfinite(X).all() or not 0<alpha<1:raise ValueError('Datos o alpha inválidos')
    d=X.shape[1];adj=np.ones((d,d),dtype=bool);np.fill_diagonal(adj,False);seps={};depth=0
    if trace is not None:trace.append({'depth':-1,'adj':adj.astype(int).tolist(),'removed':[]})
    limit=d-2 if max_cond is None else max_cond
    while depth<=limit:
        frozen=adj.copy();removals=[];found_candidate=False
        for i in range(d):
            for j in range(i+1,d):
                if not frozen[i,j]:continue
                for source,target in ((i,j),(j,i)):
                    neighbors=[v for v in range(d) if frozen[source,v] and v!=target]
                    if len(neighbors)<depth:continue
                    found_candidate=True
                    for cond in combinations(neighbors,depth):
                        if partial_pvalue(X,i,j,cond)>alpha:
                            removals.append((i,j,tuple(cond)));break
                    if removals and removals[-1][:2]==(i,j):break
        for i,j,cond in removals:adj[i,j]=adj[j,i]=False;seps[(i,j)]=seps[(j,i)]=cond
        if trace is not None:trace.append({'depth':depth,'adj':adj.astype(int).tolist(),
                                           'removed':[[i,j,list(cond)] for i,j,cond in removals]})
        if not found_candidate:break
        depth+=1
    return adj,seps

def pc_orient(adj,seps):
    """V-estructuras y reglas de Meek R1-R3; devuelve matriz de arcos."""
    A=adj.astype(int).copy();d=len(A)
    def edge(a,b):return bool(A[a,b] or A[b,a])
    def undirected(a,b):return A[a,b]==1 and A[b,a]==1
    def arrow(a,b):return A[a,b]==1 and A[b,a]==0
    def orient(a,b):
        if undirected(a,b):A[b,a]=0;return True
        return False
    for j in range(d):
        for i,k in combinations([x for x in range(d) if adj[j,x]],2):
            if not adj[i,k] and j not in seps.get((i,k),()):orient(i,j);orient(k,j)
    changed=True
    while changed:
        changed=False
        for a in range(d):
            for b in range(d):
                if not undirected(a,b):continue
                r1=any(arrow(c,a) and not edge(c,b) for c in range(d) if c not in (a,b))
                r2=any(arrow(a,c) and arrow(c,b) for c in range(d) if c not in (a,b))
                candidates=[c for c in range(d) if c not in (a,b) and undirected(a,c) and arrow(c,b)]
                r3=any(not edge(c,e) for c,e in combinations(candidates,2))
                if r1 or r2 or r3:changed=orient(a,b) or changed
    return A

def pc(data,alpha=.05,max_cond=None,trace=None):
    adj,seps=pc_skeleton(data,alpha,max_cond,trace)
    return pc_orient(adj,seps),adj,seps

def simulate(seed,d,n,noise):
    rng=np.random.default_rng(seed);W=np.zeros((d,d))
    for i in range(d):
        for j in range(i+1,d):
            if rng.random()<2/(d-1):W[i,j]=rng.choice([-1,1])*rng.uniform(.5,1.2)
    X=np.zeros((n,d))
    for j in range(d):
        scale=1. if j==0 else noise
        X[:,j]=X@W[:,j]+rng.normal(0,scale,n)
    X=(X-X.mean(axis=0))/X.std(axis=0,ddof=0)
    return X,W

def notears(X,l1=.05,threshold=.3,max_outer=30,h_tol=1e-8):
    X=np.asarray(X,float);n,d=X.shape
    if not np.isfinite(X).all():raise ValueError('Datos no finitos')
    def unpack(z):return z[:d*d].reshape(d,d)-z[d*d:].reshape(d,d)
    bounds=[(0,0) if i==j else (0,None) for i in range(d) for j in range(d)]*2
    z=np.zeros(2*d*d);rho=1.;alpha=0.;old_h=np.inf
    for _ in range(max_outer):
        while rho<1e16:
            def objective(z):
                W=unpack(z);R=X-X@W;E=expm(W*W);h=np.trace(E)-d
                loss=.5*np.sum(R*R)/n+l1*np.sum(z)+alpha*h+.5*rho*h*h
                grad=X.T@(-R)/n+(alpha+rho*h)*(E.T*(2*W))
                return loss,np.r_[(grad+l1).ravel(),(-grad+l1).ravel()]
            result=minimize(objective,z,method='L-BFGS-B',jac=True,bounds=bounds)
            W=unpack(result.x);h=float(np.trace(expm(W*W))-d)
            if h>old_h*.25:rho*=10
            else:break
        z=result.x;old_h=h;alpha+=rho*h
        if h<=h_tol or rho>=1e16:break
    W=unpack(z);W[np.abs(W)<threshold]=0
    graph=nx.from_numpy_array(W,create_using=nx.DiGraph);removed=0
    while not nx.is_directed_acyclic_graph(graph):
        cycle=nx.find_cycle(graph);edge=min(cycle,key=lambda e:abs(W[e[0],e[1]]));W[edge[0],edge[1]]=0
        graph.remove_edge(*edge);removed+=1
    return W,{'h_before_threshold':h,'removed_cycle_edges':removed,'optimizer_success':bool(result.success)}

def shd_mixed(estimate,truth):
    """Una discrepancia por par: ausente, no orientado o cada orientación."""
    a=np.asarray(estimate);b=np.asarray(truth);d=len(a)
    return int(sum((int(a[i,j]),int(a[j,i]))!=(int(b[i,j]),int(b[j,i]))
                   for i in range(d) for j in range(i+1,d)))

"""Convertir a CPDAG con causal-learn y contrastar el esqueleto PC."""
import numpy as np
from causallearn.graph.GraphNode import GraphNode
from causallearn.graph.Dag import Dag
from causallearn.utils.DAG2CPDAG import dag2cpdag
from causallearn.search.ConstraintBased.PC import pc as reference_pc

def decode(graph):
    matrix=graph.graph;d=len(matrix);out=np.zeros((d,d),int)
    for i in range(d):
        for j in range(i+1,d):
            left,right=matrix[i,j],matrix[j,i]
            if left==-1 and right==-1:out[i,j]=out[j,i]=1
            elif left==-1 and right==1:out[i,j]=1
            elif left==1 and right==-1:out[j,i]=1
            elif left==1 and right==1:out[i,j]=out[j,i]=2
            elif left!=0 or right!=0:raise ValueError('Extremos de grafo no admitidos')
    return out

def cpdag_of_dag(W):
    W=np.asarray(W);nodes=[GraphNode(f'X{i+1}') for i in range(len(W))];dag=Dag(nodes)
    for i,j in zip(*np.where(W!=0)):dag.add_directed_edge(nodes[int(i)],nodes[int(j)])
    return decode(dag2cpdag(dag))

def compare_pc(X,truth,alpha=.05):
    own,adj,_=pc(X,alpha)
    ref=reference_pc(X,alpha=alpha,indep_test='fisherz',stable=True,uc_rule=0,show_progress=False,verbose=False)
    reference=decode(ref.G)
    skel_ref=(reference+reference.T)>0
    return {'cpdag_shd':shd_mixed(own,truth),'reference_cpdag_shd':shd_mixed(reference,truth),
            'reference_conflicts':int(np.sum(np.triu(reference==2,1))),
            'skeleton_disagreements':int(np.sum(np.triu(adj!=skel_ref,1))),'own':own,'reference':reference}

"""Refutadores DoWhy sobre la regresión observacional NSW/PSID."""
import numpy as np
from dowhy import CausalModel

COVARIATES=['age','education','black','hispanic','married','nodegree','re74','re75']

def run_refuters(project='causal_project'):
    _,data=load_data(project+'/data')
    model=CausalModel(data=data,treatment='treat',outcome='re78',common_causes=COVARIATES)
    estimand=model.identify_effect()
    estimate=model.estimate_effect(estimand,method_name='backdoor.linear_regression')
    out={}
    for name,kw in [('placebo_treatment_refuter',{'placebo_type':'permute'}),
                    ('random_common_cause',{}),('data_subset_refuter',{'subset_fraction':.8})]:
        ref=model.refute_estimate(estimand,estimate,method_name=name,num_simulations=20,random_seed=801,n_jobs=1,**kw)
        out[name]={'new_effect':float(ref.new_effect),'original_effect':float(ref.estimated_effect),
                   'p_value':float(ref.refutation_result['p_value']) if ref.refutation_result else None}
    return out


"""Pruebas de sensibilidad, separación y aciclicidad."""
import numpy as np
import networkx as nx
import sensemakr

for t,df in [(3.2,120),(1.2,2000)]:
    rv=robustness_value(t,df)
    ref=float(sensemakr.robustness_value(t_statistic=float(t),dof=df,q=1,alpha=1.0).iloc[0])
    assert abs(rv-ref)<1e-10
    assert abs(adjusted_estimate(t,1,df,rv,rv))<1e-9
assert abs(evalue(1.8)-3)<1e-12 and abs(evalue(.5)-evalue(2))<1e-12
rng=np.random.default_rng(400);n=5000
a=rng.normal(size=n);b=rng.normal(size=n);c=.9*a+.9*b+rng.normal(scale=.4,size=n)
X=np.column_stack([a,b,c]);assert partial_pvalue(X,0,1,())>.001
assert partial_pvalue(X,0,1,(2,))<1e-10
graph,adj,_=pc(X,alpha=.001)
assert not adj[0,1] and adj[0,2] and adj[1,2]
assert graph[0,2] and not graph[2,0] and graph[1,2] and not graph[2,1]
W,info=notears((X-X.mean(axis=0))/X.std(axis=0),l1=.05)
assert nx.is_directed_acyclic_graph(nx.from_numpy_array(W,create_using=nx.DiGraph))
assert info['h_before_threshold']<1e-6
print('Valor de robustez, E-value, colisionador PC y aciclicidad: pasan')

"""Sensibilidad y descubrimiento: evidencia real y simulación con verdad conocida."""
import argparse,json,platform
from importlib.metadata import version
from pathlib import Path
import numpy as np
import pandas as pd
import sensemakr
from threadpoolctl import threadpool_limits
from linearmodels.datasets import card

def nsw_and_card(project):
    _,nsw=load_data(str(Path(project)/'data'))
    nsw_result=ols_summary(nsw,'re78','treat',COVARIATES,'re75')
    d=card.load();d['age2']=d.age**2
    cov=['age','age2','black','smsa66']+[f'reg66{i}' for i in range(1,9)]
    d=d[['lwage','educ']+cov].dropna()
    card_result=ols_summary(d,'lwage','educ',cov,'age')
    for row in [nsw_result,card_result]:
        ref=sensemakr.robustness_value(t_statistic=float(row['t']),dof=int(row['df']),q=1,alpha=1.0)
        assert np.isclose(row['rv_point_null'],float(ref.iloc[0]),atol=1e-10)
    return nsw,{'NSW_PSID_OLS':nsw_result,'Card_OLS':card_result}

def real_pc(nsw):
    columns=['age','education','re74','re75','re78']
    X=nsw[columns].to_numpy(float);X=(X-X.mean(axis=0))/X.std(axis=0)
    A,_,_=pc(X,alpha=.05)
    edges=[{'from':columns[i],'to':columns[j],'directed':bool(A[j,i]==0)}
           for i in range(len(columns)) for j in range(len(columns))
           if A[i,j] and (A[j,i]==0 or i<j)]
    W,diagnostics=notears(X)
    notears_edges=[{'from':columns[i],'to':columns[j],'weight':float(W[i,j])}
                   for i,j in zip(*np.where(W!=0))]
    return {'columns':columns,'edges':edges,'notears_edges':notears_edges,
            'notears_diagnostics':diagnostics,'n':len(X),
            'truth':'desconocida; variables no gaussianas y mezcla de grupos'}

def benchmark(repetitions=3):
    rows=[]
    for d in (10,20):
        for n in (200,1000):
            for noise in (.5,1.):
                for rep in range(repetitions):
                    seed=801+rep;X,W=simulate(seed,d,n,noise);truth=cpdag_of_dag(W)
                    result=compare_pc(X,truth);estimate,diag=notears(X)
                    score=shd_mixed(cpdag_of_dag(estimate),truth)
                    rows.append({'d':d,'n':n,'noise':noise,'seed':seed,'true_edges':int(np.count_nonzero(W)),
                        'pc_shd':result['cpdag_shd'],'pc_reference_shd':result['reference_cpdag_shd'],
                        'pc_skeleton_disagreements':result['skeleton_disagreements'],
                        'pc_reference_conflicts':result['reference_conflicts'],'notears_shd':score,**diag})
    return rows

def stepper_data():
    d=4;W=np.zeros((d,d));W[0,2]=.9;W[1,2]=.8;W[2,3]=.9;W[0,3]=.25
    truth=cpdag_of_dag(W);out=[]
    for n in (100,300,1000):
        rng=np.random.default_rng(950);X=np.zeros((n,d))
        for j in range(d):X[:,j]=X@W[:,j]+rng.normal(size=n)
        X=(X-X.mean(axis=0))/X.std(axis=0)
        for alpha in (.01,.05,.1):
            trace=[];A,_,_=pc(X,alpha,trace=trace)
            out.append({'n':n,'alpha':alpha,'trace':trace,'oriented':A.tolist(),
                        'truth':truth.tolist(),'shd':shd_mixed(A,truth)})
    return out

def run(project,repetitions=3):
    with threadpool_limits(limits=1):
        data,sensitivity=nsw_and_card(project)
        refutations=run_refuters(project)
        simulations=benchmark(repetitions)
        return {'sensitivity':sensitivity,'refutations':refutations,'evalue_1_8':evalue(1.8),
                'real_pc':real_pc(data),'simulations':simulations,'stepper':stepper_data(),
                'settings':{'repetitions':repetitions,'pc_alpha':.05,'notears_l1':.05,'threshold':.3},
                'versions':{'python':platform.python_version(),'numpy':np.__version__,'pandas':pd.__version__,
                            'pysensemakr':version('pysensemakr'),'causal_learn':version('causal-learn'),'dowhy':version('dowhy')}}


result=run('causal_project',3)
print('Sensibilidad:',result['sensitivity'])
print('Refutaciones:',result['refutations'])
print('PC real:',result['real_pc'])
for d in (10,20):
    for n in (200,1000):
        for noise in (.5,1.):
            rows=[r for r in result['simulations'] if (r['d'],r['n'],r['noise'])==(d,n,noise)]
            print(d,n,noise,'SHD PC/NOTEARS:',np.mean([r['pc_shd'] for r in rows]),np.mean([r['notears_shd'] for r in rows]))
print('PC stepper:',[(r['n'],r['alpha'],r['shd']) for r in result['stepper']])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Quiz
PC leaves a line without an arrow between two nodes. What can you conclude?
Quiz
A random common cause barely changes the estimate. What does this demonstrate?
Numeric
For a risk ratio of 1.8, calculate the point E-value.
ProofFrom bias to partial R²
Prove: Derive the magnitude of omitted-variable OLS bias using FWL and the two partial R² values.
0
Let u⊥ be the residual of U after projection on D and X; ν is the short model's residual degrees of freedom.

Step 1 of 3. How are the residuals of U related?

Code
Implement prune_step(adj, depth, pvalue, alpha) for a stable PC stage. adj is a symmetric Boolean matrix; for each connected pair i < j, test sets of i's neighbors excluding j of size depth. If pvalue(i,j,set) > alpha, remove both directions and store that set in a dictionary keyed by (i,j). Use graph neighbors at the start of the stage and return (new matrix, separators).
def prune_step(adj, depth, pvalue, alpha):
  pass
Shift+Enter to run

Summary

Key idea
Sensitivity quantifies what assumptions could change a conclusion. Causal discovery proposes structures under assumptions; comparison with simulated graphs and temporal knowledge helps assess their limits.