using GLM, Random, StatsPlots
function drlate(y, d, x, z; degree=5)
n = length(y)
u = x ./ std(x)
B = hcat([u .^ j for j in 0:degree]...)
Bp = hcat(ones(n), atan.(x))
fold = mod.(randperm(n), 2)
score_y = similar(y, Float64)
score_d = similar(y, Float64)
for k in 0:1
test = fold .== k
train = .!test
pfit = glm(Bp[train, :], z[train], Binomial(), LogitLink())
p = clamp.(predict(pfit, Bp[test, :]), 0.001, 0.999)
i1 = train .& z
i0 = train .& .!z
my1 = B[test, :] * (B[i1, :] \ y[i1])
my0 = B[test, :] * (B[i0, :] \ y[i0])
md1 = B[test, :] * (B[i1, :] \ d[i1])
md0 = B[test, :] * (B[i0, :] \ d[i0])
score_y[test] = my1 - my0 +
z[test] .* (y[test] - my1) ./ p -
(.!z[test]) .* (y[test] - my0) ./ (1 .- p)
score_d[test] = md1 - md0 +
z[test] .* (d[test] - md1) ./ p -
(.!z[test]) .* (d[test] - md0) ./ (1 .- p)
end
return mean(score_y) / mean(score_d)
end
function oracle_late(y, d, x, z, slope)
p = 1 ./ (1 .+ exp.(-slope .* atan.(x)))
σ = sqrt(2.5)
t0 = (x ./ 2) ./ σ
t1 = (x ./ 2 .+ 1) ./ σ
md0 = cdf.(Normal(), t0)
md1 = cdf.(Normal(), t1)
Δ = 1 .+ x.^3 ./ 10
my0 = Δ .* md0 .+ pdf.(Normal(), t0) ./ σ
my1 = Δ .* md1 .+ pdf.(Normal(), t1) ./ σ
score_y = my1 .- my0 +
z .* (y .- my1) ./ p -
(.!z) .* (y .- my0) ./ (1 .- p)
score_d = md1 .- md0 +
z .* (d .- md1) ./ p -
(.!z) .* (d .- md0) ./ (1 .- p)
return mean(score_y) / mean(score_d)
end
Random.seed!(626)
S = 50
estimates = zeros(S, 2, 4)
for r in 1:S, (j, slope) in enumerate((0.1, 2*log(0.975/0.025)/π))
ezx = x->1/(1+exp(-slope*atan(x)))
s = sim(25_000, Δ=x->(1+x^3/10), ezx=ezx)
dr = drlate(s.y, s.d, s.x, s.z)
oracle = oracle_late(s.y, s.d, s.x, s.z, slope)
estimates[r, j, 1] = mean(s.Δ[s.d1 .> s.d0])
estimates[r, j, 2] = b2sls(s.y, s.d, s.x, s.z)[2]
estimates[r, j, 3] = dr
estimates[r, j, 4] = oracle
end
methods = ["2SLS", "Doubly robust", "Oracle DR"]
late_means = [mean(estimates[:, j, 1]) for j in 1:2]
p_low = violin(estimates[:, 1, 2:4], label=methods,
xticks=(1:3, methods), ylabel="LATE estimate",
title="Low bias", legend=false)
hline!(p_low, [late_means[1]], color=:black, linestyle=:dash,
linewidth=2, label="Mean population LATE")
p_high = violin(estimates[:, 2, 2:4], label=methods,
xticks=(1:3, methods), ylabel="LATE estimate",
title="High bias", legend=false)
hline!(p_high, [late_means[2]], color=:black, linestyle=:dash,
linewidth=2, label="Mean population LATE")
plot(p_low, p_high, layout=(1, 2), size=(1200, 480),
plot_title="Sampling distributions across $S simulations")