@doc raw"""
share(δ, Σ, dFν, x)
Computes shares in random coefficient logit with mean tastes `δ`, observed characteristics `x`, unobserved taste distribution `dFν`, and taste covariances `Σ`.
# Arguments
- `δ` vector of length `J`
- `Σ` `K` by `K` matrix
- `dFν` distribution of length `K` vector
- `x` `J` by `K` array
# Returns
- vector of length `J` consisting of $s_1$, ..., $s_J$
"""
function share(δ, Σ, dFν, x, ∫ = ∫cuba)
J,K = size(x)
(length(δ) == J) || error("length(δ)=$(length(δ)) != size(x,1)=$J")
((K,K) === size(Σ)) || error("size(x,2)=$K != size(Σ)=$(size(Σ))")
function shareν(ν)
s = δ + x*Σ*ν
s .-= maximum(s)
s .= exp.(s)
s ./= sum(s)
return(s)
end
return(∫(shareν, dFν))
end
using HCubature
function ∫cuba(f, dx; rtol=1e-4)
D = length(dx)
x(t) = t./(1 .- t.^2)
Dx(t) = prod((1 .+ t.^2)./(1 .- t.^2).^2)
hcubature(t->f(x(t))*pdf(dx,x(t))*Dx(t), -ones(D),ones(D), rtol=rtol)[1]
end
using SparseGrids, FastGaussQuadrature, Distributions
function ∫sgq(f, dx::MvNormal; order=5)
X, W = sparsegrid(length(dx), order, gausshermite, sym=true)
L = cholesky(dx.Σ).L
d = length(dx)
rootdetΣ = 1 #abs(det(sqrt(2)*L))
wnorm = (π)^(d/2) * rootdetΣ
sum(f(√2*L*x + dx.μ)*w for (x,w) ∈ zip(X,W))/wnorm
end
∫mc(f, dx; ndraw=100) = mean(f(rand(dx)) for i in 1:ndraw)