|
1 | | -export UnitVector, CorrCholeskyFactor |
| 1 | +export UnitVector, UnitSimplex, CorrCholeskyFactor |
2 | 2 |
|
3 | 3 | #### |
4 | 4 | #### building blocks |
@@ -77,6 +77,67 @@ function inverse_at!(x::AbstractVector, index, t::UnitVector, y::AbstractVector) |
77 | 77 | index |
78 | 78 | end |
79 | 79 |
|
| 80 | + |
| 81 | +#### |
| 82 | +#### UnitSimplex |
| 83 | +#### |
| 84 | + |
| 85 | +""" |
| 86 | + UnitSimplex(n) |
| 87 | +
|
| 88 | +Transform `n-1` real numbers to a vector of length `n` whose elements are non-negative and sum to one. |
| 89 | +""" |
| 90 | +@calltrans struct UnitSimplex <: VectorTransform |
| 91 | + n::Int |
| 92 | + function UnitSimplex(n::Int) |
| 93 | + @argcheck n ≥ 1 "Dimension should be positive." |
| 94 | + new(n) |
| 95 | + end |
| 96 | +end |
| 97 | + |
| 98 | +dimension(t::UnitSimplex) = t.n - 1 |
| 99 | + |
| 100 | +function transform_with(flag::LogJacFlag, t::UnitSimplex, x::AbstractVector, index) |
| 101 | + @unpack n = t |
| 102 | + T = extended_eltype(x) |
| 103 | + |
| 104 | + ℓ = logjac_zero(flag, T) |
| 105 | + stick = one(T) |
| 106 | + y = Vector{T}(undef, n) |
| 107 | + @inbounds for i in 1:n-1 |
| 108 | + xi = x[index] |
| 109 | + index += 1 |
| 110 | + z = logistic(xi - log(n-i)) |
| 111 | + y[i] = z * stick |
| 112 | + |
| 113 | + if !(flag isa NoLogJac) |
| 114 | + ℓ += log(stick) - logit_logjac(z) |
| 115 | + end |
| 116 | + |
| 117 | + stick *= 1 - z |
| 118 | + end |
| 119 | + |
| 120 | + y[end] = stick |
| 121 | + |
| 122 | + y, ℓ, index |
| 123 | +end |
| 124 | + |
| 125 | +inverse_eltype(t::UnitSimplex, y::AbstractVector) = extended_eltype(y) |
| 126 | + |
| 127 | +function inverse_at!(x::AbstractVector, index, t::UnitSimplex, y::AbstractVector) |
| 128 | + @unpack n = t |
| 129 | + @argcheck length(y) == n |
| 130 | + |
| 131 | + stick = one(eltype(y)) |
| 132 | + @inbounds for i in axes(y, 1)[1:end-1] |
| 133 | + z = y[i]/stick |
| 134 | + x[index] = logit(z) + log(n-i) |
| 135 | + stick -= y[i] |
| 136 | + index += 1 |
| 137 | + end |
| 138 | + index |
| 139 | +end |
| 140 | + |
80 | 141 | #### |
81 | 142 | #### correlation cholesky factor |
82 | 143 | #### |
|
0 commit comments