Skip to content

Instantly share code, notes, and snippets.

@mschauer
Created December 4, 2024 17:38
Show Gist options
  • Save mschauer/f170c29cf01c7d5d43b6f7be70e0b68e to your computer and use it in GitHub Desktop.
Save mschauer/f170c29cf01c7d5d43b6f7be70e0b68e to your computer and use it in GitHub Desktop.
Z-Identification in Julia with CausalInference.jl
# Solving the problem in https://bsky.app/profile/p-hunermund.com/post/3lci6xojlmt25
using CausalInference, Graphs
# defining the graphical do-operator we need here
function do!(g, v)
for u in collect(inneighbors(g, v))
rem_edge!(g, u, v)
end
end
# Define the causal Dag?
U, V, X, Y, Z = 1:5
dag = digraph([U=>X, U=>Z, V=>Y, V=>Z, Z=>X, X=>Y])
@show dag
# Display: digraph([1 => 3, 1 => 5, 2 => 4, 2 => 5, 3 => 4, 5 => 3])
∅ = Set{Int}()
observed = [X, Y, Z]
# Can we estimate the causal effect from purely observational data, perhaps by a covariate adjustement?
adjustments = collect(list_covariate_adjustment(dag, X, Y, ∅, observed))
@show adjustments
# Display: (No adjustments available)
# We are not out of luck, because we can intervene on Z.
dag2 = copy(dag)
do!(dag2, Z)
@show dag2
# Display: digraph([1 => 3, 2 => 4, 3 => 4, 5 => 3])
# In the DAG with the intervation, all incoming edges to Z=5 are removed, e.g. 1=>5.
# Enumerate again the possible adjustment?
adjustments2 = collect(list_covariate_adjustment(dag2, X, Y, ∅, observed))
@show adjustments2
# Display: [], [5]
# By computing the correlation between X and Y (alternatively the conditional correlation between X and Y given Z)
# we can estimate the causal effect.
@mschauer
Copy link
Author

mschauer commented Dec 4, 2024

Code for displaying the graphs as edge-list in the Julia REPL

function Base.show(io::IO, mime::MIME"text/plain", obj::DiGraph)
    print(io, "DiGraph(")
    Base.show(io, vpairs(obj))
    println(io, ")")
end
function Base.show(io::IO, obj::DiGraph)
    print(io, "DiGraph(")
    Base.show(io, vpairs(obj))
    println(io, ")")
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment