context_start_lineno int64 1 913 | line_no int64 16 984 | repo stringclasses 5
values | id int64 0 416 | target_function_prompt stringlengths 201 13.6k | function_signature stringlengths 201 13.6k | solution_position listlengths 2 2 | raw_solution stringlengths 201 13.6k | focal_code stringlengths 201 13.6k | function_name stringlengths 2 38 | start_line int64 1 913 | end_line int64 16 984 | file_path stringlengths 10 52 | context stringlengths 4.52k 9.85k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
562 | 575 | Distributions.jl | 100 | function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = sum(Base.Fix... | function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = sum(Base.Fix... | [
562,
575
] | function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = sum(Base.Fix... | function integerunitrange_cdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = sum(Base.Fix... | integerunitrange_cdf | 562 | 575 | src/univariates.jl | #FILE: Distributions.jl/src/truncate.jl
##CHUNK 1
function ccdf(d::Truncated, x::Real)
result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1)
# Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial`
return if d.lower !== nothing && x <= d.lower
one(result)
... |
577 | 590 | Distributions.jl | 101 | function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = 1 - sum(Bas... | function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = 1 - sum(Bas... | [
577,
590
] | function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = 1 - sum(Bas... | function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = 1 - sum(Bas... | integerunitrange_ccdf | 577 | 590 | src/univariates.jl | #FILE: Distributions.jl/src/quantilealgs.jl
##CHUNK 1
return T(minimum(d))
elseif p == 1
return T(maximum(d))
else
return T(NaN)
end
end
function cquantile_newton(d::ContinuousUnivariateDistribution, p::Real, xs::Real=mode(d), tol::Real=1e-12)
x = xs + (ccdf(d, xs)-p) / pdf(d, x... |
592 | 605 | Distributions.jl | 102 | function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = logsumexp... | function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = logsumexp... | [
592,
605
] | function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = logsumexp... | function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = logsumexp... | integerunitrange_logcdf | 592 | 605 | src/univariates.jl | #FILE: Distributions.jl/src/truncate.jl
##CHUNK 1
function ccdf(d::Truncated, x::Real)
result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1)
# Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial`
return if d.lower !== nothing && x <= d.lower
one(result)
... |
607 | 620 | Distributions.jl | 103 | function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = log1mexp... | function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = log1mexp... | [
607,
620
] | function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = log1mexp... | function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = log1mexp... | integerunitrange_logccdf | 607 | 620 | src/univariates.jl | #FILE: Distributions.jl/src/truncate.jl
##CHUNK 1
function ccdf(d::Truncated, x::Real)
result = clamp((d.ucdf - cdf(d.untruncated, x)) / d.tp, 0, 1)
# Special cases for values outside of the support to avoid e.g. NaN issues with `Binomial`
return if d.lower !== nothing && x <= d.lower
one(result)
... |
43 | 53 | Distributions.jl | 104 | function LKJCholesky(d::Int, η::Real, _uplo::Union{Char,Symbol} = 'L'; check_args::Bool=true)
@check_args(
LKJCholesky,
(d, d > 0, "matrix dimension must be positive"),
(η, η > 0, "shape parameter must be positive"),
)
logc0 = lkj_logc0(d, η)
uplo = _char_uplo(_uplo)
T = Base... | function LKJCholesky(d::Int, η::Real, _uplo::Union{Char,Symbol} = 'L'; check_args::Bool=true)
@check_args(
LKJCholesky,
(d, d > 0, "matrix dimension must be positive"),
(η, η > 0, "shape parameter must be positive"),
)
logc0 = lkj_logc0(d, η)
uplo = _char_uplo(_uplo)
T = Base... | [
43,
53
] | function LKJCholesky(d::Int, η::Real, _uplo::Union{Char,Symbol} = 'L'; check_args::Bool=true)
@check_args(
LKJCholesky,
(d, d > 0, "matrix dimension must be positive"),
(η, η > 0, "shape parameter must be positive"),
)
logc0 = lkj_logc0(d, η)
uplo = _char_uplo(_uplo)
T = Base... | function LKJCholesky(d::Int, η::Real, _uplo::Union{Char,Symbol} = 'L'; check_args::Bool=true)
@check_args(
LKJCholesky,
(d, d > 0, "matrix dimension must be positive"),
(η, η > 0, "shape parameter must be positive"),
)
logc0 = lkj_logc0(d, η)
uplo = _char_uplo(_uplo)
T = Base... | LKJCholesky | 43 | 53 | src/cholesky/lkjcholesky.jl | #FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 1
!!! note
if a Cholesky factor of the correlation matrix is desired, it is more efficient to
use [`LKJCholesky`](@ref), which avoids factorizing the matrix.
"""
struct LKJ{T <: Real, D <: Integer} <: ContinuousMatrixDistribution
d::D
η::T
logc0::T
e... |
92 | 110 | Distributions.jl | 105 | function insupport(d::LKJCholesky, R::LinearAlgebra.Cholesky)
p = d.d
factors = R.factors
(isreal(factors) && size(factors, 1) == p) || return false
iinds, jinds = axes(factors)
# check that the diagonal of U'*U or L*L' is all ones
@inbounds if R.uplo === 'U'
for (j, jind) in enumerate(j... | function insupport(d::LKJCholesky, R::LinearAlgebra.Cholesky)
p = d.d
factors = R.factors
(isreal(factors) && size(factors, 1) == p) || return false
iinds, jinds = axes(factors)
# check that the diagonal of U'*U or L*L' is all ones
@inbounds if R.uplo === 'U'
for (j, jind) in enumerate(j... | [
92,
110
] | function insupport(d::LKJCholesky, R::LinearAlgebra.Cholesky)
p = d.d
factors = R.factors
(isreal(factors) && size(factors, 1) == p) || return false
iinds, jinds = axes(factors)
# check that the diagonal of U'*U or L*L' is all ones
@inbounds if R.uplo === 'U'
for (j, jind) in enumerate(j... | function insupport(d::LKJCholesky, R::LinearAlgebra.Cholesky)
p = d.d
factors = R.factors
(isreal(factors) && size(factors, 1) == p) || return false
iinds, jinds = axes(factors)
# check that the diagonal of U'*U or L*L' is all ones
@inbounds if R.uplo === 'U'
for (j, jind) in enumerate(j... | insupport | 92 | 110 | src/cholesky/lkjcholesky.jl | #FILE: Distributions.jl/test/cholesky/lkjcholesky.jl
##CHUNK 1
end
end
end
@testset "LKJCholesky marginal KS test" begin
α = 0.01
L = sum(1:(p - 1))
for i in 1:p, j in 1:(i-1)
@test pvalue_kolmogorovsmirnoff(zs[i, j, :], ma... |
130 | 141 | Distributions.jl | 106 | function logkernel(d::LKJCholesky, R::LinearAlgebra.Cholesky)
factors = R.factors
p, η = params(d)
c = p + 2(η - 1)
p == 1 && return c * log(first(factors))
# assuming D = diag(factors) with length(D) = p,
# logp = sum(i -> (c - i) * log(D[i]), 2:p)
logp = sum(Iterators.drop(enumerate(diagin... | function logkernel(d::LKJCholesky, R::LinearAlgebra.Cholesky)
factors = R.factors
p, η = params(d)
c = p + 2(η - 1)
p == 1 && return c * log(first(factors))
# assuming D = diag(factors) with length(D) = p,
# logp = sum(i -> (c - i) * log(D[i]), 2:p)
logp = sum(Iterators.drop(enumerate(diagin... | [
130,
141
] | function logkernel(d::LKJCholesky, R::LinearAlgebra.Cholesky)
factors = R.factors
p, η = params(d)
c = p + 2(η - 1)
p == 1 && return c * log(first(factors))
# assuming D = diag(factors) with length(D) = p,
# logp = sum(i -> (c - i) * log(D[i]), 2:p)
logp = sum(Iterators.drop(enumerate(diagin... | function logkernel(d::LKJCholesky, R::LinearAlgebra.Cholesky)
factors = R.factors
p, η = params(d)
c = p + 2(η - 1)
p == 1 && return c * log(first(factors))
# assuming D = diag(factors) with length(D) = p,
# logp = sum(i -> (c - i) * log(D[i]), 2:p)
logp = sum(Iterators.drop(enumerate(diagin... | logkernel | 130 | 141 | src/cholesky/lkjcholesky.jl | #FILE: Distributions.jl/src/matrix/matrixbeta.jl
##CHUNK 1
function logkernel(d::MatrixBeta, U::AbstractMatrix)
p, n1, n2 = params(d)
((n1 - p - 1) / 2) * logdet(U) + ((n2 - p - 1) / 2) * logdet(I - U)
end
# -----------------------------------------------------------------------------
# Sampling
# ---------... |
166 | 178 | Distributions.jl | 107 | function Base.rand(rng::AbstractRNG, d::LKJCholesky, dims::Dims)
p = d.d
uplo = d.uplo
T = eltype(d)
TM = Matrix{T}
Rs = Array{LinearAlgebra.Cholesky{T,TM}}(undef, dims)
for i in eachindex(Rs)
factors = TM(undef, p, p)
Rs[i] = R = LinearAlgebra.Cholesky(factors, uplo, 0)
... | function Base.rand(rng::AbstractRNG, d::LKJCholesky, dims::Dims)
p = d.d
uplo = d.uplo
T = eltype(d)
TM = Matrix{T}
Rs = Array{LinearAlgebra.Cholesky{T,TM}}(undef, dims)
for i in eachindex(Rs)
factors = TM(undef, p, p)
Rs[i] = R = LinearAlgebra.Cholesky(factors, uplo, 0)
... | [
166,
178
] | function Base.rand(rng::AbstractRNG, d::LKJCholesky, dims::Dims)
p = d.d
uplo = d.uplo
T = eltype(d)
TM = Matrix{T}
Rs = Array{LinearAlgebra.Cholesky{T,TM}}(undef, dims)
for i in eachindex(Rs)
factors = TM(undef, p, p)
Rs[i] = R = LinearAlgebra.Cholesky(factors, uplo, 0)
... | function Base.rand(rng::AbstractRNG, d::LKJCholesky, dims::Dims)
p = d.d
uplo = d.uplo
T = eltype(d)
TM = Matrix{T}
Rs = Array{LinearAlgebra.Cholesky{T,TM}}(undef, dims)
for i in eachindex(Rs)
factors = TM(undef, p, p)
Rs[i] = R = LinearAlgebra.Cholesky(factors, uplo, 0)
... | Base.rand | 166 | 178 | src/cholesky/lkjcholesky.jl | #CURRENT FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{T,TM}},
allocate::Bool,
) where {T,TM}
p = d.d
uplo = d.uplo
if allocate
for i in eachindex(Rs)
Rs[i]... |
185 | 207 | Distributions.jl | 108 | function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{T,TM}},
allocate::Bool,
) where {T,TM}
p = d.d
uplo = d.uplo
if allocate
for i in eachindex(Rs)
Rs[i] = _lkj_cholesky_onion_sampler!(
rng,
d... | function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{T,TM}},
allocate::Bool,
) where {T,TM}
p = d.d
uplo = d.uplo
if allocate
for i in eachindex(Rs)
Rs[i] = _lkj_cholesky_onion_sampler!(
rng,
d... | [
185,
207
] | function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{T,TM}},
allocate::Bool,
) where {T,TM}
p = d.d
uplo = d.uplo
if allocate
for i in eachindex(Rs)
Rs[i] = _lkj_cholesky_onion_sampler!(
rng,
d... | function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{T,TM}},
allocate::Bool,
) where {T,TM}
p = d.d
uplo = d.uplo
if allocate
for i in eachindex(Rs)
Rs[i] = _lkj_cholesky_onion_sampler!(
rng,
d... | Random.rand! | 185 | 207 | src/cholesky/lkjcholesky.jl | #FILE: Distributions.jl/src/genericrand.jl
##CHUNK 1
end
# the function barrier fixes performance issues if `sampler(s)` is type unstable
return _rand!(rng, sampler(s), x, allocate)
end
function _rand!(
rng::AbstractRNG,
s::Sampleable{ArrayLikeVariate{N}},
x::AbstractArray{<:AbstractArray{<:Rea... |
221 | 232 | Distributions.jl | 109 | function _lkj_cholesky_onion_sampler!(
rng::AbstractRNG,
d::LKJCholesky,
R::LinearAlgebra.Cholesky,
)
if R.uplo === 'U'
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:U))
else
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:L))
end
return R
end | function _lkj_cholesky_onion_sampler!(
rng::AbstractRNG,
d::LKJCholesky,
R::LinearAlgebra.Cholesky,
)
if R.uplo === 'U'
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:U))
else
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:L))
end
return R
end | [
221,
232
] | function _lkj_cholesky_onion_sampler!(
rng::AbstractRNG,
d::LKJCholesky,
R::LinearAlgebra.Cholesky,
)
if R.uplo === 'U'
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:U))
else
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:L))
end
return R
end | function _lkj_cholesky_onion_sampler!(
rng::AbstractRNG,
d::LKJCholesky,
R::LinearAlgebra.Cholesky,
)
if R.uplo === 'U'
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:U))
else
_lkj_cholesky_onion_tri!(rng, R.factors, d.d, d.η, Val(:L))
end
return R
end | _lkj_cholesky_onion_sampler! | 221 | 232 | src/cholesky/lkjcholesky.jl | #CURRENT FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
function Base.rand(rng::AbstractRNG, d::LKJCholesky)
factors = Matrix{eltype(d)}(undef, size(d))
R = LinearAlgebra.Cholesky(factors, d.uplo, 0)
return _lkj_cholesky_onion_sampler!(rng, d, R)
end
function Base.rand(rng::AbstractRNG, d::LKJ... |
234 | 272 | Distributions.jl | 110 | function _lkj_cholesky_onion_tri!(
rng::AbstractRNG,
A::AbstractMatrix,
d::Int,
η::Real,
::Val{uplo},
) where {uplo}
# Section 3.2 in LKJ (2009 JMA)
# reformulated to incrementally construct Cholesky factor as mentioned in Section 5
# equivalent steps in algorithm in reference are marked... | function _lkj_cholesky_onion_tri!(
rng::AbstractRNG,
A::AbstractMatrix,
d::Int,
η::Real,
::Val{uplo},
) where {uplo}
# Section 3.2 in LKJ (2009 JMA)
# reformulated to incrementally construct Cholesky factor as mentioned in Section 5
# equivalent steps in algorithm in reference are marked... | [
234,
272
] | function _lkj_cholesky_onion_tri!(
rng::AbstractRNG,
A::AbstractMatrix,
d::Int,
η::Real,
::Val{uplo},
) where {uplo}
# Section 3.2 in LKJ (2009 JMA)
# reformulated to incrementally construct Cholesky factor as mentioned in Section 5
# equivalent steps in algorithm in reference are marked... | function _lkj_cholesky_onion_tri!(
rng::AbstractRNG,
A::AbstractMatrix,
d::Int,
η::Real,
::Val{uplo},
) where {uplo}
# Section 3.2 in LKJ (2009 JMA)
# reformulated to incrementally construct Cholesky factor as mentioned in Section 5
# equivalent steps in algorithm in reference are marked... | _lkj_cholesky_onion_tri! | 234 | 272 | src/cholesky/lkjcholesky.jl | #FILE: Distributions.jl/src/matrix/wishart.jl
##CHUNK 1
fill!(view(A, :, axes2[(r + 1):end]), zero(eltype(A)))
else
_wishart_genA!(rng, A, d.df)
end
unwhiten!(d.S, A)
A .= A * A'
end
function _wishart_genA!(rng::AbstractRNG, A::AbstractMatrix, df::Real)
# Generate the matrix A in th... |
102 | 115 | Distributions.jl | 111 | function lkj_logc0(d::Integer, η::Real)
T = float(Base.promote_typeof(d, η))
d > 1 || return zero(η)
if isone(η)
if iseven(d)
logc0 = -lkj_onion_loginvconst_uniform_even(d, T)
else
logc0 = -lkj_onion_loginvconst_uniform_odd(d, T)
end
else
logc0 = -... | function lkj_logc0(d::Integer, η::Real)
T = float(Base.promote_typeof(d, η))
d > 1 || return zero(η)
if isone(η)
if iseven(d)
logc0 = -lkj_onion_loginvconst_uniform_even(d, T)
else
logc0 = -lkj_onion_loginvconst_uniform_odd(d, T)
end
else
logc0 = -... | [
102,
115
] | function lkj_logc0(d::Integer, η::Real)
T = float(Base.promote_typeof(d, η))
d > 1 || return zero(η)
if isone(η)
if iseven(d)
logc0 = -lkj_onion_loginvconst_uniform_even(d, T)
else
logc0 = -lkj_onion_loginvconst_uniform_odd(d, T)
end
else
logc0 = -... | function lkj_logc0(d::Integer, η::Real)
T = float(Base.promote_typeof(d, η))
d > 1 || return zero(η)
if isone(η)
if iseven(d)
logc0 = -lkj_onion_loginvconst_uniform_even(d, T)
else
logc0 = -lkj_onion_loginvconst_uniform_odd(d, T)
end
else
logc0 = -... | lkj_logc0 | 102 | 115 | src/matrix/lkj.jl | #FILE: Distributions.jl/test/matrixvariates.jl
##CHUNK 1
end
for i in 1:d
for j in 1:i-1
@test pvalue_kolmogorovsmirnoff(mymats[i, j, :], ρ) >= α / L
end
end
end
@testset "LKJ integrating constant" begin
# =============
# odd non-... |
127 | 155 | Distributions.jl | 112 | function _lkj_onion_sampler(d::Integer, η::Real, rng::AbstractRNG = Random.default_rng())
# Section 3.2 in LKJ (2009 JMA)
# 1. Initialization
R = ones(typeof(η), d, d)
d > 1 || return R
β = η + 0.5d - 1
u = rand(rng, Beta(β, β))
R[1, 2] = 2u - 1
R[2, 1] = R[1, 2]
# 2.
for k in... | function _lkj_onion_sampler(d::Integer, η::Real, rng::AbstractRNG = Random.default_rng())
# Section 3.2 in LKJ (2009 JMA)
# 1. Initialization
R = ones(typeof(η), d, d)
d > 1 || return R
β = η + 0.5d - 1
u = rand(rng, Beta(β, β))
R[1, 2] = 2u - 1
R[2, 1] = R[1, 2]
# 2.
for k in... | [
127,
155
] | function _lkj_onion_sampler(d::Integer, η::Real, rng::AbstractRNG = Random.default_rng())
# Section 3.2 in LKJ (2009 JMA)
# 1. Initialization
R = ones(typeof(η), d, d)
d > 1 || return R
β = η + 0.5d - 1
u = rand(rng, Beta(β, β))
R[1, 2] = 2u - 1
R[2, 1] = R[1, 2]
# 2.
for k in... | function _lkj_onion_sampler(d::Integer, η::Real, rng::AbstractRNG = Random.default_rng())
# Section 3.2 in LKJ (2009 JMA)
# 1. Initialization
R = ones(typeof(η), d, d)
d > 1 || return R
β = η + 0.5d - 1
u = rand(rng, Beta(β, β))
R[1, 2] = 2u - 1
R[2, 1] = R[1, 2]
# 2.
for k in... | _lkj_onion_sampler | 127 | 155 | src/matrix/lkj.jl | #FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
# Section 3.2 in LKJ (2009 JMA)
# reformulated to incrementally construct Cholesky factor as mentioned in Section 5
# equivalent steps in algorithm in reference are marked.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β... |
190 | 200 | Distributions.jl | 113 | function lkj_onion_loginvconst(d::Integer, η::Real)
# Equation (17) in LKJ (2009 JMA)
T = float(Base.promote_typeof(d, η))
h = T(1//2)
α = η + h * d - 1
loginvconst = (2*η + d - 3)*T(logtwo) + (T(logπ) / 4) * (d * (d - 1) - 2) + logbeta(α, α) - (d - 2) * loggamma(η + h * (d - 1))
for k in 2:(d ... | function lkj_onion_loginvconst(d::Integer, η::Real)
# Equation (17) in LKJ (2009 JMA)
T = float(Base.promote_typeof(d, η))
h = T(1//2)
α = η + h * d - 1
loginvconst = (2*η + d - 3)*T(logtwo) + (T(logπ) / 4) * (d * (d - 1) - 2) + logbeta(α, α) - (d - 2) * loggamma(η + h * (d - 1))
for k in 2:(d ... | [
190,
200
] | function lkj_onion_loginvconst(d::Integer, η::Real)
# Equation (17) in LKJ (2009 JMA)
T = float(Base.promote_typeof(d, η))
h = T(1//2)
α = η + h * d - 1
loginvconst = (2*η + d - 3)*T(logtwo) + (T(logπ) / 4) * (d * (d - 1) - 2) + logbeta(α, α) - (d - 2) * loggamma(η + h * (d - 1))
for k in 2:(d ... | function lkj_onion_loginvconst(d::Integer, η::Real)
# Equation (17) in LKJ (2009 JMA)
T = float(Base.promote_typeof(d, η))
h = T(1//2)
α = η + h * d - 1
loginvconst = (2*η + d - 3)*T(logtwo) + (T(logπ) / 4) * (d * (d - 1) - 2) + logbeta(α, α) - (d - 2) * loggamma(η + h * (d - 1))
for k in 2:(d ... | lkj_onion_loginvconst | 190 | 200 | src/matrix/lkj.jl | #CURRENT FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 1
function lkj_vine_loginvconst(d::Integer, η::Real)
# Equation (16) in LKJ (2009 JMA)
expsum = zero(η)
betasum = zero(η)
for k in 1:d - 1
α = η + 0.5(d - k - 1)
expsum += (2η - 2 + d - k) * (d - k)
betasum += (d - k) * l... |
222 | 233 | Distributions.jl | 114 | function lkj_vine_loginvconst(d::Integer, η::Real)
# Equation (16) in LKJ (2009 JMA)
expsum = zero(η)
betasum = zero(η)
for k in 1:d - 1
α = η + 0.5(d - k - 1)
expsum += (2η - 2 + d - k) * (d - k)
betasum += (d - k) * logbeta(α, α)
end
loginvconst = expsum * logtwo + bet... | function lkj_vine_loginvconst(d::Integer, η::Real)
# Equation (16) in LKJ (2009 JMA)
expsum = zero(η)
betasum = zero(η)
for k in 1:d - 1
α = η + 0.5(d - k - 1)
expsum += (2η - 2 + d - k) * (d - k)
betasum += (d - k) * logbeta(α, α)
end
loginvconst = expsum * logtwo + bet... | [
222,
233
] | function lkj_vine_loginvconst(d::Integer, η::Real)
# Equation (16) in LKJ (2009 JMA)
expsum = zero(η)
betasum = zero(η)
for k in 1:d - 1
α = η + 0.5(d - k - 1)
expsum += (2η - 2 + d - k) * (d - k)
betasum += (d - k) * logbeta(α, α)
end
loginvconst = expsum * logtwo + bet... | function lkj_vine_loginvconst(d::Integer, η::Real)
# Equation (16) in LKJ (2009 JMA)
expsum = zero(η)
betasum = zero(η)
for k in 1:d - 1
α = η + 0.5(d - k - 1)
expsum += (2η - 2 + d - k) * (d - k)
betasum += (d - k) * logbeta(α, α)
end
loginvconst = expsum * logtwo + bet... | lkj_vine_loginvconst | 222 | 233 | src/matrix/lkj.jl | #FILE: Distributions.jl/test/matrixvariates.jl
##CHUNK 1
end
for i in 1:d
for j in 1:i-1
@test pvalue_kolmogorovsmirnoff(mymats[i, j, :], ρ) >= α / L
end
end
end
@testset "LKJ integrating constant" begin
# =============
# odd non-... |
235 | 246 | Distributions.jl | 115 | function lkj_vine_loginvconst_uniform(d::Integer)
# Equation after (16) in LKJ (2009 JMA)
expsum = 0.0
betasum = 0.0
for k in 1:d - 1
α = (k + 1) / 2
expsum += k ^ 2
betasum += k * logbeta(α, α)
end
loginvconst = expsum * logtwo + betasum
return loginvconst
end | function lkj_vine_loginvconst_uniform(d::Integer)
# Equation after (16) in LKJ (2009 JMA)
expsum = 0.0
betasum = 0.0
for k in 1:d - 1
α = (k + 1) / 2
expsum += k ^ 2
betasum += k * logbeta(α, α)
end
loginvconst = expsum * logtwo + betasum
return loginvconst
end | [
235,
246
] | function lkj_vine_loginvconst_uniform(d::Integer)
# Equation after (16) in LKJ (2009 JMA)
expsum = 0.0
betasum = 0.0
for k in 1:d - 1
α = (k + 1) / 2
expsum += k ^ 2
betasum += k * logbeta(α, α)
end
loginvconst = expsum * logtwo + betasum
return loginvconst
end | function lkj_vine_loginvconst_uniform(d::Integer)
# Equation after (16) in LKJ (2009 JMA)
expsum = 0.0
betasum = 0.0
for k in 1:d - 1
α = (k + 1) / 2
expsum += k ^ 2
betasum += k * logbeta(α, α)
end
loginvconst = expsum * logtwo + betasum
return loginvconst
end | lkj_vine_loginvconst_uniform | 235 | 246 | src/matrix/lkj.jl | #FILE: Distributions.jl/test/matrixvariates.jl
##CHUNK 1
end
for i in 1:d
for j in 1:i-1
@test pvalue_kolmogorovsmirnoff(mymats[i, j, :], ρ) >= α / L
end
end
end
@testset "LKJ integrating constant" begin
# =============
# odd non-... |
209 | 230 | Distributions.jl | 116 | function _wishart_genA!(rng::AbstractRNG, A::AbstractMatrix, df::Real)
# Generate the matrix A in the Bartlett decomposition
#
# A is a lower triangular matrix, with
#
# A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j
# ~ Normal() when i > j
#
T = e... | function _wishart_genA!(rng::AbstractRNG, A::AbstractMatrix, df::Real)
# Generate the matrix A in the Bartlett decomposition
#
# A is a lower triangular matrix, with
#
# A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j
# ~ Normal() when i > j
#
T = e... | [
209,
230
] | function _wishart_genA!(rng::AbstractRNG, A::AbstractMatrix, df::Real)
# Generate the matrix A in the Bartlett decomposition
#
# A is a lower triangular matrix, with
#
# A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j
# ~ Normal() when i > j
#
T = e... | function _wishart_genA!(rng::AbstractRNG, A::AbstractMatrix, df::Real)
# Generate the matrix A in the Bartlett decomposition
#
# A is a lower triangular matrix, with
#
# A(i, j) ~ sqrt of Chisq(df - i + 1) when i == j
# ~ Normal() when i > j
#
T = e... | _wishart_genA! | 209 | 230 | src/matrix/wishart.jl | #FILE: Distributions.jl/src/matrix/inversewishart.jl
##CHUNK 1
(A .= inv(cholesky!(_rand!(rng, Wishart(d.df, inv(d.Ψ)), A))))
# -----------------------------------------------------------------------------
# Test utils
# -----------------------------------------------------------------------------
function _un... |
181 | 193 | Distributions.jl | 117 | function mean(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
end
end
return m
end | function mean(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
end
end
return m
end | [
181,
193
] | function mean(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
end
end
return m
end | function mean(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
end
end
return m
end | mean | 181 | 193 | src/mixtures/mixturemodel.jl | #FILE: Distributions.jl/perf/mixtures.jl
##CHUNK 1
v = 0.0
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
c = component(d, i)
v += pdf(c, x) * pi
end
end
return v
end
# compute the overhead of having a mixture
function evaluate_manual_pdf(distribut... |
200 | 222 | Distributions.jl | 118 | function var(d::UnivariateMixture)
K = ncomponents(d)
p = probs(d)
means = Vector{Float64}(undef, K)
m = 0.0
v = 0.0
for i = 1:K
pi = p[i]
if pi > 0.0
ci = component(d, i)
means[i] = mi = mean(ci)
m += pi * mi
v += pi * var(ci)
... | function var(d::UnivariateMixture)
K = ncomponents(d)
p = probs(d)
means = Vector{Float64}(undef, K)
m = 0.0
v = 0.0
for i = 1:K
pi = p[i]
if pi > 0.0
ci = component(d, i)
means[i] = mi = mean(ci)
m += pi * mi
v += pi * var(ci)
... | [
200,
222
] | function var(d::UnivariateMixture)
K = ncomponents(d)
p = probs(d)
means = Vector{Float64}(undef, K)
m = 0.0
v = 0.0
for i = 1:K
pi = p[i]
if pi > 0.0
ci = component(d, i)
means[i] = mi = mean(ci)
m += pi * mi
v += pi * var(ci)
... | function var(d::UnivariateMixture)
K = ncomponents(d)
p = probs(d)
means = Vector{Float64}(undef, K)
m = 0.0
v = 0.0
for i = 1:K
pi = p[i]
if pi > 0.0
ci = component(d, i)
means[i] = mi = mean(ci)
m += pi * mi
v += pi * var(ci)
... | var | 200 | 222 | src/mixtures/mixturemodel.jl | #FILE: Distributions.jl/perf/mixtures.jl
##CHUNK 1
using BenchmarkTools: @btime
import Random
using Distributions: AbstractMixtureModel, MixtureModel, LogNormal, Normal, pdf, ncomponents, probs, component, components, ContinuousUnivariateDistribution
using Test
# v0.22.1
function current_master(d::AbstractMixtureModel... |
228 | 253 | Distributions.jl | 119 | function cov(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
md = zeros(length(d))
V = zeros(length(d),length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
axpy!(pi, cov(c), V)
... | function cov(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
md = zeros(length(d))
V = zeros(length(d),length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
axpy!(pi, cov(c), V)
... | [
228,
253
] | function cov(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
md = zeros(length(d))
V = zeros(length(d),length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
axpy!(pi, cov(c), V)
... | function cov(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
md = zeros(length(d))
V = zeros(length(d),length(d))
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
axpy!(pi, mean(c), m)
axpy!(pi, cov(c), V)
... | cov | 228 | 253 | src/mixtures/mixturemodel.jl | #FILE: Distributions.jl/test/mixture.jl
##CHUNK 1
K = ncomponents(g)
pr = @inferred(probs(g))
@assert length(pr) == K
# mean
mu = 0.0
for k = 1:K
mu += pr[k] * mean(component(g, k))
end
@test @inferred(mean(g)) ≈ mu
# evaluation of cdf
cf = zeros(T, n)
for k = 1:K
... |
293 | 310 | Distributions.jl | 120 | function _mixpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
fill!(r, 0.0)
t = Array{eltype(p)}(undef, size(r))
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
if d isa UnivariateMixture
t .= Base.Fix1(pdf, componen... | function _mixpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
fill!(r, 0.0)
t = Array{eltype(p)}(undef, size(r))
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
if d isa UnivariateMixture
t .= Base.Fix1(pdf, componen... | [
293,
310
] | function _mixpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
fill!(r, 0.0)
t = Array{eltype(p)}(undef, size(r))
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
if d isa UnivariateMixture
t .= Base.Fix1(pdf, componen... | function _mixpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
fill!(r, 0.0)
t = Array{eltype(p)}(undef, size(r))
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
if d isa UnivariateMixture
t .= Base.Fix1(pdf, componen... | _mixpdf! | 293 | 310 | src/mixtures/mixturemodel.jl | #FILE: Distributions.jl/perf/mixtures.jl
##CHUNK 1
@inbounds c = component(d, i)
pdf(c, x) * pi
else
zero(eltype(p))
end
end
end
function improved_no_inbound(d, x)
p = probs(d)
return sum(enumerate(p)) do (i, pi)
if pi > 0
c = component... |
318 | 362 | Distributions.jl | 121 | function _mixlogpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
n = length(r)
Lp = Matrix{eltype(p)}(undef, n, K)
m = fill(-Inf, n)
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
lpri = log(pi)
lp_i = view(Lp, :, i... | function _mixlogpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
n = length(r)
Lp = Matrix{eltype(p)}(undef, n, K)
m = fill(-Inf, n)
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
lpri = log(pi)
lp_i = view(Lp, :, i... | [
318,
362
] | function _mixlogpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
n = length(r)
Lp = Matrix{eltype(p)}(undef, n, K)
m = fill(-Inf, n)
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
lpri = log(pi)
lp_i = view(Lp, :, i... | function _mixlogpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
K = ncomponents(d)
p = probs(d)
n = length(r)
Lp = Matrix{eltype(p)}(undef, n, K)
m = fill(-Inf, n)
@inbounds for i in eachindex(p)
pi = p[i]
if pi > 0.0
lpri = log(pi)
lp_i = view(Lp, :, i... | _mixlogpdf! | 318 | 362 | src/mixtures/mixturemodel.jl | #FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
issorted(x) && return lp
return oftype(lp, -Inf)
end
i = first(ranks)
xᵢ = first(x)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
... |
86 | 107 | Distributions.jl | 122 | function cov(d::Dirichlet)
α = d.alpha
α0 = d.alpha0
c = inv(α0^2 * (α0 + 1))
T = typeof(zero(eltype(α))^2 * c)
k = length(α)
C = Matrix{T}(undef, k, k)
for j = 1:k
αj = α[j]
αjc = αj * c
for i in 1:(j-1)
@inbounds C[i,j] = C[j,i]
end
@inb... | function cov(d::Dirichlet)
α = d.alpha
α0 = d.alpha0
c = inv(α0^2 * (α0 + 1))
T = typeof(zero(eltype(α))^2 * c)
k = length(α)
C = Matrix{T}(undef, k, k)
for j = 1:k
αj = α[j]
αjc = αj * c
for i in 1:(j-1)
@inbounds C[i,j] = C[j,i]
end
@inb... | [
86,
107
] | function cov(d::Dirichlet)
α = d.alpha
α0 = d.alpha0
c = inv(α0^2 * (α0 + 1))
T = typeof(zero(eltype(α))^2 * c)
k = length(α)
C = Matrix{T}(undef, k, k)
for j = 1:k
αj = α[j]
αjc = αj * c
for i in 1:(j-1)
@inbounds C[i,j] = C[j,i]
end
@inb... | function cov(d::Dirichlet)
α = d.alpha
α0 = d.alpha0
c = inv(α0^2 * (α0 + 1))
T = typeof(zero(eltype(α))^2 * c)
k = length(α)
C = Matrix{T}(undef, k, k)
for j = 1:k
αj = α[j]
αjc = αj * c
for i in 1:(j-1)
@inbounds C[i,j] = C[j,i]
end
@inb... | cov | 86 | 107 | src/multivariate/dirichlet.jl | #FILE: Distributions.jl/src/multivariate/dirichletmultinomial.jl
##CHUNK 1
function var(d::DirichletMultinomial{T}) where T <: Real
v = fill(d.n * (d.n + d.α0) / (1 + d.α0), length(d))
p = d.α / d.α0
for i in eachindex(v)
@inbounds v[i] *= p[i] * (1 - p[i])
end
v
end
function cov(d::Dirichle... |
43 | 59 | Distributions.jl | 123 | function JointOrderStatistics(
dist::ContinuousUnivariateDistribution,
n::Int,
ranks::Union{AbstractVector{Int},Tuple{Int,Vararg{Int}}}=Base.OneTo(n);
check_args::Bool=true,
)
@check_args(
JointOrderStatistics,
(n, n ≥ 1, "`n` must be a positive intege... | function JointOrderStatistics(
dist::ContinuousUnivariateDistribution,
n::Int,
ranks::Union{AbstractVector{Int},Tuple{Int,Vararg{Int}}}=Base.OneTo(n);
check_args::Bool=true,
)
@check_args(
JointOrderStatistics,
(n, n ≥ 1, "`n` must be a positive intege... | [
43,
59
] | function JointOrderStatistics(
dist::ContinuousUnivariateDistribution,
n::Int,
ranks::Union{AbstractVector{Int},Tuple{Int,Vararg{Int}}}=Base.OneTo(n);
check_args::Bool=true,
)
@check_args(
JointOrderStatistics,
(n, n ≥ 1, "`n` must be a positive intege... | function JointOrderStatistics(
dist::ContinuousUnivariateDistribution,
n::Int,
ranks::Union{AbstractVector{Int},Tuple{Int,Vararg{Int}}}=Base.OneTo(n);
check_args::Bool=true,
)
@check_args(
JointOrderStatistics,
(n, n ≥ 1, "`n` must be a positive intege... | JointOrderStatistics | 43 | 59 | src/multivariate/jointorderstatistics.jl | #FILE: Distributions.jl/src/univariate/orderstatistic.jl
##CHUNK 1
For the joint distribution of a subset of order statistics, use
[`JointOrderStatistics`](@ref) instead.
## Examples
```julia
OrderStatistic(Cauchy(), 10, 1) # distribution of the sample minimum
OrderStatistic(DiscreteUniform(10), 10, 10) ... |
74 | 85 | Distributions.jl | 124 | function insupport(d::JointOrderStatistics, x::AbstractVector)
length(d) == length(x) || return false
xi, state = iterate(x) # at least one element!
dist = d.dist
insupport(dist, xi) || return false
while (xj_state = iterate(x, state)) !== nothing
xj, state = xj_state
xj ≥ xi && insu... | function insupport(d::JointOrderStatistics, x::AbstractVector)
length(d) == length(x) || return false
xi, state = iterate(x) # at least one element!
dist = d.dist
insupport(dist, xi) || return false
while (xj_state = iterate(x, state)) !== nothing
xj, state = xj_state
xj ≥ xi && insu... | [
74,
85
] | function insupport(d::JointOrderStatistics, x::AbstractVector)
length(d) == length(x) || return false
xi, state = iterate(x) # at least one element!
dist = d.dist
insupport(dist, xi) || return false
while (xj_state = iterate(x, state)) !== nothing
xj, state = xj_state
xj ≥ xi && insu... | function insupport(d::JointOrderStatistics, x::AbstractVector)
length(d) == length(x) || return false
xi, state = iterate(x) # at least one element!
dist = d.dist
insupport(dist, xi) || return false
while (xj_state = iterate(x, state)) !== nothing
xj, state = xj_state
xj ≥ xi && insu... | insupport | 74 | 85 | src/multivariate/jointorderstatistics.jl | #FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
"""
insupport(d::UnivariateDistribution, x::Any)
When `x` is a scalar, it returns whether x is within the support of `d`
(e.g., `insupport(d, x) = minimum(d) <= x <= maximum(d)`).
When `x` is an array, it returns whether every element in x is within the support... |
94 | 119 | Distributions.jl | 125 | function logpdf(d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
ranks = d.ranks
lp = loglikelihood(d.dist, x)
T = typeof(lp)
lp += loggamma(T(n + 1))
if length(ranks) == n
issorted(x) && return lp
return oftype(lp, -Inf)
end
i = first(ranks)
xᵢ = first(x)
... | function logpdf(d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
ranks = d.ranks
lp = loglikelihood(d.dist, x)
T = typeof(lp)
lp += loggamma(T(n + 1))
if length(ranks) == n
issorted(x) && return lp
return oftype(lp, -Inf)
end
i = first(ranks)
xᵢ = first(x)
... | [
94,
119
] | function logpdf(d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
ranks = d.ranks
lp = loglikelihood(d.dist, x)
T = typeof(lp)
lp += loggamma(T(n + 1))
if length(ranks) == n
issorted(x) && return lp
return oftype(lp, -Inf)
end
i = first(ranks)
xᵢ = first(x)
... | function logpdf(d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
ranks = d.ranks
lp = loglikelihood(d.dist, x)
T = typeof(lp)
lp += loggamma(T(n + 1))
if length(ranks) == n
issorted(x) && return lp
return oftype(lp, -Inf)
end
i = first(ranks)
xᵢ = first(x)
... | logpdf | 94 | 119 | src/multivariate/jointorderstatistics.jl | #FILE: Distributions.jl/test/multivariate/jointorderstatistics.jl
##CHUNK 1
@test !insupport(d, fill(NaN, length(x)))
end
@testset "pdf/logpdf" begin
x = convert(Vector{T}, sort(rand(dist, length(r))))
@test @inferred(logpdf(d, x)) isa T
@test @inferred(p... |
128 | 168 | Distributions.jl | 126 | function _rand!(rng::AbstractRNG, d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
if n == length(d.ranks) # ranks == 1:n
# direct method, slower than inversion method for large `n` and distributions with
# fast quantile function or that use inversion sampling
rand!(rng, d.di... | function _rand!(rng::AbstractRNG, d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
if n == length(d.ranks) # ranks == 1:n
# direct method, slower than inversion method for large `n` and distributions with
# fast quantile function or that use inversion sampling
rand!(rng, d.di... | [
128,
168
] | function _rand!(rng::AbstractRNG, d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
if n == length(d.ranks) # ranks == 1:n
# direct method, slower than inversion method for large `n` and distributions with
# fast quantile function or that use inversion sampling
rand!(rng, d.di... | function _rand!(rng::AbstractRNG, d::JointOrderStatistics, x::AbstractVector{<:Real})
n = d.n
if n == length(d.ranks) # ranks == 1:n
# direct method, slower than inversion method for large `n` and distributions with
# fast quantile function or that use inversion sampling
rand!(rng, d.di... | _rand! | 128 | 168 | src/multivariate/jointorderstatistics.jl | #FILE: Distributions.jl/src/univariate/continuous/pgeneralizedgaussian.jl
##CHUNK 1
return log1pexp(logcdf(d, r)) - logtwo
end
end
function quantile(d::PGeneralizedGaussian, q::Real)
μ, α, p = params(d)
inv_p = inv(p)
r = 2 * q - 1
z = α * quantile(Gamma(inv_p, 1), abs(r))^inv_p
return ... |
120 | 130 | Distributions.jl | 127 | function entropy(d::Multinomial)
n, p = params(d)
s = -loggamma(n+1) + n*entropy(p)
for pr in p
b = Binomial(n, pr)
for x in 0:n
s += pdf(b, x) * loggamma(x+1)
end
end
return s
end | function entropy(d::Multinomial)
n, p = params(d)
s = -loggamma(n+1) + n*entropy(p)
for pr in p
b = Binomial(n, pr)
for x in 0:n
s += pdf(b, x) * loggamma(x+1)
end
end
return s
end | [
120,
130
] | function entropy(d::Multinomial)
n, p = params(d)
s = -loggamma(n+1) + n*entropy(p)
for pr in p
b = Binomial(n, pr)
for x in 0:n
s += pdf(b, x) * loggamma(x+1)
end
end
return s
end | function entropy(d::Multinomial)
n, p = params(d)
s = -loggamma(n+1) + n*entropy(p)
for pr in p
b = Binomial(n, pr)
for x in 0:n
s += pdf(b, x) * loggamma(x+1)
end
end
return s
end | entropy | 120 | 130 | src/multivariate/multinomial.jl | #FILE: Distributions.jl/src/univariate/discrete/binomial.jl
##CHUNK 1
end
function kurtosis(d::Binomial)
n, p = params(d)
u = p * (1 - p)
(1 - 6u) / (n * u)
end
function entropy(d::Binomial; approx::Bool=false)
n, p1 = params(d)
(p1 == 0 || p1 == 1 || n == 0) && return zero(p1)
p0 = 1 - p1
... |
135 | 147 | Distributions.jl | 128 | function insupport(d::Multinomial, x::AbstractVector{T}) where T<:Real
k = length(d)
length(x) == k || return false
s = 0.0
for i = 1:k
@inbounds xi = x[i]
if !(isinteger(xi) && xi >= 0)
return false
end
s += xi
end
return s == ntrials(d) # integer co... | function insupport(d::Multinomial, x::AbstractVector{T}) where T<:Real
k = length(d)
length(x) == k || return false
s = 0.0
for i = 1:k
@inbounds xi = x[i]
if !(isinteger(xi) && xi >= 0)
return false
end
s += xi
end
return s == ntrials(d) # integer co... | [
135,
147
] | function insupport(d::Multinomial, x::AbstractVector{T}) where T<:Real
k = length(d)
length(x) == k || return false
s = 0.0
for i = 1:k
@inbounds xi = x[i]
if !(isinteger(xi) && xi >= 0)
return false
end
s += xi
end
return s == ntrials(d) # integer co... | function insupport(d::Multinomial, x::AbstractVector{T}) where T<:Real
k = length(d)
length(x) == k || return false
s = 0.0
for i = 1:k
@inbounds xi = x[i]
if !(isinteger(xi) && xi >= 0)
return false
end
s += xi
end
return s == ntrials(d) # integer co... | insupport | 135 | 147 | src/multivariate/multinomial.jl | #FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
# trivial cases
x < minimum(d) && return one(P)
x >= maximum(d) && return zero(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < div(n, 2)
... |
149 | 163 | Distributions.jl | 129 | function _logpdf(d::Multinomial, x::AbstractVector{T}) where T<:Real
p = probs(d)
n = ntrials(d)
S = eltype(p)
R = promote_type(T, S)
insupport(d,x) || return -R(Inf)
s = R(loggamma(n + 1))
for i = 1:length(p)
@inbounds xi = x[i]
@inbounds p_i = p[i]
s -= R(loggamma(R... | function _logpdf(d::Multinomial, x::AbstractVector{T}) where T<:Real
p = probs(d)
n = ntrials(d)
S = eltype(p)
R = promote_type(T, S)
insupport(d,x) || return -R(Inf)
s = R(loggamma(n + 1))
for i = 1:length(p)
@inbounds xi = x[i]
@inbounds p_i = p[i]
s -= R(loggamma(R... | [
149,
163
] | function _logpdf(d::Multinomial, x::AbstractVector{T}) where T<:Real
p = probs(d)
n = ntrials(d)
S = eltype(p)
R = promote_type(T, S)
insupport(d,x) || return -R(Inf)
s = R(loggamma(n + 1))
for i = 1:length(p)
@inbounds xi = x[i]
@inbounds p_i = p[i]
s -= R(loggamma(R... | function _logpdf(d::Multinomial, x::AbstractVector{T}) where T<:Real
p = probs(d)
n = ntrials(d)
S = eltype(p)
R = promote_type(T, S)
insupport(d,x) || return -R(Inf)
s = R(loggamma(n + 1))
for i = 1:length(p)
@inbounds xi = x[i]
@inbounds p_i = p[i]
s -= R(loggamma(R... | _logpdf | 149 | 163 | src/multivariate/multinomial.jl | #FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
function _mixlogpdf1(d::AbstractMixtureModel, x)
p = probs(d)
lp = logsumexp(log(pi) + logpdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return lp
end
function _mixlogpdf!(r::AbstractArray, d::AbstractMixtureModel, x)
... |
100 | 125 | Distributions.jl | 130 | function _vmf_estkappa(p::Int, ρ::Float64)
# Using the fixed-point iteration algorithm in the following paper:
#
# Akihiro Tanabe, Kenji Fukumizu, and Shigeyuki Oba, Takashi Takenouchi, and Shin Ishii
# Parameter estimation for von Mises-Fisher distributions.
# Computational Statistics, 2007, ... | function _vmf_estkappa(p::Int, ρ::Float64)
# Using the fixed-point iteration algorithm in the following paper:
#
# Akihiro Tanabe, Kenji Fukumizu, and Shigeyuki Oba, Takashi Takenouchi, and Shin Ishii
# Parameter estimation for von Mises-Fisher distributions.
# Computational Statistics, 2007, ... | [
100,
125
] | function _vmf_estkappa(p::Int, ρ::Float64)
# Using the fixed-point iteration algorithm in the following paper:
#
# Akihiro Tanabe, Kenji Fukumizu, and Shigeyuki Oba, Takashi Takenouchi, and Shin Ishii
# Parameter estimation for von Mises-Fisher distributions.
# Computational Statistics, 2007, ... | function _vmf_estkappa(p::Int, ρ::Float64)
# Using the fixed-point iteration algorithm in the following paper:
#
# Akihiro Tanabe, Kenji Fukumizu, and Shigeyuki Oba, Takashi Takenouchi, and Shin Ishii
# Parameter estimation for von Mises-Fisher distributions.
# Computational Statistics, 2007, ... | _vmf_estkappa | 100 | 125 | src/multivariate/vonmisesfisher.jl | #FILE: Distributions.jl/src/samplers/vonmises.jl
##CHUNK 1
struct VonMisesSampler <: Sampleable{Univariate,Continuous}
μ::Float64
κ::Float64
r::Float64
function VonMisesSampler(μ::Float64, κ::Float64)
τ = 1.0 + sqrt(1.0 + 4 * abs2(κ))
ρ = (τ - sqrt(2.0 * τ)) / (2.0 * κ)
new(μ, ... |
3 | 20 | Distributions.jl | 131 | function binompvec(n::Int, p::Float64)
pv = Vector{Float64}(undef, n+1)
if p == 0.0
fill!(pv, 0.0)
pv[1] = 1.0
elseif p == 1.0
fill!(pv, 0.0)
pv[n+1] = 1.0
else
q = 1.0 - p
a = p / q
@inbounds pv[1] = pk = q ^ n
for k = 1:n
@inb... | function binompvec(n::Int, p::Float64)
pv = Vector{Float64}(undef, n+1)
if p == 0.0
fill!(pv, 0.0)
pv[1] = 1.0
elseif p == 1.0
fill!(pv, 0.0)
pv[n+1] = 1.0
else
q = 1.0 - p
a = p / q
@inbounds pv[1] = pk = q ^ n
for k = 1:n
@inb... | [
3,
20
] | function binompvec(n::Int, p::Float64)
pv = Vector{Float64}(undef, n+1)
if p == 0.0
fill!(pv, 0.0)
pv[1] = 1.0
elseif p == 1.0
fill!(pv, 0.0)
pv[n+1] = 1.0
else
q = 1.0 - p
a = p / q
@inbounds pv[1] = pk = q ^ n
for k = 1:n
@inb... | function binompvec(n::Int, p::Float64)
pv = Vector{Float64}(undef, n+1)
if p == 0.0
fill!(pv, 0.0)
pv[1] = 1.0
elseif p == 1.0
fill!(pv, 0.0)
pv[n+1] = 1.0
else
q = 1.0 - p
a = p / q
@inbounds pv[1] = pk = q ^ n
for k = 1:n
@inb... | binompvec | 3 | 20 | src/samplers/binomial.jl | #FILE: Distributions.jl/src/univariate/discrete/poissonbinomial.jl
##CHUNK 1
kp1 = k + 1
for j in 1:(i - 1)
A[j, k] = pi * A[j, k] + qi * A[j, kp1]
end
for j in (i+1):n
A[j, k] = pi * A[j, k] + qi * A[j, kp1]
end
end
... |
18 | 28 | Distributions.jl | 132 | function rand(rng::AbstractRNG, s::CategoricalDirectSampler)
p = s.prob
n = length(p)
i = 1
c = p[1]
u = rand(rng)
while c < u && i < n
c += p[i += 1]
end
return i
end | function rand(rng::AbstractRNG, s::CategoricalDirectSampler)
p = s.prob
n = length(p)
i = 1
c = p[1]
u = rand(rng)
while c < u && i < n
c += p[i += 1]
end
return i
end | [
18,
28
] | function rand(rng::AbstractRNG, s::CategoricalDirectSampler)
p = s.prob
n = length(p)
i = 1
c = p[1]
u = rand(rng)
while c < u && i < n
c += p[i += 1]
end
return i
end | function rand(rng::AbstractRNG, s::CategoricalDirectSampler)
p = s.prob
n = length(p)
i = 1
c = p[1]
u = rand(rng)
while c < u && i < n
c += p[i += 1]
end
return i
end | rand | 18 | 28 | src/samplers/categorical.jl | #FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
isapprox(probs(c1), probs(c2); kwargs...)
end
# Sampling
function rand(rng::AbstractRNG, d::DiscreteNonParametric)
x = support(d)
p = probs(d)
n = length(p)
draw = rand(rng, float(eltype(p)))
cp = p[1]
i... |
78 | 119 | Distributions.jl | 133 | function rand(rng::AbstractRNG, s::GammaGDSampler)
# Step 2
t = randn(rng)
x = s.s + 0.5t
t >= 0.0 && return x*x*s.scale
# Step 3
u = rand(rng)
s.d*u <= t*t*t && return x*x*s.scale
# Step 5
if x > 0.0
# Step 6
q = calc_q(s, t)
# Step 7
log1p(-u) <= q... | function rand(rng::AbstractRNG, s::GammaGDSampler)
# Step 2
t = randn(rng)
x = s.s + 0.5t
t >= 0.0 && return x*x*s.scale
# Step 3
u = rand(rng)
s.d*u <= t*t*t && return x*x*s.scale
# Step 5
if x > 0.0
# Step 6
q = calc_q(s, t)
# Step 7
log1p(-u) <= q... | [
78,
119
] | function rand(rng::AbstractRNG, s::GammaGDSampler)
# Step 2
t = randn(rng)
x = s.s + 0.5t
t >= 0.0 && return x*x*s.scale
# Step 3
u = rand(rng)
s.d*u <= t*t*t && return x*x*s.scale
# Step 5
if x > 0.0
# Step 6
q = calc_q(s, t)
# Step 7
log1p(-u) <= q... | function rand(rng::AbstractRNG, s::GammaGDSampler)
# Step 2
t = randn(rng)
x = s.s + 0.5t
t >= 0.0 && return x*x*s.scale
# Step 3
u = rand(rng)
s.d*u <= t*t*t && return x*x*s.scale
# Step 5
if x > 0.0
# Step 6
q = calc_q(s, t)
# Step 7
log1p(-u) <= q... | rand | 78 | 119 | src/samplers/gamma.jl | #FILE: Distributions.jl/src/samplers/vonmises.jl
##CHUNK 1
u = 4 * (d + e)
break
end
end
z = (1.0 - t) / (1.0 + t)
f = (1.0 + s.r * z) / (s.r + z)
c = s.κ * (s.r - f)
if c * (2.0 - c) > u || log(c / u) + ... |
173 | 183 | Distributions.jl | 134 | function GammaMTSampler(g::Gamma)
# Setup (Step 1)
d = shape(g) - 1//3
c = inv(3 * sqrt(d))
# Pre-compute scaling factor
κ = d * scale(g)
# We also pre-compute the factor in the squeeze function
return GammaMTSampler(promote(d, c, κ, 331//10_000)...)
end | function GammaMTSampler(g::Gamma)
# Setup (Step 1)
d = shape(g) - 1//3
c = inv(3 * sqrt(d))
# Pre-compute scaling factor
κ = d * scale(g)
# We also pre-compute the factor in the squeeze function
return GammaMTSampler(promote(d, c, κ, 331//10_000)...)
end | [
173,
183
] | function GammaMTSampler(g::Gamma)
# Setup (Step 1)
d = shape(g) - 1//3
c = inv(3 * sqrt(d))
# Pre-compute scaling factor
κ = d * scale(g)
# We also pre-compute the factor in the squeeze function
return GammaMTSampler(promote(d, c, κ, 331//10_000)...)
end | function GammaMTSampler(g::Gamma)
# Setup (Step 1)
d = shape(g) - 1//3
c = inv(3 * sqrt(d))
# Pre-compute scaling factor
κ = d * scale(g)
# We also pre-compute the factor in the squeeze function
return GammaMTSampler(promote(d, c, κ, 331//10_000)...)
end | GammaMTSampler | 173 | 183 | src/samplers/gamma.jl | #FILE: Distributions.jl/src/univariate/continuous/gamma.jl
##CHUNK 1
insupport(Gamma, x) ? (d.α - 1) / x - 1 / d.θ : zero(T)
function rand(rng::AbstractRNG, d::Gamma)
if shape(d) < 1.0
# TODO: shape(d) = 0.5 : use scaled chisq
return rand(rng, GammaIPSampler(d))
elseif shape(d) == 1.0
... |
1 | 40 | Distributions.jl | 135 | function multinom_rand!(rng::AbstractRNG, n::Int, p::AbstractVector{<:Real},
x::AbstractVector{<:Real})
k = length(p)
length(x) == k || throw(DimensionMismatch("Invalid argument dimension."))
z = zero(eltype(p))
rp = oftype(z + z, 1) # remaining total probability (widens type i... | function multinom_rand!(rng::AbstractRNG, n::Int, p::AbstractVector{<:Real},
x::AbstractVector{<:Real})
k = length(p)
length(x) == k || throw(DimensionMismatch("Invalid argument dimension."))
z = zero(eltype(p))
rp = oftype(z + z, 1) # remaining total probability (widens type i... | [
1,
40
] | function multinom_rand!(rng::AbstractRNG, n::Int, p::AbstractVector{<:Real},
x::AbstractVector{<:Real})
k = length(p)
length(x) == k || throw(DimensionMismatch("Invalid argument dimension."))
z = zero(eltype(p))
rp = oftype(z + z, 1) # remaining total probability (widens type i... | function multinom_rand!(rng::AbstractRNG, n::Int, p::AbstractVector{<:Real},
x::AbstractVector{<:Real})
k = length(p)
length(x) == k || throw(DimensionMismatch("Invalid argument dimension."))
z = zero(eltype(p))
rp = oftype(z + z, 1) # remaining total probability (widens type i... | multinom_rand! | 1 | 40 | src/samplers/multinomial.jl | #FILE: Distributions.jl/src/univariate/discrete/binomial.jl
##CHUNK 1
z = zero(eltype(x))
ns = z + z # possibly widened and different from `z`, e.g., if `z = true`
for xi in x
0 <= xi <= n || throw(DomainError(xi, "samples must be between 0 and $n"))
ns += xi
end
BinomialStats(ns, le... |
52 | 67 | Distributions.jl | 136 | function _rand!(rng::AbstractRNG, s::MultinomialSampler,
x::AbstractVector{<:Real})
n = s.n
k = length(s)
if n^2 > k
multinom_rand!(rng, n, s.prob, x)
else
# Use an alias table
fill!(x, zero(eltype(x)))
a = s.alias
for i = 1:n
x[rand(rn... | function _rand!(rng::AbstractRNG, s::MultinomialSampler,
x::AbstractVector{<:Real})
n = s.n
k = length(s)
if n^2 > k
multinom_rand!(rng, n, s.prob, x)
else
# Use an alias table
fill!(x, zero(eltype(x)))
a = s.alias
for i = 1:n
x[rand(rn... | [
52,
67
] | function _rand!(rng::AbstractRNG, s::MultinomialSampler,
x::AbstractVector{<:Real})
n = s.n
k = length(s)
if n^2 > k
multinom_rand!(rng, n, s.prob, x)
else
# Use an alias table
fill!(x, zero(eltype(x)))
a = s.alias
for i = 1:n
x[rand(rn... | function _rand!(rng::AbstractRNG, s::MultinomialSampler,
x::AbstractVector{<:Real})
n = s.n
k = length(s)
if n^2 > k
multinom_rand!(rng, n, s.prob, x)
else
# Use an alias table
fill!(x, zero(eltype(x)))
a = s.alias
for i = 1:n
x[rand(rn... | _rand! | 52 | 67 | src/samplers/multinomial.jl | #FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
n = ntrials(d)
S = eltype(p)
R = promote_type(T, S)
insupport(d,x) || return -R(Inf)
s = R(loggamma(n + 1))
for i = 1:length(p)
@inbounds xi = x[i]
@inbounds p_i = p[i]
s -= R(loggamma(R(xi) + 1))
s... |
16 | 69 | Distributions.jl | 137 | function DiscreteDistributionTable(probs::Vector{T}) where T <: Real
# Cache the cardinality of the outcome set
n = length(probs)
# Convert all Float64's into integers
vals = Vector{Int64}(undef, n)
for i in 1:n
vals[i] = round(Int, probs[i] * 64^9)
end
# Allocate digit table and d... | function DiscreteDistributionTable(probs::Vector{T}) where T <: Real
# Cache the cardinality of the outcome set
n = length(probs)
# Convert all Float64's into integers
vals = Vector{Int64}(undef, n)
for i in 1:n
vals[i] = round(Int, probs[i] * 64^9)
end
# Allocate digit table and d... | [
16,
69
] | function DiscreteDistributionTable(probs::Vector{T}) where T <: Real
# Cache the cardinality of the outcome set
n = length(probs)
# Convert all Float64's into integers
vals = Vector{Int64}(undef, n)
for i in 1:n
vals[i] = round(Int, probs[i] * 64^9)
end
# Allocate digit table and d... | function DiscreteDistributionTable(probs::Vector{T}) where T <: Real
# Cache the cardinality of the outcome set
n = length(probs)
# Convert all Float64's into integers
vals = Vector{Int64}(undef, n)
for i in 1:n
vals[i] = round(Int, probs[i] * 64^9)
end
# Allocate digit table and d... | DiscreteDistributionTable | 16 | 69 | src/samplers/obsoleted.jl | #FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
MultinomialStats(n::Int, scnts::Vector{Float64}, tw::Real) = new(n, scnts, Float64(tw))
end
function suffstats(::Type{<:Multinomial}, x::Matrix{T}) where T<:Real
K = size(x, 1)
n::T = zero(T)
scnts = zeros(K)
for j = 1:size(x,2)
... |
71 | 87 | Distributions.jl | 138 | function rand(table::DiscreteDistributionTable)
# 64^9 - 1 == 0x003fffffffffffff
i = rand(1:(64^9 - 1))
# if i == 64^9
# return table.table[9][rand(1:length(table.table[9]))]
# end
bound = 1
while i > table.bounds[bound] && bound < 9
bound += 1
end
if bound > 1
inde... | function rand(table::DiscreteDistributionTable)
# 64^9 - 1 == 0x003fffffffffffff
i = rand(1:(64^9 - 1))
# if i == 64^9
# return table.table[9][rand(1:length(table.table[9]))]
# end
bound = 1
while i > table.bounds[bound] && bound < 9
bound += 1
end
if bound > 1
inde... | [
71,
87
] | function rand(table::DiscreteDistributionTable)
# 64^9 - 1 == 0x003fffffffffffff
i = rand(1:(64^9 - 1))
# if i == 64^9
# return table.table[9][rand(1:length(table.table[9]))]
# end
bound = 1
while i > table.bounds[bound] && bound < 9
bound += 1
end
if bound > 1
inde... | function rand(table::DiscreteDistributionTable)
# 64^9 - 1 == 0x003fffffffffffff
i = rand(1:(64^9 - 1))
# if i == 64^9
# return table.table[9][rand(1:length(table.table[9]))]
# end
bound = 1
while i > table.bounds[bound] && bound < 9
bound += 1
end
if bound > 1
inde... | rand | 71 | 87 | src/samplers/obsoleted.jl | #FILE: Distributions.jl/test/truncated/discrete_uniform.jl
##CHUNK 1
using Distributions, Test
@testset "truncated DiscreteUniform" begin
# just test equivalence of truncation results
bounds = [(1, 10), (-3, 7), (-5, -2)]
@testset "lower=$lower, upper=$upper" for (lower, upper) in bounds
d = Discre... |
22 | 32 | Distributions.jl | 139 | function rand(rng::AbstractRNG, s::PoissonCountSampler)
μ = s.μ
T = typeof(μ)
n = 0
c = randexp(rng, T)
while c < μ
n += 1
c += randexp(rng, T)
end
return n
end | function rand(rng::AbstractRNG, s::PoissonCountSampler)
μ = s.μ
T = typeof(μ)
n = 0
c = randexp(rng, T)
while c < μ
n += 1
c += randexp(rng, T)
end
return n
end | [
22,
32
] | function rand(rng::AbstractRNG, s::PoissonCountSampler)
μ = s.μ
T = typeof(μ)
n = 0
c = randexp(rng, T)
while c < μ
n += 1
c += randexp(rng, T)
end
return n
end | function rand(rng::AbstractRNG, s::PoissonCountSampler)
μ = s.μ
T = typeof(μ)
n = 0
c = randexp(rng, T)
while c < μ
n += 1
c += randexp(rng, T)
end
return n
end | rand | 22 | 32 | src/samplers/poisson.jl | #FILE: Distributions.jl/src/univariate/discrete/skellam.jl
##CHUNK 1
function cdf(d::Skellam, t::Integer)
μ1, μ2 = params(d)
return if t < 0
nchisqcdf(-2*t, 2*μ1, 2*μ2)
else
1 - nchisqcdf(2*(t+1), 2*μ2, 2*μ1)
end
end
#### Sampling
rand(rng::AbstractRNG, d::Skellam) =
rand(rng, Poiss... |
112 | 138 | Distributions.jl | 140 | function procf(μ, K::Int, s)
# can be pre-computed, but does not seem to affect performance
ω = 0.3989422804014327/s
b1 = 0.041666666666666664/μ
b2 = 0.3*b1*b1
c3 = 0.14285714285714285*b1*b2
c2 = b2 - 15 * c3
c1 = b1 - 6 * b2 + 45 * c3
c0 = 1 - b1 + 3 * b2 - 15 * c3
if K < 10
... | function procf(μ, K::Int, s)
# can be pre-computed, but does not seem to affect performance
ω = 0.3989422804014327/s
b1 = 0.041666666666666664/μ
b2 = 0.3*b1*b1
c3 = 0.14285714285714285*b1*b2
c2 = b2 - 15 * c3
c1 = b1 - 6 * b2 + 45 * c3
c0 = 1 - b1 + 3 * b2 - 15 * c3
if K < 10
... | [
112,
138
] | function procf(μ, K::Int, s)
# can be pre-computed, but does not seem to affect performance
ω = 0.3989422804014327/s
b1 = 0.041666666666666664/μ
b2 = 0.3*b1*b1
c3 = 0.14285714285714285*b1*b2
c2 = b2 - 15 * c3
c1 = b1 - 6 * b2 + 45 * c3
c0 = 1 - b1 + 3 * b2 - 15 * c3
if K < 10
... | function procf(μ, K::Int, s)
# can be pre-computed, but does not seem to affect performance
ω = 0.3989422804014327/s
b1 = 0.041666666666666664/μ
b2 = 0.3*b1*b1
c3 = 0.14285714285714285*b1*b2
c2 = b2 - 15 * c3
c1 = b1 - 6 * b2 + 45 * c3
c0 = 1 - b1 + 3 * b2 - 15 * c3
if K < 10
... | procf | 112 | 138 | src/samplers/poisson.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
return σ^2 * (g(d, 2) - g(d, 1) ^ 2) / ξ^2
else
return T(Inf)
end
end
function skewness(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
ret... |
18 | 46 | Distributions.jl | 141 | function rand(rng::AbstractRNG, s::VonMisesSampler)
f = 0.0
local x::Float64
if s.κ > 700.0
x = s.μ + randn(rng) / sqrt(s.κ)
else
while true
t, u = 0.0, 0.0
while true
d = abs2(rand(rng) - 0.5)
e = abs2(rand(rng) - 0.5)
... | function rand(rng::AbstractRNG, s::VonMisesSampler)
f = 0.0
local x::Float64
if s.κ > 700.0
x = s.μ + randn(rng) / sqrt(s.κ)
else
while true
t, u = 0.0, 0.0
while true
d = abs2(rand(rng) - 0.5)
e = abs2(rand(rng) - 0.5)
... | [
18,
46
] | function rand(rng::AbstractRNG, s::VonMisesSampler)
f = 0.0
local x::Float64
if s.κ > 700.0
x = s.μ + randn(rng) / sqrt(s.κ)
else
while true
t, u = 0.0, 0.0
while true
d = abs2(rand(rng) - 0.5)
e = abs2(rand(rng) - 0.5)
... | function rand(rng::AbstractRNG, s::VonMisesSampler)
f = 0.0
local x::Float64
if s.κ > 700.0
x = s.μ + randn(rng) / sqrt(s.κ)
else
while true
t, u = 0.0, 0.0
while true
d = abs2(rand(rng) - 0.5)
e = abs2(rand(rng) - 0.5)
... | rand | 18 | 46 | src/samplers/vonmises.jl | #FILE: Distributions.jl/src/truncated/normal.jl
##CHUNK 1
u = rand(rng)
if u < exp(-0.5 * (r - a)^2) && r < ub
return r
end
end
elseif ub < 0 && ub - lb > 2.0 / (-ub + sqrt(ub^2 + 4.0)) * exp((ub^2 + ub * sqrt(ub^2 + 4.0)) / 4.0)
... |
30 | 47 | Distributions.jl | 142 | function _rand!(rng::AbstractRNG, spl::VonMisesFisherSampler, x::AbstractVector)
w = _vmf_genw(rng, spl)
p = spl.p
x[1] = w
s = 0.0
@inbounds for i = 2:p
x[i] = xi = randn(rng)
s += abs2(xi)
end
# normalize x[2:p]
r = sqrt((1.0 - abs2(w)) / s)
@inbounds for i = 2:p
... | function _rand!(rng::AbstractRNG, spl::VonMisesFisherSampler, x::AbstractVector)
w = _vmf_genw(rng, spl)
p = spl.p
x[1] = w
s = 0.0
@inbounds for i = 2:p
x[i] = xi = randn(rng)
s += abs2(xi)
end
# normalize x[2:p]
r = sqrt((1.0 - abs2(w)) / s)
@inbounds for i = 2:p
... | [
30,
47
] | function _rand!(rng::AbstractRNG, spl::VonMisesFisherSampler, x::AbstractVector)
w = _vmf_genw(rng, spl)
p = spl.p
x[1] = w
s = 0.0
@inbounds for i = 2:p
x[i] = xi = randn(rng)
s += abs2(xi)
end
# normalize x[2:p]
r = sqrt((1.0 - abs2(w)) / s)
@inbounds for i = 2:p
... | function _rand!(rng::AbstractRNG, spl::VonMisesFisherSampler, x::AbstractVector)
w = _vmf_genw(rng, spl)
p = spl.p
x[1] = w
s = 0.0
@inbounds for i = 2:p
x[i] = xi = randn(rng)
s += abs2(xi)
end
# normalize x[2:p]
r = sqrt((1.0 - abs2(w)) / s)
@inbounds for i = 2:p
... | _rand! | 30 | 47 | src/samplers/vonmisesfisher.jl | #FILE: Distributions.jl/test/multivariate/vonmisesfisher.jl
##CHUNK 1
end
return X
end
function test_vmf_rot(p::Int, rng::Union{AbstractRNG, Missing} = missing)
if ismissing(rng)
μ = randn(p)
x = randn(p)
else
μ = randn(rng, p)
x = randn(rng, p)
end
κ = norm(μ)
... |
59 | 69 | Distributions.jl | 143 | function _vmf_genwp(rng::AbstractRNG, p, b, x0, c, κ)
r = (p - 1) / 2.0
betad = Beta(r, r)
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 - b) * z)
while κ * w + (p - 1) * log(1 - x0 * w) - c < log(rand(rng))
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 ... | function _vmf_genwp(rng::AbstractRNG, p, b, x0, c, κ)
r = (p - 1) / 2.0
betad = Beta(r, r)
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 - b) * z)
while κ * w + (p - 1) * log(1 - x0 * w) - c < log(rand(rng))
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 ... | [
59,
69
] | function _vmf_genwp(rng::AbstractRNG, p, b, x0, c, κ)
r = (p - 1) / 2.0
betad = Beta(r, r)
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 - b) * z)
while κ * w + (p - 1) * log(1 - x0 * w) - c < log(rand(rng))
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 ... | function _vmf_genwp(rng::AbstractRNG, p, b, x0, c, κ)
r = (p - 1) / 2.0
betad = Beta(r, r)
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 - b) * z)
while κ * w + (p - 1) * log(1 - x0 * w) - c < log(rand(rng))
z = rand(rng, betad)
w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 ... | _vmf_genwp | 59 | 69 | src/samplers/vonmisesfisher.jl | #FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
if x + y ≤ one(x)
if (x + y > 0)
return x / (x + y)
else
logX = log(u) / α
logY = log(v) / β
logM = logX > logY ? logX : logY
... |
87 | 102 | Distributions.jl | 144 | function _vmf_householder_vec(μ::Vector{Float64})
# assuming μ is a unit-vector (which it should be)
# can compute v in a single pass over μ
p = length(μ)
v = similar(μ)
v[1] = μ[1] - 1.0
s = sqrt(-2*v[1])
v[1] /= s
@inbounds for i in 2:p
v[i] = μ[i] / s
end
return v
... | function _vmf_householder_vec(μ::Vector{Float64})
# assuming μ is a unit-vector (which it should be)
# can compute v in a single pass over μ
p = length(μ)
v = similar(μ)
v[1] = μ[1] - 1.0
s = sqrt(-2*v[1])
v[1] /= s
@inbounds for i in 2:p
v[i] = μ[i] / s
end
return v
... | [
87,
102
] | function _vmf_householder_vec(μ::Vector{Float64})
# assuming μ is a unit-vector (which it should be)
# can compute v in a single pass over μ
p = length(μ)
v = similar(μ)
v[1] = μ[1] - 1.0
s = sqrt(-2*v[1])
v[1] /= s
@inbounds for i in 2:p
v[i] = μ[i] / s
end
return v
... | function _vmf_householder_vec(μ::Vector{Float64})
# assuming μ is a unit-vector (which it should be)
# can compute v in a single pass over μ
p = length(μ)
v = similar(μ)
v[1] = μ[1] - 1.0
s = sqrt(-2*v[1])
v[1] /= s
@inbounds for i in 2:p
v[i] = μ[i] / s
end
return v
... | _vmf_householder_vec | 87 | 102 | src/samplers/vonmisesfisher.jl | #FILE: Distributions.jl/test/multivariate/vonmisesfisher.jl
##CHUNK 1
end
return X
end
function test_vmf_rot(p::Int, rng::Union{AbstractRNG, Missing} = missing)
if ismissing(rng)
μ = randn(p)
x = randn(p)
else
μ = randn(rng, p)
x = randn(rng, p)
end
κ = norm(μ)
... |
12 | 34 | Distributions.jl | 145 | function _tnmom1(a, b)
mid = float(middle(a, b))
if !(a ≤ b)
return oftype(mid, NaN)
elseif a == b
return mid
elseif abs(a) > abs(b)
return -_tnmom1(-b, -a)
elseif isinf(a) && isinf(b)
return zero(mid)
end
Δ = (b - a) * mid
a′ = a * invsqrt2
b′ = b * i... | function _tnmom1(a, b)
mid = float(middle(a, b))
if !(a ≤ b)
return oftype(mid, NaN)
elseif a == b
return mid
elseif abs(a) > abs(b)
return -_tnmom1(-b, -a)
elseif isinf(a) && isinf(b)
return zero(mid)
end
Δ = (b - a) * mid
a′ = a * invsqrt2
b′ = b * i... | [
12,
34
] | function _tnmom1(a, b)
mid = float(middle(a, b))
if !(a ≤ b)
return oftype(mid, NaN)
elseif a == b
return mid
elseif abs(a) > abs(b)
return -_tnmom1(-b, -a)
elseif isinf(a) && isinf(b)
return zero(mid)
end
Δ = (b - a) * mid
a′ = a * invsqrt2
b′ = b * i... | function _tnmom1(a, b)
mid = float(middle(a, b))
if !(a ≤ b)
return oftype(mid, NaN)
elseif a == b
return mid
elseif abs(a) > abs(b)
return -_tnmom1(-b, -a)
elseif isinf(a) && isinf(b)
return zero(mid)
end
Δ = (b - a) * mid
a′ = a * invsqrt2
b′ = b * i... | _tnmom1 | 12 | 34 | src/truncated/normal.jl | #FILE: Distributions.jl/src/univariate/continuous/triangular.jl
##CHUNK 1
res = (x - a)^2 / ((b - a) * (c - a))
return x < a ? zero(res) : res
else
res = 1 - (b - x)^2 / ((b - a) * (b - c))
return x ≥ b ? one(res) : res
end
end
function quantile(d::TriangularDist, p::Real)
(... |
213 | 237 | Distributions.jl | 146 | function fit_mle(::Type{<:Beta}, x::AbstractArray{T};
maxiter::Int=1000, tol::Float64=1e-14) where T<:Real
α₀,β₀ = params(fit(Beta,x)) #initial guess of parameters
g₁ = mean(log.(x))
g₂ = mean(log.(one(T) .- x))
θ= [α₀ ; β₀ ]
converged = false
t=0
while !converged && t < maxiter #newto... | function fit_mle(::Type{<:Beta}, x::AbstractArray{T};
maxiter::Int=1000, tol::Float64=1e-14) where T<:Real
α₀,β₀ = params(fit(Beta,x)) #initial guess of parameters
g₁ = mean(log.(x))
g₂ = mean(log.(one(T) .- x))
θ= [α₀ ; β₀ ]
converged = false
t=0
while !converged && t < maxiter #newto... | [
213,
237
] | function fit_mle(::Type{<:Beta}, x::AbstractArray{T};
maxiter::Int=1000, tol::Float64=1e-14) where T<:Real
α₀,β₀ = params(fit(Beta,x)) #initial guess of parameters
g₁ = mean(log.(x))
g₂ = mean(log.(one(T) .- x))
θ= [α₀ ; β₀ ]
converged = false
t=0
while !converged && t < maxiter #newto... | function fit_mle(::Type{<:Beta}, x::AbstractArray{T};
maxiter::Int=1000, tol::Float64=1e-14) where T<:Real
α₀,β₀ = params(fit(Beta,x)) #initial guess of parameters
g₁ = mean(log.(x))
g₂ = mean(log.(one(T) .- x))
θ= [α₀ ; β₀ ]
converged = false
t=0
while !converged && t < maxiter #newto... | fit_mle | 213 | 237 | src/univariate/continuous/beta.jl | #FILE: Distributions.jl/src/univariate/continuous/rician.jl
##CHUNK 1
function fit(::Type{<:Rician}, x::AbstractArray{T}; tol=1e-12, maxiters=500) where T
μ₁ = mean(x)
μ₂ = var(x)
r = μ₁ / √μ₂
if r < sqrt(π/(4-π))
ν = zero(float(T))
σ = scale(fit(Rayleigh, x))
else
ξ(θ) = 2 +... |
158 | 200 | Distributions.jl | 147 | function quantile(d::Chernoff, tau::Real)
# some commonly used quantiles were precomputed
precomputedquants=[
0.0 -Inf;
0.01 -1.171534341573129;
0.025 -0.9981810946684274;
0.05 -0.8450811886357725;
0.1 -0.6642351964332931;
0.2 -0.43982766604886553;
0.25 -0... | function quantile(d::Chernoff, tau::Real)
# some commonly used quantiles were precomputed
precomputedquants=[
0.0 -Inf;
0.01 -1.171534341573129;
0.025 -0.9981810946684274;
0.05 -0.8450811886357725;
0.1 -0.6642351964332931;
0.2 -0.43982766604886553;
0.25 -0... | [
158,
200
] | function quantile(d::Chernoff, tau::Real)
# some commonly used quantiles were precomputed
precomputedquants=[
0.0 -Inf;
0.01 -1.171534341573129;
0.025 -0.9981810946684274;
0.05 -0.8450811886357725;
0.1 -0.6642351964332931;
0.2 -0.43982766604886553;
0.25 -0... | function quantile(d::Chernoff, tau::Real)
# some commonly used quantiles were precomputed
precomputedquants=[
0.0 -Inf;
0.01 -1.171534341573129;
0.025 -0.9981810946684274;
0.05 -0.8450811886357725;
0.1 -0.6642351964332931;
0.2 -0.43982766604886553;
0.25 -0... | quantile | 158 | 200 | src/univariate/continuous/chernoff.jl | #FILE: Distributions.jl/test/univariate/continuous/skewedexponentialpower.jl
##CHUNK 1
@testset "α != 0.5" begin
# Format is [x, pdf, cdf] from the asymmetric
# exponential power function in R from package
# VaRES. Values are set to μ = 0, σ = 1, p = 0.5, α = 0.7
test = [
... |
217 | 306 | Distributions.jl | 148 | function rand(rng::AbstractRNG, d::Chernoff) # Ziggurat random number generator --- slow in the tails
# constants needed for the Ziggurat algorithm
A = 0.03248227216266608
x = [
1.4765521793744492
1.3583996502410562
1.2788224934376338
1.2167121025431031
... | function rand(rng::AbstractRNG, d::Chernoff) # Ziggurat random number generator --- slow in the tails
# constants needed for the Ziggurat algorithm
A = 0.03248227216266608
x = [
1.4765521793744492
1.3583996502410562
1.2788224934376338
1.2167121025431031
... | [
217,
306
] | function rand(rng::AbstractRNG, d::Chernoff) # Ziggurat random number generator --- slow in the tails
# constants needed for the Ziggurat algorithm
A = 0.03248227216266608
x = [
1.4765521793744492
1.3583996502410562
1.2788224934376338
1.2167121025431031
... | function rand(rng::AbstractRNG, d::Chernoff) # Ziggurat random number generator --- slow in the tails
# constants needed for the Ziggurat algorithm
A = 0.03248227216266608
x = [
1.4765521793744492
1.3583996502410562
1.2788224934376338
1.2167121025431031
... | rand | 217 | 306 | src/univariate/continuous/chernoff.jl | #FILE: Distributions.jl/test/univariate/continuous/skewedexponentialpower.jl
##CHUNK 1
@testset "α != 0.5" begin
# Format is [x, pdf, cdf] from the asymmetric
# exponential power function in R from package
# VaRES. Values are set to μ = 0, σ = 1, p = 0.5, α = 0.7
test = [
... |
223 | 233 | Distributions.jl | 149 | function logcdf(d::GeneralizedExtremeValue, x::Real)
μ, σ, ξ = params(d)
z = (x - μ) / σ
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-exp(- z)
else
# y(x) = y(bound) = 0 if x is not in the support with lower/upper bound
y = max(1 + z * ξ, 0)
- y^(-1/ξ)
end
end | function logcdf(d::GeneralizedExtremeValue, x::Real)
μ, σ, ξ = params(d)
z = (x - μ) / σ
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-exp(- z)
else
# y(x) = y(bound) = 0 if x is not in the support with lower/upper bound
y = max(1 + z * ξ, 0)
- y^(-1/ξ)
end
end | [
223,
233
] | function logcdf(d::GeneralizedExtremeValue, x::Real)
μ, σ, ξ = params(d)
z = (x - μ) / σ
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-exp(- z)
else
# y(x) = y(bound) = 0 if x is not in the support with lower/upper bound
y = max(1 + z * ξ, 0)
- y^(-1/ξ)
end
end | function logcdf(d::GeneralizedExtremeValue, x::Real)
μ, σ, ξ = params(d)
z = (x - μ) / σ
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-exp(- z)
else
# y(x) = y(bound) = 0 if x is not in the support with lower/upper bound
y = max(1 + z * ξ, 0)
- y^(-1/ξ)
end
end | logcdf | 223 | 233 | src/univariate/continuous/generalizedextremevalue.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedpareto.jl
##CHUNK 1
# The logpdf is log(0) outside the support range.
p = -T(Inf)
if x >= μ
z = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ... |
241 | 254 | Distributions.jl | 150 | function rand(rng::AbstractRNG, d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(ξ) < eps(one(ξ)) # ξ == 0
rd = - log(- log(u))
else
rd = expm1(- ξ * log(- log(u))) / ξ
end
return μ + σ * rd
e... | function rand(rng::AbstractRNG, d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(ξ) < eps(one(ξ)) # ξ == 0
rd = - log(- log(u))
else
rd = expm1(- ξ * log(- log(u))) / ξ
end
return μ + σ * rd
e... | [
241,
254
] | function rand(rng::AbstractRNG, d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(ξ) < eps(one(ξ)) # ξ == 0
rd = - log(- log(u))
else
rd = expm1(- ξ * log(- log(u))) / ξ
end
return μ + σ * rd
e... | function rand(rng::AbstractRNG, d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(ξ) < eps(one(ξ)) # ξ == 0
rd = - log(- log(u))
else
rd = expm1(- ξ * log(- log(u))) / ξ
end
return μ + σ * rd
e... | rand | 241 | 254 | src/univariate/continuous/generalizedextremevalue.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedpareto.jl
##CHUNK 1
end
#### Sampling
function rand(rng::AbstractRNG, d::GeneralizedPareto)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(d.ξ) < eps()
rd = -log(u)
else
rd = expm1(-d.ξ * lo... |
128 | 144 | Distributions.jl | 151 | function logpdf(d::GeneralizedPareto{T}, x::Real) where T<:Real
(μ, σ, ξ) = params(d)
# The logpdf is log(0) outside the support range.
p = -T(Inf)
if x >= μ
z = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = ... | function logpdf(d::GeneralizedPareto{T}, x::Real) where T<:Real
(μ, σ, ξ) = params(d)
# The logpdf is log(0) outside the support range.
p = -T(Inf)
if x >= μ
z = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = ... | [
128,
144
] | function logpdf(d::GeneralizedPareto{T}, x::Real) where T<:Real
(μ, σ, ξ) = params(d)
# The logpdf is log(0) outside the support range.
p = -T(Inf)
if x >= μ
z = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = ... | function logpdf(d::GeneralizedPareto{T}, x::Real) where T<:Real
(μ, σ, ξ) = params(d)
# The logpdf is log(0) outside the support range.
p = -T(Inf)
if x >= μ
z = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = ... | logpdf | 128 | 144 | src/univariate/continuous/generalizedpareto.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
function logpdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return -T(Inf)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if ab... |
146 | 157 | Distributions.jl | 152 | function logccdf(d::GeneralizedPareto, x::Real)
μ, σ, ξ = params(d)
z = max((x - μ) / σ, 0) # z(x) = z(μ) = 0 if x < μ (lower bound)
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-z
elseif ξ < 0
# y(x) = y(μ - σ / ξ) = -1 if x > μ - σ / ξ (upper bound)
-log1p(max(z * ξ, -1)) / ξ
el... | function logccdf(d::GeneralizedPareto, x::Real)
μ, σ, ξ = params(d)
z = max((x - μ) / σ, 0) # z(x) = z(μ) = 0 if x < μ (lower bound)
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-z
elseif ξ < 0
# y(x) = y(μ - σ / ξ) = -1 if x > μ - σ / ξ (upper bound)
-log1p(max(z * ξ, -1)) / ξ
el... | [
146,
157
] | function logccdf(d::GeneralizedPareto, x::Real)
μ, σ, ξ = params(d)
z = max((x - μ) / σ, 0) # z(x) = z(μ) = 0 if x < μ (lower bound)
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-z
elseif ξ < 0
# y(x) = y(μ - σ / ξ) = -1 if x > μ - σ / ξ (upper bound)
-log1p(max(z * ξ, -1)) / ξ
el... | function logccdf(d::GeneralizedPareto, x::Real)
μ, σ, ξ = params(d)
z = max((x - μ) / σ, 0) # z(x) = z(μ) = 0 if x < μ (lower bound)
return if abs(ξ) < eps(one(ξ)) # ξ == 0
-z
elseif ξ < 0
# y(x) = y(μ - σ / ξ) = -1 if x > μ - σ / ξ (upper bound)
-log1p(max(z * ξ, -1)) / ξ
el... | logccdf | 146 | 157 | src/univariate/continuous/generalizedpareto.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
return (t * exp(-t)) / σ
else
if z * ξ == -1 # In this case: zero to the power something.
return zero(T)
else
t = (1 + z*ξ)^(- 1 / ξ)
return ... |
163 | 181 | Distributions.jl | 153 | function quantile(d::GeneralizedPareto{T}, p::Real) where T<:Real
(μ, σ, ξ) = params(d)
if p == 0
z = zero(T)
elseif p == 1
z = ξ < 0 ? -1 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
en... | function quantile(d::GeneralizedPareto{T}, p::Real) where T<:Real
(μ, σ, ξ) = params(d)
if p == 0
z = zero(T)
elseif p == 1
z = ξ < 0 ? -1 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
en... | [
163,
181
] | function quantile(d::GeneralizedPareto{T}, p::Real) where T<:Real
(μ, σ, ξ) = params(d)
if p == 0
z = zero(T)
elseif p == 1
z = ξ < 0 ? -1 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
en... | function quantile(d::GeneralizedPareto{T}, p::Real) where T<:Real
(μ, σ, ξ) = params(d)
if p == 0
z = zero(T)
elseif p == 1
z = ξ < 0 ? -1 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
en... | quantile | 163 | 181 | src/univariate/continuous/generalizedpareto.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(... |
186 | 197 | Distributions.jl | 154 | function rand(rng::AbstractRNG, d::GeneralizedPareto)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(d.ξ) < eps()
rd = -log(u)
else
rd = expm1(-d.ξ * log(u)) / d.ξ
end
return d.μ + d.σ * rd
end | function rand(rng::AbstractRNG, d::GeneralizedPareto)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(d.ξ) < eps()
rd = -log(u)
else
rd = expm1(-d.ξ * log(u)) / d.ξ
end
return d.μ + d.σ * rd
end | [
186,
197
] | function rand(rng::AbstractRNG, d::GeneralizedPareto)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(d.ξ) < eps()
rd = -log(u)
else
rd = expm1(-d.ξ * log(u)) / d.ξ
end
return d.μ + d.σ * rd
end | function rand(rng::AbstractRNG, d::GeneralizedPareto)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(d.ξ) < eps()
rd = -log(u)
else
rd = expm1(-d.ξ * log(u)) / d.ξ
end
return d.μ + d.σ * rd
end | rand | 186 | 197 | src/univariate/continuous/generalizedpareto.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
function rand(rng::AbstractRNG, d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
# Generate a Float64 random number uniformly in (0,1].
u = 1 - rand(rng)
if abs(ξ) < eps(one(ξ)) # ξ == 0
rd = - log(- log(u)... |
97 | 109 | Distributions.jl | 155 | function cdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = clam... | function cdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = clam... | [
97,
109
] | function cdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = clam... | function cdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = clam... | cdf | 97 | 109 | src/univariate/continuous/inversegaussian.jl | #FILE: Distributions.jl/src/univariate/continuous/pgeneralizedgaussian.jl
##CHUNK 1
return ccdf(d, r) / 2
else
return (1 + cdf(d, r)) / 2
end
end
function logcdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
return _normlogcdf_pgeneralizedgaussian(p, (x - μ) / α)
end
function lo... |
111 | 123 | Distributions.jl | 156 | function ccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = cla... | function ccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = cla... | [
111,
123
] | function ccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = cla... | function ccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
# 2λ/μ and normlogcdf(-u*(v+1)) are similar magnitude, opp. sign
# truncating to [0, 1] as an additional precaution
# Ref https://github.com/JuliaStats/Distributions.jl/issues/1873
z = cla... | ccdf | 111 | 123 | src/univariate/continuous/inversegaussian.jl | #FILE: Distributions.jl/src/univariate/continuous/pgeneralizedgaussian.jl
##CHUNK 1
function logccdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
return _normlogcdf_pgeneralizedgaussian(p, (μ - x) / α)
end
function _normlogcdf_pgeneralizedgaussian(p::Real, z::Real)
r = abs(z)^p
d = Gamma(inv(p)... |
125 | 137 | Distributions.jl | 157 | function logcdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogcdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logaddexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | function logcdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogcdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logaddexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | [
125,
137
] | function logcdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogcdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logaddexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | function logcdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogcdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logaddexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | logcdf | 125 | 137 | src/univariate/continuous/inversegaussian.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedpareto.jl
##CHUNK 1
logcdf(d::GeneralizedPareto, x::Real) = log1mexp(logccdf(d, x))
function quantile(d::GeneralizedPareto{T}, p::Real) where T<:Real
(μ, σ, ξ) = params(d)
if p == 0
z = zero(T)
elseif p == 1
z = ξ < 0 ? -1 / ξ : ... |
139 | 151 | Distributions.jl | 158 | function logccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogccdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logsubexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? oftype(z, -Inf) : z
end | function logccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogccdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logsubexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? oftype(z, -Inf) : z
end | [
139,
151
] | function logccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogccdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logsubexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? oftype(z, -Inf) : z
end | function logccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
a = normlogccdf(u * (v - 1))
b = 2λ / μ + normlogcdf(-u * (v + 1))
z = logsubexp(a, b)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? oftype(z, -Inf) : z
end | logccdf | 139 | 151 | src/univariate/continuous/inversegaussian.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedpareto.jl
##CHUNK 1
logcdf(d::GeneralizedPareto, x::Real) = log1mexp(logccdf(d, x))
function quantile(d::GeneralizedPareto{T}, p::Real) where T<:Real
(μ, σ, ξ) = params(d)
if p == 0
z = zero(T)
elseif p == 1
z = ξ < 0 ? -1 / ξ : ... |
143 | 156 | Distributions.jl | 159 | function _lambertwm1(x, n=6)
if -exp(-one(x)) < x <= -1//4
β = -1 - sqrt2 * sqrt(1 + ℯ * x)
elseif x < 0
lnmx = log(-x)
β = lnmx - log(-lnmx)
else
throw(DomainError(x))
end
for i in 1:n
β = β / (1 + β) * (1 + log(x / β))
end
return β
end | function _lambertwm1(x, n=6)
if -exp(-one(x)) < x <= -1//4
β = -1 - sqrt2 * sqrt(1 + ℯ * x)
elseif x < 0
lnmx = log(-x)
β = lnmx - log(-lnmx)
else
throw(DomainError(x))
end
for i in 1:n
β = β / (1 + β) * (1 + log(x / β))
end
return β
end | [
143,
156
] | function _lambertwm1(x, n=6)
if -exp(-one(x)) < x <= -1//4
β = -1 - sqrt2 * sqrt(1 + ℯ * x)
elseif x < 0
lnmx = log(-x)
β = lnmx - log(-lnmx)
else
throw(DomainError(x))
end
for i in 1:n
β = β / (1 + β) * (1 + log(x / β))
end
return β
end | function _lambertwm1(x, n=6)
if -exp(-one(x)) < x <= -1//4
β = -1 - sqrt2 * sqrt(1 + ℯ * x)
elseif x < 0
lnmx = log(-x)
β = lnmx - log(-lnmx)
else
throw(DomainError(x))
end
for i in 1:n
β = β / (1 + β) * (1 + log(x / β))
end
return β
end | _lambertwm1 | 143 | 156 | src/univariate/continuous/lindley.jl | #FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
iβ = s.iβ
while true
u = rand(rng) # the Uniform sampler just calls rand()
v = rand(rng)
x = u^iα
y = v^iβ
if x + y ≤ one(x)
if (x + y > 0)
... |
124 | 139 | Distributions.jl | 160 | function fit_mle(::Type{<:Pareto}, x::AbstractArray{T}) where T<:Real
# Based on
# https://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
θ = minimum(x)
n = length(x)
lθ = log(θ)
temp1 = zero(T)
for i=1:n
temp1 += log(x[i]) - lθ
end
α = n/temp1
return P... | function fit_mle(::Type{<:Pareto}, x::AbstractArray{T}) where T<:Real
# Based on
# https://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
θ = minimum(x)
n = length(x)
lθ = log(θ)
temp1 = zero(T)
for i=1:n
temp1 += log(x[i]) - lθ
end
α = n/temp1
return P... | [
124,
139
] | function fit_mle(::Type{<:Pareto}, x::AbstractArray{T}) where T<:Real
# Based on
# https://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
θ = minimum(x)
n = length(x)
lθ = log(θ)
temp1 = zero(T)
for i=1:n
temp1 += log(x[i]) - lθ
end
α = n/temp1
return P... | function fit_mle(::Type{<:Pareto}, x::AbstractArray{T}) where T<:Real
# Based on
# https://en.wikipedia.org/wiki/Pareto_distribution#Parameter_estimation
θ = minimum(x)
n = length(x)
lθ = log(θ)
temp1 = zero(T)
for i=1:n
temp1 += log(x[i]) - lθ
end
α = n/temp1
return P... | fit_mle | 124 | 139 | src/univariate/continuous/pareto.jl | #FILE: Distributions.jl/src/univariate/continuous/generalizedpareto.jl
##CHUNK 1
return T(Inf)
end
end
#### Evaluation
function logpdf(d::GeneralizedPareto{T}, x::Real) where T<:Real
(μ, σ, ξ) = params(d)
# The logpdf is log(0) outside the support range.
p = -T(Inf)
if x >= μ
z ... |
94 | 105 | Distributions.jl | 161 | function pdf(d::TriangularDist, x::Real)
a, b, c = params(d)
res = if x < c
2 * (x - a) / ((b - a) * (c - a))
elseif x > c
2 * (b - x) / ((b - a) * (b - c))
else
# Handle x == c separately to avoid `NaN` if `c == a` or `c == b`
oftype(x - a, 2) / (b - a)
end
retur... | function pdf(d::TriangularDist, x::Real)
a, b, c = params(d)
res = if x < c
2 * (x - a) / ((b - a) * (c - a))
elseif x > c
2 * (b - x) / ((b - a) * (b - c))
else
# Handle x == c separately to avoid `NaN` if `c == a` or `c == b`
oftype(x - a, 2) / (b - a)
end
retur... | [
94,
105
] | function pdf(d::TriangularDist, x::Real)
a, b, c = params(d)
res = if x < c
2 * (x - a) / ((b - a) * (c - a))
elseif x > c
2 * (b - x) / ((b - a) * (b - c))
else
# Handle x == c separately to avoid `NaN` if `c == a` or `c == b`
oftype(x - a, 2) / (b - a)
end
retur... | function pdf(d::TriangularDist, x::Real)
a, b, c = params(d)
res = if x < c
2 * (x - a) / ((b - a) * (c - a))
elseif x > c
2 * (b - x) / ((b - a) * (b - c))
else
# Handle x == c separately to avoid `NaN` if `c == a` or `c == b`
oftype(x - a, 2) / (b - a)
end
retur... | pdf | 94 | 105 | src/univariate/continuous/triangular.jl | #FILE: Distributions.jl/src/univariate/continuous/uniform.jl
##CHUNK 1
end
function ccdf(d::Uniform, x::Real)
a, b = params(d)
return clamp((b - x) / (b - a), 0, 1)
end
quantile(d::Uniform, p::Real) = d.a + p * (d.b - d.a)
cquantile(d::Uniform, p::Real) = d.b + p * (d.a - d.b)
function mgf(d::Uniform, t::Rea... |
80 | 91 | Distributions.jl | 162 | function _vmcdf(κ::Real, I0κx::Real, x::Real, tol::Real)
tol *= exp(-κ)
j = 1
cj = besselix(j, κ) / j
s = cj * sin(j * x)
while abs(cj) > tol
j += 1
cj = besselix(j, κ) / j
s += cj * sin(j * x)
end
return (x + 2s / I0κx) / twoπ + 1//2
end | function _vmcdf(κ::Real, I0κx::Real, x::Real, tol::Real)
tol *= exp(-κ)
j = 1
cj = besselix(j, κ) / j
s = cj * sin(j * x)
while abs(cj) > tol
j += 1
cj = besselix(j, κ) / j
s += cj * sin(j * x)
end
return (x + 2s / I0κx) / twoπ + 1//2
end | [
80,
91
] | function _vmcdf(κ::Real, I0κx::Real, x::Real, tol::Real)
tol *= exp(-κ)
j = 1
cj = besselix(j, κ) / j
s = cj * sin(j * x)
while abs(cj) > tol
j += 1
cj = besselix(j, κ) / j
s += cj * sin(j * x)
end
return (x + 2s / I0κx) / twoπ + 1//2
end | function _vmcdf(κ::Real, I0κx::Real, x::Real, tol::Real)
tol *= exp(-κ)
j = 1
cj = besselix(j, κ) / j
s = cj * sin(j * x)
while abs(cj) > tol
j += 1
cj = besselix(j, κ) / j
s += cj * sin(j * x)
end
return (x + 2s / I0κx) / twoπ + 1//2
end | _vmcdf | 80 | 91 | src/univariate/continuous/vonmises.jl | #FILE: Distributions.jl/src/samplers/vonmisesfisher.jl
##CHUNK 1
_vmf_bval(p::Int, κ::Real) = (p - 1) / (2.0κ + sqrt(4 * abs2(κ) + abs2(p - 1)))
function _vmf_genw3(rng::AbstractRNG, p, b, x0, c, κ)
ξ = rand(rng)
w = 1.0 + (log(ξ + (1.0 - ξ)*exp(-2κ))/κ)
return w::Float64
end
function _vmf_genwp(rng::Abst... |
145 | 187 | Distributions.jl | 163 | function fit_mle(::Type{<:Weibull}, x::AbstractArray{<:Real};
alpha0::Real = 1, maxiter::Int = 1000, tol::Real = 1e-16)
N = 0
lnx = map(log, x)
lnxsq = lnx.^2
mean_lnx = mean(lnx)
# first iteration outside loop, prevents type instability in α, ϵ
xpow0 = x.^alpha0
sum_xpow0 = sum(xpow... | function fit_mle(::Type{<:Weibull}, x::AbstractArray{<:Real};
alpha0::Real = 1, maxiter::Int = 1000, tol::Real = 1e-16)
N = 0
lnx = map(log, x)
lnxsq = lnx.^2
mean_lnx = mean(lnx)
# first iteration outside loop, prevents type instability in α, ϵ
xpow0 = x.^alpha0
sum_xpow0 = sum(xpow... | [
145,
187
] | function fit_mle(::Type{<:Weibull}, x::AbstractArray{<:Real};
alpha0::Real = 1, maxiter::Int = 1000, tol::Real = 1e-16)
N = 0
lnx = map(log, x)
lnxsq = lnx.^2
mean_lnx = mean(lnx)
# first iteration outside loop, prevents type instability in α, ϵ
xpow0 = x.^alpha0
sum_xpow0 = sum(xpow... | function fit_mle(::Type{<:Weibull}, x::AbstractArray{<:Real};
alpha0::Real = 1, maxiter::Int = 1000, tol::Real = 1e-16)
N = 0
lnx = map(log, x)
lnxsq = lnx.^2
mean_lnx = mean(lnx)
# first iteration outside loop, prevents type instability in α, ϵ
xpow0 = x.^alpha0
sum_xpow0 = sum(xpow... | fit_mle | 145 | 187 | src/univariate/continuous/weibull.jl | #FILE: Distributions.jl/src/univariate/continuous/rician.jl
##CHUNK 1
function fit(::Type{<:Rician}, x::AbstractArray{T}; tol=1e-12, maxiters=500) where T
μ₁ = mean(x)
μ₂ = var(x)
r = μ₁ / √μ₂
if r < sqrt(π/(4-π))
ν = zero(float(T))
σ = scale(fit(Rayleigh, x))
else
ξ(θ) = 2 +... |
72 | 83 | Distributions.jl | 164 | function kurtosis(d::BetaBinomial)
n, α, β = d.n, d.α, d.β
alpha_beta_sum = α + β
alpha_beta_product = α * β
numerator = ((alpha_beta_sum)^2) * (1 + alpha_beta_sum)
denominator = (n * alpha_beta_product) * (alpha_beta_sum + 2) * (alpha_beta_sum + 3) * (alpha_beta_sum + n)
left = numerator / deno... | function kurtosis(d::BetaBinomial)
n, α, β = d.n, d.α, d.β
alpha_beta_sum = α + β
alpha_beta_product = α * β
numerator = ((alpha_beta_sum)^2) * (1 + alpha_beta_sum)
denominator = (n * alpha_beta_product) * (alpha_beta_sum + 2) * (alpha_beta_sum + 3) * (alpha_beta_sum + n)
left = numerator / deno... | [
72,
83
] | function kurtosis(d::BetaBinomial)
n, α, β = d.n, d.α, d.β
alpha_beta_sum = α + β
alpha_beta_product = α * β
numerator = ((alpha_beta_sum)^2) * (1 + alpha_beta_sum)
denominator = (n * alpha_beta_product) * (alpha_beta_sum + 2) * (alpha_beta_sum + 3) * (alpha_beta_sum + n)
left = numerator / deno... | function kurtosis(d::BetaBinomial)
n, α, β = d.n, d.α, d.β
alpha_beta_sum = α + β
alpha_beta_product = α * β
numerator = ((alpha_beta_sum)^2) * (1 + alpha_beta_sum)
denominator = (n * alpha_beta_product) * (alpha_beta_sum + 2) * (alpha_beta_sum + 3) * (alpha_beta_sum + n)
left = numerator / deno... | kurtosis | 72 | 83 | src/univariate/discrete/betabinomial.jl | #FILE: Distributions.jl/src/univariate/continuous/skewedexponentialpower.jl
##CHUNK 1
inv_p = inv(p)
return k * (logtwo + inv_p * log(p) + log(σ)) + loggamma((1 + k) * inv_p) -
loggamma(inv_p) + log(abs((-1)^k * α^(1 + k) + (1 - α)^(1 + k)))
end
# needed for odd moments in log scale
sgn(d::SkewedExpon... |
92 | 113 | Distributions.jl | 165 | function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real}
vfirst = round(Int, first(rgn))
vlast = round(Int, last(rgn))
vl = max(vfirst, 1)
vr = min(vlast, ncategories(d))
p = probs(d)
if vl > vfirst
for i = 1:(vl - vfirst)
r[i] = zero(T)
... | function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real}
vfirst = round(Int, first(rgn))
vlast = round(Int, last(rgn))
vl = max(vfirst, 1)
vr = min(vlast, ncategories(d))
p = probs(d)
if vl > vfirst
for i = 1:(vl - vfirst)
r[i] = zero(T)
... | [
92,
113
] | function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real}
vfirst = round(Int, first(rgn))
vlast = round(Int, last(rgn))
vl = max(vfirst, 1)
vr = min(vlast, ncategories(d))
p = probs(d)
if vl > vfirst
for i = 1:(vl - vfirst)
r[i] = zero(T)
... | function _pdf!(r::AbstractArray{<:Real}, d::Categorical{T}, rgn::UnitRange) where {T<:Real}
vfirst = round(Int, first(rgn))
vlast = round(Int, last(rgn))
vl = max(vfirst, 1)
vr = min(vlast, ncategories(d))
p = probs(d)
if vl > vfirst
for i = 1:(vl - vfirst)
r[i] = zero(T)
... | _pdf! | 92 | 113 | src/univariate/discrete/categorical.jl | #FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
r[v - fm1] = pdf(d, v)
end
return r
end
abstract type RecursiveProbabilityEvaluator end
function _pdf!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange, rpe::RecursiveProbabilityEvaluator)
vl,vr, vfirst, vlast = _pdf_fill_outsi... |
76 | 87 | Distributions.jl | 166 | function rand(rng::AbstractRNG, d::DiscreteNonParametric)
x = support(d)
p = probs(d)
n = length(p)
draw = rand(rng, float(eltype(p)))
cp = p[1]
i = 1
while cp <= draw && i < n
@inbounds cp += p[i +=1]
end
return x[i]
end | function rand(rng::AbstractRNG, d::DiscreteNonParametric)
x = support(d)
p = probs(d)
n = length(p)
draw = rand(rng, float(eltype(p)))
cp = p[1]
i = 1
while cp <= draw && i < n
@inbounds cp += p[i +=1]
end
return x[i]
end | [
76,
87
] | function rand(rng::AbstractRNG, d::DiscreteNonParametric)
x = support(d)
p = probs(d)
n = length(p)
draw = rand(rng, float(eltype(p)))
cp = p[1]
i = 1
while cp <= draw && i < n
@inbounds cp += p[i +=1]
end
return x[i]
end | function rand(rng::AbstractRNG, d::DiscreteNonParametric)
x = support(d)
p = probs(d)
n = length(p)
draw = rand(rng, float(eltype(p)))
cp = p[1]
i = 1
while cp <= draw && i < n
@inbounds cp += p[i +=1]
end
return x[i]
end | rand | 76 | 87 | src/univariate/discrete/discretenonparametric.jl | #FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
n, p = params(d)
s = -loggamma(n+1) + n*entropy(p)
for pr in p
b = Binomial(n, pr)
for x in 0:n
s += pdf(b, x) * loggamma(x+1)
end
end
return s
end
# Evaluation
function insupport(d::Multinomial,... |
112 | 136 | Distributions.jl | 167 | function cdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return zero(P)
x >= maximum(d) && return one(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < di... | function cdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return zero(P)
x >= maximum(d) && return one(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < di... | [
112,
136
] | function cdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return zero(P)
x >= maximum(d) && return one(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < di... | function cdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return zero(P)
x >= maximum(d) && return one(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < di... | cdf | 112 | 136 | src/univariate/discrete/discretenonparametric.jl | #FILE: Distributions.jl/src/univariate/discrete/noncentralhypergeometric.jl
##CHUNK 1
function quantile(d::NoncentralHypergeometric{T}, q::Real) where T<:Real
if !(zero(q) <= q <= one(q))
T(NaN)
else
range = support(d)
if q > 1/2
q = 1 - q
range = reverse(range)
... |
138 | 162 | Distributions.jl | 168 | function ccdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return one(P)
x >= maximum(d) && return zero(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < d... | function ccdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return one(P)
x >= maximum(d) && return zero(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < d... | [
138,
162
] | function ccdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return one(P)
x >= maximum(d) && return zero(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < d... | function ccdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
x < minimum(d) && return one(P)
x >= maximum(d) && return zero(P)
isnan(x) && return P(NaN)
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < d... | ccdf | 138 | 162 | src/univariate/discrete/discretenonparametric.jl | #FILE: Distributions.jl/src/univariate/discrete/categorical.jl
##CHUNK 1
while cp < 1/2 && i <= k
i += 1
@inbounds cp += p[i]
end
i
end
### Evaluation
# the fallbacks are overridden by `DiscreteNonParameteric`
cdf(d::Categorical, x::Real) = cdf_int(d, x)
ccdf(d::Categorical, x::Real) = ccd... |
78 | 88 | Distributions.jl | 169 | function cdf(d::DiscreteUniform, x::Int)
a = d.a
result = (x - a + 1) * d.pv
return if x < a
zero(result)
elseif x >= d.b
one(result)
else
result
end
end | function cdf(d::DiscreteUniform, x::Int)
a = d.a
result = (x - a + 1) * d.pv
return if x < a
zero(result)
elseif x >= d.b
one(result)
else
result
end
end | [
78,
88
] | function cdf(d::DiscreteUniform, x::Int)
a = d.a
result = (x - a + 1) * d.pv
return if x < a
zero(result)
elseif x >= d.b
one(result)
else
result
end
end | function cdf(d::DiscreteUniform, x::Int)
a = d.a
result = (x - a + 1) * d.pv
return if x < a
zero(result)
elseif x >= d.b
one(result)
else
result
end
end | cdf | 78 | 88 | src/univariate/discrete/discreteuniform.jl | #FILE: Distributions.jl/src/samplers/binomial.jl
##CHUNK 1
# compute probability vector of a Binomial distribution
function binompvec(n::Int, p::Float64)
pv = Vector{Float64}(undef, n+1)
if p == 0.0
fill!(pv, 0.0)
pv[1] = 1.0
elseif p == 1.0
fill!(pv, 0.0)
pv[n+1] = 1.0
... |
97 | 108 | Distributions.jl | 170 | function logpdf(d::NegativeBinomial, k::Real)
r, p = params(d)
z = xlogy(r, p) + xlog1py(k, -p)
if iszero(k)
# in this case `logpdf(d, k) = z - log(k + r) - logbeta(r, k + 1) = z` analytically
# but unfortunately not numerically, so we handle this case separately to improve accuracy
... | function logpdf(d::NegativeBinomial, k::Real)
r, p = params(d)
z = xlogy(r, p) + xlog1py(k, -p)
if iszero(k)
# in this case `logpdf(d, k) = z - log(k + r) - logbeta(r, k + 1) = z` analytically
# but unfortunately not numerically, so we handle this case separately to improve accuracy
... | [
97,
108
] | function logpdf(d::NegativeBinomial, k::Real)
r, p = params(d)
z = xlogy(r, p) + xlog1py(k, -p)
if iszero(k)
# in this case `logpdf(d, k) = z - log(k + r) - logbeta(r, k + 1) = z` analytically
# but unfortunately not numerically, so we handle this case separately to improve accuracy
... | function logpdf(d::NegativeBinomial, k::Real)
r, p = params(d)
z = xlogy(r, p) + xlog1py(k, -p)
if iszero(k)
# in this case `logpdf(d, k) = z - log(k + r) - logbeta(r, k + 1) = z` analytically
# but unfortunately not numerically, so we handle this case separately to improve accuracy
... | logpdf | 97 | 108 | src/univariate/discrete/negativebinomial.jl | #FILE: Distributions.jl/ext/DistributionsChainRulesCoreExt/univariate/discrete/negativebinomial.jl
##CHUNK 1
return ChainRulesCore.NoTangent(), Δd, ChainRulesCore.NoTangent()
end
function ChainRulesCore.rrule(::typeof(logpdf), d::NegativeBinomial, k::Real)
# Compute log probability (as in the definition of `lo... |
85 | 129 | Distributions.jl | 171 | function pdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if !insupport(d, k)
return zero(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
fₖ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d... | function pdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if !insupport(d, k)
return zero(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
fₖ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d... | [
85,
129
] | function pdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if !insupport(d, k)
return zero(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
fₖ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d... | function pdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if !insupport(d, k)
return zero(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
fₖ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d... | pdf | 85 | 129 | src/univariate/discrete/noncentralhypergeometric.jl | #FILE: Distributions.jl/src/univariate/continuous/rician.jl
##CHUNK 1
function fit(::Type{<:Rician}, x::AbstractArray{T}; tol=1e-12, maxiters=500) where T
μ₁ = mean(x)
μ₂ = var(x)
r = μ₁ / √μ₂
if r < sqrt(π/(4-π))
ν = zero(float(T))
σ = scale(fit(Rayleigh, x))
else
ξ(θ) = 2 +... |
133 | 177 | Distributions.jl | 172 | function cdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if k < l
return zero(ω)
elseif k >= u
return one(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
Fₖ = k >= η ? one(ω) : zero(ω)
for i ... | function cdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if k < l
return zero(ω)
elseif k >= u
return one(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
Fₖ = k >= η ? one(ω) : zero(ω)
for i ... | [
133,
177
] | function cdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if k < l
return zero(ω)
elseif k >= u
return one(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
Fₖ = k >= η ? one(ω) : zero(ω)
for i ... | function cdf(d::FisherNoncentralHypergeometric, k::Integer)
ω, _ = promote(d.ω, float(k))
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
if k < l
return zero(ω)
elseif k >= u
return one(ω)
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
Fₖ = k >= η ? one(ω) : zero(ω)
for i ... | cdf | 133 | 177 | src/univariate/discrete/noncentralhypergeometric.jl | #FILE: Distributions.jl/src/univariate/continuous/rician.jl
##CHUNK 1
function fit(::Type{<:Rician}, x::AbstractArray{T}; tol=1e-12, maxiters=500) where T
μ₁ = mean(x)
μ₂ = var(x)
r = μ₁ / √μ₂
if r < sqrt(π/(4-π))
ν = zero(float(T))
σ = scale(fit(Rayleigh, x))
else
ξ(θ) = 2 +... |
179 | 216 | Distributions.jl | 173 | function _expectation(f, d::FisherNoncentralHypergeometric)
ω = float(d.ω)
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
η = mode(d)
s = one(ω)
m = f(η)*s
fᵢ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if ter... | function _expectation(f, d::FisherNoncentralHypergeometric)
ω = float(d.ω)
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
η = mode(d)
s = one(ω)
m = f(η)*s
fᵢ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if ter... | [
179,
216
] | function _expectation(f, d::FisherNoncentralHypergeometric)
ω = float(d.ω)
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
η = mode(d)
s = one(ω)
m = f(η)*s
fᵢ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if ter... | function _expectation(f, d::FisherNoncentralHypergeometric)
ω = float(d.ω)
l = max(0, d.n - d.nf)
u = min(d.ns, d.n)
η = mode(d)
s = one(ω)
m = f(η)*s
fᵢ = one(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if ter... | _expectation | 179 | 216 | src/univariate/discrete/noncentralhypergeometric.jl | #FILE: Distributions.jl/src/univariate/continuous/rician.jl
##CHUNK 1
function fit(::Type{<:Rician}, x::AbstractArray{T}; tol=1e-12, maxiters=500) where T
μ₁ = mean(x)
μ₂ = var(x)
r = μ₁ / √μ₂
if r < sqrt(π/(4-π))
ν = zero(float(T))
σ = scale(fit(Rayleigh, x))
else
ξ(θ) = 2 +... |
30 | 40 | Distributions.jl | 174 | function PoissonBinomial{T}(p::AbstractVector{T}; check_args::Bool=true) where {T <: Real}
@check_args(
PoissonBinomial,
(
p,
all(x -> zero(x) <= x <= one(x), p),
"p must be a vector of success probabilities",
),
)
... | function PoissonBinomial{T}(p::AbstractVector{T}; check_args::Bool=true) where {T <: Real}
@check_args(
PoissonBinomial,
(
p,
all(x -> zero(x) <= x <= one(x), p),
"p must be a vector of success probabilities",
),
)
... | [
30,
40
] | function PoissonBinomial{T}(p::AbstractVector{T}; check_args::Bool=true) where {T <: Real}
@check_args(
PoissonBinomial,
(
p,
all(x -> zero(x) <= x <= one(x), p),
"p must be a vector of success probabilities",
),
)
... | function PoissonBinomial{T}(p::AbstractVector{T}; check_args::Bool=true) where {T <: Real}
@check_args(
PoissonBinomial,
(
p,
all(x -> zero(x) <= x <= one(x), p),
"p must be a vector of success probabilities",
),
)
... | PoissonBinomial{T} | 30 | 40 | src/univariate/discrete/poissonbinomial.jl | #FILE: Distributions.jl/src/univariate/discrete/negativebinomial.jl
##CHUNK 1
succprob(d) # Get the success rate, i.e. p
failprob(d) # Get the failure rate, i.e. 1 - p
```
External links:
* [Negative binomial distribution on Wolfram](https://reference.wolfram.com/language/ref/NegativeBinomialDistribution.html... |
153 | 164 | Distributions.jl | 175 | function poissonbinomial_pdf(p)
S = zeros(eltype(p), length(p) + 1)
S[1] = 1
@inbounds for (col, p_col) in enumerate(p)
q_col = 1 - p_col
for row in col:(-1):1
S[row + 1] = q_col * S[row + 1] + p_col * S[row]
end
S[1] *= q_col
end
return S
end | function poissonbinomial_pdf(p)
S = zeros(eltype(p), length(p) + 1)
S[1] = 1
@inbounds for (col, p_col) in enumerate(p)
q_col = 1 - p_col
for row in col:(-1):1
S[row + 1] = q_col * S[row + 1] + p_col * S[row]
end
S[1] *= q_col
end
return S
end | [
153,
164
] | function poissonbinomial_pdf(p)
S = zeros(eltype(p), length(p) + 1)
S[1] = 1
@inbounds for (col, p_col) in enumerate(p)
q_col = 1 - p_col
for row in col:(-1):1
S[row + 1] = q_col * S[row + 1] + p_col * S[row]
end
S[1] *= q_col
end
return S
end | function poissonbinomial_pdf(p)
S = zeros(eltype(p), length(p) + 1)
S[1] = 1
@inbounds for (col, p_col) in enumerate(p)
q_col = 1 - p_col
for row in col:(-1):1
S[row + 1] = q_col * S[row + 1] + p_col * S[row]
end
S[1] *= q_col
end
return S
end | poissonbinomial_pdf | 153 | 164 | src/univariate/discrete/poissonbinomial.jl | #FILE: Distributions.jl/src/samplers/poisson.jl
##CHUNK 1
function poissonpvec(μ::Float64, n::Int)
# Poisson probabilities, from 0 to n
pv = Vector{Float64}(undef, n+1)
@inbounds pv[1] = p = exp(-μ)
for i = 1:n
@inbounds pv[i+1] = (p *= (μ / i))
end
return pv
end
#FILE: Distributions.j... |
222 | 250 | Distributions.jl | 176 | function poissonbinomial_pdf_partialderivatives(p::AbstractVector{<:Real})
n = length(p)
A = zeros(eltype(p), n, n + 1)
@inbounds for j in 1:n
A[j, end] = 1
end
@inbounds for (i, pi) in enumerate(p)
qi = 1 - pi
for k in (n - i + 1):n
kp1 = k + 1
for j ... | function poissonbinomial_pdf_partialderivatives(p::AbstractVector{<:Real})
n = length(p)
A = zeros(eltype(p), n, n + 1)
@inbounds for j in 1:n
A[j, end] = 1
end
@inbounds for (i, pi) in enumerate(p)
qi = 1 - pi
for k in (n - i + 1):n
kp1 = k + 1
for j ... | [
222,
250
] | function poissonbinomial_pdf_partialderivatives(p::AbstractVector{<:Real})
n = length(p)
A = zeros(eltype(p), n, n + 1)
@inbounds for j in 1:n
A[j, end] = 1
end
@inbounds for (i, pi) in enumerate(p)
qi = 1 - pi
for k in (n - i + 1):n
kp1 = k + 1
for j ... | function poissonbinomial_pdf_partialderivatives(p::AbstractVector{<:Real})
n = length(p)
A = zeros(eltype(p), n, n + 1)
@inbounds for j in 1:n
A[j, end] = 1
end
@inbounds for (i, pi) in enumerate(p)
qi = 1 - pi
for k in (n - i + 1):n
kp1 = k + 1
for j ... | poissonbinomial_pdf_partialderivatives | 222 | 250 | src/univariate/discrete/poissonbinomial.jl | #FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
issorted(x) && return lp
return oftype(lp, -Inf)
end
i = first(ranks)
xᵢ = first(x)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
... |
167 | 182 | QuantEcon.jl | 177 | function impulse_response(arma::ARMA; impulse_length=30)
# Compute the impulse response function associated with ARMA process arma
err_msg = "Impulse length must be greater than number of AR coefficients"
@assert impulse_length >= arma.p err_msg
# == Pad theta with zeros at the end == #
theta = [arm... | function impulse_response(arma::ARMA; impulse_length=30)
# Compute the impulse response function associated with ARMA process arma
err_msg = "Impulse length must be greater than number of AR coefficients"
@assert impulse_length >= arma.p err_msg
# == Pad theta with zeros at the end == #
theta = [arm... | [
167,
182
] | function impulse_response(arma::ARMA; impulse_length=30)
# Compute the impulse response function associated with ARMA process arma
err_msg = "Impulse length must be greater than number of AR coefficients"
@assert impulse_length >= arma.p err_msg
# == Pad theta with zeros at the end == #
theta = [arm... | function impulse_response(arma::ARMA; impulse_length=30)
# Compute the impulse response function associated with ARMA process arma
err_msg = "Impulse length must be greater than number of AR coefficients"
@assert impulse_length >= arma.p err_msg
# == Pad theta with zeros at the end == #
theta = [arm... | impulse_response | 167 | 182 | src/arma.jl | #FILE: QuantEcon.jl/test/test_arma.jl
##CHUNK 1
@testset "Testing arma.jl" begin
# set up
phi = [.95, -.4, -.4]
theta = zeros(3)
sigma = .15
lp = ARMA(phi, theta, sigma)
# test simulate
sim = simulation(lp, ts_length=250)
@test length(sim) == 250
# test impulse response
imp_re... |
199 | 210 | QuantEcon.jl | 178 | function simulation(arma::ARMA; ts_length=90, impulse_length=30)
# Simulate the ARMA process arma assuming Gaussian shocks
J = impulse_length
T = ts_length
psi = impulse_response(arma, impulse_length=impulse_length)
epsilon = arma.sigma * randn(T + J)
X = Vector{Float64}(undef, T)
for t=1:T
... | function simulation(arma::ARMA; ts_length=90, impulse_length=30)
# Simulate the ARMA process arma assuming Gaussian shocks
J = impulse_length
T = ts_length
psi = impulse_response(arma, impulse_length=impulse_length)
epsilon = arma.sigma * randn(T + J)
X = Vector{Float64}(undef, T)
for t=1:T
... | [
199,
210
] | function simulation(arma::ARMA; ts_length=90, impulse_length=30)
# Simulate the ARMA process arma assuming Gaussian shocks
J = impulse_length
T = ts_length
psi = impulse_response(arma, impulse_length=impulse_length)
epsilon = arma.sigma * randn(T + J)
X = Vector{Float64}(undef, T)
for t=1:T
... | function simulation(arma::ARMA; ts_length=90, impulse_length=30)
# Simulate the ARMA process arma assuming Gaussian shocks
J = impulse_length
T = ts_length
psi = impulse_response(arma, impulse_length=impulse_length)
epsilon = arma.sigma * randn(T + J)
X = Vector{Float64}(undef, T)
for t=1:T
... | simulation | 199 | 210 | src/arma.jl | #FILE: QuantEcon.jl/test/test_arma.jl
##CHUNK 1
@testset "Testing arma.jl" begin
# set up
phi = [.95, -.4, -.4]
theta = zeros(3)
sigma = .15
lp = ARMA(phi, theta, sigma)
# test simulate
sim = simulation(lp, ts_length=250)
@test length(sim) == 250
# test impulse response
imp_re... |
51 | 85 | QuantEcon.jl | 179 | function compute_fixed_point(T::Function,
v::TV;
err_tol=1e-4,
max_iter=100,
verbose=2,
print_skip=10) where TV
if !(verbose in (0, 1, 2))
throw(ArgumentError("verbose... | function compute_fixed_point(T::Function,
v::TV;
err_tol=1e-4,
max_iter=100,
verbose=2,
print_skip=10) where TV
if !(verbose in (0, 1, 2))
throw(ArgumentError("verbose... | [
51,
85
] | function compute_fixed_point(T::Function,
v::TV;
err_tol=1e-4,
max_iter=100,
verbose=2,
print_skip=10) where TV
if !(verbose in (0, 1, 2))
throw(ArgumentError("verbose... | function compute_fixed_point(T::Function,
v::TV;
err_tol=1e-4,
max_iter=100,
verbose=2,
print_skip=10) where TV
if !(verbose in (0, 1, 2))
throw(ArgumentError("verbose... | compute_fixed_point | 51 | 85 | src/compute_fp.jl | #FILE: QuantEcon.jl/test/test_compute_fp.jl
##CHUNK 1
@testset "Testing compute_fp.jl" begin
# set up
mu_1 = 0.2 # 0 is unique fixed point forall x_0 \in [0, 1]
# (4mu - 1)/(4mu) is a fixed point forall x_0 \in [0, 1]
mu_2 = 0.3
# starting points on (0, 1)
unit_inverval = [0.1, 0.3, 0.6, 0.9... |
30 | 67 | QuantEcon.jl | 180 | function smooth(x::Array, window_len::Int, window::AbstractString="hanning")
if length(x) < window_len
throw(ArgumentError("Input vector length must be >= window length"))
end
if window_len < 3
throw(ArgumentError("Window length must be at least 3."))
end
if iseven(window_len)
... | function smooth(x::Array, window_len::Int, window::AbstractString="hanning")
if length(x) < window_len
throw(ArgumentError("Input vector length must be >= window length"))
end
if window_len < 3
throw(ArgumentError("Window length must be at least 3."))
end
if iseven(window_len)
... | [
30,
67
] | function smooth(x::Array, window_len::Int, window::AbstractString="hanning")
if length(x) < window_len
throw(ArgumentError("Input vector length must be >= window length"))
end
if window_len < 3
throw(ArgumentError("Window length must be at least 3."))
end
if iseven(window_len)
... | function smooth(x::Array, window_len::Int, window::AbstractString="hanning")
if length(x) < window_len
throw(ArgumentError("Input vector length must be >= window length"))
end
if window_len < 3
throw(ArgumentError("Window length must be at least 3."))
end
if iseven(window_len)
... | smooth | 30 | 67 | src/estspec.jl | #FILE: QuantEcon.jl/test/test_estspec.jl
##CHUNK 1
n_w, n_Iw, n_x = length(w), length(I_w), length(x)
@test n_w == floor(Int, n_x / 2 + 1)
@test n_Iw == floor(Int, n_x / 2 + 1)
w, I_w = ar_periodogram(x)
n_w, n_Iw, n_x = length(w), length(I_w), length(x)
... |
74 | 84 | QuantEcon.jl | 181 | function periodogram(x::Vector)
n = length(x)
I_w = abs.(fft(x)).^2 ./ n
w = 2pi * (0:n-1) ./ n # Fourier frequencies
# int rounds to nearest integer. We want to round up or take 1/2 + 1 to
# make sure we get the whole interval from [0, pi]
ind = iseven(n) ? round(Int, n / 2 + 1) : ceil(Int, ... | function periodogram(x::Vector)
n = length(x)
I_w = abs.(fft(x)).^2 ./ n
w = 2pi * (0:n-1) ./ n # Fourier frequencies
# int rounds to nearest integer. We want to round up or take 1/2 + 1 to
# make sure we get the whole interval from [0, pi]
ind = iseven(n) ? round(Int, n / 2 + 1) : ceil(Int, ... | [
74,
84
] | function periodogram(x::Vector)
n = length(x)
I_w = abs.(fft(x)).^2 ./ n
w = 2pi * (0:n-1) ./ n # Fourier frequencies
# int rounds to nearest integer. We want to round up or take 1/2 + 1 to
# make sure we get the whole interval from [0, pi]
ind = iseven(n) ? round(Int, n / 2 + 1) : ceil(Int, ... | function periodogram(x::Vector)
n = length(x)
I_w = abs.(fft(x)).^2 ./ n
w = 2pi * (0:n-1) ./ n # Fourier frequencies
# int rounds to nearest integer. We want to round up or take 1/2 + 1 to
# make sure we get the whole interval from [0, pi]
ind = iseven(n) ? round(Int, n / 2 + 1) : ceil(Int, ... | periodogram | 74 | 84 | src/estspec.jl | #FILE: QuantEcon.jl/test/test_estspec.jl
##CHUNK 1
@testset "Testing estspec" begin
# set up
x_20 = rand(20)
x_21 = rand(21)
@testset "testing output sizes of periodogram and ar_periodogram" begin
# test shapes of periodogram and ar_periodogram functions
for x in Any[x_20, x_21]
... |
138 | 157 | QuantEcon.jl | 182 | function ar_periodogram(x::Array, window::AbstractString="hanning", window_len::Int=7)
# run regression
x_current, x_lagged = x[2:end], x[1:end-1] # x_t and x_{t-1}
coefs = hcat(ones(size(x_lagged, 1)), x_lagged) \ x_current
# get estimated values and compute residual
est = [fill!(similar(x_lagge... | function ar_periodogram(x::Array, window::AbstractString="hanning", window_len::Int=7)
# run regression
x_current, x_lagged = x[2:end], x[1:end-1] # x_t and x_{t-1}
coefs = hcat(ones(size(x_lagged, 1)), x_lagged) \ x_current
# get estimated values and compute residual
est = [fill!(similar(x_lagge... | [
138,
157
] | function ar_periodogram(x::Array, window::AbstractString="hanning", window_len::Int=7)
# run regression
x_current, x_lagged = x[2:end], x[1:end-1] # x_t and x_{t-1}
coefs = hcat(ones(size(x_lagged, 1)), x_lagged) \ x_current
# get estimated values and compute residual
est = [fill!(similar(x_lagge... | function ar_periodogram(x::Array, window::AbstractString="hanning", window_len::Int=7)
# run regression
x_current, x_lagged = x[2:end], x[1:end-1] # x_t and x_{t-1}
coefs = hcat(ones(size(x_lagged, 1)), x_lagged) \ x_current
# get estimated values and compute residual
est = [fill!(similar(x_lagge... | ar_periodogram | 138 | 157 | src/estspec.jl | #FILE: QuantEcon.jl/src/filter.jl
##CHUNK 1
- `y_cycle::Vector` : cyclical component
- `y_trend::Vector` : trend component
"""
function hamilton_filter(y::AbstractVector, h::Integer, p::Integer)
y = Vector(y)
T = length(y)
y_cycle = fill(NaN, T)
# construct X matrix of lags
X = ones(T-p-h+1)
fo... |
12 | 24 | QuantEcon.jl | 183 | function hp_filter(y::AbstractVector{T}, λ::Real) where T <: Real
y = Vector(y)
N = length(y)
H = spdiagm(-2 => fill(λ, N-2),
-1 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
0 => vcat(1 + λ, 1 + 5λ, fill(1 + 6λ, N-4),
1 + 5λ, 1 + λ),
1 => ... | function hp_filter(y::AbstractVector{T}, λ::Real) where T <: Real
y = Vector(y)
N = length(y)
H = spdiagm(-2 => fill(λ, N-2),
-1 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
0 => vcat(1 + λ, 1 + 5λ, fill(1 + 6λ, N-4),
1 + 5λ, 1 + λ),
1 => ... | [
12,
24
] | function hp_filter(y::AbstractVector{T}, λ::Real) where T <: Real
y = Vector(y)
N = length(y)
H = spdiagm(-2 => fill(λ, N-2),
-1 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
0 => vcat(1 + λ, 1 + 5λ, fill(1 + 6λ, N-4),
1 + 5λ, 1 + λ),
1 => ... | function hp_filter(y::AbstractVector{T}, λ::Real) where T <: Real
y = Vector(y)
N = length(y)
H = spdiagm(-2 => fill(λ, N-2),
-1 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
0 => vcat(1 + λ, 1 + 5λ, fill(1 + 6λ, N-4),
1 + 5λ, 1 + λ),
1 => ... | hp_filter | 12 | 24 | src/filter.jl | #FILE: QuantEcon.jl/src/markov/markov_approx.jl
##CHUNK 1
##### Returns
- `mc::MarkovChain` : Markov chain holding the state values and transition matrix
"""
function tauchen(N::Integer, ρ::T1, σ::T2, μ=zero(promote_type(T1, T2)), n_std::T3=3) where {T1 <: Real, T2 <: Real, T3 <: Real}
# Get discretized space
... |
44 | 60 | QuantEcon.jl | 184 | function hamilton_filter(y::AbstractVector, h::Integer, p::Integer)
y = Vector(y)
T = length(y)
y_cycle = fill(NaN, T)
# construct X matrix of lags
X = ones(T-p-h+1)
for j = 1:p
X = hcat(X, y[p-j+1:T-h-j+1])
end
# do OLS regression
b = (X'*X)\(X'*y[p+h:T])
y_cycle[p+h:T... | function hamilton_filter(y::AbstractVector, h::Integer, p::Integer)
y = Vector(y)
T = length(y)
y_cycle = fill(NaN, T)
# construct X matrix of lags
X = ones(T-p-h+1)
for j = 1:p
X = hcat(X, y[p-j+1:T-h-j+1])
end
# do OLS regression
b = (X'*X)\(X'*y[p+h:T])
y_cycle[p+h:T... | [
44,
60
] | function hamilton_filter(y::AbstractVector, h::Integer, p::Integer)
y = Vector(y)
T = length(y)
y_cycle = fill(NaN, T)
# construct X matrix of lags
X = ones(T-p-h+1)
for j = 1:p
X = hcat(X, y[p-j+1:T-h-j+1])
end
# do OLS regression
b = (X'*X)\(X'*y[p+h:T])
y_cycle[p+h:T... | function hamilton_filter(y::AbstractVector, h::Integer, p::Integer)
y = Vector(y)
T = length(y)
y_cycle = fill(NaN, T)
# construct X matrix of lags
X = ones(T-p-h+1)
for j = 1:p
X = hcat(X, y[p-j+1:T-h-j+1])
end
# do OLS regression
b = (X'*X)\(X'*y[p+h:T])
y_cycle[p+h:T... | hamilton_filter | 44 | 60 | src/filter.jl | #FILE: QuantEcon.jl/src/estspec.jl
##CHUNK 1
##### Returns
- `w::Array{Float64}`: Fourier frequencies at which the periodogram is evaluated
- `I_w::Array{Float64}`: The periodogram at frequences `w`
"""
function ar_periodogram(x::Array, window::AbstractString="hanning", window_len::Int=7)
# run regression
x_... |
186 | 214 | QuantEcon.jl | 185 | function smooth(kn::Kalman, y::AbstractMatrix)
G, R = kn.G, kn.R
T = size(y, 2)
n = kn.n
x_filtered = Matrix{Float64}(undef, n, T)
sigma_filtered = Array{Float64}(undef, n, n, T)
sigma_forecast = Array{Float64}(undef, n, n, T)
logL = 0
# forecast and update
for t in 1:T
logL... | function smooth(kn::Kalman, y::AbstractMatrix)
G, R = kn.G, kn.R
T = size(y, 2)
n = kn.n
x_filtered = Matrix{Float64}(undef, n, T)
sigma_filtered = Array{Float64}(undef, n, n, T)
sigma_forecast = Array{Float64}(undef, n, n, T)
logL = 0
# forecast and update
for t in 1:T
logL... | [
186,
214
] | function smooth(kn::Kalman, y::AbstractMatrix)
G, R = kn.G, kn.R
T = size(y, 2)
n = kn.n
x_filtered = Matrix{Float64}(undef, n, T)
sigma_filtered = Array{Float64}(undef, n, n, T)
sigma_forecast = Array{Float64}(undef, n, n, T)
logL = 0
# forecast and update
for t in 1:T
logL... | function smooth(kn::Kalman, y::AbstractMatrix)
G, R = kn.G, kn.R
T = size(y, 2)
n = kn.n
x_filtered = Matrix{Float64}(undef, n, T)
sigma_filtered = Array{Float64}(undef, n, n, T)
sigma_forecast = Array{Float64}(undef, n, n, T)
logL = 0
# forecast and update
for t in 1:T
logL... | smooth | 186 | 214 | src/kalman.jl | #FILE: QuantEcon.jl/test/test_kalman.jl
##CHUNK 1
curr_x, curr_sigma = fill(one(Float64), 2, 1), Matrix(I, 2, 2) .* .75
y_observed = fill(0.75, 2, 1)
set_state!(kf, curr_x, curr_sigma)
update!(kf, y_observed)
mat_inv = inv(G * curr_sigma * G' + R)
curr_k = A * curr_sigma * (G') * mat_inv
new... |
221 | 234 | QuantEcon.jl | 186 | function stationary_values(lq::LQ)
_lq = LQ(copy(lq.Q),
copy(lq.R),
copy(lq.A),
copy(lq.B),
copy(lq.C),
copy(lq.N),
bet=copy(lq.bet),
capT=lq.capT,
rf=copy(lq.rf))
stationary_values!(_lq)
return _lq.P, _... | function stationary_values(lq::LQ)
_lq = LQ(copy(lq.Q),
copy(lq.R),
copy(lq.A),
copy(lq.B),
copy(lq.C),
copy(lq.N),
bet=copy(lq.bet),
capT=lq.capT,
rf=copy(lq.rf))
stationary_values!(_lq)
return _lq.P, _... | [
221,
234
] | function stationary_values(lq::LQ)
_lq = LQ(copy(lq.Q),
copy(lq.R),
copy(lq.A),
copy(lq.B),
copy(lq.C),
copy(lq.N),
bet=copy(lq.bet),
capT=lq.capT,
rf=copy(lq.rf))
stationary_values!(_lq)
return _lq.P, _... | function stationary_values(lq::LQ)
_lq = LQ(copy(lq.Q),
copy(lq.R),
copy(lq.A),
copy(lq.B),
copy(lq.C),
copy(lq.N),
bet=copy(lq.bet),
capT=lq.capT,
rf=copy(lq.rf))
stationary_values!(_lq)
return _lq.P, _... | stationary_values | 221 | 234 | src/lqcontrol.jl | #FILE: QuantEcon.jl/src/robustlq.jl
##CHUNK 1
- `F::Matrix{Float64}` : The optimal control matrix from above
- `P::Matrix{Float64}` : The positive semi-definite matrix defining the value function
- `K::Matrix{Float64}` : the worst-case shock matrix ``K``, where ``w_{t+1} = K x_t`` is the worst case shock
"""
function... |
61 | 116 | QuantEcon.jl | 187 | function nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2;
beta::Float64=1.0, tol::Float64=1e-8, max_iter::Int=1000)
# Apply discounting
a, b1, b2 = map(x->sqrt(beta) * x, Any[a, b1, b2])
dd = 10
its = 0
n = size(a, 1)
# NOTE: if b1/b2 has 2 dimensions, this is exactly wh... | function nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2;
beta::Float64=1.0, tol::Float64=1e-8, max_iter::Int=1000)
# Apply discounting
a, b1, b2 = map(x->sqrt(beta) * x, Any[a, b1, b2])
dd = 10
its = 0
n = size(a, 1)
# NOTE: if b1/b2 has 2 dimensions, this is exactly wh... | [
61,
116
] | function nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2;
beta::Float64=1.0, tol::Float64=1e-8, max_iter::Int=1000)
# Apply discounting
a, b1, b2 = map(x->sqrt(beta) * x, Any[a, b1, b2])
dd = 10
its = 0
n = size(a, 1)
# NOTE: if b1/b2 has 2 dimensions, this is exactly wh... | function nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2;
beta::Float64=1.0, tol::Float64=1e-8, max_iter::Int=1000)
# Apply discounting
a, b1, b2 = map(x->sqrt(beta) * x, Any[a, b1, b2])
dd = 10
its = 0
n = size(a, 1)
# NOTE: if b1/b2 has 2 dimensions, this is exactly wh... | nnash | 61 | 116 | src/lqnash.jl | #FILE: QuantEcon.jl/test/test_lqnash.jl
##CHUNK 1
0 d[1, 1]]
q2 = [-0.5*e2[3] 0
0 d[2, 2]]
s1 = zeros(2, 2)
s2 = copy(s1)
w1 = [0 0
0 0
-0.5*e1[2] B[1]/2.]
w2 = [0 0
0 0
-0.5*e2[2] B[2]/2.]
m1 = [0 0... |
97 | 108 | QuantEcon.jl | 188 | function simulate(lss::LSS, ts_length=100)
x = Matrix{Float64}(undef, lss.n, ts_length)
x[:, 1] = rand(lss.dist)
w = randn(lss.m, ts_length - 1)
v = randn(lss.l, ts_length)
for t=1:ts_length-1
x[:, t+1] = lss.A * x[:, t] .+ lss.C * w[:, t]
end
y = lss.G * x + lss.H * v
return x,... | function simulate(lss::LSS, ts_length=100)
x = Matrix{Float64}(undef, lss.n, ts_length)
x[:, 1] = rand(lss.dist)
w = randn(lss.m, ts_length - 1)
v = randn(lss.l, ts_length)
for t=1:ts_length-1
x[:, t+1] = lss.A * x[:, t] .+ lss.C * w[:, t]
end
y = lss.G * x + lss.H * v
return x,... | [
97,
108
] | function simulate(lss::LSS, ts_length=100)
x = Matrix{Float64}(undef, lss.n, ts_length)
x[:, 1] = rand(lss.dist)
w = randn(lss.m, ts_length - 1)
v = randn(lss.l, ts_length)
for t=1:ts_length-1
x[:, t+1] = lss.A * x[:, t] .+ lss.C * w[:, t]
end
y = lss.G * x + lss.H * v
return x,... | function simulate(lss::LSS, ts_length=100)
x = Matrix{Float64}(undef, lss.n, ts_length)
x[:, 1] = rand(lss.dist)
w = randn(lss.m, ts_length - 1)
v = randn(lss.l, ts_length)
for t=1:ts_length-1
x[:, t+1] = lss.A * x[:, t] .+ lss.C * w[:, t]
end
y = lss.G * x + lss.H * v
return x,... | simulate | 97 | 108 | src/lss.jl | #FILE: QuantEcon.jl/test/test_lss.jl
##CHUNK 1
@test_throws ErrorException geometric_sums(sys, 0.97, rand(3))
end
end
@testset "test stability checks: stable systems" begin
phi_0, phi_1, phi_2 = 1.1, 0.8, -0.8
A = [1.0 0.0 0
phi_0 phi_1 phi_2
0... |
127 | 137 | QuantEcon.jl | 189 | function replicate(lss::LSS, t::Integer, num_reps::Integer=100)
x = Matrix{Float64}(undef, lss.n, num_reps)
v = randn(lss.l, num_reps)
for j=1:num_reps
x_t, _ = simulate(lss, t+1)
x[:, j] = x_t[:, end]
end
y = lss.G * x + lss.H * v
return x, y
end | function replicate(lss::LSS, t::Integer, num_reps::Integer=100)
x = Matrix{Float64}(undef, lss.n, num_reps)
v = randn(lss.l, num_reps)
for j=1:num_reps
x_t, _ = simulate(lss, t+1)
x[:, j] = x_t[:, end]
end
y = lss.G * x + lss.H * v
return x, y
end | [
127,
137
] | function replicate(lss::LSS, t::Integer, num_reps::Integer=100)
x = Matrix{Float64}(undef, lss.n, num_reps)
v = randn(lss.l, num_reps)
for j=1:num_reps
x_t, _ = simulate(lss, t+1)
x[:, j] = x_t[:, end]
end
y = lss.G * x + lss.H * v
return x, y
end | function replicate(lss::LSS, t::Integer, num_reps::Integer=100)
x = Matrix{Float64}(undef, lss.n, num_reps)
v = randn(lss.l, num_reps)
for j=1:num_reps
x_t, _ = simulate(lss, t+1)
x[:, j] = x_t[:, end]
end
y = lss.G * x + lss.H * v
return x, y
end | replicate | 127 | 137 | src/lss.jl | #FILE: QuantEcon.jl/test/test_lss.jl
##CHUNK 1
@test_throws ErrorException geometric_sums(sys, 0.97, rand(3))
end
end
@testset "test stability checks: stable systems" begin
phi_0, phi_1, phi_2 = 1.1, 0.8, -0.8
A = [1.0 0.0 0
phi_0 phi_1 phi_2
0... |
146 | 158 | QuantEcon.jl | 190 | function Base.iterate(L::LSSMoments, state=(copy(L.lss.mu_0),
copy(L.lss.Sigma_0)))
A, C, G, H = L.lss.A, L.lss.C, L.lss.G, L.lss.H
mu_x, Sigma_x = state
mu_y, Sigma_y = G * mu_x, G * Sigma_x * G' + H * H'
# Update moments of x
mu_x2 = A * mu_x
Sigma... | function Base.iterate(L::LSSMoments, state=(copy(L.lss.mu_0),
copy(L.lss.Sigma_0)))
A, C, G, H = L.lss.A, L.lss.C, L.lss.G, L.lss.H
mu_x, Sigma_x = state
mu_y, Sigma_y = G * mu_x, G * Sigma_x * G' + H * H'
# Update moments of x
mu_x2 = A * mu_x
Sigma... | [
146,
158
] | function Base.iterate(L::LSSMoments, state=(copy(L.lss.mu_0),
copy(L.lss.Sigma_0)))
A, C, G, H = L.lss.A, L.lss.C, L.lss.G, L.lss.H
mu_x, Sigma_x = state
mu_y, Sigma_y = G * mu_x, G * Sigma_x * G' + H * H'
# Update moments of x
mu_x2 = A * mu_x
Sigma... | function Base.iterate(L::LSSMoments, state=(copy(L.lss.mu_0),
copy(L.lss.Sigma_0)))
A, C, G, H = L.lss.A, L.lss.C, L.lss.G, L.lss.H
mu_x, Sigma_x = state
mu_y, Sigma_y = G * mu_x, G * Sigma_x * G' + H * H'
# Update moments of x
mu_x2 = A * mu_x
Sigma... | Base.iterate | 146 | 158 | src/lss.jl | #FILE: QuantEcon.jl/src/kalman.jl
##CHUNK 1
R
k
n
cur_x_hat
cur_sigma
end
# Initializes current mean and cov to zeros
function Kalman(A, G, Q, R)
k = size(G, 1)
n = size(G, 2)
xhat = n == 1 ? zero(eltype(A)) : zeros(n)
Sigma = n == 1 ? zero(eltype(A)) : zeros(n, n)
return Kalma... |
266 | 279 | QuantEcon.jl | 191 | function remove_constants(lss::LSS)
# Get size of matrix
A = lss.A
n, m = size(A)
@assert n==m
# Sum the absolute values of each row -> Do this because we
# want to find rows that the sum of the absolute values is 1
row_sums_to_one = (vec(sum(abs, A, dims = 2) .- 1.0)) .< 1e-14
is_ii_on... | function remove_constants(lss::LSS)
# Get size of matrix
A = lss.A
n, m = size(A)
@assert n==m
# Sum the absolute values of each row -> Do this because we
# want to find rows that the sum of the absolute values is 1
row_sums_to_one = (vec(sum(abs, A, dims = 2) .- 1.0)) .< 1e-14
is_ii_on... | [
266,
279
] | function remove_constants(lss::LSS)
# Get size of matrix
A = lss.A
n, m = size(A)
@assert n==m
# Sum the absolute values of each row -> Do this because we
# want to find rows that the sum of the absolute values is 1
row_sums_to_one = (vec(sum(abs, A, dims = 2) .- 1.0)) .< 1e-14
is_ii_on... | function remove_constants(lss::LSS)
# Get size of matrix
A = lss.A
n, m = size(A)
@assert n==m
# Sum the absolute values of each row -> Do this because we
# want to find rows that the sum of the absolute values is 1
row_sums_to_one = (vec(sum(abs, A, dims = 2) .- 1.0)) .< 1e-14
is_ii_on... | remove_constants | 266 | 279 | src/lss.jl | #FILE: QuantEcon.jl/test/test_lss.jl
##CHUNK 1
C = zeros(3, 1)
G = [0.0 1.0 0.0]
lss = LSS(A, C, G)
lss2 = LSS(A[2:end, 2:end], C[2:end, :], G[:, 2:end]) # system without constant
lss_vec = [lss, lss2]
for sys in lss_vec
@test is_stable(sys) == false
... |
35 | 66 | QuantEcon.jl | 192 | function solve_discrete_lyapunov(A::ScalarOrArray,
B::ScalarOrArray,
max_it::Int=50)
# TODO: Implement Bartels-Stewardt
n = size(A, 2)
alpha0 = reshape([A;], n, n)
gamma0 = reshape([B;], n, n)
alpha1 = fill!(similar(alpha0), zero(elt... | function solve_discrete_lyapunov(A::ScalarOrArray,
B::ScalarOrArray,
max_it::Int=50)
# TODO: Implement Bartels-Stewardt
n = size(A, 2)
alpha0 = reshape([A;], n, n)
gamma0 = reshape([B;], n, n)
alpha1 = fill!(similar(alpha0), zero(elt... | [
35,
66
] | function solve_discrete_lyapunov(A::ScalarOrArray,
B::ScalarOrArray,
max_it::Int=50)
# TODO: Implement Bartels-Stewardt
n = size(A, 2)
alpha0 = reshape([A;], n, n)
gamma0 = reshape([B;], n, n)
alpha1 = fill!(similar(alpha0), zero(elt... | function solve_discrete_lyapunov(A::ScalarOrArray,
B::ScalarOrArray,
max_it::Int=50)
# TODO: Implement Bartels-Stewardt
n = size(A, 2)
alpha0 = reshape([A;], n, n)
gamma0 = reshape([B;], n, n)
alpha1 = fill!(similar(alpha0), zero(elt... | solve_discrete_lyapunov | 35 | 66 | src/matrix_eqn.jl | #FILE: QuantEcon.jl/src/quadsums.jl
##CHUNK 1
"""
function var_quadratic_sum(A::ScalarOrArray, C::ScalarOrArray, H::ScalarOrArray,
bet::Real, x0::ScalarOrArray)
n = size(A, 1)
# coerce shapes
A = reshape([A;], n, n)
C = reshape([C;], n, n)
H = reshape([H;], n, n)
x0 ... |
103 | 177 | QuantEcon.jl | 193 | function solve_discrete_riccati(A::ScalarOrArray, B::ScalarOrArray,
Q::ScalarOrArray,
R::ScalarOrArray,
N::ScalarOrArray=zeros(size(R, 1), size(Q, 1));
tolerance::Float64=1e-10,
... | function solve_discrete_riccati(A::ScalarOrArray, B::ScalarOrArray,
Q::ScalarOrArray,
R::ScalarOrArray,
N::ScalarOrArray=zeros(size(R, 1), size(Q, 1));
tolerance::Float64=1e-10,
... | [
103,
177
] | function solve_discrete_riccati(A::ScalarOrArray, B::ScalarOrArray,
Q::ScalarOrArray,
R::ScalarOrArray,
N::ScalarOrArray=zeros(size(R, 1), size(Q, 1));
tolerance::Float64=1e-10,
... | function solve_discrete_riccati(A::ScalarOrArray, B::ScalarOrArray,
Q::ScalarOrArray,
R::ScalarOrArray,
N::ScalarOrArray=zeros(size(R, 1), size(Q, 1));
tolerance::Float64=1e-10,
... | solve_discrete_riccati | 103 | 177 | src/matrix_eqn.jl | #FILE: QuantEcon.jl/test/test_lqcontrol.jl
##CHUNK 1
r = 0.05
bet = 1 / (1 + r)
t = 45
c_bar = 2.0
sigma = 0.25
mu = 1.0
q = 1e6
# == Formulate as an LQ problem == #
Q = 1.0
R = zeros(2, 2)
Rf = zeros(2, 2); Rf[1, 1] = q
A ... |
53 | 102 | QuantEcon.jl | 194 | function qnwlege(n::Int, a::Real, b::Real)
maxit = 10000
m = fix((n + 1) / 2.0)
xm = 0.5 * (b + a)
xl = 0.5 * (b - a)
nodes = zeros(n)
weights = copy(nodes)
i = 1:m
z = cos.(pi * (i .- 0.25) ./ (n + 0.5))
# allocate memory for loop arrays
p3 = similar(z)
pp = similar(z)
... | function qnwlege(n::Int, a::Real, b::Real)
maxit = 10000
m = fix((n + 1) / 2.0)
xm = 0.5 * (b + a)
xl = 0.5 * (b - a)
nodes = zeros(n)
weights = copy(nodes)
i = 1:m
z = cos.(pi * (i .- 0.25) ./ (n + 0.5))
# allocate memory for loop arrays
p3 = similar(z)
pp = similar(z)
... | [
53,
102
] | function qnwlege(n::Int, a::Real, b::Real)
maxit = 10000
m = fix((n + 1) / 2.0)
xm = 0.5 * (b + a)
xl = 0.5 * (b - a)
nodes = zeros(n)
weights = copy(nodes)
i = 1:m
z = cos.(pi * (i .- 0.25) ./ (n + 0.5))
# allocate memory for loop arrays
p3 = similar(z)
pp = similar(z)
... | function qnwlege(n::Int, a::Real, b::Real)
maxit = 10000
m = fix((n + 1) / 2.0)
xm = 0.5 * (b + a)
xl = 0.5 * (b - a)
nodes = zeros(n)
weights = copy(nodes)
i = 1:m
z = cos.(pi * (i .- 0.25) ./ (n + 0.5))
# allocate memory for loop arrays
p3 = similar(z)
pp = similar(z)
... | qnwlege | 53 | 102 | src/quad.jl | #FILE: QuantEcon.jl/other/quadrature.jl
##CHUNK 1
p2 = 1
for j=2:n
p3 = p2
p2 = p1
temp = 2 * j + ab
aa = 2 * j * (j + ab) * (temp - 2)
bb = (temp - 1) * (a * a - b * b + temp * (temp - 2) * z)
c = 2 * (j - 1 + a... |
158 | 220 | QuantEcon.jl | 195 | function qnwnorm(n::Int)
maxit = 100
pim4 = 1 / pi^(0.25)
m = floor(Int, (n + 1) / 2)
nodes = zeros(n)
weights = zeros(n)
z = sqrt(2n + 1) - 1.85575 * ((2n + 1).^(-1 / 6))
for i = 1:m
# Reasonable starting values for root finding
if i == 1
z = sqrt(2n + 1) - 1.8... | function qnwnorm(n::Int)
maxit = 100
pim4 = 1 / pi^(0.25)
m = floor(Int, (n + 1) / 2)
nodes = zeros(n)
weights = zeros(n)
z = sqrt(2n + 1) - 1.85575 * ((2n + 1).^(-1 / 6))
for i = 1:m
# Reasonable starting values for root finding
if i == 1
z = sqrt(2n + 1) - 1.8... | [
158,
220
] | function qnwnorm(n::Int)
maxit = 100
pim4 = 1 / pi^(0.25)
m = floor(Int, (n + 1) / 2)
nodes = zeros(n)
weights = zeros(n)
z = sqrt(2n + 1) - 1.85575 * ((2n + 1).^(-1 / 6))
for i = 1:m
# Reasonable starting values for root finding
if i == 1
z = sqrt(2n + 1) - 1.8... | function qnwnorm(n::Int)
maxit = 100
pim4 = 1 / pi^(0.25)
m = floor(Int, (n + 1) / 2)
nodes = zeros(n)
weights = zeros(n)
z = sqrt(2n + 1) - 1.85575 * ((2n + 1).^(-1 / 6))
for i = 1:m
# Reasonable starting values for root finding
if i == 1
z = sqrt(2n + 1) - 1.8... | qnwnorm | 158 | 220 | src/quad.jl | #FILE: QuantEcon.jl/other/quadrature.jl
##CHUNK 1
r1 = (1 + 0.235b) / (0.766 + 0.119b)
r2 = 1 / (1 + 0.639 * (n - 4) / (1 + 0.71 * (n - 4)))
r3 = 1 / (1 + 20a / ((7.5+ a ) * n * n))
z = z + (z - x[n-3]) * r1 * r2 * r3
elseif i == n
r1 = (1 + 0.37b) / ... |
237 | 255 | QuantEcon.jl | 196 | function qnwsimp(n::Int, a::Real, b::Real)
if n <= 1
error("In qnwsimp: n must be integer greater than one.")
end
if n % 2 == 0
@warn("In qnwsimp: n must be odd integer - increasing by 1.")
n += 1
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = repeat([... | function qnwsimp(n::Int, a::Real, b::Real)
if n <= 1
error("In qnwsimp: n must be integer greater than one.")
end
if n % 2 == 0
@warn("In qnwsimp: n must be odd integer - increasing by 1.")
n += 1
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = repeat([... | [
237,
255
] | function qnwsimp(n::Int, a::Real, b::Real)
if n <= 1
error("In qnwsimp: n must be integer greater than one.")
end
if n % 2 == 0
@warn("In qnwsimp: n must be odd integer - increasing by 1.")
n += 1
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = repeat([... | function qnwsimp(n::Int, a::Real, b::Real)
if n <= 1
error("In qnwsimp: n must be integer greater than one.")
end
if n % 2 == 0
@warn("In qnwsimp: n must be odd integer - increasing by 1.")
n += 1
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = repeat([... | qnwsimp | 237 | 255 | src/quad.jl | #CURRENT FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
if abs(z - z1) < 1e-14
break
end
end
if it >= maxit
error("Failed to converge in qnwnorm")
end
nodes[n + 1 - i] = z
nodes[i] = -z
weights[i] = 2 ./ (pp .* pp)
w... |
272 | 282 | QuantEcon.jl | 197 | function qnwtrap(n::Int, a::Real, b::Real)
if n < 1
error("n must be at least 1")
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = fill(dx, n)
weights[[1, n]] .*= 0.5
return nodes, weights
end | function qnwtrap(n::Int, a::Real, b::Real)
if n < 1
error("n must be at least 1")
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = fill(dx, n)
weights[[1, n]] .*= 0.5
return nodes, weights
end | [
272,
282
] | function qnwtrap(n::Int, a::Real, b::Real)
if n < 1
error("n must be at least 1")
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = fill(dx, n)
weights[[1, n]] .*= 0.5
return nodes, weights
end | function qnwtrap(n::Int, a::Real, b::Real)
if n < 1
error("n must be at least 1")
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = fill(dx, n)
weights[[1, n]] .*= 0.5
return nodes, weights
end | qnwtrap | 272 | 282 | src/quad.jl | #CURRENT FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
if n % 2 == 0
@warn("In qnwsimp: n must be odd integer - increasing by 1.")
n += 1
end
dx = (b - a) / (n - 1)
nodes = collect(a:dx:b)
weights = repeat([2.0, 4.0], Int((n + 1) / 2))
weights = weights[1:n]
weights[1] = 1
w... |
301 | 391 | QuantEcon.jl | 198 | function qnwbeta(n::Int, a::Real, b::Real)
a -= 1
b -= 1
ab = a + b
maxit = 25
x = zeros(n)
w = zeros(n)
z::Float64 = 0.0
for i = 1:n
if i == 1
an = a / n
bn = b / n
r1 = (1 + a) * (2.78 / (4 + n * n) + 0.768an / n)
r2 = 1 + 1.4... | function qnwbeta(n::Int, a::Real, b::Real)
a -= 1
b -= 1
ab = a + b
maxit = 25
x = zeros(n)
w = zeros(n)
z::Float64 = 0.0
for i = 1:n
if i == 1
an = a / n
bn = b / n
r1 = (1 + a) * (2.78 / (4 + n * n) + 0.768an / n)
r2 = 1 + 1.4... | [
301,
391
] | function qnwbeta(n::Int, a::Real, b::Real)
a -= 1
b -= 1
ab = a + b
maxit = 25
x = zeros(n)
w = zeros(n)
z::Float64 = 0.0
for i = 1:n
if i == 1
an = a / n
bn = b / n
r1 = (1 + a) * (2.78 / (4 + n * n) + 0.768an / n)
r2 = 1 + 1.4... | function qnwbeta(n::Int, a::Real, b::Real)
a -= 1
b -= 1
ab = a + b
maxit = 25
x = zeros(n)
w = zeros(n)
z::Float64 = 0.0
for i = 1:n
if i == 1
an = a / n
bn = b / n
r1 = (1 + a) * (2.78 / (4 + n * n) + 0.768an / n)
r2 = 1 + 1.4... | qnwbeta | 301 | 391 | src/quad.jl | #FILE: QuantEcon.jl/other/quadrature.jl
##CHUNK 1
if i == 1
an = a / n
bn = b / n
r1 = (1 + a) * (2.78 / (4 + n * n) + 0.768an / n)
r2 = 1 + 1.48 * an + 0.96bn + 0.452an*an + 0.83an*bn
z = 1 - r1 / r2
elseif i == 2
r1 = (4.1 + a) /... |
410 | 464 | QuantEcon.jl | 199 | function qnwgamma(n::Int, a::Real = 1.0, b::Real = 1.0)
a < 0 && error("shape parameter must be positive")
b < 0 && error("scale parameter must be positive")
a -= 1
maxit = 25
fact = -exp((logabsgamma(a + n))[1] - (logabsgamma(n))[1] - (logabsgamma(a + 1))[1] )
nodes = zeros(n)
weights = ze... | function qnwgamma(n::Int, a::Real = 1.0, b::Real = 1.0)
a < 0 && error("shape parameter must be positive")
b < 0 && error("scale parameter must be positive")
a -= 1
maxit = 25
fact = -exp((logabsgamma(a + n))[1] - (logabsgamma(n))[1] - (logabsgamma(a + 1))[1] )
nodes = zeros(n)
weights = ze... | [
410,
464
] | function qnwgamma(n::Int, a::Real = 1.0, b::Real = 1.0)
a < 0 && error("shape parameter must be positive")
b < 0 && error("scale parameter must be positive")
a -= 1
maxit = 25
fact = -exp((logabsgamma(a + n))[1] - (logabsgamma(n))[1] - (logabsgamma(a + 1))[1] )
nodes = zeros(n)
weights = ze... | function qnwgamma(n::Int, a::Real = 1.0, b::Real = 1.0)
a < 0 && error("shape parameter must be positive")
b < 0 && error("scale parameter must be positive")
a -= 1
maxit = 25
fact = -exp((logabsgamma(a + n))[1] - (logabsgamma(n))[1] - (logabsgamma(a + 1))[1] )
nodes = zeros(n)
weights = ze... | qnwgamma | 410 | 464 | src/quad.jl | #FILE: QuantEcon.jl/other/quadrature.jl
##CHUNK 1
function qnwbeta(n::Int, a::T, b::S) where {T <: Real, S <: Real}
a -= 1
b -= 1
maxit = 25
x = zeros(n)
w = zeros(n)
for i=1:n
if i == 1
an = a / n
bn = b / n
r1 = (1 + a) * (2.78 / (4 + n * n) + 0.7... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.