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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? one(c) : c
end
return result
end | 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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? one(c) : c
end
return result
end | [
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? one(c) : c
end
return result
end | 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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? one(c) : c
end
return result
end | 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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
end
function logccdf(d::Truncated, x::Real)
result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp
return if d.lower !== nothing && x <= d.lower
zero(result)
elseif d.upper !== nothing && x > d.upper
oftype(result, -Inf)
else
result
##CHUNK 2
result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper !== nothing && x >= d.upper
zero(result)
else
result
end
end
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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
#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, xs)
T = typeof(x)
if 0 < p < 1
x0 = T(xs)
while abs(x-x0) > max(abs(x),abs(x0)) * tol
x0 = x
x = x0 + (ccdf(d, x0)-p) / pdf(d, x0)
end
return x
elseif p == 1
return T(minimum(d))
#FILE: Distributions.jl/src/censored.jl
##CHUNK 1
lower = d.lower
upper = d.upper
px = float(pdf(d0, x))
return if _in_open_interval(x, lower, upper)
px
elseif x == lower
x == upper ? one(px) : oftype(px, cdf(d0, x))
elseif x == upper
if value_support(typeof(d0)) === Discrete
oftype(px, ccdf(d0, x) + px)
else
oftype(px, ccdf(d0, x))
end
else # not in support
zero(px)
end
end
function logpdf(d::Censored, x::Real)
d0 = d.uncensored
##CHUNK 2
result = logcdf(d.uncensored, x)
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper === nothing || x < d.upper
result
else
zero(result)
end
end
function ccdf(d::Censored, x::Real)
lower = d.lower
upper = d.upper
result = ccdf(d.uncensored, x)
return if lower !== nothing && x < lower
one(result)
elseif upper === nothing || x < upper
result
else
zero(result)
#CURRENT FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end
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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
##CHUNK 2
# note: incorrect for discrete distributions whose support includes non-integer numbers
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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end
function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
##CHUNK 3
elseif isnan(x)
oftype(c, NaN)
elseif x < 0
zero(c)
else
oftype(c, -Inf)
end
end
# implementation of the cdf for distributions whose support is a unitrange of integers
# note: incorrect for discrete distributions whose support includes non-integer numbers
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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
##CHUNK 4
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
##CHUNK 5
end
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end
### macros to use StatsFuns for method implementation
macro _delegate_statsfuns(D, fpre, psyms...)
|
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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end | 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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end | [
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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end | 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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end | 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, xs)
T = typeof(x)
if 0 < p < 1
x0 = T(xs)
while abs(x-x0) > max(abs(x),abs(x0)) * tol
x0 = x
x = x0 + (ccdf(d, x0)-p) / pdf(d, x0)
end
return x
elseif p == 1
return T(minimum(d))
#FILE: Distributions.jl/src/truncate.jl
##CHUNK 1
result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper !== nothing && x >= d.upper
zero(result)
else
result
end
end
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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
##CHUNK 2
return if d.lower !== nothing && x < d.lower
zero(result)
elseif d.upper !== nothing && x >= d.upper
one(result)
else
result
end
end
function logcdf(d::Truncated, x::Real)
result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper !== nothing && x >= d.upper
zero(result)
else
result
end
end
#FILE: Distributions.jl/src/censored.jl
##CHUNK 1
result = logcdf(d.uncensored, x)
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper === nothing || x < d.upper
result
else
zero(result)
end
end
function ccdf(d::Censored, x::Real)
lower = d.lower
upper = d.upper
result = ccdf(d.uncensored, x)
return if lower !== nothing && x < lower
one(result)
elseif upper === nothing || x < upper
result
else
zero(result)
##CHUNK 2
_clamp(x, l, u) = clamp(x, l, u)
_clamp(x, ::Nothing, u) = min(x, u)
_clamp(x, l, ::Nothing) = max(x, l)
_clamp(x, ::Nothing, u::Nothing) = x
_to_truncated(d::Censored) = truncated(d.uncensored, d.lower, d.upper)
# utilities for non-inclusive CDF p(x < u) and inclusive CCDF (p ≥ u)
_logcdf_noninclusive(d::UnivariateDistribution, x) = logcdf(d, x)
function _logcdf_noninclusive(d::DiscreteUnivariateDistribution, x)
return logsubexp(logcdf(d, x), logpdf(d, x))
end
_ccdf_inclusive(d::UnivariateDistribution, x) = ccdf(d, x)
_ccdf_inclusive(d::DiscreteUnivariateDistribution, x) = ccdf(d, x) + pdf(d, x)
_logccdf_inclusive(d::UnivariateDistribution, x) = logccdf(d, x)
function _logccdf_inclusive(d::DiscreteUnivariateDistribution, x)
return logaddexp(logccdf(d, x), logpdf(d, x))
#CURRENT FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
x >= maximum_d ? one(c) : c
end
return result
end
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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
##CHUNK 2
elseif isnan(x)
oftype(c, NaN)
elseif x < 0
zero(c)
else
oftype(c, -Inf)
end
end
# implementation of the cdf for distributions whose support is a unitrange of integers
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
##CHUNK 3
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? one(c) : c
end
return result
end
function integerunitrange_logcdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
##CHUNK 4
end
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end
### macros to use StatsFuns for method implementation
macro _delegate_statsfuns(D, fpre, psyms...)
##CHUNK 5
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
|
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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end | 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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end | [
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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end | 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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end | 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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
end
function logccdf(d::Truncated, x::Real)
result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp
return if d.lower !== nothing && x <= d.lower
zero(result)
elseif d.upper !== nothing && x > d.upper
oftype(result, -Inf)
else
result
##CHUNK 2
result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper !== nothing && x >= d.upper
zero(result)
else
result
end
end
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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
##CHUNK 3
end
function logpdf(d::Truncated, x::Real)
result = logpdf(d.untruncated, x) - d.logtp
return _in_closed_interval(x, d.lower, d.upper) ? result : oftype(result, -Inf)
end
function cdf(d::Truncated, x::Real)
result = clamp((cdf(d.untruncated, x) - d.lcdf) / 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
zero(result)
elseif d.upper !== nothing && x >= d.upper
one(result)
else
result
end
end
function logcdf(d::Truncated, x::Real)
#FILE: Distributions.jl/src/quantilealgs.jl
##CHUNK 1
elseif p == 0
return T(maximum(d))
else
return T(NaN)
end
end
function invlogcdf_newton(d::ContinuousUnivariateDistribution, lp::Real, xs::Real=mode(d), tol::Real=1e-12)
T = typeof(lp - logpdf(d,xs))
if -Inf < lp < 0
x0 = T(xs)
if lp < logcdf(d,x0)
x = x0 - exp(lp - logpdf(d,x0) + logexpm1(max(logcdf(d,x0)-lp,0)))
while abs(x-x0) >= max(abs(x),abs(x0)) * tol
x0 = x
x = x0 - exp(lp - logpdf(d,x0) + logexpm1(max(logcdf(d,x0)-lp,0)))
end
else
x = x0 + exp(lp - logpdf(d,x0) + log1mexp(min(logcdf(d,x0)-lp,0)))
while abs(x-x0) >= max(abs(x),abs(x0))*tol
#CURRENT FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = 1 - sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
##CHUNK 2
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end
### macros to use StatsFuns for method implementation
macro _delegate_statsfuns(D, fpre, psyms...)
##CHUNK 3
elseif isnan(x)
oftype(c, NaN)
elseif x < 0
zero(c)
else
oftype(c, -Inf)
end
end
# implementation of the cdf for distributions whose support is a unitrange of integers
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
##CHUNK 4
x >= maximum_d ? one(c) : c
end
return result
end
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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end
##CHUNK 5
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? one(c) : c
end
return result
end
function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
##CHUNK 6
# gradlogpdf
gradlogpdf(d::ContinuousUnivariateDistribution, x::Real) = throw(MethodError(gradlogpdf, (d, x)))
function _pdf_fill_outside!(r::AbstractArray, d::DiscreteUnivariateDistribution, X::UnitRange)
vl = vfirst = first(X)
vr = vlast = last(X)
n = vlast - vfirst + 1
if islowerbounded(d)
lb = minimum(d)
if vl < lb
vl = lb
end
end
if isupperbounded(d)
ub = maximum(d)
if vr > ub
vr = ub
end
|
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end | 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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end | [
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end | 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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end | 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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
end
function logccdf(d::Truncated, x::Real)
result = logsubexp(logccdf(d.untruncated, x), log1p(-d.ucdf)) - d.logtp
return if d.lower !== nothing && x <= d.lower
zero(result)
elseif d.upper !== nothing && x > d.upper
oftype(result, -Inf)
else
result
##CHUNK 2
result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper !== nothing && x >= d.upper
zero(result)
else
result
end
end
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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
#FILE: Distributions.jl/src/censored.jl
##CHUNK 1
lower = d.lower
upper = d.upper
logpx = logpdf(d0, x)
return if _in_open_interval(x, lower, upper)
logpx
elseif x == lower
x == upper ? zero(logpx) : oftype(logpx, logcdf(d0, x))
elseif x == upper
if value_support(typeof(d0)) === Discrete
oftype(logpx, logaddexp(logccdf(d0, x), logpx))
else
oftype(logpx, logccdf(d0, x))
end
else # not in support
oftype(logpx, -Inf)
end
end
function loglikelihood(d::Censored, x::AbstractArray{<:Real})
d0 = d.uncensored
##CHUNK 2
function _logcdf_noninclusive(d::DiscreteUnivariateDistribution, x)
return logsubexp(logcdf(d, x), logpdf(d, x))
end
_ccdf_inclusive(d::UnivariateDistribution, x) = ccdf(d, x)
_ccdf_inclusive(d::DiscreteUnivariateDistribution, x) = ccdf(d, x) + pdf(d, x)
_logccdf_inclusive(d::UnivariateDistribution, x) = logccdf(d, x)
function _logccdf_inclusive(d::DiscreteUnivariateDistribution, x)
return logaddexp(logccdf(d, x), logpdf(d, x))
end
# like xlogx but for input on log scale, safe when x == -Inf
function xexpx(x::Real)
result = x * exp(x)
return x == -Inf ? zero(result) : result
end
# x * exp(y) with correct limit for y == -Inf
function xexpy(x::Real, y::Real)
#CURRENT FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
result = if isfinite(minimum_d) && !(isfinite(maximum_d) && x >= div(minimum_d + maximum_d, 2))
c = 1 - sum(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end
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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
##CHUNK 2
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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end
### macros to use StatsFuns for method implementation
macro _delegate_statsfuns(D, fpre, psyms...)
##CHUNK 3
x >= maximum_d ? one(c) : c
end
return result
end
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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end
##CHUNK 4
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? one(c) : c
end
return result
end
function integerunitrange_ccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
##CHUNK 5
elseif isnan(x)
oftype(c, NaN)
elseif x < 0
zero(c)
else
oftype(c, -Inf)
end
end
# implementation of the cdf for distributions whose support is a unitrange of integers
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
##CHUNK 6
end
end
function logccdf_int(d::DiscreteUnivariateDistribution, x::Real)
# handle `NaN` and `±Inf` which can't be truncated to `Int`
isfinite_x = isfinite(x)
_x = isfinite_x ? x : zero(x)
c = float(logccdf(d, floor(Int, _x)))
return if isfinite_x
c
elseif isnan(x)
oftype(c, NaN)
elseif x < 0
zero(c)
else
oftype(c, -Inf)
end
end
# implementation of the cdf for distributions whose support is a unitrange of integers
|
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.promote_eltype(η, logc0)
return LKJCholesky(d, T(η), uplo, T(logc0))
end | 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.promote_eltype(η, logc0)
return LKJCholesky(d, T(η), uplo, T(logc0))
end | [
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.promote_eltype(η, logc0)
return LKJCholesky(d, T(η), uplo, T(logc0))
end | 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.promote_eltype(η, logc0)
return LKJCholesky(d, T(η), uplo, T(logc0))
end | 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
end
# -----------------------------------------------------------------------------
# Constructors
# -----------------------------------------------------------------------------
function LKJ(d::Integer, η::Real; check_args::Bool=true)
@check_args(
LKJ,
(d, d > 0, "matrix dimension must be positive."),
(η, η > 0, "shape parameter must be positive."),
)
##CHUNK 2
# -----------------------------------------------------------------------------
# Constructors
# -----------------------------------------------------------------------------
function LKJ(d::Integer, η::Real; check_args::Bool=true)
@check_args(
LKJ,
(d, d > 0, "matrix dimension must be positive."),
(η, η > 0, "shape parameter must be positive."),
)
logc0 = lkj_logc0(d, η)
T = Base.promote_eltype(η, logc0)
LKJ{T, typeof(d)}(d, T(η), T(logc0))
end
# -----------------------------------------------------------------------------
# REPL display
# -----------------------------------------------------------------------------
show(io::IO, d::LKJ) = show_multline(io, d, [(:d, d.d), (:η, d.η)])
##CHUNK 3
σ² * (ones(partype(lkj), d, d) - I)
end
params(d::LKJ) = (d.d, d.η)
@inline partype(d::LKJ{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
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
#FILE: Distributions.jl/test/cholesky/lkjcholesky.jl
##CHUNK 1
return L
end
function cholesky_vec_to_corr_vec(l)
L = vec_to_stricttril(l)
for i in axes(L, 1)
w = view(L, i, 1:(i-1))
wnorm = norm(w)
if wnorm > 1
w ./= wnorm
wnorm = 1
end
L[i, i] = sqrt(1 - wnorm^2)
end
return stricttril_to_vec(L * L')
end
@testset "Constructors" begin
@testset for p in (4, 5), η in (2, 3.5)
d = LKJCholesky(p, η)
@test d.d == p
#CURRENT FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
"""
struct LKJCholesky{T <: Real} <: Distribution{CholeskyVariate,Continuous}
d::Int
η::T
uplo::Char
logc0::T
end
# -----------------------------------------------------------------------------
# Constructors
# -----------------------------------------------------------------------------
# adapted from LinearAlgebra.char_uplo
function _char_uplo(uplo::Union{Symbol,Char})
uplo ∈ (:U, 'U') && return 'U'
uplo ∈ (:L, 'L') && return 'L'
throw(ArgumentError("uplo argument must be either 'U' (upper) or 'L' (lower)"))
end
##CHUNK 2
end
else # R.uplo === 'L'
for (i, iind) in enumerate(iinds)
row_jinds = view(jinds, 1:i)
sum(abs2, view(factors, iind, row_jinds)) ≈ 1 || return false
end
end
return true
end
function mode(d::LKJCholesky; check_args::Bool=true)
@check_args(
LKJCholesky,
@setup(η = d.η),
(η, η > 1, "mode is defined only when η > 1."),
)
factors = Matrix{eltype(d)}(LinearAlgebra.I, size(d))
return LinearAlgebra.Cholesky(factors, d.uplo, 0)
end
##CHUNK 3
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_tri!(
rng::AbstractRNG,
A::AbstractMatrix,
d::Int,
η::Real,
::Val{uplo},
) where {uplo}
# Section 3.2 in LKJ (2009 JMA)
##CHUNK 4
function mode(d::LKJCholesky; check_args::Bool=true)
@check_args(
LKJCholesky,
@setup(η = d.η),
(η, η > 1, "mode is defined only when η > 1."),
)
factors = Matrix{eltype(d)}(LinearAlgebra.I, size(d))
return LinearAlgebra.Cholesky(factors, d.uplo, 0)
end
StatsBase.params(d::LKJCholesky) = (d.d, d.η, d.uplo)
@inline partype(::LKJCholesky{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function logkernel(d::LKJCholesky, R::LinearAlgebra.Cholesky)
factors = R.factors
##CHUNK 5
end
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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
##CHUNK 6
# -----------------------------------------------------------------------------
# REPL display
# -----------------------------------------------------------------------------
Base.show(io::IO, d::LKJCholesky) = show(io, d, (:d, :η, :uplo))
# -----------------------------------------------------------------------------
# Conversion
# -----------------------------------------------------------------------------
function Base.convert(::Type{LKJCholesky{T}}, d::LKJCholesky) where T <: Real
return LKJCholesky{T}(d.d, T(d.η), d.uplo, T(d.logc0))
end
Base.convert(::Type{LKJCholesky{T}}, d::LKJCholesky{T}) where T <: Real = d
function convert(::Type{LKJCholesky{T}}, d::Integer, η::Real, uplo::Char, logc0::Real) where T <: Real
return LKJCholesky{T}(Int(d), T(η), uplo, T(logc0))
end
# -----------------------------------------------------------------------------
|
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(jinds)
col_iinds = view(iinds, 1:j)
sum(abs2, view(factors, col_iinds, jind)) ≈ 1 || return false
end
else # R.uplo === 'L'
for (i, iind) in enumerate(iinds)
row_jinds = view(jinds, 1:i)
sum(abs2, view(factors, iind, row_jinds)) ≈ 1 || return false
end
end
return true
end | 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(jinds)
col_iinds = view(iinds, 1:j)
sum(abs2, view(factors, col_iinds, jind)) ≈ 1 || return false
end
else # R.uplo === 'L'
for (i, iind) in enumerate(iinds)
row_jinds = view(jinds, 1:i)
sum(abs2, view(factors, iind, row_jinds)) ≈ 1 || return false
end
end
return true
end | [
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(jinds)
col_iinds = view(iinds, 1:j)
sum(abs2, view(factors, col_iinds, jind)) ≈ 1 || return false
end
else # R.uplo === 'L'
for (i, iind) in enumerate(iinds)
row_jinds = view(jinds, 1:i)
sum(abs2, view(factors, iind, row_jinds)) ≈ 1 || return false
end
end
return true
end | 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(jinds)
col_iinds = view(iinds, 1:j)
sum(abs2, view(factors, col_iinds, jind)) ≈ 1 || return false
end
else # R.uplo === 'L'
for (i, iind) in enumerate(iinds)
row_jinds = view(jinds, 1:i)
sum(abs2, view(factors, iind, row_jinds)) ≈ 1 || return false
end
end
return true
end | 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, :], marginal) >= α / L / nkstests
end
end
end
# Compute logdetjac of ϕ: L → L L' where only strict lower triangle of L and L L' are unique
function cholesky_inverse_logdetjac(L)
size(L, 1) == 1 && return 0.0
J = jacobian(central_fdm(5, 1), cholesky_vec_to_corr_vec, stricttril_to_vec(L))[1]
return logabsdet(J)[1]
end
stricttril_to_vec(L) = [L[i, j] for i in axes(L, 1) for j in 1:(i - 1)]
##CHUNK 2
end
end
# Compute logdetjac of ϕ: L → L L' where only strict lower triangle of L and L L' are unique
function cholesky_inverse_logdetjac(L)
size(L, 1) == 1 && return 0.0
J = jacobian(central_fdm(5, 1), cholesky_vec_to_corr_vec, stricttril_to_vec(L))[1]
return logabsdet(J)[1]
end
stricttril_to_vec(L) = [L[i, j] for i in axes(L, 1) for j in 1:(i - 1)]
function vec_to_stricttril(l)
n = length(l)
p = Int((1 + sqrt(8n + 1)) / 2)
L = similar(l, p, p)
fill!(L, 0)
k = 1
for i in 1:p, j in 1:(i - 1)
L[i, j] = l[k]
k += 1
end
##CHUNK 3
end
L[i, i] = sqrt(1 - wnorm^2)
end
return stricttril_to_vec(L * L')
end
@testset "Constructors" begin
@testset for p in (4, 5), η in (2, 3.5)
d = LKJCholesky(p, η)
@test d.d == p
@test d.η == η
@test d.uplo == 'L'
@test d.logc0 == LKJ(p, η).logc0
end
@test_throws DomainError LKJCholesky(0, 2)
@test_throws DomainError LKJCholesky(4, 0.0)
@test_throws DomainError LKJCholesky(4, -1)
for uplo in (:U, 'U')
#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 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 = eltype(A)
z = zero(T)
axes1 = axes(A, 1)
@inbounds for (j, jdx) in enumerate(axes(A, 2)), (i, idx) in enumerate(axes1)
#FILE: Distributions.jl/src/multivariate/mvnormal.jl
##CHUNK 1
end
function fit_mle(D::Type{FullNormal}, x::AbstractMatrix{Float64}, w::AbstractVector)
m = size(x, 1)
n = size(x, 2)
length(w) == n || throw(DimensionMismatch("Inconsistent argument dimensions"))
inv_sw = inv(sum(w))
mu = BLAS.gemv('N', inv_sw, x, w)
z = Matrix{Float64}(undef, m, n)
for j = 1:n
cj = sqrt(w[j])
for i = 1:m
@inbounds z[i,j] = (x[i,j] - mu[i]) * cj
end
end
C = BLAS.syrk('U', 'N', inv_sw, z)
LinearAlgebra.copytri!(C, 'U')
MvNormal(mu, PDMat(C))
#CURRENT FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
end
StatsBase.params(d::LKJCholesky) = (d.d, d.η, d.uplo)
@inline partype(::LKJCholesky{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
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(diagind(factors)), 1)) do (i, di)
return (c - i) * log(factors[di])
end
##CHUNK 2
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::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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end
##CHUNK 3
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{<:Real}},
)
allocate = any(!isassigned(Rs, i) for i in eachindex(Rs)) || any(R -> size(R, 1) != d.d, Rs)
return Random.rand!(rng, d, Rs, allocate)
end
#
# onion method
#
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))
##CHUNK 4
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(diagind(factors)), 1)) do (i, di)
return (c - i) * log(factors[di])
end
return logp
end
function logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky)
lp = _logpdf(d, R)
return insupport(d, R) ? lp : oftype(lp, -Inf)
end
_logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logkernel(d, R) + d.logc0
##CHUNK 5
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_tri!(
rng::AbstractRNG,
A::AbstractMatrix,
d::Int,
η::Real,
::Val{uplo},
|
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(diagind(factors)), 1)) do (i, di)
return (c - i) * log(factors[di])
end
return logp
end | 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(diagind(factors)), 1)) do (i, di)
return (c - i) * log(factors[di])
end
return logp
end | [
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(diagind(factors)), 1)) do (i, di)
return (c - i) * log(factors[di])
end
return logp
end | 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(diagind(factors)), 1)) do (i, di)
return (c - i) * log(factors[di])
end
return logp
end | 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
# -----------------------------------------------------------------------------
# Mitra (1970 Sankhyā)
function _rand!(rng::AbstractRNG, d::MatrixBeta, A::AbstractMatrix)
S1 = PDMat( rand(rng, d.W1) )
S2 = PDMat( rand(rng, d.W2) )
S = S1 + S2
invL = Matrix( inv(S.chol.L) )
A .= X_A_Xt(S1, invL)
end
# -----------------------------------------------------------------------------
#FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 1
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_onion_loginvconst(d, η)
end
return logc0
end
logkernel(d::LKJ, R::AbstractMatrix) = (d.η - 1) * logdet(R)
# -----------------------------------------------------------------------------
# Sampling
##CHUNK 2
function _marginal(lkj::LKJ)
d = lkj.d
η = lkj.η
α = η + 0.5d - 1
AffineDistribution(-1, 2, Beta(α, α))
end
# -----------------------------------------------------------------------------
# Test utils
# -----------------------------------------------------------------------------
function _univariate(d::LKJ)
check_univariate(d)
return DiscreteNonParametric([one(d.η)], [one(d.η)])
end
function _rand_params(::Type{LKJ}, elty, n::Int, p::Int)
n == p || throw(ArgumentError("dims must be equal for LKJ"))
η = abs(3randn(elty))
return n, η
##CHUNK 3
σ² * (ones(partype(lkj), d, d) - I)
end
params(d::LKJ) = (d.d, d.η)
@inline partype(d::LKJ{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
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
#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)
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)
# compute logpdf in batch and store
if d isa UnivariateMixture
#FILE: Distributions.jl/src/univariate/discrete/noncentralhypergeometric.jl
##CHUNK 1
logpdf(d::FisherNoncentralHypergeometric, k::Real) = log(pdf(d, k))
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 in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
#FILE: Distributions.jl/src/matrix/wishart.jl
##CHUNK 1
function var(d::Wishart, i::Integer, j::Integer)
S = d.S
return d.df * (S[i, i] * S[j, j] + S[i, j] ^ 2)
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function wishart_logc0(df::T, S::AbstractPDMat{T}, rnk::Integer) where {T<:Real}
p = size(S, 1)
if df <= p - 1
return singular_wishart_logc0(p, df, S, rnk)
else
return nonsingular_wishart_logc0(p, df, S)
end
end
function logkernel(d::Wishart, X::AbstractMatrix)
if d.singular
#CURRENT FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
"""
LKJCholesky(d::Int, η::Real, uplo='L')
The `LKJCholesky` distribution of size ``d`` with shape parameter ``\\eta`` is a
distribution over `LinearAlgebra.Cholesky` factorisations of ``d\\times d`` real correlation
matrices (positive-definite matrices with ones on the diagonal).
Variates or samples of the distribution are `LinearAlgebra.Cholesky` objects, as might
be returned by `F = LinearAlgebra.cholesky(R)`, so that `Matrix(F) ≈ R` is a variate or
sample of [`LKJ`](@ref).
##CHUNK 2
function logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky)
lp = _logpdf(d, R)
return insupport(d, R) ? lp : oftype(lp, -Inf)
end
_logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logkernel(d, R) + d.logc0
pdf(d::LKJCholesky, R::LinearAlgebra.Cholesky) = exp(logpdf(d, R))
loglikelihood(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logpdf(d, R)
function loglikelihood(d::LKJCholesky, Rs::AbstractArray{<:LinearAlgebra.Cholesky})
return sum(R -> logpdf(d, R), Rs)
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
function Base.rand(rng::AbstractRNG, d::LKJCholesky)
factors = Matrix{eltype(d)}(undef, size(d))
##CHUNK 3
StatsBase.params(d::LKJCholesky) = (d.d, d.η, d.uplo)
@inline partype(::LKJCholesky{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky)
lp = _logpdf(d, R)
return insupport(d, R) ? lp : oftype(lp, -Inf)
end
_logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logkernel(d, R) + d.logc0
pdf(d::LKJCholesky, R::LinearAlgebra.Cholesky) = exp(logpdf(d, R))
loglikelihood(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logpdf(d, R)
|
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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end | 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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end | [
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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end | 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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end | 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] = _lkj_cholesky_onion_sampler!(
rng,
d,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
##CHUNK 2
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
Random.rand!(d::LKJCholesky, R::LinearAlgebra.Cholesky) = Random.rand!(default_rng(), d, R)
function Random.rand!(rng::AbstractRNG, d::LKJCholesky, R::LinearAlgebra.Cholesky)
return _lkj_cholesky_onion_sampler!(rng, d, R)
end
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
##CHUNK 3
for i in eachindex(Rs)
Rs[i] = _lkj_cholesky_onion_sampler!(
rng,
d,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
end
end
return Rs
end
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{<:Real}},
)
allocate = any(!isassigned(Rs, i) for i in eachindex(Rs)) || any(R -> size(R, 1) != d.d, Rs)
##CHUNK 4
return Random.rand!(rng, d, Rs, allocate)
end
#
# onion method
#
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
##CHUNK 5
end
end
return Rs
end
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{<:Real}},
)
allocate = any(!isassigned(Rs, i) for i in eachindex(Rs)) || any(R -> size(R, 1) != d.d, Rs)
return Random.rand!(rng, d, Rs, allocate)
end
#
# onion method
#
function _lkj_cholesky_onion_sampler!(
rng::AbstractRNG,
d::LKJCholesky,
##CHUNK 6
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_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.
##CHUNK 7
loglikelihood(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logpdf(d, R)
function loglikelihood(d::LKJCholesky, Rs::AbstractArray{<:LinearAlgebra.Cholesky})
return sum(R -> logpdf(d, R), Rs)
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
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
Random.rand!(d::LKJCholesky, R::LinearAlgebra.Cholesky) = Random.rand!(default_rng(), d, R)
function Random.rand!(rng::AbstractRNG, d::LKJCholesky, R::LinearAlgebra.Cholesky)
return _lkj_cholesky_onion_sampler!(rng, d, R)
end
##CHUNK 8
# -----------------------------------------------------------------------------
# Properties
# -----------------------------------------------------------------------------
Base.eltype(::Type{LKJCholesky{T}}) where {T} = T
function Base.size(d::LKJCholesky)
p = d.d
return (p, p)
end
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(jinds)
col_iinds = view(iinds, 1:j)
##CHUNK 9
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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
##CHUNK 10
function mode(d::LKJCholesky; check_args::Bool=true)
@check_args(
LKJCholesky,
@setup(η = d.η),
(η, η > 1, "mode is defined only when η > 1."),
)
factors = Matrix{eltype(d)}(LinearAlgebra.I, size(d))
return LinearAlgebra.Cholesky(factors, d.uplo, 0)
end
StatsBase.params(d::LKJCholesky) = (d.d, d.η, d.uplo)
@inline partype(::LKJCholesky{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function logkernel(d::LKJCholesky, R::LinearAlgebra.Cholesky)
|
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,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
end
end
return Rs
end | 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,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
end
end
return Rs
end | [
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,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
end
end
return Rs
end | 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,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
end
end
return Rs
end | 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{<:Real,N}},
allocate::Bool,
) where {N}
if allocate
@inbounds for i in eachindex(x)
x[i] = rand(rng, s)
end
else
@inbounds for xi in x
rand!(rng, s, xi)
end
end
#FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 1
# -----------------------------------------------------------------------------
function _rand!(rng::AbstractRNG, d::LKJ, R::AbstractMatrix)
R .= _lkj_onion_sampler(d.d, d.η, rng)
end
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 2:d - 1
# (a)
β -= 0.5
# (b)
#CURRENT FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end
Random.rand!(d::LKJCholesky, R::LinearAlgebra.Cholesky) = Random.rand!(default_rng(), d, R)
function Random.rand!(rng::AbstractRNG, d::LKJCholesky, R::LinearAlgebra.Cholesky)
return _lkj_cholesky_onion_sampler!(rng, d, R)
end
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{<:Real}},
)
allocate = any(!isassigned(Rs, i) for i in eachindex(Rs)) || any(R -> size(R, 1) != d.d, Rs)
##CHUNK 2
function Random.rand!(rng::AbstractRNG, d::LKJCholesky, R::LinearAlgebra.Cholesky)
return _lkj_cholesky_onion_sampler!(rng, d, R)
end
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{<:Real}},
)
allocate = any(!isassigned(Rs, i) for i in eachindex(Rs)) || any(R -> size(R, 1) != d.d, Rs)
return Random.rand!(rng, d, Rs, allocate)
end
#
# onion method
#
function _lkj_cholesky_onion_sampler!(
rng::AbstractRNG,
d::LKJCholesky,
##CHUNK 3
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::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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end
Random.rand!(d::LKJCholesky, R::LinearAlgebra.Cholesky) = Random.rand!(default_rng(), d, R)
##CHUNK 4
return Random.rand!(rng, d, Rs, allocate)
end
#
# onion method
#
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
##CHUNK 5
loglikelihood(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logpdf(d, R)
function loglikelihood(d::LKJCholesky, Rs::AbstractArray{<:LinearAlgebra.Cholesky})
return sum(R -> logpdf(d, R), Rs)
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
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::LKJCholesky, dims::Dims)
p = d.d
uplo = d.uplo
T = eltype(d)
TM = Matrix{T}
##CHUNK 6
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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
##CHUNK 7
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_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.
##CHUNK 8
"""
LKJCholesky(d::Int, η::Real, uplo='L')
The `LKJCholesky` distribution of size ``d`` with shape parameter ``\\eta`` is a
distribution over `LinearAlgebra.Cholesky` factorisations of ``d\\times d`` real correlation
matrices (positive-definite matrices with ones on the diagonal).
Variates or samples of the distribution are `LinearAlgebra.Cholesky` objects, as might
be returned by `F = LinearAlgebra.cholesky(R)`, so that `Matrix(F) ≈ R` is a variate or
sample of [`LKJ`](@ref).
Sampling `LKJCholesky` is faster than sampling `LKJ`, and often having the correlation
matrix in factorized form makes subsequent computations cheaper as well.
!!! note
`LinearAlgebra.Cholesky` stores either the upper or lower Cholesky factor, related by
`F.U == F.L'`. Both can be accessed with `F.U` and `F.L`, but if the factor
not stored is requested, then a copy is made. The `uplo` parameter specifies whether the
upper (`'U'`) or lower (`'L'`) Cholesky factor is stored when randomly generating
samples. Set `uplo` to `'U'` if the upper factor is desired to avoid allocating a copy
|
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::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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end
Random.rand!(d::LKJCholesky, R::LinearAlgebra.Cholesky) = Random.rand!(default_rng(), d, R)
##CHUNK 2
loglikelihood(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logpdf(d, R)
function loglikelihood(d::LKJCholesky, Rs::AbstractArray{<:LinearAlgebra.Cholesky})
return sum(R -> logpdf(d, R), Rs)
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
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::LKJCholesky, dims::Dims)
p = d.d
uplo = d.uplo
T = eltype(d)
TM = Matrix{T}
##CHUNK 3
function Random.rand!(rng::AbstractRNG, d::LKJCholesky, R::LinearAlgebra.Cholesky)
return _lkj_cholesky_onion_sampler!(rng, d, R)
end
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,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
##CHUNK 4
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)
_lkj_cholesky_onion_sampler!(rng, d, R)
end
return Rs
end
Random.rand!(d::LKJCholesky, R::LinearAlgebra.Cholesky) = Random.rand!(default_rng(), d, R)
function Random.rand!(rng::AbstractRNG, d::LKJCholesky, R::LinearAlgebra.Cholesky)
return _lkj_cholesky_onion_sampler!(rng, d, R)
end
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{T,TM}},
allocate::Bool,
) where {T,TM}
##CHUNK 5
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
end
end
return Rs
end
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
Rs::AbstractArray{<:LinearAlgebra.Cholesky{<:Real}},
)
allocate = any(!isassigned(Rs, i) for i in eachindex(Rs)) || any(R -> size(R, 1) != d.d, Rs)
return Random.rand!(rng, d, Rs, allocate)
end
#
# onion method
#
##CHUNK 6
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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
##CHUNK 7
p = d.d
uplo = d.uplo
if allocate
for i in eachindex(Rs)
Rs[i] = _lkj_cholesky_onion_sampler!(
rng,
d,
LinearAlgebra.Cholesky(TM(undef, p, p), uplo, 0),
)
end
else
for i in eachindex(Rs)
_lkj_cholesky_onion_sampler!(rng, d, Rs[i])
end
end
return Rs
end
function Random.rand!(
rng::AbstractRNG,
d::LKJCholesky,
##CHUNK 8
Rs::AbstractArray{<:LinearAlgebra.Cholesky{<:Real}},
)
allocate = any(!isassigned(Rs, i) for i in eachindex(Rs)) || any(R -> size(R, 1) != d.d, Rs)
return Random.rand!(rng, d, Rs, allocate)
end
#
# onion method
#
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
##CHUNK 9
function mode(d::LKJCholesky; check_args::Bool=true)
@check_args(
LKJCholesky,
@setup(η = d.η),
(η, η > 1, "mode is defined only when η > 1."),
)
factors = Matrix{eltype(d)}(LinearAlgebra.I, size(d))
return LinearAlgebra.Cholesky(factors, d.uplo, 0)
end
StatsBase.params(d::LKJCholesky) = (d.d, d.η, d.uplo)
@inline partype(::LKJCholesky{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function logkernel(d::LKJCholesky, R::LinearAlgebra.Cholesky)
##CHUNK 10
end
function logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky)
lp = _logpdf(d, R)
return insupport(d, R) ? lp : oftype(lp, -Inf)
end
_logpdf(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logkernel(d, R) + d.logc0
pdf(d::LKJCholesky, R::LinearAlgebra.Cholesky) = exp(logpdf(d, R))
loglikelihood(d::LKJCholesky, R::LinearAlgebra.Cholesky) = logpdf(d, R)
function loglikelihood(d::LKJCholesky, Rs::AbstractArray{<:LinearAlgebra.Cholesky})
return sum(R -> logpdf(d, R), Rs)
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
|
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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
return A
end | 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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
return A
end | [
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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
return A
end | 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.
@assert size(A) == (d, d)
A[1, 1] = 1
d > 1 || return A
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
return A
end | _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 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 = eltype(A)
z = zero(T)
axes1 = axes(A, 1)
@inbounds for (j, jdx) in enumerate(axes(A, 2)), (i, idx) in enumerate(axes1)
##CHUNK 2
df = oftype(logdet_S, d.df)
for i in 0:(p - 1)
v += digamma((df - i) / 2)
end
return d.singular ? oftype(v, -Inf) : v
end
function entropy(d::Wishart)
d.singular && throw(ArgumentError("entropy not defined for singular Wishart."))
p = size(d, 1)
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
##CHUNK 3
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
function var(d::Wishart, i::Integer, j::Integer)
S = d.S
return d.df * (S[i, i] * S[j, j] + S[i, j] ^ 2)
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function wishart_logc0(df::T, S::AbstractPDMat{T}, rnk::Integer) where {T<:Real}
#FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 1
# -----------------------------------------------------------------------------
function _rand!(rng::AbstractRNG, d::LKJ, R::AbstractMatrix)
R .= _lkj_onion_sampler(d.d, d.η, rng)
end
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 2:d - 1
# (a)
β -= 0.5
# (b)
##CHUNK 2
end
# -----------------------------------------------------------------------------
# Several redundant implementations of the reciprocal integrating constant.
# If f(R; n) = c₀ |R|ⁿ⁻¹, these give log(1 / c₀).
# Every integrating constant formula given in LKJ (2009 JMA) is an expression
# for 1 / c₀, even if they say that it is not.
# -----------------------------------------------------------------------------
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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end
#FILE: Distributions.jl/test/multivariate/jointorderstatistics.jl
##CHUNK 1
if dist isa Uniform
# Arnold (2008). A first course in order statistics. Eq 2.3.16
s = @. n - r + 1
xcor_exact = Symmetric(sqrt.((r .* collect(s)') ./ (collect(r)' .* s)))
elseif dist isa Exponential
# Arnold (2008). A first course in order statistics. Eq 4.6.8
v = [sum(k -> inv((n - k + 1)^2), 1:i) for i in r]
xcor_exact = Symmetric(sqrt.(v ./ v'))
end
for ii in 1:m, ji in (ii + 1):m
i = r[ii]
j = r[ji]
ρ = xcor[ii, ji]
ρ_exact = xcor_exact[ii, ji]
# use variance-stabilizing transformation, recommended in §3.6 of
# Van der Vaart, A. W. (2000). Asymptotic statistics (Vol. 3).
@test atanh(ρ) ≈ atanh(ρ_exact) atol = tol
end
end
end
#FILE: Distributions.jl/test/multivariate/vonmisesfisher.jl
##CHUNK 1
# Tests for Von-Mises Fisher distribution
using Distributions, Random
using LinearAlgebra, Test
using SpecialFunctions
logvmfCp(p::Int, κ::Real) = (p / 2 - 1) * log(κ) - log(besselix(p / 2 - 1, κ)) - κ - p / 2 * log(2π)
safe_logvmfpdf(μ::Vector, κ::Real, x::Vector) = logvmfCp(length(μ), κ) + κ * dot(μ, x)
function gen_vmf_tdata(n::Int, p::Int,
rng::Union{AbstractRNG, Missing} = missing)
if ismissing(rng)
X = randn(p, n)
else
X = randn(rng, p, n)
end
for i = 1:n
X[:,i] = X[:,i] ./ norm(X[:,i])
#FILE: Distributions.jl/src/matrix/matrixtdist.jl
##CHUNK 1
params(d::MatrixTDist) = (d.ν, d.M, d.Σ, d.Ω)
@inline partype(d::MatrixTDist{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function matrixtdist_logc0(Σ::AbstractPDMat, Ω::AbstractPDMat, ν::Real)
# returns the natural log of the normalizing constant for the pdf
n = size(Σ, 1)
p = size(Ω, 1)
term1 = logmvgamma(p, (ν + n + p - 1) / 2)
term2 = - (n * p / 2) * logπ
term3 = - logmvgamma(p, (ν + p - 1) / 2)
term4 = (-n / 2) * logdet(Ω)
term5 = (-p / 2) * logdet(Σ)
term1 + term2 + term3 + term4 + term5
end
#FILE: Distributions.jl/src/samplers/poisson.jl
##CHUNK 1
# Procedure F
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
px = -μ
py = μ^K/factorial(K)
else
δ = 0.08333333333333333/K
δ -= 4.8*δ^3
V = (μ-K)/K
px = K*log1pmx(V) - δ # avoids need for table
py = 0.3989422804014327/sqrt(K)
#CURRENT FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
sum(abs2, view(factors, col_iinds, jind)) ≈ 1 || return false
end
else # R.uplo === 'L'
for (i, iind) in enumerate(iinds)
row_jinds = view(jinds, 1:i)
sum(abs2, view(factors, iind, row_jinds)) ≈ 1 || return false
end
end
return true
end
function mode(d::LKJCholesky; check_args::Bool=true)
@check_args(
LKJCholesky,
@setup(η = d.η),
(η, η > 1, "mode is defined only when η > 1."),
)
factors = Matrix{eltype(d)}(LinearAlgebra.I, size(d))
return LinearAlgebra.Cholesky(factors, d.uplo, 0)
end
|
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 = -lkj_onion_loginvconst(d, η)
end
return logc0
end | 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_onion_loginvconst(d, η)
end
return logc0
end | [
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 = -lkj_onion_loginvconst(d, η)
end
return logc0
end | 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_onion_loginvconst(d, η)
end
return logc0
end | 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-uniform
# =============
d = 5
η = 2.3
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst(d, η)
# =============
# odd uniform
# =============
##CHUNK 2
# =============
d = 5
η = 2.3
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst(d, η)
# =============
# odd uniform
# =============
d = 5
η = 1.0
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst_uniform_odd(d, Float64)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_vine_loginvconst_uniform(d)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.corr_logvolume(d)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst_uniform_odd(d, Float64)
# =============
##CHUNK 3
# even non-uniform
# =============
d = 6
η = 2.3
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst(d, η)
# =============
# even uniform
# =============
d = 6
η = 1.0
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst_uniform_even(d, Float64)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_vine_loginvconst_uniform(d)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.corr_logvolume(d)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst_uniform_even(d, Float64)
##CHUNK 4
d = 5
η = 1.0
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst_uniform_odd(d, Float64)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_vine_loginvconst_uniform(d)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.corr_logvolume(d)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst_uniform_odd(d, Float64)
# =============
# even non-uniform
# =============
d = 6
η = 2.3
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst(d, η)
# =============
# even uniform
#CURRENT FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
##CHUNK 2
# If f(R; n) = c₀ |R|ⁿ⁻¹, these give log(1 / c₀).
# Every integrating constant formula given in LKJ (2009 JMA) is an expression
# for 1 / c₀, even if they say that it is not.
# -----------------------------------------------------------------------------
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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
##CHUNK 3
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_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
end
return loginvconst
##CHUNK 4
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = d * ((d - 2) * (T(logπ) / 4) + (3 * d - 4) * (T(logtwo) / 4) + loggamma(h * d)) - (d - 1) * loggamma(T(d))
for k in 2:2:(d - 2)
loginvconst += loggamma(k)
end
return loginvconst
end
function lkj_vine_loginvconst(d::Integer, η::Real)
# Equation (16) in LKJ (2009 JMA)
expsum = zero(η)
##CHUNK 5
return loginvconst
end
function lkj_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
end
return loginvconst
end
function corr_logvolume(n::Integer)
# https://doi.org/10.4169/amer.math.monthly.123.9.909
logvol = 0.0
for k in 1:n - 1
logvol += 0.5k*logπ + k*loggamma((k+1)/2) - k*loggamma((k+2)/2)
end
return logvol
end
##CHUNK 6
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 + 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
|
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 2:d - 1
# (a)
β -= 0.5
# (b)
y = rand(rng, Beta(k / 2, β))
# (c)
u = randn(rng, k)
u = u / norm(u)
# (d)
w = sqrt(y) * u
A = cholesky(R[1:k, 1:k]).L
z = A * w
# (e)
R[1:k, k + 1] = z
R[k + 1, 1:k] = z'
end
# 3.
return R
end | 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 2:d - 1
# (a)
β -= 0.5
# (b)
y = rand(rng, Beta(k / 2, β))
# (c)
u = randn(rng, k)
u = u / norm(u)
# (d)
w = sqrt(y) * u
A = cholesky(R[1:k, 1:k]).L
z = A * w
# (e)
R[1:k, k + 1] = z
R[k + 1, 1:k] = z'
end
# 3.
return R
end | [
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 2:d - 1
# (a)
β -= 0.5
# (b)
y = rand(rng, Beta(k / 2, β))
# (c)
u = randn(rng, k)
u = u / norm(u)
# (d)
w = sqrt(y) * u
A = cholesky(R[1:k, 1:k]).L
z = A * w
# (e)
R[1:k, k + 1] = z
R[k + 1, 1:k] = z'
end
# 3.
return R
end | 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 2:d - 1
# (a)
β -= 0.5
# (b)
y = rand(rng, Beta(k / 2, β))
# (c)
u = randn(rng, k)
u = u / norm(u)
# (d)
w = sqrt(y) * u
A = cholesky(R[1:k, 1:k]).L
z = A * w
# (e)
R[1:k, k + 1] = z
R[k + 1, 1:k] = z'
end
# 3.
return R
end | _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
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
##CHUNK 2
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
#FILE: Distributions.jl/src/univariate/continuous/lindley.jl
##CHUNK 1
end
for i in 1:n
β = β / (1 + β) * (1 + log(x / β))
end
return β
end
### Sampling
# Ghitany, M. E., Atieh, B., & Nadarajah, S. (2008). Lindley distribution and its
# application. Mathematics and Computers in Simulation, 78(4), 493–506.
function rand(rng::AbstractRNG, d::Lindley)
θ = shape(d)
λ = inv(θ)
T = typeof(λ)
u = rand(rng)
p = θ / (1 + θ)
return oftype(u, rand(rng, u <= p ? Exponential{T}(λ) : Gamma{T}(2, λ)))
end
#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::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 - b) * z)
end
return w::Float64
end
#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(μ, κ, (1.0 + abs2(ρ)) / (2.0 * ρ))
end
end
# algorithm from
# DJ Best & NI Fisher (1979). Efficient Simulation of the von Mises
# Distribution. Journal of the Royal Statistical Society. Series C
# (Applied Statistics), 28(2), 152-157.
function rand(rng::AbstractRNG, s::VonMisesSampler)
f = 0.0
local x::Float64
#FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
return 12sqrt(6) * zeta(3) / pi ^ 3 * one(T)
elseif ξ < 1/3
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
return sign(ξ) * (g3 - 3g1 * g2 + 2g1^3) / (g2 - g1^2) ^ (3/2)
else
return T(Inf)
end
end
function kurtosis(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return T(12)/5
elseif ξ < 1 / 4
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
##CHUNK 2
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
return 12sqrt(6) * zeta(3) / pi ^ 3 * one(T)
elseif ξ < 1/3
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
return sign(ξ) * (g3 - 3g1 * g2 + 2g1^3) / (g2 - g1^2) ^ (3/2)
else
return T(Inf)
end
end
##CHUNK 3
function kurtosis(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return T(12)/5
elseif ξ < 1 / 4
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
g4 = g(d, 4)
return (g4 - 4g1 * g3 + 6g2 * g1^2 - 3 * g1^4) / (g2 - g1^2)^2 - 3
else
return T(Inf)
end
end
function entropy(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
return log(σ) + MathConstants.γ * ξ + (1 + MathConstants.γ)
#FILE: Distributions.jl/test/univariate/continuous.jl
##CHUNK 1
@testset "NormalInverseGaussian random repeatable and basic metrics" begin
rng = Random.MersenneTwister(42)
rng2 = copy(rng)
µ = 0.0
α = 1.0
β = 0.5
δ = 3.0
g = sqrt(α^2 - β^2)
d = NormalInverseGaussian(μ, α, β, δ)
v1 = rand(rng, d)
v2 = rand(rng, d)
v3 = rand(rng2, d)
@test v1 ≈ v3
@test v1 ≉ v2
@test mean(d) ≈ µ + β * δ / g
@test var(d) ≈ δ * α^2 / g^3
@test skewness(d) ≈ 3β/(α*sqrt(δ*g))
end
#FILE: Distributions.jl/src/matrix/matrixtdist.jl
##CHUNK 1
n = size(Σ, 1)
p = size(Ω, 1)
term1 = logmvgamma(p, (ν + n + p - 1) / 2)
term2 = - (n * p / 2) * logπ
term3 = - logmvgamma(p, (ν + p - 1) / 2)
term4 = (-n / 2) * logdet(Ω)
term5 = (-p / 2) * logdet(Σ)
term1 + term2 + term3 + term4 + term5
end
function logkernel(d::MatrixTDist, X::AbstractMatrix)
n, p = size(d)
A = X - d.M
(-(d.ν + n + p - 1) / 2) * logdet( I + (d.Σ \ A) * (d.Ω \ A') )
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
#CURRENT FILE: Distributions.jl/src/matrix/lkj.jl |
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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end | 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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end | [
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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end | 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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end | 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) * 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
##CHUNK 2
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = d * ((d - 2) * (T(logπ) / 4) + (3 * d - 4) * (T(logtwo) / 4) + loggamma(h * d)) - (d - 1) * loggamma(T(d))
for k in 2:2:(d - 2)
loginvconst += loggamma(k)
end
return loginvconst
end
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 + betasum
##CHUNK 3
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
function lkj_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
##CHUNK 4
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = d * ((d - 2) * (T(logπ) / 4) + (3 * d - 4) * (T(logtwo) / 4) + loggamma(h * d)) - (d - 1) * loggamma(T(d))
for k in 2:2:(d - 2)
loginvconst += loggamma(k)
end
return loginvconst
end
##CHUNK 5
betasum += k * logbeta(α, α)
end
loginvconst = expsum * logtwo + betasum
return loginvconst
end
function lkj_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
end
return loginvconst
end
function corr_logvolume(n::Integer)
# https://doi.org/10.4169/amer.math.monthly.123.9.909
logvol = 0.0
for k in 1:n - 1
logvol += 0.5k*logπ + k*loggamma((k+1)/2) - k*loggamma((k+2)/2)
##CHUNK 6
end
# -----------------------------------------------------------------------------
# Several redundant implementations of the reciprocal integrating constant.
# If f(R; n) = c₀ |R|ⁿ⁻¹, these give log(1 / c₀).
# Every integrating constant formula given in LKJ (2009 JMA) is an expression
# for 1 / c₀, even if they say that it is not.
# -----------------------------------------------------------------------------
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
##CHUNK 7
σ² * (ones(partype(lkj), d, d) - I)
end
params(d::LKJ) = (d.d, d.η)
@inline partype(d::LKJ{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
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
##CHUNK 8
else
logc0 = -lkj_onion_loginvconst(d, η)
end
return logc0
end
logkernel(d::LKJ, R::AbstractMatrix) = (d.η - 1) * logdet(R)
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
function _rand!(rng::AbstractRNG, d::LKJ, R::AbstractMatrix)
R .= _lkj_onion_sampler(d.d, d.η, rng)
end
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)
##CHUNK 9
# -----------------------------------------------------------------------------
function _rand!(rng::AbstractRNG, d::LKJ, R::AbstractMatrix)
R .= _lkj_onion_sampler(d.d, d.η, rng)
end
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 2:d - 1
# (a)
β -= 0.5
# (b)
##CHUNK 10
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
end
return loginvconst
end
function corr_logvolume(n::Integer)
# https://doi.org/10.4169/amer.math.monthly.123.9.909
logvol = 0.0
for k in 1:n - 1
logvol += 0.5k*logπ + k*loggamma((k+1)/2) - k*loggamma((k+2)/2)
end
return logvol
end
|
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 + betasum
return loginvconst
end | 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 + betasum
return loginvconst
end | [
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 + betasum
return loginvconst
end | 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 + betasum
return loginvconst
end | 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-uniform
# =============
d = 5
η = 2.3
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst(d, η)
# =============
# odd uniform
# =============
#CURRENT FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 1
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = d * ((d - 2) * (T(logπ) / 4) + (3 * d - 4) * (T(logtwo) / 4) + loggamma(h * d)) - (d - 1) * loggamma(T(d))
for k in 2:2:(d - 2)
loginvconst += loggamma(k)
end
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(α, α)
##CHUNK 2
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_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
##CHUNK 3
# 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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
##CHUNK 4
end
# -----------------------------------------------------------------------------
# Several redundant implementations of the reciprocal integrating constant.
# If f(R; n) = c₀ |R|ⁿ⁻¹, these give log(1 / c₀).
# Every integrating constant formula given in LKJ (2009 JMA) is an expression
# for 1 / c₀, even if they say that it is not.
# -----------------------------------------------------------------------------
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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end
##CHUNK 5
end
loginvconst = expsum * logtwo + betasum
return loginvconst
end
function lkj_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
end
return loginvconst
end
function corr_logvolume(n::Integer)
# https://doi.org/10.4169/amer.math.monthly.123.9.909
logvol = 0.0
for k in 1:n - 1
logvol += 0.5k*logπ + k*loggamma((k+1)/2) - k*loggamma((k+2)/2)
end
##CHUNK 6
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = d * ((d - 2) * (T(logπ) / 4) + (3 * d - 4) * (T(logtwo) / 4) + loggamma(h * d)) - (d - 1) * loggamma(T(d))
for k in 2:2:(d - 2)
loginvconst += loggamma(k)
end
return loginvconst
end
##CHUNK 7
σ² * (ones(partype(lkj), d, d) - I)
end
params(d::LKJ) = (d.d, d.η)
@inline partype(d::LKJ{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
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
##CHUNK 8
else
logc0 = -lkj_onion_loginvconst(d, η)
end
return logc0
end
logkernel(d::LKJ, R::AbstractMatrix) = (d.η - 1) * logdet(R)
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
function _rand!(rng::AbstractRNG, d::LKJ, R::AbstractMatrix)
R .= _lkj_onion_sampler(d.d, d.η, rng)
end
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)
##CHUNK 9
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_onion_loginvconst(d, η)
end
return logc0
end
logkernel(d::LKJ, R::AbstractMatrix) = (d.η - 1) * logdet(R)
# -----------------------------------------------------------------------------
# Sampling
|
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-uniform
# =============
d = 5
η = 2.3
lkj = LKJ(d, η)
@test Distributions.lkj_vine_loginvconst(d, η) ≈ Distributions.lkj_onion_loginvconst(d, η)
@test Distributions.lkj_onion_loginvconst(d, η) ≈ Distributions.lkj_loginvconst_alt(d, η)
@test lkj.logc0 == -Distributions.lkj_onion_loginvconst(d, η)
# =============
# odd uniform
# =============
#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) * logbeta(α, α)
end
loginvconst = expsum * logtwo + betasum
return loginvconst
end
function lkj_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
##CHUNK 2
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = d * ((d - 2) * (T(logπ) / 4) + (3 * d - 4) * (T(logtwo) / 4) + loggamma(h * d)) - (d - 1) * loggamma(T(d))
for k in 2:2:(d - 2)
loginvconst += loggamma(k)
end
return loginvconst
end
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
##CHUNK 3
# 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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
##CHUNK 4
function lkj_onion_loginvconst_uniform_odd(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = (d - 1) * ((d + 1) * (T(logπ) / 4) - (d - 1) * (T(logtwo) / 4) - loggamma(h * (d + 1)))
for k in 2:2:(d - 1)
loginvconst += loggamma(T(k))
end
return loginvconst
end
function lkj_onion_loginvconst_uniform_even(d::Integer, ::Type{T}) where {T <: Real}
# Theorem 5 in LKJ (2009 JMA)
h = T(1//2)
loginvconst = d * ((d - 2) * (T(logπ) / 4) + (3 * d - 4) * (T(logtwo) / 4) + loggamma(h * d)) - (d - 1) * loggamma(T(d))
for k in 2:2:(d - 2)
loginvconst += loggamma(k)
end
return loginvconst
end
##CHUNK 5
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_onion_loginvconst(d, η)
end
return logc0
end
logkernel(d::LKJ, R::AbstractMatrix) = (d.η - 1) * logdet(R)
# -----------------------------------------------------------------------------
# Sampling
##CHUNK 6
σ² * (ones(partype(lkj), d, d) - I)
end
params(d::LKJ) = (d.d, d.η)
@inline partype(d::LKJ{T}) where {T <: Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
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
##CHUNK 7
loginvconst = expsum * logtwo + betasum
return loginvconst
end
function lkj_loginvconst_alt(d::Integer, η::Real)
# Third line in first proof of Section 3.3 in LKJ (2009 JMA)
loginvconst = zero(η)
for k in 1:d - 1
loginvconst += 0.5k*logπ + loggamma(η + 0.5(d - 1 - k)) - loggamma(η + 0.5(d - 1))
end
return loginvconst
end
function corr_logvolume(n::Integer)
# https://doi.org/10.4169/amer.math.monthly.123.9.909
logvol = 0.0
for k in 1:n - 1
logvol += 0.5k*logπ + k*loggamma((k+1)/2) - k*loggamma((k+2)/2)
end
##CHUNK 8
end
# -----------------------------------------------------------------------------
# Several redundant implementations of the reciprocal integrating constant.
# If f(R; n) = c₀ |R|ⁿ⁻¹, these give log(1 / c₀).
# Every integrating constant formula given in LKJ (2009 JMA) is an expression
# for 1 / c₀, even if they say that it is not.
# -----------------------------------------------------------------------------
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 - 1)
loginvconst += loggamma(η + h * (d - 1 - k))
end
return loginvconst
end
##CHUNK 9
else
logc0 = -lkj_onion_loginvconst(d, η)
end
return logc0
end
logkernel(d::LKJ, R::AbstractMatrix) = (d.η - 1) * logdet(R)
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
function _rand!(rng::AbstractRNG, d::LKJ, R::AbstractMatrix)
R .= _lkj_onion_sampler(d.d, d.η, rng)
end
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)
|
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 = eltype(A)
z = zero(T)
axes1 = axes(A, 1)
@inbounds for (j, jdx) in enumerate(axes(A, 2)), (i, idx) in enumerate(axes1)
A[idx, jdx] = if i < j
z
elseif i > j
randn(rng, T)
else
rand(rng, Chi(df - i + 1))
end
end
return A
end | 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 = eltype(A)
z = zero(T)
axes1 = axes(A, 1)
@inbounds for (j, jdx) in enumerate(axes(A, 2)), (i, idx) in enumerate(axes1)
A[idx, jdx] = if i < j
z
elseif i > j
randn(rng, T)
else
rand(rng, Chi(df - i + 1))
end
end
return A
end | [
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 = eltype(A)
z = zero(T)
axes1 = axes(A, 1)
@inbounds for (j, jdx) in enumerate(axes(A, 2)), (i, idx) in enumerate(axes1)
A[idx, jdx] = if i < j
z
elseif i > j
randn(rng, T)
else
rand(rng, Chi(df - i + 1))
end
end
return A
end | 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 = eltype(A)
z = zero(T)
axes1 = axes(A, 1)
@inbounds for (j, jdx) in enumerate(axes(A, 2)), (i, idx) in enumerate(axes1)
A[idx, jdx] = if i < j
z
elseif i > j
randn(rng, T)
else
rand(rng, Chi(df - i + 1))
end
end
return A
end | _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 _univariate(d::InverseWishart)
check_univariate(d)
ν, Ψ = params(d)
α = ν / 2
β = Matrix(Ψ)[1] / 2
return InverseGamma(α, β)
end
function _rand_params(::Type{InverseWishart}, elty, n::Int, p::Int)
n == p || throw(ArgumentError("dims must be equal for InverseWishart"))
ν = elty( n + 3 + abs(10randn()) )
Ψ = (X = 2rand(elty, n, n) .- 1 ; X * X')
return ν, Ψ
end
#FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
##CHUNK 2
# 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
β = η + (d - 2)//2
# 1. Initialization
w0 = 2 * rand(rng, Beta(β, β)) - 1
@inbounds if uplo === :L
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
##CHUNK 3
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
return A
end
#FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
# given ∏ₖf(xₖ), marginalize all xₖ for i < k < j
function _marginalize_range(dist, i, j, xᵢ, xⱼ, T)
k = j - i - 1
k == 0 && return zero(T)
return k * T(logdiffcdf(dist, xⱼ, xᵢ)) - loggamma(T(k + 1))
end
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.dist, x)
sort!(x)
else
# use exponential generation method with inversion, where for gaps in the ranks, we
# use the fact that the sum Y of k IID variables xₘ ~ Exp(1) is Y ~ Gamma(k, 1).
# Lurie, D., and H. O. Hartley. "Machine-generation of order statistics for Monte
# Carlo computations." The American Statistician 26.1 (1972): 26-27.
# this is slow if length(d.ranks) is close to n and quantile for d.dist is expensive,
#FILE: Distributions.jl/src/multivariate/dirichletmultinomial.jl
##CHUNK 1
α = ones(size(ss.s, 1))
rng = 0.0:(k - 1)
@inbounds for iter in 1:maxiter
α_old = copy(α)
αsum = sum(α)
denom = ss.tw * sum(inv, αsum .+ rng)
for j in eachindex(α)
αj = α[j]
num = αj * sum(vec(ss.s[j, :]) ./ (αj .+ rng)) # vec needed for 0.4
α[j] = num / denom
end
maximum(abs, α_old - α) < tol && break
end
DirichletMultinomial(ss.n, α)
end
#FILE: Distributions.jl/src/matrix/lkj.jl
##CHUNK 1
y = rand(rng, Beta(k / 2, β))
# (c)
u = randn(rng, k)
u = u / norm(u)
# (d)
w = sqrt(y) * u
A = cholesky(R[1:k, 1:k]).L
z = A * w
# (e)
R[1:k, k + 1] = z
R[k + 1, 1:k] = z'
end
# 3.
return R
end
# -----------------------------------------------------------------------------
# The free elements of an LKJ matrix each have the same marginal distribution
# -----------------------------------------------------------------------------
#FILE: Distributions.jl/src/matrixvariates.jl
##CHUNK 1
Compute the covariance matrix for `vec(X)`, where `X` is a random matrix with distribution `d`.
"""
function cov(d::MatrixDistribution)
M = length(d)
V = zeros(partype(d), M, M)
iter = CartesianIndices(size(d))
for el1 = 1:M
for el2 = 1:el1
i, j = Tuple(iter[el1])
k, l = Tuple(iter[el2])
V[el1, el2] = cov(d, i, j, k, l)
end
end
return V + tril(V, -1)'
end
cov(d::MatrixDistribution, ::Val{true}) = cov(d)
"""
cov(d::MatrixDistribution, flattened = Val(false))
#CURRENT FILE: Distributions.jl/src/matrix/wishart.jl
##CHUNK 1
# Nonsingular Wishart pdf
function nonsingular_wishart_logc0(p::Integer, df::T, S::AbstractPDMat{T}) where {T<:Real}
logdet_S = logdet(S)
h_df = oftype(logdet_S, df) / 2
return -h_df * (logdet_S + p * oftype(logdet_S, logtwo)) - logmvgamma(p, h_df)
end
function nonsingular_wishart_logkernel(d::Wishart, X::AbstractMatrix)
return ((d.df - (size(d, 1) + 1)) * logdet(cholesky(X)) - tr(d.S \ X)) / 2
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
function _rand!(rng::AbstractRNG, d::Wishart, A::AbstractMatrix)
if d.singular
axes2 = axes(A, 2)
r = rank(d)
randn!(rng, view(A, :, axes2[1:r]))
##CHUNK 2
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
# -----------------------------------------------------------------------------
# Test utils
# -----------------------------------------------------------------------------
function _univariate(d::Wishart)
check_univariate(d)
df, S = params(d)
α = df / 2
β = 2 * first(S)
return Gamma(α, β)
end
|
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(distributions, priors, x)
return sum(pdf(d, x) * p for (d, p) in zip(distributions, priors))
end
function improved_version(d, x)
p = probs(d)
return sum(enumerate(p)) do (i, pi)
if pi > 0
##CHUNK 2
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, x)
K = ncomponents(d)
p = probs(d)
@assert length(p) == K
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
#CURRENT FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
function var(d::MultivariateMixture)
return diag(cov(d))
end
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)
end
end
for i = 1:K
##CHUNK 2
"""
var(d::UnivariateMixture)
Compute the overall variance (only for `UnivariateMixture`).
"""
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)
end
##CHUNK 3
end
for i = 1:K
pi = p[i]
if pi > 0.0
v += pi * abs2(means[i] - m)
end
end
return v
end
function var(d::MultivariateMixture)
return diag(cov(d))
end
function cov(d::MultivariateMixture)
K = ncomponents(d)
p = probs(d)
m = zeros(length(d))
md = zeros(length(d))
V = zeros(length(d),length(d))
##CHUNK 4
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
function _mixlogpdf1(d::AbstractMixtureModel, x)
p = probs(d)
##CHUNK 5
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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
md .= mean(c) .- m
BLAS.syr!('U', Float64(pi), md, V)
end
end
LinearAlgebra.copytri!(V, 'U')
return V
end
##CHUNK 6
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
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)
K = ncomponents(d)
p = probs(d)
n = length(r)
Lp = Matrix{eltype(p)}(undef, n, K)
m = fill(-Inf, n)
##CHUNK 7
r = sum(pi * cdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return r
end
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
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, component(d, i)).(x)
else
##CHUNK 8
minimum(d::MixtureModel) = minimum([minimum(dci) for dci in d.components])
maximum(d::MixtureModel) = maximum([maximum(dci) for dci in d.components])
function mean(d::UnivariateMixture)
p = probs(d)
m = sum(pi * mean(component(d, i)) for (i, pi) in enumerate(p) if !iszero(pi))
return m
end
"""
var(d::UnivariateMixture)
Compute the overall variance (only for `UnivariateMixture`).
"""
function var(d::UnivariateMixture)
K = ncomponents(d)
p = probs(d)
means = Vector{Float64}(undef, K)
|
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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
v += pi * abs2(means[i] - m)
end
end
return v
end | 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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
v += pi * abs2(means[i] - m)
end
end
return v
end | [
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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
v += pi * abs2(means[i] - m)
end
end
return v
end | 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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
v += pi * abs2(means[i] - m)
end
end
return v
end | 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, x)
K = ncomponents(d)
p = probs(d)
@assert length(p) == K
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
##CHUNK 2
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(distributions, priors, x)
return sum(pdf(d, x) * p for (d, p) in zip(distributions, priors))
end
function improved_version(d, x)
p = probs(d)
return sum(enumerate(p)) do (i, pi)
if pi > 0
##CHUNK 3
@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(d, i)
pdf(c, x) * pi
else
zero(eltype(p))
end
end
end
#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
c_k = component(g, k)
for i = 1:n
cf[i] += pr[k] * cdf(c_k, X[i])
end
end
#FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
@inbounds p_i = p[i]
v[i] = n * p_i * (1 - p_i)
end
v
end
function cov(d::Multinomial{T}) where T<:Real
p = probs(d)
k = length(p)
n = ntrials(d)
C = Matrix{T}(undef, k, k)
for j = 1:k
pj = p[j]
for i = 1:j-1
@inbounds C[i,j] = - n * p[i] * pj
end
@inbounds C[j,j] = n * pj * (1-pj)
end
#CURRENT FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
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
"""
var(d::UnivariateMixture)
Compute the overall variance (only for `UnivariateMixture`).
"""
##CHUNK 2
function var(d::MultivariateMixture)
return diag(cov(d))
end
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)
end
end
for i = 1:K
##CHUNK 3
minimum(d::MixtureModel) = minimum([minimum(dci) for dci in d.components])
maximum(d::MixtureModel) = maximum([maximum(dci) for dci in d.components])
function mean(d::UnivariateMixture)
p = probs(d)
m = sum(pi * mean(component(d, i)) for (i, pi) in enumerate(p) if !iszero(pi))
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
##CHUNK 4
r = sum(pi * cdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return r
end
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
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, component(d, i)).(x)
else
##CHUNK 5
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
function _mixlogpdf1(d::AbstractMixtureModel, x)
p = probs(d)
|
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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
md .= mean(c) .- m
BLAS.syr!('U', Float64(pi), md, V)
end
end
LinearAlgebra.copytri!(V, 'U')
return V
end | 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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
md .= mean(c) .- m
BLAS.syr!('U', Float64(pi), md, V)
end
end
LinearAlgebra.copytri!(V, 'U')
return V
end | [
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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
md .= mean(c) .- m
BLAS.syr!('U', Float64(pi), md, V)
end
end
LinearAlgebra.copytri!(V, 'U')
return V
end | 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)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
c = component(d, i)
md .= mean(c) .- m
BLAS.syr!('U', Float64(pi), md, V)
end
end
LinearAlgebra.copytri!(V, 'U')
return V
end | 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
c_k = component(g, k)
for i = 1:n
cf[i] += pr[k] * cdf(c_k, X[i])
end
end
#FILE: Distributions.jl/src/multivariate/mvnormal.jl
##CHUNK 1
end
function fit_mle(D::Type{FullNormal}, x::AbstractMatrix{Float64}, w::AbstractVector)
m = size(x, 1)
n = size(x, 2)
length(w) == n || throw(DimensionMismatch("Inconsistent argument dimensions"))
inv_sw = inv(sum(w))
mu = BLAS.gemv('N', inv_sw, x, w)
z = Matrix{Float64}(undef, m, n)
for j = 1:n
cj = sqrt(w[j])
for i = 1:m
@inbounds z[i,j] = (x[i,j] - mu[i]) * cj
end
end
C = BLAS.syrk('U', 'N', inv_sw, z)
LinearAlgebra.copytri!(C, 'U')
MvNormal(mu, PDMat(C))
#FILE: Distributions.jl/src/matrix/matrixnormal.jl
##CHUNK 1
@inline partype(d::MatrixNormal{T}) where {T<:Real} = T
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function matrixnormal_logc0(U::AbstractPDMat, V::AbstractPDMat)
n = size(U, 1)
p = size(V, 1)
-(n * p / 2) * (logtwo + logπ) - (n / 2) * logdet(V) - (p / 2) * logdet(U)
end
function logkernel(d::MatrixNormal, X::AbstractMatrix)
A = X - d.M
-0.5 * tr( (d.V \ A') * (d.U \ A) )
end
# -----------------------------------------------------------------------------
# Sampling
# -----------------------------------------------------------------------------
#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::DirichletMultinomial{<:Real})
v = var(d)
c = d.α * d.α'
lmul!(-d.n * (d.n + d.α0) / (d.α0^2 * (1 + d.α0)), c)
for (i, vi) in zip(diagind(c), v)
@inbounds c[i] = vi
end
c
end
# Evaluation
#CURRENT FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
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
"""
var(d::UnivariateMixture)
Compute the overall variance (only for `UnivariateMixture`).
"""
function var(d::UnivariateMixture)
##CHUNK 2
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
##CHUNK 3
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
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
##CHUNK 4
minimum(d::MixtureModel) = minimum([minimum(dci) for dci in d.components])
maximum(d::MixtureModel) = maximum([maximum(dci) for dci in d.components])
function mean(d::UnivariateMixture)
p = probs(d)
m = sum(pi * mean(component(d, i)) for (i, pi) in enumerate(p) if !iszero(pi))
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
##CHUNK 5
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)
# compute logpdf in batch and store
if d isa UnivariateMixture
lp_i .= Base.Fix1(logpdf, component(d, i)).(x)
else
logpdf!(lp_i, component(d, i), x)
end
##CHUNK 6
m += pi * mi
v += pi * var(ci)
end
end
for i = 1:K
pi = p[i]
if pi > 0.0
v += pi * abs2(means[i] - m)
end
end
return v
end
function var(d::MultivariateMixture)
return diag(cov(d))
end
|
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end | 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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end | [
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end | 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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end | _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(d, i)
pdf(c, x) * pi
else
zero(eltype(p))
end
end
end
##CHUNK 2
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, x)
K = ncomponents(d)
p = probs(d)
@assert length(p) == K
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
##CHUNK 3
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(distributions, priors, x)
return sum(pdf(d, x) * p for (d, p) in zip(distributions, priors))
end
function improved_version(d, x)
p = probs(d)
return sum(enumerate(p)) do (i, pi)
if pi > 0
#FILE: Distributions.jl/test/censored.jl
##CHUNK 1
ccdf(d0, d.upper) + pdf(d0, d.upper)
end
prob_interval = 1 - (prob_lower + prob_upper)
components = Distribution[dtrunc]
probs = [prob_interval]
if prob_lower > 0
# workaround for MixtureModel currently not supporting mixtures of discrete and
# continuous components
push!(components, d0 isa DiscreteDistribution ? Dirac(d.lower) : Normal(d.lower, 0))
push!(probs, prob_lower)
end
if prob_upper > 0
push!(components, d0 isa DiscreteDistribution ? Dirac(d.upper) : Normal(d.upper, 0))
push!(probs, prob_upper)
end
return MixtureModel(map(identity, components), probs)
end
@testset "censored" begin
d0 = Normal(0, 1)
#CURRENT FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
end
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)
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)
##CHUNK 2
function cdf(d::UnivariateMixture, x::Real)
p = probs(d)
r = sum(pi * cdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return r
end
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
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)
##CHUNK 3
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)
# compute logpdf in batch and store
if d isa UnivariateMixture
lp_i .= Base.Fix1(logpdf, component(d, i)).(x)
else
logpdf!(lp_i, component(d, i), x)
end
# in the mean time, add log(prior) to lp and
# update the maximum for each sample
##CHUNK 4
end
#### Evaluation
function insupport(d::AbstractMixtureModel, x::AbstractVector)
p = probs(d)
return any(insupport(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
function cdf(d::UnivariateMixture, x::Real)
p = probs(d)
r = sum(pi * cdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return r
end
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
##CHUNK 5
minimum(d::MixtureModel) = minimum([minimum(dci) for dci in d.components])
maximum(d::MixtureModel) = maximum([maximum(dci) for dci in d.components])
function mean(d::UnivariateMixture)
p = probs(d)
m = sum(pi * mean(component(d, i)) for (i, pi) in enumerate(p) if !iszero(pi))
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
##CHUNK 6
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
"""
var(d::UnivariateMixture)
Compute the overall variance (only for `UnivariateMixture`).
"""
function var(d::UnivariateMixture)
|
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)
# compute logpdf in batch and store
if d isa UnivariateMixture
lp_i .= Base.Fix1(logpdf, component(d, i)).(x)
else
logpdf!(lp_i, component(d, i), x)
end
# in the mean time, add log(prior) to lp and
# update the maximum for each sample
for j = 1:n
lp_i[j] += lpri
if lp_i[j] > m[j]
m[j] = lp_i[j]
end
end
end
end
fill!(r, 0.0)
@inbounds for i = 1:K
if p[i] > 0.0
lp_i = view(Lp, :, i)
for j = 1:n
r[j] += exp(lp_i[j] - m[j])
end
end
end
@inbounds for j = 1:n
r[j] = log(r[j]) + m[j]
end
return r
end | 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)
# compute logpdf in batch and store
if d isa UnivariateMixture
lp_i .= Base.Fix1(logpdf, component(d, i)).(x)
else
logpdf!(lp_i, component(d, i), x)
end
# in the mean time, add log(prior) to lp and
# update the maximum for each sample
for j = 1:n
lp_i[j] += lpri
if lp_i[j] > m[j]
m[j] = lp_i[j]
end
end
end
end
fill!(r, 0.0)
@inbounds for i = 1:K
if p[i] > 0.0
lp_i = view(Lp, :, i)
for j = 1:n
r[j] += exp(lp_i[j] - m[j])
end
end
end
@inbounds for j = 1:n
r[j] = log(r[j]) + m[j]
end
return r
end | [
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)
# compute logpdf in batch and store
if d isa UnivariateMixture
lp_i .= Base.Fix1(logpdf, component(d, i)).(x)
else
logpdf!(lp_i, component(d, i), x)
end
# in the mean time, add log(prior) to lp and
# update the maximum for each sample
for j = 1:n
lp_i[j] += lpri
if lp_i[j] > m[j]
m[j] = lp_i[j]
end
end
end
end
fill!(r, 0.0)
@inbounds for i = 1:K
if p[i] > 0.0
lp_i = view(Lp, :, i)
for j = 1:n
r[j] += exp(lp_i[j] - m[j])
end
end
end
@inbounds for j = 1:n
r[j] = log(r[j]) + m[j]
end
return r
end | 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)
# compute logpdf in batch and store
if d isa UnivariateMixture
lp_i .= Base.Fix1(logpdf, component(d, i)).(x)
else
logpdf!(lp_i, component(d, i), x)
end
# in the mean time, add log(prior) to lp and
# update the maximum for each sample
for j = 1:n
lp_i[j] += lpri
if lp_i[j] > m[j]
m[j] = lp_i[j]
end
end
end
end
fill!(r, 0.0)
@inbounds for i = 1:K
if p[i] > 0.0
lp_i = view(Lp, :, i)
for j = 1:n
r[j] += exp(lp_i[j] - m[j])
end
end
end
@inbounds for j = 1:n
r[j] = log(r[j]) + m[j]
end
return r
end | _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
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end
#FILE: Distributions.jl/src/matrix/wishart.jl
##CHUNK 1
df = oftype(logdet_S, d.df)
for i in 0:(p - 1)
v += digamma((df - i) / 2)
end
return d.singular ? oftype(v, -Inf) : v
end
function entropy(d::Wishart)
d.singular && throw(ArgumentError("entropy not defined for singular Wishart."))
p = size(d, 1)
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
##CHUNK 2
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
function var(d::Wishart, i::Integer, j::Integer)
S = d.S
return d.df * (S[i, i] * S[j, j] + S[i, j] ^ 2)
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function wishart_logc0(df::T, S::AbstractPDMat{T}, rnk::Integer) where {T<:Real}
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
cc = Vector{Float64}(undef, nv)
lp = Vector{Float64}(undef, nv)
lc = Vector{Float64}(undef, nv)
lcc = Vector{Float64}(undef, nv)
ci = 0.
for (i, v) in enumerate(vs)
p[i] = pdf(d, v)
c[i] = cdf(d, v)
cc[i] = ccdf(d, v)
lp[i] = logpdf(d, v)
lc[i] = logcdf(d, v)
lcc[i] = logccdf(d, v)
@assert p[i] >= 0.0
@assert (i == 1 || c[i] >= c[i-1])
ci += p[i]
@test ci ≈ c[i]
@test isapprox(c[i] + cc[i], 1.0 , atol=1.0e-12)
##CHUNK 2
elseif islowerbounded(d)
@test map(Base.Fix1(pdf, d), rmin-2:rmax) ≈ vcat(0.0, 0.0, p0)
end
end
function test_evaluation(d::DiscreteUnivariateDistribution, vs::AbstractVector, testquan::Bool=true)
nv = length(vs)
p = Vector{Float64}(undef, nv)
c = Vector{Float64}(undef, nv)
cc = Vector{Float64}(undef, nv)
lp = Vector{Float64}(undef, nv)
lc = Vector{Float64}(undef, nv)
lcc = Vector{Float64}(undef, nv)
ci = 0.
for (i, v) in enumerate(vs)
p[i] = pdf(d, v)
c[i] = cdf(d, v)
cc[i] = ccdf(d, v)
#FILE: Distributions.jl/test/mixture.jl
##CHUNK 1
for i = 1:n
@test @inferred(cdf(g, X[i])) ≈ cf[i]
end
@test Base.Fix1(cdf, g).(X) ≈ cf
# evaluation
P0 = zeros(T, n, K)
LP0 = zeros(T, n, K)
for k = 1:K
c_k = component(g, k)
for i = 1:n
x_i = X[i]
P0[i,k] = pdf(c_k, x_i)
LP0[i,k] = logpdf(c_k, x_i)
end
end
mix_p0 = P0 * pr
mix_lp0 = log.(mix_p0)
#FILE: Distributions.jl/src/matrixvariates.jl
##CHUNK 1
Compute the 4-dimensional array whose `(i, j, k, l)` element is `cov(X[i,j], X[k, l])`.
"""
function cov(d::MatrixDistribution, ::Val{false})
n, p = size(d)
[cov(d, i, j, k, l) for i in 1:n, j in 1:p, k in 1:n, l in 1:p]
end
# pdf & logpdf
# TODO: Remove or restrict - this causes many ambiguity errors...
_logpdf(d::MatrixDistribution, X::AbstractMatrix{<:Real}) = logkernel(d, X) + d.logc0
# for testing
is_univariate(d::MatrixDistribution) = size(d) == (1, 1)
check_univariate(d::MatrixDistribution) = is_univariate(d) || throw(ArgumentError("not 1 x 1"))
##### Specific distributions #####
for fname in ["wishart.jl", "inversewishart.jl", "matrixnormal.jl",
#CURRENT FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
end
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
##CHUNK 2
if d isa UnivariateMixture
t .= Base.Fix1(pdf, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
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
pdf(d::UnivariateMixture, x::Real) = _mixpdf1(d, x)
logpdf(d::UnivariateMixture, x::Real) = _mixlogpdf1(d, x)
##CHUNK 3
end
function _cwise_logpdf1!(r::AbstractVector, d::AbstractMixtureModel, x)
K = ncomponents(d)
length(r) == K || error("The length of r should match the number of components.")
for i = 1:K
r[i] = logpdf(component(d, i), x)
end
r
end
function _cwise_pdf!(r::AbstractMatrix, d::AbstractMixtureModel, X)
K = ncomponents(d)
n = size(X, ndims(X))
size(r) == (n, K) || error("The size of r is incorrect.")
for i = 1:K
if d isa UnivariateMixture
view(r,:,i) .= Base.Fix1(pdf, component(d, i)).(X)
else
pdf!(view(r,:,i),component(d, i), X)
|
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
@inbounds C[j,j] = (α0 - αj) * αjc
for i in (j+1):k
@inbounds C[i,j] = - α[i] * αjc
end
end
return C
end | 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
@inbounds C[j,j] = (α0 - αj) * αjc
for i in (j+1):k
@inbounds C[i,j] = - α[i] * αjc
end
end
return C
end | [
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
@inbounds C[j,j] = (α0 - αj) * αjc
for i in (j+1):k
@inbounds C[i,j] = - α[i] * αjc
end
end
return C
end | 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
@inbounds C[j,j] = (α0 - αj) * αjc
for i in (j+1):k
@inbounds C[i,j] = - α[i] * αjc
end
end
return C
end | 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::DirichletMultinomial{<:Real})
v = var(d)
c = d.α * d.α'
lmul!(-d.n * (d.n + d.α0) / (d.α0^2 * (1 + d.α0)), c)
for (i, vi) in zip(diagind(c), v)
@inbounds c[i] = vi
end
c
end
# Evaluation
##CHUNK 2
c = d.α * d.α'
lmul!(-d.n * (d.n + d.α0) / (d.α0^2 * (1 + d.α0)), c)
for (i, vi) in zip(diagind(c), v)
@inbounds c[i] = vi
end
c
end
# Evaluation
function insupport(d::DirichletMultinomial, x::AbstractVector{T}) where T<:Real
k = length(d)
length(x) == k || return false
for xi in x
(isinteger(xi) && xi >= 0) || return false
end
return sum(x) == ntrials(d)
end
function _logpdf(d::DirichletMultinomial{S}, x::AbstractVector{T}) where {T<:Real, S<:Real}
c = loggamma(S(d.n + 1)) + loggamma(d.α0) - loggamma(d.n + d.α0)
##CHUNK 3
α = ones(size(ss.s, 1))
rng = 0.0:(k - 1)
@inbounds for iter in 1:maxiter
α_old = copy(α)
αsum = sum(α)
denom = ss.tw * sum(inv, αsum .+ rng)
for j in eachindex(α)
αj = α[j]
num = αj * sum(vec(ss.s[j, :]) ./ (αj .+ rng)) # vec needed for 0.4
α[j] = num / denom
end
maximum(abs, α_old - α) < tol && break
end
DirichletMultinomial(ss.n, α)
end
#FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
#FILE: Distributions.jl/src/matrix/matrixbeta.jl
##CHUNK 1
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*(-(2/n)*Ω[i,j]*Ω[k,l] + Ω[j,l]*Ω[i,k] + Ω[i,l]*Ω[k,j])
end
function var(d::MatrixBeta, i::Integer, j::Integer)
p, n1, n2 = params(d)
n = n1 + n2
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*((1 - (2/n))*Ω[i,j]^2 + Ω[j,j]*Ω[i,i])
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function matrixbeta_logc0(p::Int, n1::Real, n2::Real)
# returns the natural log of the normalizing constant for the pdf
return -logmvbeta(p, n1 / 2, n2 / 2)
end
#FILE: Distributions.jl/src/univariate/continuous/ksdist.jl
##CHUNK 1
H[i,1] = H[m,m-i+1] = ch*r
r += h^i
end
H[m,1] += h <= 0.5 ? -h^m : -h^m+(h-ch)
for i = 1:m, j = 1:m
for g = 1:max(i-j+1,0)
H[i,j] /= g
end
# we can avoid keeping track of the exponent by dividing by e
# (from Stirling's approximation)
H[i,j] /= ℯ
end
Q = H^n
s = Q[k,k]
s*stirling(n)
end
# Miller (1956) approximation
function ccdf_miller(d::KSDist, x::Real)
2*ccdf(KSOneSided(d.n),x)
#CURRENT FILE: Distributions.jl/src/multivariate/dirichlet.jl
##CHUNK 1
en = d.lmnB + (α0 - k) * digamma(α0) - sum(αj -> (αj - 1) * digamma(αj), α)
return en
end
function dirichlet_mode!(r::AbstractVector{<:Real}, α::AbstractVector{<:Real}, α0::Real)
all(x -> x > 1, α) || error("Dirichlet has a mode only when alpha[i] > 1 for all i")
k = length(α)
inv_s = inv(α0 - k)
@. r = inv_s * (α - 1)
return r
end
function dirichlet_mode(α::AbstractVector{<:Real}, α0::Real)
all(x -> x > 1, α) || error("Dirichlet has a mode only when alpha[i] > 1 for all i")
inv_s = inv(α0 - length(α))
r = map(α) do αi
inv_s * (αi - 1)
end
return r
end
##CHUNK 2
@inbounds γk = γ[k]
ak = (μk - γk) / (γk - μk * μk)
α0 += ak
end
α0 /= K
lmul!(α0, μ)
end
function dirichlet_mle_init(P::AbstractMatrix{Float64})
K = size(P, 1)
n = size(P, 2)
μ = vec(sum(P, dims=2)) # E[p]
γ = vec(sum(abs2, P, dims=2)) # E[p^2]
c = 1.0 / n
μ .*= c
γ .*= c
##CHUNK 3
_dirichlet_mle_init2(μ, γ)
end
function dirichlet_mle_init(P::AbstractMatrix{Float64}, w::AbstractArray{Float64})
K = size(P, 1)
n = size(P, 2)
μ = zeros(K) # E[p]
γ = zeros(K) # E[p^2]
tw = 0.0
for i in 1:n
@inbounds wi = w[i]
tw += wi
for k in 1:K
pk = P[k, i]
@inbounds μ[k] += pk * wi
@inbounds γ[k] += pk * pk * wi
end
end
##CHUNK 4
αi * (α0 - αi) * c
end
return v
end
function entropy(d::Dirichlet)
α0 = d.alpha0
α = d.alpha
k = length(d.alpha)
en = d.lmnB + (α0 - k) * digamma(α0) - sum(αj -> (αj - 1) * digamma(αj), α)
return en
end
function dirichlet_mode!(r::AbstractVector{<:Real}, α::AbstractVector{<:Real}, α0::Real)
all(x -> x > 1, α) || error("Dirichlet has a mode only when alpha[i] > 1 for all i")
k = length(α)
inv_s = inv(α0 - k)
@. r = inv_s * (α - 1)
return r
|
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 integer."),
(
ranks,
_are_ranks_valid(ranks, n),
"`ranks` must be a sorted vector or tuple of unique integers between 1 and `n`.",
),
)
return new{typeof(dist),typeof(ranks)}(dist, n, ranks)
end | 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 integer."),
(
ranks,
_are_ranks_valid(ranks, n),
"`ranks` must be a sorted vector or tuple of unique integers between 1 and `n`.",
),
)
return new{typeof(dist),typeof(ranks)}(dist, n, ranks)
end | [
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 integer."),
(
ranks,
_are_ranks_valid(ranks, n),
"`ranks` must be a sorted vector or tuple of unique integers between 1 and `n`.",
),
)
return new{typeof(dist),typeof(ranks)}(dist, n, ranks)
end | 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 integer."),
(
ranks,
_are_ranks_valid(ranks, n),
"`ranks` must be a sorted vector or tuple of unique integers between 1 and `n`.",
),
)
return new{typeof(dist),typeof(ranks)}(dist, n, ranks)
end | 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) # distribution of the sample maximum
OrderStatistic(Gamma(1, 1), 11, 5) # distribution of the sample median
```
"""
struct OrderStatistic{D<:UnivariateDistribution,S<:ValueSupport} <:
UnivariateDistribution{S}
dist::D
n::Int
rank::Int
function OrderStatistic(
dist::UnivariateDistribution, n::Int, rank::Int; check_args::Bool=true
)
@check_args(OrderStatistic, 1 ≤ rank ≤ n)
##CHUNK 2
"""
struct OrderStatistic{D<:UnivariateDistribution,S<:ValueSupport} <:
UnivariateDistribution{S}
dist::D
n::Int
rank::Int
function OrderStatistic(
dist::UnivariateDistribution, n::Int, rank::Int; check_args::Bool=true
)
@check_args(OrderStatistic, 1 ≤ rank ≤ n)
return new{typeof(dist),value_support(typeof(dist))}(dist, n, rank)
end
end
minimum(d::OrderStatistic) = minimum(d.dist)
maximum(d::OrderStatistic) = maximum(d.dist)
insupport(d::OrderStatistic, x::Real) = insupport(d.dist, x)
params(d::OrderStatistic) = tuple(params(d.dist)..., d.n, d.rank)
partype(d::OrderStatistic) = partype(d.dist)
#FILE: Distributions.jl/test/multivariate/jointorderstatistics.jl
##CHUNK 1
JointOrderStatistics(dist, 5, (3, 2); check_args=false)
JointOrderStatistics(dist, 5, (3, 3); check_args=false)
end
@testset for T in [Float32, Float64],
dist in [Uniform(T(2), T(10)), Exponential(T(10)), Normal(T(100), T(10))],
n in [16, 40],
r in [
1:n,
([i, j] for j in 2:n for i in 1:min(10, j - 1))...,
vcat(2:4, (n - 10):(n - 5)),
(2, n ÷ 2, n - 5),
]
d = JointOrderStatistics(dist, n, r)
@testset "basic" begin
@test d isa JointOrderStatistics
@test d.dist === dist
@test d.n === n
#FILE: Distributions.jl/test/univariate/orderstatistic.jl
##CHUNK 1
using Test, Distributions
using Random
using StatsBase
@testset "OrderStatistic" begin
@testset "basic" begin
for dist in [Uniform(), Normal(), DiscreteUniform(10)], n in [1, 2, 10], i in 1:n
d = OrderStatistic(dist, n, i)
@test d isa OrderStatistic
if dist isa DiscreteUnivariateDistribution
@test d isa DiscreteUnivariateDistribution
else
@test d isa ContinuousUnivariateDistribution
end
@test d.dist === dist
@test d.n == n
@test d.rank == i
end
@test_throws ArgumentError OrderStatistic(Normal(), 0, 1)
OrderStatistic(Normal(), 0, 1; check_args=false)
##CHUNK 2
@test d isa DiscreteUnivariateDistribution
else
@test d isa ContinuousUnivariateDistribution
end
@test d.dist === dist
@test d.n == n
@test d.rank == i
end
@test_throws ArgumentError OrderStatistic(Normal(), 0, 1)
OrderStatistic(Normal(), 0, 1; check_args=false)
@test_throws ArgumentError OrderStatistic(Normal(), 10, 11)
OrderStatistic(Normal(), 10, 11; check_args=false)
@test_throws ArgumentError OrderStatistic(Normal(), 10, 0)
OrderStatistic(Normal(), 10, 0; check_args=false)
end
@testset "params" begin
for dist in [Uniform(), Normal(), DiscreteUniform(10)], n in [1, 2, 10], i in 1:n
d = OrderStatistic(dist, n, i)
@test params(d) == (params(dist)..., n, i)
#FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
"""
struct Multinomial{T<:Real, TV<:AbstractVector{T}} <: DiscreteMultivariateDistribution
n::Int
p::TV
Multinomial{T, TV}(n::Int, p::TV) where {T <: Real, TV <: AbstractVector{T}} = new{T, TV}(n, p)
end
function Multinomial(n::Integer, p::AbstractVector{T}; check_args::Bool=true) where {T<:Real}
@check_args(
Multinomial,
(n, n >= 0),
(p, isprobvec(p), "p is not a probability vector."),
)
return Multinomial{T,typeof(p)}(n, p)
end
function Multinomial(n::Integer, k::Integer; check_args::Bool=true)
@check_args Multinomial (n, n >= 0) (k, k >= 1)
return Multinomial{Float64, Vector{Float64}}(round(Int, n), fill(1.0 / k, k))
end
#CURRENT FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
JointOrderStatistics(
dist::ContinuousUnivariateDistribution,
n::Int,
ranks=Base.OneTo(n);
check_args::Bool=true,
)
Construct the joint distribution of order statistics for the specified `ranks` from an IID
sample of size `n` from `dist`.
The ``i``th order statistic of a sample is the ``i``th element of the sorted sample.
For example, the 1st order statistic is the sample minimum, while the ``n``th order
statistic is the sample maximum.
`ranks` must be a sorted vector or tuple of unique `Int`s between 1 and `n`.
For a single order statistic, use [`OrderStatistic`](@ref) instead.
## Examples
##CHUNK 2
```julia
JointOrderStatistics(Normal(), 10) # Product(fill(Normal(), 10)) restricted to ordered vectors
JointOrderStatistics(Cauchy(), 10, 2:9) # joint distribution of all but the extrema
JointOrderStatistics(Cauchy(), 10, (1, 10)) # joint distribution of only the extrema
```
"""
struct JointOrderStatistics{
D<:ContinuousUnivariateDistribution,R<:Union{AbstractVector{Int},Tuple{Int,Vararg{Int}}}
} <: ContinuousMultivariateDistribution
dist::D
n::Int
ranks::R
end
_islesseq(x, y) = isless(x, y) || isequal(x, y)
function _are_ranks_valid(ranks, n)
# this is equivalent to but faster than
# issorted(ranks) && allunique(ranks)
!isempty(ranks) && first(ranks) ≥ 1 && last(ranks) ≤ n && issorted(ranks; lt=_islesseq)
##CHUNK 3
The ``i``th order statistic of a sample is the ``i``th element of the sorted sample.
For example, the 1st order statistic is the sample minimum, while the ``n``th order
statistic is the sample maximum.
`ranks` must be a sorted vector or tuple of unique `Int`s between 1 and `n`.
For a single order statistic, use [`OrderStatistic`](@ref) instead.
## Examples
```julia
JointOrderStatistics(Normal(), 10) # Product(fill(Normal(), 10)) restricted to ordered vectors
JointOrderStatistics(Cauchy(), 10, 2:9) # joint distribution of all but the extrema
JointOrderStatistics(Cauchy(), 10, (1, 10)) # joint distribution of only the extrema
```
"""
struct JointOrderStatistics{
D<:ContinuousUnivariateDistribution,R<:Union{AbstractVector{Int},Tuple{Int,Vararg{Int}}}
} <: ContinuousMultivariateDistribution
dist::D
##CHUNK 4
# Implementation based on chapters 2-4 of
# Arnold, Barry C., Narayanaswamy Balakrishnan, and Haikady Navada Nagaraja.
# A first course in order statistics. Society for Industrial and Applied Mathematics, 2008.
"""
JointOrderStatistics <: ContinuousMultivariateDistribution
The joint distribution of a subset of order statistics from a sample from a continuous
univariate distribution.
JointOrderStatistics(
dist::ContinuousUnivariateDistribution,
n::Int,
ranks=Base.OneTo(n);
check_args::Bool=true,
)
Construct the joint distribution of order statistics for the specified `ranks` from an IID
sample of size `n` from `dist`.
|
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 && insupport(dist, xj) || return false
xi = xj
end
return true
end | 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 && insupport(dist, xj) || return false
xi = xj
end
return true
end | [
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 && insupport(dist, xj) || return false
xi = xj
end
return true
end | 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 && insupport(dist, xj) || return false
xi = xj
end
return true
end | 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 of `d`.
Generic fallback methods are provided, but it is often the case that `insupport` can be
done more efficiently, and a specialized `insupport` is thus desirable.
You should also override this function if the support is composed of multiple disjoint intervals.
"""
insupport{D<:UnivariateDistribution}(d::Union{D, Type{D}}, x::Any)
function insupport!(r::AbstractArray, d::Union{D,Type{D}}, X::AbstractArray) where D<:UnivariateDistribution
length(r) == length(X) ||
throw(DimensionMismatch("Inconsistent array dimensions."))
for i in 1 : length(X)
@inbounds r[i] = insupport(d, X[i])
end
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
@test all(insupport(d, vs))
if islowerbounded(d)
@test isfinite(minimum(d))
@test insupport(d, minimum(d))
@test !insupport(d, minimum(d)-1)
end
if isupperbounded(d)
@test isfinite(maximum(d))
@test insupport(d, maximum(d))
@test !insupport(d, maximum(d)+1)
end
@test isbounded(d) == (isupperbounded(d) && islowerbounded(d))
# Test the `Base.in` or `∈` operator
# The `support` function is buggy for unbounded `DiscreteUnivariateDistribution`s
if isbounded(d) || isa(d, ContinuousUnivariateDistribution)
s = support(d)
for v in vs
##CHUNK 2
@test !insupport(d, maximum(d)+1)
end
@test isbounded(d) == (isupperbounded(d) && islowerbounded(d))
# Test the `Base.in` or `∈` operator
# The `support` function is buggy for unbounded `DiscreteUnivariateDistribution`s
if isbounded(d) || isa(d, ContinuousUnivariateDistribution)
s = support(d)
for v in vs
@test v ∈ s
end
if islowerbounded(d)
@test minimum(d) ∈ s
@test (minimum(d) - 1) ∉ s
end
if isupperbounded(d)
@test maximum(d) ∈ s
@test (maximum(d) + 1) ∉ s
##CHUNK 3
@test v ∈ s
end
if islowerbounded(d)
@test minimum(d) ∈ s
@test (minimum(d) - 1) ∉ s
end
if isupperbounded(d)
@test maximum(d) ∈ s
@test (maximum(d) + 1) ∉ s
end
end
if isbounded(d) && isa(d, DiscreteUnivariateDistribution)
s = support(d)
@test isa(s, AbstractUnitRange)
@test first(s) == minimum(d)
@test last(s) == maximum(d)
end
end
##CHUNK 4
lv = quantile(d, q/2)
hv = cquantile(d, q/2)
@assert isfinite(lv) && isfinite(hv) && lv <= hv
return _linspace(lv, hv, n)
end
function test_support(d::UnivariateDistribution, vs::AbstractVector)
for v in vs
@test insupport(d, v)
end
@test all(insupport(d, vs))
if islowerbounded(d)
@test isfinite(minimum(d))
@test insupport(d, minimum(d))
@test !insupport(d, minimum(d)-1)
end
if isupperbounded(d)
@test isfinite(maximum(d))
@test insupport(d, maximum(d))
#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)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
##CHUNK 2
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
while cp < q && i < k #Note: is i < k necessary?
i += 1
@inbounds cp += p[i]
end
x[i]
end
minimum(d::DiscreteNonParametric) = first(support(d))
maximum(d::DiscreteNonParametric) = last(support(d))
insupport(d::DiscreteNonParametric, x::Real) =
#FILE: Distributions.jl/test/univariate/orderstatistic.jl
##CHUNK 1
@test partype(d) === partype(dist)
end
end
@testset "support" begin
n = 10
for i in 1:10
d1 = OrderStatistic(Uniform(), n, i)
@test minimum(d1) == 0
@test maximum(d1) == 1
@test insupport(d1, 0)
@test insupport(d1, 0.5)
@test insupport(d1, 1)
@test !insupport(d1, -eps())
@test !insupport(d1, 1 + eps())
@test !hasfinitesupport(d1)
@test islowerbounded(d1)
@test isupperbounded(d1)
d2 = OrderStatistic(Normal(), n, i)
#FILE: Distributions.jl/test/multivariate/jointorderstatistics.jl
##CHUNK 1
@test d.ranks === r
@test length(d) == length(r)
@test params(d) == (params(dist)..., d.n, d.ranks)
@test partype(d) === partype(dist)
@test eltype(d) === eltype(dist)
length(r) == n && @test JointOrderStatistics(dist, n) == d
end
@testset "support" begin
@test minimum(d) == fill(minimum(dist), length(r))
@test maximum(d) == fill(maximum(dist), length(r))
x = sort(rand(dist, length(r)))
x2 = sort(rand(dist, length(r) + 1))
@test insupport(d, x)
if length(x) > 1
@test !insupport(d, reverse(x))
@test !insupport(d, x[1:(end - 1)])
end
@test !insupport(d, x2)
#CURRENT FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
_islesseq(x, y) = isless(x, y) || isequal(x, y)
function _are_ranks_valid(ranks, n)
# this is equivalent to but faster than
# issorted(ranks) && allunique(ranks)
!isempty(ranks) && first(ranks) ≥ 1 && last(ranks) ≤ n && issorted(ranks; lt=_islesseq)
end
function _are_ranks_valid(ranks::AbstractRange, n)
!isempty(ranks) && first(ranks) ≥ 1 && last(ranks) ≤ n && step(ranks) > 0
end
length(d::JointOrderStatistics) = length(d.ranks)
minimum(d::JointOrderStatistics) = Fill(minimum(d.dist), length(d))
maximum(d::JointOrderStatistics) = Fill(maximum(d.dist), length(d))
params(d::JointOrderStatistics) = tuple(params(d.dist)..., d.n, d.ranks)
partype(d::JointOrderStatistics) = partype(d.dist)
Base.eltype(::Type{<:JointOrderStatistics{D}}) where {D} = Base.eltype(D)
Base.eltype(d::JointOrderStatistics) = eltype(d.dist)
|
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)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end | 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)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end | [
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)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end | 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)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end | 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(pdf(d, x)) isa T
if length(r) == 1
@test logpdf(d, x) ≈ logpdf(OrderStatistic(dist, n, r[1]), x[1])
@test pdf(d, x) ≈ pdf(OrderStatistic(dist, n, r[1]), x[1])
elseif length(r) == 2
i, j = r
xi, xj = x
lc = T(
logfactorial(n) - logfactorial(i - 1) - logfactorial(n - j) -
logfactorial(j - i - 1),
)
lp = (
lc +
##CHUNK 2
(i - 1) * logcdf(dist, xi) +
(n - j) * logccdf(dist, xj) +
(j - i - 1) * logdiffcdf(dist, xj, xi) +
logpdf(dist, xi) +
logpdf(dist, xj)
)
@test logpdf(d, x) ≈ lp
@test pdf(d, x) ≈ exp(lp)
elseif collect(r) == 1:n
@test logpdf(d, x) ≈ sum(Base.Fix1(logpdf, d.dist), x) + loggamma(T(n + 1))
@test pdf(d, x) ≈ exp(logpdf(d, x))
end
@testset "no density for vectors out of support" begin
# check unsorted vectors have 0 density
x2 = copy(x)
x2[1], x2[2] = x2[2], x2[1]
@test logpdf(d, x2) == T(-Inf)
@test pdf(d, x2) == zero(T)
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# 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 / μ
##CHUNK 2
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end
##CHUNK 3
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
#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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
#FILE: Distributions.jl/src/univariate/orderstatistic.jl
##CHUNK 1
Base.eltype(::Type{<:OrderStatistic{D}}) where {D} = Base.eltype(D)
Base.eltype(d::OrderStatistic) = eltype(d.dist)
# distribution of the ith order statistic from an IID uniform distribution, with CDF Uᵢₙ(x)
function _uniform_orderstatistic(d::OrderStatistic)
n = d.n
rank = d.rank
return Beta{Int}(rank, n - rank + 1)
end
function logpdf(d::OrderStatistic, x::Real)
b = _uniform_orderstatistic(d)
p = cdf(d.dist, x)
if value_support(typeof(d)) === Continuous
return logpdf(b, p) + logpdf(d.dist, x)
else
return logdiffcdf(b, p, p - pdf(d.dist, x))
end
end
#FILE: Distributions.jl/src/univariate/continuous/logitnormal.jl
##CHUNK 1
cdf(d::LogitNormal{T}, x::Real) where {T<:Real} =
x ≤ 0 ? zero(T) : x ≥ 1 ? one(T) : normcdf(d.μ, d.σ, logit(x))
ccdf(d::LogitNormal{T}, x::Real) where {T<:Real} =
x ≤ 0 ? one(T) : x ≥ 1 ? zero(T) : normccdf(d.μ, d.σ, logit(x))
logcdf(d::LogitNormal{T}, x::Real) where {T<:Real} =
x ≤ 0 ? -T(Inf) : x ≥ 1 ? zero(T) : normlogcdf(d.μ, d.σ, logit(x))
logccdf(d::LogitNormal{T}, x::Real) where {T<:Real} =
x ≤ 0 ? zero(T) : x ≥ 1 ? -T(Inf) : normlogccdf(d.μ, d.σ, logit(x))
quantile(d::LogitNormal, q::Real) = logistic(norminvcdf(d.μ, d.σ, q))
cquantile(d::LogitNormal, q::Real) = logistic(norminvccdf(d.μ, d.σ, q))
invlogcdf(d::LogitNormal, lq::Real) = logistic(norminvlogcdf(d.μ, d.σ, lq))
invlogccdf(d::LogitNormal, lq::Real) = logistic(norminvlogccdf(d.μ, d.σ, lq))
function gradlogpdf(d::LogitNormal, x::Real)
μ, σ = params(d)
_insupport = insupport(d, x)
_x = _insupport ? x : zero(x)
z = (μ - logit(_x) + σ^2 * (2 * _x - 1)) / (σ^2 * _x * (1 - _x))
#CURRENT FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
Base.eltype(::Type{<:JointOrderStatistics{D}}) where {D} = Base.eltype(D)
Base.eltype(d::JointOrderStatistics) = eltype(d.dist)
# given ∏ₖf(xₖ), marginalize all xₖ for i < k < j
function _marginalize_range(dist, i, j, xᵢ, xⱼ, T)
k = j - i - 1
k == 0 && return zero(T)
return k * T(logdiffcdf(dist, xⱼ, xᵢ)) - loggamma(T(k + 1))
end
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.dist, x)
sort!(x)
else
# use exponential generation method with inversion, where for gaps in the ranks, we
##CHUNK 2
xj ≥ xi && insupport(dist, xj) || return false
xi = xj
end
return true
end
minimum(d::JointOrderStatistics) = Fill(minimum(d.dist), length(d))
maximum(d::JointOrderStatistics) = Fill(maximum(d.dist), length(d))
params(d::JointOrderStatistics) = tuple(params(d.dist)..., d.n, d.ranks)
partype(d::JointOrderStatistics) = partype(d.dist)
Base.eltype(::Type{<:JointOrderStatistics{D}}) where {D} = Base.eltype(D)
Base.eltype(d::JointOrderStatistics) = eltype(d.dist)
# given ∏ₖf(xₖ), marginalize all xₖ for i < k < j
function _marginalize_range(dist, i, j, xᵢ, xⱼ, T)
k = j - i - 1
k == 0 && return zero(T)
return k * T(logdiffcdf(dist, xⱼ, xᵢ)) - loggamma(T(k + 1))
end
|
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.dist, x)
sort!(x)
else
# use exponential generation method with inversion, where for gaps in the ranks, we
# use the fact that the sum Y of k IID variables xₘ ~ Exp(1) is Y ~ Gamma(k, 1).
# Lurie, D., and H. O. Hartley. "Machine-generation of order statistics for Monte
# Carlo computations." The American Statistician 26.1 (1972): 26-27.
# this is slow if length(d.ranks) is close to n and quantile for d.dist is expensive,
# but this branch is probably taken when length(d.ranks) is small or much smaller than n.
T = typeof(one(eltype(x)))
s = zero(eltype(x))
i = 0
for (m, j) in zip(eachindex(x), d.ranks)
k = j - i
if k > 1
# specify GammaMTSampler directly to avoid unnecessarily checking the shape
# parameter again and because it has been benchmarked to be the fastest for
# shape k ≥ 1 and scale 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
i = j
x[m] = s
end
j = n + 1
k = j - i
if k > 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
x .= Base.Fix1(quantile, d.dist).(x ./ s)
end
return x
end | 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.dist, x)
sort!(x)
else
# use exponential generation method with inversion, where for gaps in the ranks, we
# use the fact that the sum Y of k IID variables xₘ ~ Exp(1) is Y ~ Gamma(k, 1).
# Lurie, D., and H. O. Hartley. "Machine-generation of order statistics for Monte
# Carlo computations." The American Statistician 26.1 (1972): 26-27.
# this is slow if length(d.ranks) is close to n and quantile for d.dist is expensive,
# but this branch is probably taken when length(d.ranks) is small or much smaller than n.
T = typeof(one(eltype(x)))
s = zero(eltype(x))
i = 0
for (m, j) in zip(eachindex(x), d.ranks)
k = j - i
if k > 1
# specify GammaMTSampler directly to avoid unnecessarily checking the shape
# parameter again and because it has been benchmarked to be the fastest for
# shape k ≥ 1 and scale 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
i = j
x[m] = s
end
j = n + 1
k = j - i
if k > 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
x .= Base.Fix1(quantile, d.dist).(x ./ s)
end
return x
end | [
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.dist, x)
sort!(x)
else
# use exponential generation method with inversion, where for gaps in the ranks, we
# use the fact that the sum Y of k IID variables xₘ ~ Exp(1) is Y ~ Gamma(k, 1).
# Lurie, D., and H. O. Hartley. "Machine-generation of order statistics for Monte
# Carlo computations." The American Statistician 26.1 (1972): 26-27.
# this is slow if length(d.ranks) is close to n and quantile for d.dist is expensive,
# but this branch is probably taken when length(d.ranks) is small or much smaller than n.
T = typeof(one(eltype(x)))
s = zero(eltype(x))
i = 0
for (m, j) in zip(eachindex(x), d.ranks)
k = j - i
if k > 1
# specify GammaMTSampler directly to avoid unnecessarily checking the shape
# parameter again and because it has been benchmarked to be the fastest for
# shape k ≥ 1 and scale 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
i = j
x[m] = s
end
j = n + 1
k = j - i
if k > 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
x .= Base.Fix1(quantile, d.dist).(x ./ s)
end
return x
end | 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.dist, x)
sort!(x)
else
# use exponential generation method with inversion, where for gaps in the ranks, we
# use the fact that the sum Y of k IID variables xₘ ~ Exp(1) is Y ~ Gamma(k, 1).
# Lurie, D., and H. O. Hartley. "Machine-generation of order statistics for Monte
# Carlo computations." The American Statistician 26.1 (1972): 26-27.
# this is slow if length(d.ranks) is close to n and quantile for d.dist is expensive,
# but this branch is probably taken when length(d.ranks) is small or much smaller than n.
T = typeof(one(eltype(x)))
s = zero(eltype(x))
i = 0
for (m, j) in zip(eachindex(x), d.ranks)
k = j - i
if k > 1
# specify GammaMTSampler directly to avoid unnecessarily checking the shape
# parameter again and because it has been benchmarked to be the fastest for
# shape k ≥ 1 and scale 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
i = j
x[m] = s
end
j = n + 1
k = j - i
if k > 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
x .= Base.Fix1(quantile, d.dist).(x ./ s)
end
return x
end | _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 μ + copysign(z, r)
end
#### Sampling
# The sampling procedure is implemented from from [1].
# [1] Gonzalez-Farias, G., Molina, J. A. D., & Rodríguez-Dagnino, R. M. (2009).
# Efficiency of the approximated shape parameter estimator in the generalized
# Gaussian distribution. IEEE Transactions on Vehicular Technology, 58(8),
# 4214-4223.
function rand(rng::AbstractRNG, d::PGeneralizedGaussian)
#FILE: Distributions.jl/test/univariate/orderstatistic.jl
##CHUNK 1
α = (0.01 / nchecks) / 2 # multiple correction
tol = quantile(Normal(), 1 - α)
@testset for dist in [Uniform(), Exponential(), Poisson(20), Binomial(20, 0.3)]
@testset for n in [1, 10, 100], i in 1:n
d = OrderStatistic(dist, n, i)
x = rand(d, ndraws)
m, v = mean_and_var(x)
if dist isa Uniform
# Arnold (2008). A first course in order statistics. Eqs 2.2.20-21
m_exact = i / (n + 1)
v_exact = m_exact * (1 - m_exact) / (n + 2)
elseif dist isa Exponential
# Arnold (2008). A first course in order statistics. Eqs 4.6.6-7
m_exact = sum(k -> inv(n - k + 1), 1:i)
v_exact = sum(k -> inv((n - k + 1)^2), 1:i)
elseif dist isa DiscreteUnivariateDistribution
# estimate mean and variance with explicit sum, Eqs 3.2.6-7 from
# Arnold (2008). A first course in order statistics.
xs = 0:quantile(dist, 0.9999)
#FILE: Distributions.jl/test/multivariate/jointorderstatistics.jl
##CHUNK 1
if dist isa Uniform
# Arnold (2008). A first course in order statistics. Eq 2.3.16
s = @. n - r + 1
xcor_exact = Symmetric(sqrt.((r .* collect(s)') ./ (collect(r)' .* s)))
elseif dist isa Exponential
# Arnold (2008). A first course in order statistics. Eq 4.6.8
v = [sum(k -> inv((n - k + 1)^2), 1:i) for i in r]
xcor_exact = Symmetric(sqrt.(v ./ v'))
end
for ii in 1:m, ji in (ii + 1):m
i = r[ii]
j = r[ji]
ρ = xcor[ii, ji]
ρ_exact = xcor_exact[ii, ji]
# use variance-stabilizing transformation, recommended in §3.6 of
# Van der Vaart, A. W. (2000). Asymptotic statistics (Vol. 3).
@test atanh(ρ) ≈ atanh(ρ_exact) atol = tol
end
end
end
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
end
@quantile_newton InverseGaussian
#### Sampling
# rand method from:
# John R. Michael, William R. Schucany and Roy W. Haas (1976)
# Generating Random Variates Using Transformations with Multiple Roots
# The American Statistician , Vol. 30, No. 2, pp. 88-90
function rand(rng::AbstractRNG, d::InverseGaussian)
μ, λ = params(d)
z = randn(rng)
v = z * z
w = μ * v
x1 = μ + μ / (2λ) * (w - sqrt(w * (4λ + w)))
p1 = μ / (μ + x1)
u = rand(rng)
u >= p1 ? μ^2 / x1 : x1
end
#FILE: Distributions.jl/src/univariate/continuous/lindley.jl
##CHUNK 1
end
for i in 1:n
β = β / (1 + β) * (1 + log(x / β))
end
return β
end
### Sampling
# Ghitany, M. E., Atieh, B., & Nadarajah, S. (2008). Lindley distribution and its
# application. Mathematics and Computers in Simulation, 78(4), 493–506.
function rand(rng::AbstractRNG, d::Lindley)
θ = shape(d)
λ = inv(θ)
T = typeof(λ)
u = rand(rng)
p = θ / (1 + θ)
return oftype(u, rand(rng, u <= p ? Exponential{T}(λ) : Gamma{T}(2, λ)))
end
#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
θ =
return rand(rng, Exponential{partype(d)}(scale(d)))
else
return rand(rng, GammaMTSampler(d))
end
end
function sampler(d::Gamma)
if shape(d) < 1.0
# TODO: shape(d) = 0.5 : use scaled chisq
return GammaIPSampler(d)
elseif shape(d) == 1.0
return sampler(Exponential{partype(d)}(scale(d)))
#FILE: Distributions.jl/src/univariate/discrete/poissonbinomial.jl
##CHUNK 1
y = zeros(complex(float(T)), n)
@inbounds for j = 0:n-1, k = 0:n-1
y[k+1] += x[j+1] * cis(-π * float(T)(2 * mod(j * k, n)) / n)
end
return y
end
#### Sampling
sampler(d::PoissonBinomial) = PoissBinAliasSampler(d)
# Compute matrix of partial derivatives [∂P(X=j-1)/∂pᵢ]_{i=1,…,n; j=1,…,n+1}
#
# This implementation uses the same dynamic programming "trick" as for the computation of
# the primals.
#
# Reference (for the primal):
#
# Marlin A. Thomas & Audrey E. Taub (1982)
# Calculating binomial probabilities when the trial probabilities are unequal,
##CHUNK 2
x[n + 1 - l + 1] = conj(x[l + 1])
end
end
[max(0, real(xi)) for xi in _dft(x)]
end
# A simple implementation of a DFT to avoid introducing a dependency
# on an external FFT package just for this one distribution
function _dft(x::Vector{T}) where T
n = length(x)
y = zeros(complex(float(T)), n)
@inbounds for j = 0:n-1, k = 0:n-1
y[k+1] += x[j+1] * cis(-π * float(T)(2 * mod(j * k, n)) / n)
end
return y
end
#### Sampling
sampler(d::PoissonBinomial) = PoissBinAliasSampler(d)
#FILE: Distributions.jl/src/univariate/continuous/chernoff.jl
##CHUNK 1
## chernoff.jl
##
## The code below is intended to go with the Distributions package of Julia.
## It was written by Joris Pinkse, joris@psu.edu, on December 12, 2017. Caveat emptor.
##
## It computes pdf, cdf, moments, quantiles, and random numbers for the Chernoff distribution.
##
## Most of the symbols have the same meaning as in the Groeneboom and Wellner paper.
##
## Random numbers are drawn using a Ziggurat algorithm. To obtain draws in the tails, the
## algorithm reverts to quantiles, which is slow.
"""
Chernoff()
The *Chernoff distribution* is the distribution of the random variable
```math
\\underset{t \\in (-\\infty,\\infty)}{\\arg\\max} ( G(t) - t^2 ),
```
where ``G`` is standard two-sided Brownian motion.
#FILE: Distributions.jl/test/multivariate/vonmisesfisher.jl
##CHUNK 1
# Tests for Von-Mises Fisher distribution
using Distributions, Random
using LinearAlgebra, Test
using SpecialFunctions
logvmfCp(p::Int, κ::Real) = (p / 2 - 1) * log(κ) - log(besselix(p / 2 - 1, κ)) - κ - p / 2 * log(2π)
safe_logvmfpdf(μ::Vector, κ::Real, x::Vector) = logvmfCp(length(μ), κ) + κ * dot(μ, x)
function gen_vmf_tdata(n::Int, p::Int,
rng::Union{AbstractRNG, Missing} = missing)
if ismissing(rng)
X = randn(p, n)
else
X = randn(rng, p, n)
end
for i = 1:n
X[:,i] = X[:,i] ./ norm(X[:,i])
#CURRENT FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl |
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
if approx
return (log(twoπ * n * p0 * p1) + 1) / 2
else
lg = log(p1 / p0)
lp = n * log(p0)
s = exp(lp) * lp
for k = 1:n
lp += log((n - k + 1) / k) + lg
##CHUNK 2
p, n = d.p, d.n
if p <= 0.5
r = p
else
r = 1.0-p
end
if r*n <= 10.0
y = rand(rng, BinomialGeomSampler(n,r))
else
y = rand(rng, BinomialTPESampler(n,r))
end
p <= 0.5 ? y : n-y
end
function mgf(d::Binomial, t::Real)
n, p = params(d)
(one(p) - p + p * exp(t)) ^ n
end
function cgf(d::Binomial, t)
n, p = params(d)
##CHUNK 3
floor_mean
else
floor_mean + 1
end
end
function skewness(d::Binomial)
n, p1 = params(d)
p0 = 1 - p1
(p0 - p1) / sqrt(n * p0 * p1)
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)
##CHUNK 4
end
p <= 0.5 ? y : n-y
end
function mgf(d::Binomial, t::Real)
n, p = params(d)
(one(p) - p + p * exp(t)) ^ n
end
function cgf(d::Binomial, t)
n, p = params(d)
n * cgf(Bernoulli{typeof(p)}(p), t)
end
function cf(d::Binomial, t::Real)
n, p = params(d)
(one(p) - p + p * cis(t)) ^ n
end
#### Fit model
#FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
(α, β) = params(d)
if α == β
return zero(α)
else
s = α + β
(2(β - α) * sqrt(s + 1)) / ((s + 2) * sqrt(α * β))
end
end
function kurtosis(d::Beta)
α, β = params(d)
s = α + β
p = α * β
6(abs2(α - β) * (s + 1) - p * (s + 2)) / (p * (s + 2) * (s + 3))
end
function entropy(d::Beta)
α, β = params(d)
s = α + β
logbeta(α, β) - (α - 1) * digamma(α) - (β - 1) * digamma(β) +
#FILE: Distributions.jl/src/functionals.jl
##CHUNK 1
## Leave undefined until we've implemented a numerical integration procedure
# function entropy(distr::UnivariateDistribution)
# pf = typeof(distr)<:ContinuousDistribution ? pdf : pmf
# f = x -> pf(distr, x)
# expectation(distr, x -> -log(f(x)))
# end
function kldivergence(p::Distribution{V}, q::Distribution{V}; kwargs...) where {V<:VariateForm}
return expectation(p; kwargs...) do x
logp = logpdf(p, x)
return (logp > oftype(logp, -Inf)) * (logp - logpdf(q, x))
end
end
#FILE: Distributions.jl/src/univariate/continuous/pgeneralizedgaussian.jl
##CHUNK 1
skewness(d::PGeneralizedGaussian) = zero(d.p)
kurtosis(d::PGeneralizedGaussian) = gamma(5 / d.p) * gamma(1 / d.p) / gamma(3 / d.p)^2 - 3
entropy(d::PGeneralizedGaussian) = 1 / d.p - log(d.p / (2 * d.α * gamma(1 / d.p)))
#### Evaluation
function pdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
return (p / (2 * α * gamma(1 / p))) * exp(- (abs(x - μ) / α)^p)
end
function logpdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
return log(p / (2 * α)) - loggamma(1 / p) - (abs(x - μ) / α)^p
end
# To determine the CDF, the incomplete gamma function is required.
# The CDF of the Gamma distribution provides this, with the necessary 1/Γ(a) normalization.
function cdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
#FILE: Distributions.jl/src/univariate/continuous/ksonesided.jl
##CHUNK 1
n::Int
end
@distr_support KSOneSided 0.0 1.0
#### Evaluation
# formula of Birnbaum and Tingey (1951)
function ccdf(d::KSOneSided, x::Float64)
if x >= 1
return 0.0
elseif x <= 0
return 1.0
end
n = d.n
s = 0.0
for j = 0:floor(Int,n-n*x)
p = x+j/n
s += pdf(Binomial(n,p),j) / p
#CURRENT FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
return false
end
s += xi
end
return s == ntrials(d) # integer computation would not yield truncation errors
end
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(xi) + 1))
s += xlogy(xi, p_i)
end
##CHUNK 2
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 += xlogy(xi, p_i)
end
return s
end
# Sampling
# if only a single sample is requested, no alias table is created
_rand!(rng::AbstractRNG, d::Multinomial, x::AbstractVector{<:Real}) =
multinom_rand!(rng, ntrials(d), probs(d), x)
sampler(d::Multinomial) = MultinomialSampler(ntrials(d), probs(d))
|
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 computation would not yield truncation errors
end | 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 computation would not yield truncation errors
end | [
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 computation would not yield truncation errors
end | 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 computation would not yield truncation errors
end | 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)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
#FILE: Distributions.jl/src/multivariate/dirichletmultinomial.jl
##CHUNK 1
function insupport(d::DirichletMultinomial, x::AbstractVector{T}) where T<:Real
k = length(d)
length(x) == k || return false
for xi in x
(isinteger(xi) && xi >= 0) || return false
end
return sum(x) == ntrials(d)
end
function _logpdf(d::DirichletMultinomial{S}, x::AbstractVector{T}) where {T<:Real, S<:Real}
c = loggamma(S(d.n + 1)) + loggamma(d.α0) - loggamma(d.n + d.α0)
for j in eachindex(x)
@inbounds xj, αj = x[j], d.α[j]
c += loggamma(xj + αj) - loggamma(xj + 1) - loggamma(αj)
end
c
end
# Sampling
_rand!(rng::AbstractRNG, d::DirichletMultinomial, x::AbstractVector{<:Real}) =
##CHUNK 2
c = d.α * d.α'
lmul!(-d.n * (d.n + d.α0) / (d.α0^2 * (1 + d.α0)), c)
for (i, vi) in zip(diagind(c), v)
@inbounds c[i] = vi
end
c
end
# Evaluation
function insupport(d::DirichletMultinomial, x::AbstractVector{T}) where T<:Real
k = length(d)
length(x) == k || return false
for xi in x
(isinteger(xi) && xi >= 0) || return false
end
return sum(x) == ntrials(d)
end
function _logpdf(d::DirichletMultinomial{S}, x::AbstractVector{T}) where {T<:Real, S<:Real}
c = loggamma(S(d.n + 1)) + loggamma(d.α0) - loggamma(d.n + d.α0)
#FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
elseif isnan(x)
oftype(c, NaN)
elseif x < 0
zero(c)
else
oftype(c, -Inf)
end
end
# implementation of the cdf for distributions whose support is a unitrange of integers
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
##CHUNK 2
Get the number of trials.
"""
ntrials(d::UnivariateDistribution)
"""
dof(d::UnivariateDistribution)
Get the degrees of freedom.
"""
dof(d::UnivariateDistribution)
"""
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 of `d`.
Generic fallback methods are provided, but it is often the case that `insupport` can be
done more efficiently, and a specialized `insupport` is thus desirable.
##CHUNK 3
x >= maximum_d ? zero(c) : c
end
return result
end
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(logsumexp(logpdf(d, y) for y in minimum_d:(max(x, minimum_d))))
x < minimum_d ? zero(c) : c
else
c = logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? oftype(c, -Inf) : c
end
return result
end
##CHUNK 4
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(logpdf(d, y) for y in minimum_d:(max(x, minimum_d)))
x < minimum_d ? oftype(c, -Inf) : c
else
c = log1mexp(logsumexp(logpdf(d, y) for y in (min(x + 1, maximum_d)):maximum_d))
x >= maximum_d ? zero(c) : c
end
return result
end
function integerunitrange_logccdf(d::DiscreteUnivariateDistribution, x::Integer)
minimum_d, maximum_d = extrema(d)
isfinite(minimum_d) || isfinite(maximum_d) || error("support is unbounded")
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
@test !insupport(d, maximum(d)+1)
end
@test isbounded(d) == (isupperbounded(d) && islowerbounded(d))
# Test the `Base.in` or `∈` operator
# The `support` function is buggy for unbounded `DiscreteUnivariateDistribution`s
if isbounded(d) || isa(d, ContinuousUnivariateDistribution)
s = support(d)
for v in vs
@test v ∈ s
end
if islowerbounded(d)
@test minimum(d) ∈ s
@test (minimum(d) - 1) ∉ s
end
if isupperbounded(d)
@test maximum(d) ∈ s
@test (maximum(d) + 1) ∉ s
#CURRENT FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
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 += xlogy(xi, p_i)
end
return s
end
# Sampling
# if only a single sample is requested, no alias table is created
_rand!(rng::AbstractRNG, d::Multinomial, x::AbstractVector{<:Real}) =
multinom_rand!(rng, ntrials(d), probs(d), x)
sampler(d::Multinomial) = MultinomialSampler(ntrials(d), probs(d))
##CHUNK 2
# Evaluation
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(xi) + 1))
s += xlogy(xi, p_i)
end
return s
end
|
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(xi) + 1))
s += xlogy(xi, p_i)
end
return s
end | 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(xi) + 1))
s += xlogy(xi, p_i)
end
return s
end | [
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(xi) + 1))
s += xlogy(xi, p_i)
end
return s
end | 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(xi) + 1))
s += xlogy(xi, p_i)
end
return s
end | _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)
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)
# compute logpdf in batch and store
if d isa UnivariateMixture
##CHUNK 2
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)
# compute logpdf in batch and store
if d isa UnivariateMixture
lp_i .= Base.Fix1(logpdf, component(d, i)).(x)
else
logpdf!(lp_i, component(d, i), x)
end
# in the mean time, add log(prior) to lp and
# update the maximum for each sample
for j = 1:n
lp_i[j] += lpri
##CHUNK 3
function cdf(d::UnivariateMixture, x::Real)
p = probs(d)
r = sum(pi * cdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return r
end
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
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
#FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
#FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
Base.eltype(::Type{<:JointOrderStatistics{D}}) where {D} = Base.eltype(D)
Base.eltype(d::JointOrderStatistics) = eltype(d.dist)
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)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
#FILE: Distributions.jl/src/univariate/discrete/geometric.jl
##CHUNK 1
x = succprob(p)
y = succprob(q)
if x == y
return zero(float(x / y))
elseif isone(x)
return -log(y / x)
else
return log(x) - log(y) + (inv(x) - one(x)) * (log1p(-x) - log1p(-y))
end
end
### Evaluations
function logpdf(d::Geometric, x::Real)
insupport(d, x) ? log(d.p) + log1p(-d.p) * x : log(zero(d.p))
end
function cdf(d::Geometric, x::Int)
p = succprob(d)
#CURRENT 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, 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]
##CHUNK 2
p = probs(d)
n = ntrials(d)
s = zero(Complex{T})
for i in 1:length(p)
s += p[i] * exp(im * t[i])
end
return s^n
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
##CHUNK 3
p = probs(d)
n = ntrials(p)
s = zero(T)
for i in 1:length(p)
s += p[i] * exp(t[i])
end
return s^n
end
function cf(d::Multinomial{T}, t::AbstractVector) where T<:Real
p = probs(d)
n = ntrials(d)
s = zero(Complex{T})
for i in 1:length(p)
s += p[i] * exp(im * t[i])
end
return s^n
end
function entropy(d::Multinomial)
##CHUNK 4
for j = 1:k-1
for i = j+1:k
@inbounds C[i,j] = C[j,i]
end
end
C
end
function mgf(d::Multinomial{T}, t::AbstractVector) where T<:Real
p = probs(d)
n = ntrials(p)
s = zero(T)
for i in 1:length(p)
s += p[i] * exp(t[i])
end
return s^n
end
function cf(d::Multinomial{T}, t::AbstractVector) where T<:Real
|
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, Vol. 22:145-157.
#
maxiter = 200
half_p = 0.5 * p
ρ2 = abs2(ρ)
κ = ρ * (p - ρ2) / (1 - ρ2)
i = 0
while i < maxiter
i += 1
κ_prev = κ
a = (ρ / _vmfA(half_p, κ))
# println("i = $i, a = $a, abs(a - 1) = $(abs(a - 1))")
κ *= a
if abs(a - 1.0) < 1.0e-12
break
end
end
return κ
end | 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, Vol. 22:145-157.
#
maxiter = 200
half_p = 0.5 * p
ρ2 = abs2(ρ)
κ = ρ * (p - ρ2) / (1 - ρ2)
i = 0
while i < maxiter
i += 1
κ_prev = κ
a = (ρ / _vmfA(half_p, κ))
# println("i = $i, a = $a, abs(a - 1) = $(abs(a - 1))")
κ *= a
if abs(a - 1.0) < 1.0e-12
break
end
end
return κ
end | [
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, Vol. 22:145-157.
#
maxiter = 200
half_p = 0.5 * p
ρ2 = abs2(ρ)
κ = ρ * (p - ρ2) / (1 - ρ2)
i = 0
while i < maxiter
i += 1
κ_prev = κ
a = (ρ / _vmfA(half_p, κ))
# println("i = $i, a = $a, abs(a - 1) = $(abs(a - 1))")
κ *= a
if abs(a - 1.0) < 1.0e-12
break
end
end
return κ
end | 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, Vol. 22:145-157.
#
maxiter = 200
half_p = 0.5 * p
ρ2 = abs2(ρ)
κ = ρ * (p - ρ2) / (1 - ρ2)
i = 0
while i < maxiter
i += 1
κ_prev = κ
a = (ρ / _vmfA(half_p, κ))
# println("i = $i, a = $a, abs(a - 1) = $(abs(a - 1))")
κ *= a
if abs(a - 1.0) < 1.0e-12
break
end
end
return κ
end | _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(μ, κ, (1.0 + abs2(ρ)) / (2.0 * ρ))
end
end
# algorithm from
# DJ Best & NI Fisher (1979). Efficient Simulation of the von Mises
# Distribution. Journal of the Royal Statistical Society. Series C
# (Applied Statistics), 28(2), 152-157.
function rand(rng::AbstractRNG, s::VonMisesSampler)
f = 0.0
local x::Float64
#FILE: Distributions.jl/src/univariate/continuous/lindley.jl
##CHUNK 1
# upper bound on the error for this algorithm is (1/2)^(2^n), where n is the number of
# recursion steps. The default here is set such that this error is less than `eps()`.
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
### Sampling
# Ghitany, M. E., Atieh, B., & Nadarajah, S. (2008). Lindley distribution and its
##CHUNK 2
end
for i in 1:n
β = β / (1 + β) * (1 + log(x / β))
end
return β
end
### Sampling
# Ghitany, M. E., Atieh, B., & Nadarajah, S. (2008). Lindley distribution and its
# application. Mathematics and Computers in Simulation, 78(4), 493–506.
function rand(rng::AbstractRNG, d::Lindley)
θ = shape(d)
λ = inv(θ)
T = typeof(λ)
u = rand(rng)
p = θ / (1 + θ)
return oftype(u, rand(rng, u <= p ? Exponential{T}(λ) : Gamma{T}(2, λ)))
end
#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 μ + copysign(z, r)
end
#### Sampling
# The sampling procedure is implemented from from [1].
# [1] Gonzalez-Farias, G., Molina, J. A. D., & Rodríguez-Dagnino, R. M. (2009).
# Efficiency of the approximated shape parameter estimator in the generalized
# Gaussian distribution. IEEE Transactions on Vehicular Technology, 58(8),
# 4214-4223.
function rand(rng::AbstractRNG, d::PGeneralizedGaussian)
#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::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 - b) * z)
end
return w::Float64
end
#FILE: Distributions.jl/test/multivariate/jointorderstatistics.jl
##CHUNK 1
if dist isa Uniform
# Arnold (2008). A first course in order statistics. Eq 2.3.16
s = @. n - r + 1
xcor_exact = Symmetric(sqrt.((r .* collect(s)') ./ (collect(r)' .* s)))
elseif dist isa Exponential
# Arnold (2008). A first course in order statistics. Eq 4.6.8
v = [sum(k -> inv((n - k + 1)^2), 1:i) for i in r]
xcor_exact = Symmetric(sqrt.(v ./ v'))
end
for ii in 1:m, ji in (ii + 1):m
i = r[ii]
j = r[ji]
ρ = xcor[ii, ji]
ρ_exact = xcor_exact[ii, ji]
# use variance-stabilizing transformation, recommended in §3.6 of
# Van der Vaart, A. W. (2000). Asymptotic statistics (Vol. 3).
@test atanh(ρ) ≈ atanh(ρ_exact) atol = tol
end
end
end
#FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
g4 = g(d, 4)
return (g4 - 4g1 * g3 + 6g2 * g1^2 - 3 * g1^4) / (g2 - g1^2)^2 - 3
else
return T(Inf)
end
end
function entropy(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
return log(σ) + MathConstants.γ * ξ + (1 + MathConstants.γ)
end
function quantile(d::GeneralizedExtremeValue, p::Real)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * (-log(-log(p)))
else
return μ + σ * ((-log(p))^(-ξ) - 1) / ξ
end
##CHUNK 2
g(d::GeneralizedExtremeValue, k::Real) = gamma(1 - k * d.ξ) # This should not be exported.
function median(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps() # ξ == 0
return μ - σ * log(log(2))
else
return μ + σ * (log(2) ^ (- ξ) - 1) / ξ
end
end
function mean(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * MathConstants.γ
elseif ξ < 1
return μ + σ * (gamma(1 - ξ) - 1) / ξ
else
##CHUNK 3
function kurtosis(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return T(12)/5
elseif ξ < 1 / 4
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
g4 = g(d, 4)
return (g4 - 4g1 * g3 + 6g2 * g1^2 - 3 * g1^4) / (g2 - g1^2)^2 - 3
else
return T(Inf)
end
end
function entropy(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
return log(σ) + MathConstants.γ * ξ + (1 + MathConstants.γ)
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
end
@quantile_newton InverseGaussian
#### Sampling
# rand method from:
# John R. Michael, William R. Schucany and Roy W. Haas (1976)
# Generating Random Variates Using Transformations with Multiple Roots
# The American Statistician , Vol. 30, No. 2, pp. 88-90
function rand(rng::AbstractRNG, d::InverseGaussian)
μ, λ = params(d)
z = randn(rng)
v = z * z
w = μ * v
x1 = μ + μ / (2λ) * (w - sqrt(w * (4λ + w)))
p1 = μ / (μ + x1)
u = rand(rng)
u >= p1 ? μ^2 / x1 : x1
end
#CURRENT FILE: Distributions.jl/src/multivariate/vonmisesfisher.jl |
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
@inbounds pv[k+1] = (pk *= ((n - k + 1) / k) * a)
end
end
return pv
end | 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
@inbounds pv[k+1] = (pk *= ((n - k + 1) / k) * a)
end
end
return pv
end | [
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
@inbounds pv[k+1] = (pk *= ((n - k + 1) / k) * a)
end
end
return pv
end | 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
@inbounds pv[k+1] = (pk *= ((n - k + 1) / k) * a)
end
end
return pv
end | 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
for j in 1:(i-1)
A[j, end] *= pi
end
for j in (i+1):n
A[j, end] *= pi
end
end
@inbounds for j in 1:n, i in 1:n
A[i, j] -= A[i, j+1]
end
return A
end
##CHUNK 2
# Journal of Statistical Computation and Simulation, 14:2, 125-131, DOI: 10.1080/00949658208810534
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 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
for j in 1:(i-1)
A[j, end] *= pi
#FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
@inbounds p_i = p[i]
v[i] = n * p_i * (1 - p_i)
end
v
end
function cov(d::Multinomial{T}) where T<:Real
p = probs(d)
k = length(p)
n = ntrials(d)
C = Matrix{T}(undef, k, k)
for j = 1:k
pj = p[j]
for i = 1:j-1
@inbounds C[i,j] = - n * p[i] * pj
end
@inbounds C[j,j] = n * pj * (1-pj)
end
#FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
vs = Vector{T}(undef,N)
ps = zeros(Float64, N)
x = sort(vec(x))
vs[1] = x[1]
ps[1] += 1.
xprev = x[1]
@inbounds for i = 2:N
xi = x[i]
if xi != xprev
n += 1
vs[n] = xi
end
ps[n] += 1.
xprev = xi
end
resize!(vs, n)
resize!(ps, n)
#FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
if lp_i[j] > m[j]
m[j] = lp_i[j]
end
end
end
end
fill!(r, 0.0)
@inbounds for i = 1:K
if p[i] > 0.0
lp_i = view(Lp, :, i)
for j = 1:n
r[j] += exp(lp_i[j] - m[j])
end
end
end
@inbounds for j = 1:n
r[j] = log(r[j]) + m[j]
end
##CHUNK 2
end
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
#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)
end
qsum, i = zero(T), 0
while qsum < q
i += 1
qsum += pdf(d, range[i])
end
range[i]
end
end
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
elseif islowerbounded(d)
@test map(Base.Fix1(pdf, d), rmin-2:rmax) ≈ vcat(0.0, 0.0, p0)
end
end
function test_evaluation(d::DiscreteUnivariateDistribution, vs::AbstractVector, testquan::Bool=true)
nv = length(vs)
p = Vector{Float64}(undef, nv)
c = Vector{Float64}(undef, nv)
cc = Vector{Float64}(undef, nv)
lp = Vector{Float64}(undef, nv)
lc = Vector{Float64}(undef, nv)
lcc = Vector{Float64}(undef, nv)
ci = 0.
for (i, v) in enumerate(vs)
p[i] = pdf(d, v)
c[i] = cdf(d, v)
cc[i] = ccdf(d, v)
##CHUNK 2
cc = Vector{Float64}(undef, nv)
lp = Vector{Float64}(undef, nv)
lc = Vector{Float64}(undef, nv)
lcc = Vector{Float64}(undef, nv)
ci = 0.
for (i, v) in enumerate(vs)
p[i] = pdf(d, v)
c[i] = cdf(d, v)
cc[i] = ccdf(d, v)
lp[i] = logpdf(d, v)
lc[i] = logcdf(d, v)
lcc[i] = logccdf(d, v)
@assert p[i] >= 0.0
@assert (i == 1 || c[i] >= c[i-1])
ci += p[i]
@test ci ≈ c[i]
@test isapprox(c[i] + cc[i], 1.0 , atol=1.0e-12)
#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_outside!(r, d, X)
# fill central part: with non-zero pdf
if vl <= vr
fm1 = vfirst - 1
r[vl - fm1] = pv = pdf(d, vl)
for v = (vl+1):vr
r[v - fm1] = pv = nextpdf(rpe, pv, v)
end
end
#CURRENT FILE: Distributions.jl/src/samplers/binomial.jl |
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 = 1
while cp <= draw && i < n
@inbounds cp += p[i +=1]
end
return x[i]
end
sampler(d::DiscreteNonParametric) =
DiscreteNonParametricSampler(support(d), probs(d))
##CHUNK 2
Get the vector of probabilities associated with the support of `d`.
"""
probs(d::DiscreteNonParametric) = d.p
function Base.isapprox(c1::DiscreteNonParametric, c2::DiscreteNonParametric; kwargs...)
support_c1 = support(c1)
support_c2 = support(c2)
return length(support_c1) == length(support_c2) &&
isapprox(support_c1, support_c2; kwargs...) &&
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)))
##CHUNK 3
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
#FILE: Distributions.jl/src/univariate/discrete/categorical.jl
##CHUNK 1
end
return r
end
# sampling
sampler(d::Categorical{P,Ps}) where {P<:Real,Ps<:AbstractVector{P}} =
AliasTable(probs(d))
### sufficient statistics
struct CategoricalStats <: SufficientStats
h::Vector{Float64}
end
function add_categorical_counts!(h::Vector{Float64}, x::AbstractArray{T}) where T<:Integer
for i = 1 : length(x)
@inbounds xi = x[i]
#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 += xlogy(xi, p_i)
end
return s
end
# Sampling
# if only a single sample is requested, no alias table is created
_rand!(rng::AbstractRNG, d::Multinomial, x::AbstractVector{<:Real}) =
multinom_rand!(rng, ntrials(d), probs(d), x)
##CHUNK 2
p = probs(d)
n = ntrials(d)
s = zero(Complex{T})
for i in 1:length(p)
s += p[i] * exp(im * t[i])
end
return s^n
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
#FILE: Distributions.jl/src/samplers/multinomial.jl
##CHUNK 1
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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
#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, x)
K = ncomponents(d)
p = probs(d)
@assert length(p) == K
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
#CURRENT FILE: Distributions.jl/src/samplers/categorical.jl
##CHUNK 1
#### naive sampling
struct CategoricalDirectSampler{T<:Real,Ts<:AbstractVector{T}} <: Sampleable{Univariate,Discrete}
prob::Ts
function CategoricalDirectSampler{T,Ts}(p::Ts) where {
T<:Real,Ts<:AbstractVector{T}}
isempty(p) && throw(ArgumentError("p is empty."))
new{T,Ts}(p)
end
##CHUNK 2
#### naive sampling
struct CategoricalDirectSampler{T<:Real,Ts<:AbstractVector{T}} <: Sampleable{Univariate,Discrete}
prob::Ts
function CategoricalDirectSampler{T,Ts}(p::Ts) where {
T<:Real,Ts<:AbstractVector{T}}
isempty(p) && throw(ArgumentError("p is empty."))
new{T,Ts}(p)
end
end
CategoricalDirectSampler(p::Ts) where {T<:Real,Ts<:AbstractVector{T}} =
CategoricalDirectSampler{T,Ts}(p)
ncategories(s::CategoricalDirectSampler) = length(s.prob)
|
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 && return x*x*s.scale
end
# Step 8
t = 0.0
while true
e = 0.0
u = 0.0
while true
e = randexp(rng)
u = 2.0rand(rng) - 1.0
t = s.b + e*s.σ*sign(u)
# Step 9
t ≥ -0.718_744_837_717_19 && break
end
# Step 10
q = calc_q(s, t)
# Step 11
(q > 0.0) && (s.c*abs(u) ≤ expm1(q)*exp(e-0.5t*t)) && break
end
# Step 12
x = s.s+0.5t
return x*x*s.scale
end | 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 && return x*x*s.scale
end
# Step 8
t = 0.0
while true
e = 0.0
u = 0.0
while true
e = randexp(rng)
u = 2.0rand(rng) - 1.0
t = s.b + e*s.σ*sign(u)
# Step 9
t ≥ -0.718_744_837_717_19 && break
end
# Step 10
q = calc_q(s, t)
# Step 11
(q > 0.0) && (s.c*abs(u) ≤ expm1(q)*exp(e-0.5t*t)) && break
end
# Step 12
x = s.s+0.5t
return x*x*s.scale
end | [
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 && return x*x*s.scale
end
# Step 8
t = 0.0
while true
e = 0.0
u = 0.0
while true
e = randexp(rng)
u = 2.0rand(rng) - 1.0
t = s.b + e*s.σ*sign(u)
# Step 9
t ≥ -0.718_744_837_717_19 && break
end
# Step 10
q = calc_q(s, t)
# Step 11
(q > 0.0) && (s.c*abs(u) ≤ expm1(q)*exp(e-0.5t*t)) && break
end
# Step 12
x = s.s+0.5t
return x*x*s.scale
end | 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 && return x*x*s.scale
end
# Step 8
t = 0.0
while true
e = 0.0
u = 0.0
while true
e = randexp(rng)
u = 2.0rand(rng) - 1.0
t = s.b + e*s.σ*sign(u)
# Step 9
t ≥ -0.718_744_837_717_19 && break
end
# Step 10
q = calc_q(s, t)
# Step 11
(q > 0.0) && (s.c*abs(u) ≤ expm1(q)*exp(e-0.5t*t)) && break
end
# Step 12
x = s.s+0.5t
return x*x*s.scale
end | 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) + 1 >= c
break
end
end
acf = acos(f)
x = s.μ + (rand(rng, Bool) ? acf : -acf)
end
return x
end
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end
#FILE: Distributions.jl/src/univariate/continuous/biweight.jl
##CHUNK 1
function cdf(d::Biweight{T}, x::Real) where T<:Real
u = (x - d.μ) / d.σ
u ≤ -1 ? zero(T) :
u ≥ 1 ? one(T) :
(u + 1)^3/16 * @horner(u,8,-9,3)
end
function ccdf(d::Biweight{T}, x::Real) where T<:Real
u = (d.μ - x) / d.σ
u ≤ -1 ? zero(T) :
u ≥ 1 ? one(T) :
(u + 1)^3/16 * @horner(u, 8, -9, 3)
end
@quantile_newton Biweight
function mgf(d::Biweight{T}, t::Real) where T<:Real
a = d.σ*t
a2 = a^2
a == 0 ? one(T) :
#FILE: Distributions.jl/src/samplers/poisson.jl
##CHUNK 1
while true
# Step E
E = randexp(rng, μType)
U = 2 * rand(rng, μType) - one(μType)
T = 1.8 + copysign(E, U)
if T <= -0.6744
continue
end
K = floor(Int, μ + s * T)
px, py, fx, fy = procf(μ, K, s)
c = 0.1069 / μ
# Step H
if c*abs(U) <= py*exp(px + E) - fy*exp(fx + E)
return K
end
end
end
#FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
g4 = g(d, 4)
return (g4 - 4g1 * g3 + 6g2 * g1^2 - 3 * g1^4) / (g2 - g1^2)^2 - 3
else
return T(Inf)
end
end
function entropy(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
return log(σ) + MathConstants.γ * ξ + (1 + MathConstants.γ)
end
function quantile(d::GeneralizedExtremeValue, p::Real)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * (-log(-log(p)))
else
return μ + σ * ((-log(p))^(-ξ) - 1) / ξ
end
##CHUNK 2
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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
#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)
a = (-ub + sqrt(ub^2 + 4.0)) / 2.0
while true
r = rand(rng, Exponential(1.0 / a)) - ub
u = rand(rng)
if u < exp(-0.5 * (r - a)^2) && r < -lb
return -r
end
end
else
while true
r = lb + rand(rng) * (ub - lb)
u = rand(rng)
if lb > 0
rho = exp((lb^2 - r^2) * 0.5)
#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::Real)
(a, b) = params(d)
u = (b - a) * t / 2
u == zero(u) && return one(u)
v = (a + b) * t / 2
exp(v) * (sinh(u) / u)
end
function cgf_uniform_around_zero_kernel(x)
# taylor series of (exp(x) - x - 1) / x
T = typeof(x)
#FILE: Distributions.jl/src/univariate/continuous/epanechnikov.jl
##CHUNK 1
u = (d.μ - x) / d.σ
u <= -1 ? zero(T) :
u >= 1 ? one(T) :
1//2 + u * (3//4 - u^2/4)
end
@quantile_newton Epanechnikov
function mgf(d::Epanechnikov{T}, t::Real) where T<:Real
a = d.σ * t
a == 0 ? one(T) :
3exp(d.μ * t) * (cosh(a) - sinh(a) / a) / a^2
end
function cf(d::Epanechnikov{T}, t::Real) where T<:Real
a = d.σ * t
a == 0 ? one(T)+zero(T)*im :
-3exp(im * d.μ * t) * (cos(a) - sin(a) / a) / a^2
end
#CURRENT FILE: Distributions.jl/src/samplers/gamma.jl
##CHUNK 1
else
b = 1.77
σ = 0.75
c = 0.1515/s
end
GammaGDSampler(T(a), T(s2), T(s), T(i2s), T(d), T(q0), T(b), T(σ), T(c), scale(g))
end
function calc_q(s::GammaGDSampler, t)
v = t*s.i2s
if abs(v) > 0.25
return s.q0 - s.s*t + 0.25*t*t + 2.0*s.s2*log1p(v)
else
return s.q0 + 0.5*t*t*(v*@horner(v,
0.333333333,
-0.249999949,
0.199999867,
-0.1666774828,
0.142873973,
|
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
θ =
return rand(rng, Exponential{partype(d)}(scale(d)))
else
return rand(rng, GammaMTSampler(d))
end
end
function sampler(d::Gamma)
if shape(d) < 1.0
# TODO: shape(d) = 0.5 : use scaled chisq
return GammaIPSampler(d)
elseif shape(d) == 1.0
return sampler(Exponential{partype(d)}(scale(d)))
##CHUNK 2
return rand(rng, GammaMTSampler(d))
end
end
function sampler(d::Gamma)
if shape(d) < 1.0
# TODO: shape(d) = 0.5 : use scaled chisq
return GammaIPSampler(d)
elseif shape(d) == 1.0
return sampler(Exponential{partype(d)}(scale(d)))
else
return GammaMTSampler(d)
end
end
#### Fit model
struct GammaStats <: SufficientStats
sx::Float64 # (weighted) sum of x
slogx::Float64 # (weighted) sum of log(x)
##CHUNK 3
```julia
Gamma() # Gamma distribution with unit shape and unit scale, i.e. Gamma(1, 1)
Gamma(α) # Gamma distribution with shape α and unit scale, i.e. Gamma(α, 1)
Gamma(α, θ) # Gamma distribution with shape α and scale θ
params(d) # Get the parameters, i.e. (α, θ)
shape(d) # Get the shape parameter, i.e. α
scale(d) # Get the scale parameter, i.e. θ
```
External links
* [Gamma distribution on Wikipedia](http://en.wikipedia.org/wiki/Gamma_distribution)
"""
struct Gamma{T<:Real} <: ContinuousUnivariateDistribution
α::T
θ::T
Gamma{T}(α, θ) where {T} = new{T}(α, θ)
##CHUNK 4
mean(d::Gamma) = d.α * d.θ
var(d::Gamma) = d.α * d.θ^2
skewness(d::Gamma) = 2 / sqrt(d.α)
kurtosis(d::Gamma) = 6 / d.α
function mode(d::Gamma)
(α, θ) = params(d)
α >= 1 ? θ * (α - 1) : error("Gamma has no mode when shape < 1")
end
function entropy(d::Gamma)
(α, θ) = params(d)
α + loggamma(α) + (1 - α) * digamma(α) + log(θ)
end
mgf(d::Gamma, t::Real) = (1 - t * d.θ)^(-d.α)
function cgf(d::Gamma, t)
##CHUNK 5
"""
Gamma(α,θ)
The *Gamma distribution* with shape parameter `α` and scale `θ` has probability density
function
```math
f(x; \\alpha, \\theta) = \\frac{x^{\\alpha-1} e^{-x/\\theta}}{\\Gamma(\\alpha) \\theta^\\alpha},
\\quad x > 0
```
```julia
Gamma() # Gamma distribution with unit shape and unit scale, i.e. Gamma(1, 1)
Gamma(α) # Gamma distribution with shape α and unit scale, i.e. Gamma(α, 1)
Gamma(α, θ) # Gamma distribution with shape α and scale θ
params(d) # Get the parameters, i.e. (α, θ)
shape(d) # Get the shape parameter, i.e. α
scale(d) # Get the scale parameter, i.e. θ
```
#CURRENT FILE: Distributions.jl/src/samplers/gamma.jl
##CHUNK 1
s2::T
s::T
i2s::T
d::T
q0::T
b::T
σ::T
c::T
scale::T
end
function GammaGDSampler(g::Gamma{T}) where {T}
a = shape(g)
# Step 1
s2 = a - 0.5
s = sqrt(s2)
i2s = 0.5/s
d = 5.656854249492381 - 12.0s # 4*sqrt(2) - 12s
# Step 4
##CHUNK 2
# step 3
x = -log(s.ia*(s.b-p))
e < log(x)*(1.0-s.a) || return s.scale*x
end
end
end
# "A simple method for generating gamma variables"
# G. Marsaglia and W.W. Tsang
# ACM Transactions on Mathematical Software (TOMS), 2000, Volume 26(3), pp. 363-372
# doi:10.1145/358407.358414
# http://www.cparity.com/projects/AcmClassification/samples/358414.pdf
# valid for shape >= 1
struct GammaMTSampler{T<:Real} <: Sampleable{Univariate,Continuous}
d::T
c::T
κ::T
r::T
##CHUNK 3
# Inverse Power sampler
# uses the x*u^(1/a) trick from Marsaglia and Tsang (2000) for when shape < 1
struct GammaIPSampler{S<:Sampleable{Univariate,Continuous},T<:Real} <: Sampleable{Univariate,Continuous}
s::S #sampler for Gamma(1+shape,scale)
nia::T #-1/scale
end
GammaIPSampler(d::Gamma) = GammaIPSampler(d, GammaMTSampler)
function GammaIPSampler(d::Gamma, ::Type{S}) where {S<:Sampleable}
shape_d = shape(d)
sampler = S(Gamma{partype(d)}(1 + shape_d, scale(d)))
return GammaIPSampler(sampler, -inv(shape_d))
end
function rand(rng::AbstractRNG, s::GammaIPSampler)
x = rand(rng, s.s)
e = randexp(rng, typeof(x))
x*exp(s.nia*e)
end
##CHUNK 4
end
function rand(rng::AbstractRNG, s::GammaMTSampler{T}) where {T<:Real}
d = s.d
c = s.c
κ = s.κ
r = s.r
z = zero(T)
while true
# Generate v (Step 2)
x = randn(rng, T)
cbrt_v = 1 + c * x
while cbrt_v <= z # requires x <= -sqrt(9 * shape - 3)
x = randn(rng, T)
cbrt_v = 1 + c * x
end
v = cbrt_v^3
# Generate uniform u (Step 3)
##CHUNK 5
0.0001710320)
if a <= 3.686
b = 0.463 + s + 0.178s2
σ = 1.235
c = 0.195/s - 0.079 + 0.16s
elseif a <= 13.022
b = 1.654 + 0.0076s2
σ = 1.68/s + 0.275
c = 0.062/s + 0.024
else
b = 1.77
σ = 0.75
c = 0.1515/s
end
GammaGDSampler(T(a), T(s2), T(s), T(i2s), T(d), T(q0), T(b), T(σ), T(c), scale(g))
end
function calc_q(s::GammaGDSampler, t)
|
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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
# from Binomial. Just assign remaining counts
# to xi.
@inbounds x[i] = n
n = 0
# rp = 0.0 (no need for this, as rp is no longer needed)
end
end
if i == km1
@inbounds x[k] = n
else # n must have been zero
z = zero(eltype(x))
for j = i+1 : k
@inbounds x[j] = z
end
end
return x
end | 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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
# from Binomial. Just assign remaining counts
# to xi.
@inbounds x[i] = n
n = 0
# rp = 0.0 (no need for this, as rp is no longer needed)
end
end
if i == km1
@inbounds x[k] = n
else # n must have been zero
z = zero(eltype(x))
for j = i+1 : k
@inbounds x[j] = z
end
end
return x
end | [
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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
# from Binomial. Just assign remaining counts
# to xi.
@inbounds x[i] = n
n = 0
# rp = 0.0 (no need for this, as rp is no longer needed)
end
end
if i == km1
@inbounds x[k] = n
else # n must have been zero
z = zero(eltype(x))
for j = i+1 : k
@inbounds x[j] = z
end
end
return x
end | 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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
# from Binomial. Just assign remaining counts
# to xi.
@inbounds x[i] = n
n = 0
# rp = 0.0 (no need for this, as rp is no longer needed)
end
end
if i == km1
@inbounds x[k] = n
else # n must have been zero
z = zero(eltype(x))
for j = i+1 : k
@inbounds x[j] = z
end
end
return x
end | 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, length(x), n)
end
function suffstats(::Type{<:Binomial}, n::Integer, x::AbstractArray{<:Integer}, w::AbstractArray{<:Real})
z = zero(eltype(x)) * zero(eltype(w))
ns = ne = z + z # possibly widened and different from `z`, e.g., if `z = true`
for (xi, wi) in zip(x, w)
0 <= xi <= n || throw(DomainError(xi, "samples must be between 0 and $n"))
ns += xi * wi
ne += wi
end
BinomialStats(ns, ne, n)
end
##CHUNK 2
struct BinomialStats{N<:Real} <: SufficientStats
ns::N # the total number of successes
ne::N # the number of experiments
n::Int # the number of trials in each experiment
end
BinomialStats(ns::Real, ne::Real, n::Integer) = BinomialStats(promote(ns, ne)..., Int(n))
function suffstats(::Type{<:Binomial}, n::Integer, x::AbstractArray{<:Integer})
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, length(x), n)
end
function suffstats(::Type{<:Binomial}, n::Integer, x::AbstractArray{<:Integer}, w::AbstractArray{<:Real})
#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
else
q = 1.0 - p
a = p / q
@inbounds pv[1] = pk = q ^ n
for k = 1:n
@inbounds pv[k+1] = (pk *= ((n - k + 1) / k) * a)
end
end
return pv
end
#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
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end
##CHUNK 2
# given ∏ₖf(xₖ), marginalize all xₖ for i < k < j
function _marginalize_range(dist, i, j, xᵢ, xⱼ, T)
k = j - i - 1
k == 0 && return zero(T)
return k * T(logdiffcdf(dist, xⱼ, xᵢ)) - loggamma(T(k + 1))
end
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.dist, x)
sort!(x)
else
# use exponential generation method with inversion, where for gaps in the ranks, we
# use the fact that the sum Y of k IID variables xₘ ~ Exp(1) is Y ~ Gamma(k, 1).
# Lurie, D., and H. O. Hartley. "Machine-generation of order statistics for Monte
# Carlo computations." The American Statistician 26.1 (1972): 26-27.
# this is slow if length(d.ranks) is close to n and quantile for d.dist is expensive,
#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)
nj = zero(T)
for i = 1:K
@inbounds xi = x[i,j]
@inbounds scnts[i] += xi
nj += xi
end
if j == 1
n = nj
elseif nj != n
error("Each sample in X should sum to the same value.")
#FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
#FILE: Distributions.jl/src/matrix/wishart.jl
##CHUNK 1
df = oftype(logdet_S, d.df)
for i in 0:(p - 1)
v += digamma((df - i) / 2)
end
return d.singular ? oftype(v, -Inf) : v
end
function entropy(d::Wishart)
d.singular && throw(ArgumentError("entropy not defined for singular Wishart."))
p = size(d, 1)
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
#FILE: Distributions.jl/test/multivariate/vonmisesfisher.jl
##CHUNK 1
# Tests for Von-Mises Fisher distribution
using Distributions, Random
using LinearAlgebra, Test
using SpecialFunctions
logvmfCp(p::Int, κ::Real) = (p / 2 - 1) * log(κ) - log(besselix(p / 2 - 1, κ)) - κ - p / 2 * log(2π)
safe_logvmfpdf(μ::Vector, κ::Real, x::Vector) = logvmfCp(length(μ), κ) + κ * dot(μ, x)
function gen_vmf_tdata(n::Int, p::Int,
rng::Union{AbstractRNG, Missing} = missing)
if ismissing(rng)
X = randn(p, n)
else
X = randn(rng, p, n)
end
for i = 1:n
X[:,i] = X[:,i] ./ norm(X[:,i])
#FILE: Distributions.jl/test/univariate/discrete/binomial.jl
##CHUNK 1
using Distributions
using Test, Random
Random.seed!(1234)
@testset "binomial" begin
# Test the consistency between the recursive and nonrecursive computation of the pdf
# of the Binomial distribution
for (p, n) in [(0.6, 10), (0.8, 6), (0.5, 40), (0.04, 20), (1., 100), (0., 10), (0.999999, 1000), (1e-7, 1000)]
d = Binomial(n, p)
a = Base.Fix1(pdf, d).(0:n)
for t=0:n
@test pdf(d, t) ≈ a[1+t]
end
li = rand(0:n, 2)
rng = minimum(li):maximum(li)
b = Base.Fix1(pdf, d).(rng)
for t in rng
#CURRENT FILE: Distributions.jl/src/samplers/multinomial.jl |
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(rng, a)] += 1
end
end
return x
end | 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(rng, a)] += 1
end
end
return x
end | [
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(rng, a)] += 1
end
end
return x
end | 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(rng, a)] += 1
end
end
return x
end | _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 += xlogy(xi, p_i)
end
return s
end
# Sampling
# if only a single sample is requested, no alias table is created
_rand!(rng::AbstractRNG, d::Multinomial, x::AbstractVector{<:Real}) =
multinom_rand!(rng, ntrials(d), probs(d), x)
##CHUNK 2
end
return s
end
# Sampling
# if only a single sample is requested, no alias table is created
_rand!(rng::AbstractRNG, d::Multinomial, x::AbstractVector{<:Real}) =
multinom_rand!(rng, ntrials(d), probs(d), x)
sampler(d::Multinomial) = MultinomialSampler(ntrials(d), probs(d))
## Fit model
struct MultinomialStats <: SufficientStats
n::Int # number of trials in each experiment
scnts::Vector{Float64} # sum of counts
tw::Float64 # total sample weight
#FILE: Distributions.jl/src/genericrand.jl
##CHUNK 1
function _rand!(
rng::AbstractRNG,
s::Sampleable{<:ArrayLikeVariate},
x::AbstractArray{<:Real},
)
@inbounds for xi in eachvariate(x, variate_form(typeof(s)))
rand!(rng, s, xi)
end
return x
end
Base.@propagate_inbounds function rand!(
rng::AbstractRNG,
s::Sampleable{ArrayLikeVariate{N}},
x::AbstractArray{<:AbstractArray{<:Real,N}},
) where {N}
sz = size(s)
allocate = !all(isassigned(x, i) && size(@inbounds x[i]) == sz for i in eachindex(x))
return rand!(rng, s, x, allocate)
end
##CHUNK 2
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{<:Real,N}},
allocate::Bool,
) where {N}
if allocate
@inbounds for i in eachindex(x)
x[i] = rand(rng, s)
end
else
@inbounds for xi in x
rand!(rng, s, xi)
end
end
#FILE: Distributions.jl/src/samplers/binomial.jl
##CHUNK 1
# 6
(s.comp ? s.n - y : y)::Int
end
# Constructing an alias table by directly computing the probability vector
#
struct BinomialAliasSampler <: Sampleable{Univariate,Discrete}
table::AliasTable
end
BinomialAliasSampler(n::Int, p::Float64) = BinomialAliasSampler(AliasTable(binompvec(n, p)))
rand(rng::AbstractRNG, s::BinomialAliasSampler) = rand(rng, s.table) - 1
# Integrated Polyalgorithm sampler that automatically chooses the proper one
#
# It is important for type-stability
#
#FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
end
Base.length(s::MixtureSampler) = length(first(s.csamplers))
rand(rng::AbstractRNG, s::MixtureSampler{Univariate}) =
rand(rng, s.csamplers[rand(rng, s.psampler)])
rand(rng::AbstractRNG, d::MixtureModel{Univariate}) =
rand(rng, component(d, rand(rng, d.prior)))
# multivariate mixture sampler for a vector
_rand!(rng::AbstractRNG, s::MixtureSampler{Multivariate}, x::AbstractVector{<:Real}) =
@inbounds rand!(rng, s.csamplers[rand(rng, s.psampler)], x)
# if only a single sample is requested, no alias table is created
_rand!(rng::AbstractRNG, d::MixtureModel{Multivariate}, x::AbstractVector{<:Real}) =
@inbounds rand!(rng, component(d, rand(rng, d.prior)), x)
sampler(d::MixtureModel) = MixtureSampler(d)
#FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
function rand!(rng::AbstractRNG, s::Sampleable{Univariate}, A::AbstractArray{<:Real})
return _rand!(rng, sampler(s), A)
end
function _rand!(rng::AbstractRNG, sampler::Sampleable{Univariate}, A::AbstractArray{<:Real})
for i in eachindex(A)
@inbounds A[i] = rand(rng, sampler)
end
return A
end
"""
rand(rng::AbstractRNG, d::UnivariateDistribution)
Generate a scalar sample from `d`. The general fallback is `quantile(d, rand())`.
"""
rand(rng::AbstractRNG, d::UnivariateDistribution) = quantile(d, rand(rng))
## statistics
#CURRENT FILE: Distributions.jl/src/samplers/multinomial.jl
##CHUNK 1
@inbounds x[k] = n
else # n must have been zero
z = zero(eltype(x))
for j = i+1 : k
@inbounds x[j] = z
end
end
return x
end
struct MultinomialSampler{T<:Real} <: Sampleable{Multivariate,Discrete}
n::Int
prob::Vector{T}
alias::AliasTable
end
function MultinomialSampler(n::Int, prob::Vector{<:Real})
return MultinomialSampler(n, prob, AliasTable(prob))
end
##CHUNK 2
struct MultinomialSampler{T<:Real} <: Sampleable{Multivariate,Discrete}
n::Int
prob::Vector{T}
alias::AliasTable
end
function MultinomialSampler(n::Int, prob::Vector{<:Real})
return MultinomialSampler(n, prob, AliasTable(prob))
end
length(s::MultinomialSampler) = length(s.prob)
##CHUNK 3
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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
|
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 digit sums as table bounds
table = Vector{Vector{Int64}}(undef, 9)
bounds = zeros(Int64, 9)
# Special case for deterministic distributions
for i in 1:n
if vals[i] == 64^9
table[1] = Vector{Int64}(undef, 64)
for j in 1:64
table[1][j] = i
end
bounds[1] = 64^9
for j in 2:9
table[j] = Vector{Int64}()
bounds[j] = 64^9
end
return DiscreteDistributionTable(table, bounds)
end
end
# Fill tables
multiplier = 1
for index in 9:-1:1
counts = Vector{Int64}()
for i in 1:n
digit = mod(vals[i], 64)
# vals[i] = fld(vals[i], 64)
vals[i] >>= 6
bounds[index] += digit
for itr in 1:digit
push!(counts, i)
end
end
bounds[index] *= multiplier
table[index] = counts
# multiplier *= 64
multiplier <<= 6
end
# Make bounds cumulative
bounds = cumsum(bounds)
return DiscreteDistributionTable(table, bounds)
end | 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 digit sums as table bounds
table = Vector{Vector{Int64}}(undef, 9)
bounds = zeros(Int64, 9)
# Special case for deterministic distributions
for i in 1:n
if vals[i] == 64^9
table[1] = Vector{Int64}(undef, 64)
for j in 1:64
table[1][j] = i
end
bounds[1] = 64^9
for j in 2:9
table[j] = Vector{Int64}()
bounds[j] = 64^9
end
return DiscreteDistributionTable(table, bounds)
end
end
# Fill tables
multiplier = 1
for index in 9:-1:1
counts = Vector{Int64}()
for i in 1:n
digit = mod(vals[i], 64)
# vals[i] = fld(vals[i], 64)
vals[i] >>= 6
bounds[index] += digit
for itr in 1:digit
push!(counts, i)
end
end
bounds[index] *= multiplier
table[index] = counts
# multiplier *= 64
multiplier <<= 6
end
# Make bounds cumulative
bounds = cumsum(bounds)
return DiscreteDistributionTable(table, bounds)
end | [
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 digit sums as table bounds
table = Vector{Vector{Int64}}(undef, 9)
bounds = zeros(Int64, 9)
# Special case for deterministic distributions
for i in 1:n
if vals[i] == 64^9
table[1] = Vector{Int64}(undef, 64)
for j in 1:64
table[1][j] = i
end
bounds[1] = 64^9
for j in 2:9
table[j] = Vector{Int64}()
bounds[j] = 64^9
end
return DiscreteDistributionTable(table, bounds)
end
end
# Fill tables
multiplier = 1
for index in 9:-1:1
counts = Vector{Int64}()
for i in 1:n
digit = mod(vals[i], 64)
# vals[i] = fld(vals[i], 64)
vals[i] >>= 6
bounds[index] += digit
for itr in 1:digit
push!(counts, i)
end
end
bounds[index] *= multiplier
table[index] = counts
# multiplier *= 64
multiplier <<= 6
end
# Make bounds cumulative
bounds = cumsum(bounds)
return DiscreteDistributionTable(table, bounds)
end | 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 digit sums as table bounds
table = Vector{Vector{Int64}}(undef, 9)
bounds = zeros(Int64, 9)
# Special case for deterministic distributions
for i in 1:n
if vals[i] == 64^9
table[1] = Vector{Int64}(undef, 64)
for j in 1:64
table[1][j] = i
end
bounds[1] = 64^9
for j in 2:9
table[j] = Vector{Int64}()
bounds[j] = 64^9
end
return DiscreteDistributionTable(table, bounds)
end
end
# Fill tables
multiplier = 1
for index in 9:-1:1
counts = Vector{Int64}()
for i in 1:n
digit = mod(vals[i], 64)
# vals[i] = fld(vals[i], 64)
vals[i] >>= 6
bounds[index] += digit
for itr in 1:digit
push!(counts, i)
end
end
bounds[index] *= multiplier
table[index] = counts
# multiplier *= 64
multiplier <<= 6
end
# Make bounds cumulative
bounds = cumsum(bounds)
return DiscreteDistributionTable(table, bounds)
end | 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)
nj = zero(T)
for i = 1:K
@inbounds xi = x[i,j]
@inbounds scnts[i] += xi
nj += xi
end
if j == 1
n = nj
elseif nj != n
error("Each sample in X should sum to the same value.")
#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, length(x), n)
end
function suffstats(::Type{<:Binomial}, n::Integer, x::AbstractArray{<:Integer}, w::AbstractArray{<:Real})
z = zero(eltype(x)) * zero(eltype(w))
ns = ne = z + z # possibly widened and different from `z`, e.g., if `z = true`
for (xi, wi) in zip(x, w)
0 <= xi <= n || throw(DomainError(xi, "samples must be between 0 and $n"))
ns += xi * wi
ne += wi
end
BinomialStats(ns, ne, n)
end
#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
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end
#FILE: Distributions.jl/src/matrix/wishart.jl
##CHUNK 1
df = oftype(logdet_S, d.df)
for i in 0:(p - 1)
v += digamma((df - i) / 2)
end
return d.singular ? oftype(v, -Inf) : v
end
function entropy(d::Wishart)
d.singular && throw(ArgumentError("entropy not defined for singular Wishart."))
p = size(d, 1)
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
#FILE: Distributions.jl/test/fit.jl
##CHUNK 1
w = func[1](n0)
x = func[2](DiscreteUniform(10, 15), n0)
d = fit(DiscreteUniform, x)
@test isa(d, DiscreteUniform)
@test minimum(d) == minimum(x)
@test maximum(d) == maximum(x)
d = fit(DiscreteUniform, func[2](DiscreteUniform(10, 15), N))
@test minimum(d) == 10
@test maximum(d) == 15
end
end
@testset "Testing fit for Bernoulli" begin
for rng in ((), (rng,)), D in (Bernoulli, Bernoulli{Float64}, Bernoulli{Float32})
v = rand(rng..., n0)
z = rand(rng..., Bernoulli(0.7), n0)
for x in (z, OffsetArray(z, -n0 ÷ 2)), w in (v, OffsetArray(v, -n0 ÷ 2))
#FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
#FILE: Distributions.jl/test/univariate/discrete/categorical.jl
##CHUNK 1
p = ones(10^6) * 1.0e-6
@test Distributions.isprobvec(p)
@test convert(Categorical{Float64,Vector{Float64}}, d) === d
for x in (d, probs(d))
d32 = convert(Categorical{Float32,Vector{Float32}}, d)
@test d32 isa Categorical{Float32,Vector{Float32}}
@test probs(d32) == map(Float32, probs(d))
end
@testset "test args... constructor" begin
@test Categorical(0.3, 0.7) == Categorical([0.3, 0.7])
end
@testset "reproducibility across julia versions" begin
d = Categorical([0.1, 0.2, 0.7])
rng = StableRNGs.StableRNG(600)
@test rand(rng, d, 10) == [3, 1, 1, 2, 3, 2, 3, 3, 2, 3]
end
##CHUNK 2
@testset "test args... constructor" begin
@test Categorical(0.3, 0.7) == Categorical([0.3, 0.7])
end
@testset "reproducibility across julia versions" begin
d = Categorical([0.1, 0.2, 0.7])
rng = StableRNGs.StableRNG(600)
@test rand(rng, d, 10) == [3, 1, 1, 2, 3, 2, 3, 3, 2, 3]
end
@testset "comparisons" begin
d1 = Categorical([0.4, 0.6])
d2 = Categorical([0.6, 0.4])
d3 = Categorical([0.2, 0.7, 0.1])
# Same distribution
for d in (d1, d2, d3)
@test d == d
@test d ≈ d
end
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
# Utilities to support the testing of distributions and samplers
using Distributions
using Random
using Printf: @printf
using Test: @test
import FiniteDifferences
import ForwardDiff
# to workaround issues of Base.linspace
function _linspace(a::Float64, b::Float64, n::Int)
intv = (b - a) / (n - 1)
r = Vector{Float64}(undef, n)
@inbounds for i = 1:n
r[i] = a + (i-1) * intv
end
r[n] = b
return r
end
#CURRENT FILE: Distributions.jl/src/samplers/obsoleted.jl
##CHUNK 1
table::Vector{Vector{Int64}}
bounds::Vector{Int64}
end
# TODO: Test if bit operations can speed up Base64 mod's and fld's
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
index = fld(i - table.bounds[bound - 1] - 1, 64^(9 - bound)) + 1
else
index = fld(i - 1, 64^(9 - bound)) + 1
|
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
index = fld(i - table.bounds[bound - 1] - 1, 64^(9 - bound)) + 1
else
index = fld(i - 1, 64^(9 - bound)) + 1
end
return table.table[bound][index]
end | 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
index = fld(i - table.bounds[bound - 1] - 1, 64^(9 - bound)) + 1
else
index = fld(i - 1, 64^(9 - bound)) + 1
end
return table.table[bound][index]
end | [
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
index = fld(i - table.bounds[bound - 1] - 1, 64^(9 - bound)) + 1
else
index = fld(i - 1, 64^(9 - bound)) + 1
end
return table.table[bound][index]
end | 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
index = fld(i - table.bounds[bound - 1] - 1, 64^(9 - bound)) + 1
else
index = fld(i - 1, 64^(9 - bound)) + 1
end
return table.table[bound][index]
end | 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 = DiscreteUniform(lower, upper)
@test truncated(d, -Inf, Inf) == d
@test truncated(d, nothing, nothing) === d
@test truncated(d, lower - 0.1, Inf) == d
@test truncated(d, lower - 0.1, nothing) == d
@test truncated(d, -Inf, upper + 0.1) == d
@test truncated(d, nothing, upper + 0.1) == d
@test truncated(d, lower + 0.3, Inf) == DiscreteUniform(lower + 1, upper)
@test truncated(d, lower + 0.3, nothing) == DiscreteUniform(lower + 1, upper)
@test truncated(d, -Inf, upper - 0.5) == DiscreteUniform(lower, upper - 1)
@test truncated(d, nothing, upper - 0.5) == DiscreteUniform(lower, upper - 1)
@test truncated(d, lower + 1.5, upper - 1) == DiscreteUniform(lower + 2, upper - 1)
end
end
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
# Utilities to support the testing of distributions and samplers
using Distributions
using Random
using Printf: @printf
using Test: @test
import FiniteDifferences
import ForwardDiff
# to workaround issues of Base.linspace
function _linspace(a::Float64, b::Float64, n::Int)
intv = (b - a) / (n - 1)
r = Vector{Float64}(undef, n)
@inbounds for i = 1:n
r[i] = a + (i-1) * intv
end
r[n] = b
return r
end
#FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
#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)
a = (-ub + sqrt(ub^2 + 4.0)) / 2.0
while true
r = rand(rng, Exponential(1.0 / a)) - ub
u = rand(rng)
if u < exp(-0.5 * (r - a)^2) && r < -lb
return -r
end
end
else
while true
r = lb + rand(rng) * (ub - lb)
u = rand(rng)
if lb > 0
rho = exp((lb^2 - r^2) * 0.5)
#FILE: Distributions.jl/src/univariate/continuous/chernoff.jl
##CHUNK 1
1.0432985878313983
1.113195213997703
1.1899583790598025
1.2764995726449935
1.3789927085182485
1.516689116183566
]
n = length(x)
i = rand(rng, 0:n-1)
r = (2.0*rand(rng)-1) * ((i>0) ? x[i] : A/y[1])
rabs = abs(r)
if rabs < x[i+1]
return r
end
s = (i>0) ? (y[i]+rand(rng)*(y[i+1]-y[i])) : rand(rng)*y[1]
if s < 2.0*ChernoffComputations._pdf(rabs)
return r
end
if i > 0
return rand(rng, d)
#FILE: Distributions.jl/test/fit.jl
##CHUNK 1
w = func[1](n0)
x = func[2](DiscreteUniform(10, 15), n0)
d = fit(DiscreteUniform, x)
@test isa(d, DiscreteUniform)
@test minimum(d) == minimum(x)
@test maximum(d) == maximum(x)
d = fit(DiscreteUniform, func[2](DiscreteUniform(10, 15), N))
@test minimum(d) == 10
@test maximum(d) == 15
end
end
@testset "Testing fit for Bernoulli" begin
for rng in ((), (rng,)), D in (Bernoulli, Bernoulli{Float64}, Bernoulli{Float32})
v = rand(rng..., n0)
z = rand(rng..., Bernoulli(0.7), n0)
for x in (z, OffsetArray(z, -n0 ÷ 2)), w in (v, OffsetArray(v, -n0 ÷ 2))
#CURRENT FILE: Distributions.jl/src/samplers/obsoleted.jl
##CHUNK 1
for i in 1:n
if vals[i] == 64^9
table[1] = Vector{Int64}(undef, 64)
for j in 1:64
table[1][j] = i
end
bounds[1] = 64^9
for j in 2:9
table[j] = Vector{Int64}()
bounds[j] = 64^9
end
return DiscreteDistributionTable(table, bounds)
end
end
# Fill tables
multiplier = 1
for index in 9:-1:1
counts = Vector{Int64}()
for i in 1:n
##CHUNK 2
digit = mod(vals[i], 64)
# vals[i] = fld(vals[i], 64)
vals[i] >>= 6
bounds[index] += digit
for itr in 1:digit
push!(counts, i)
end
end
bounds[index] *= multiplier
table[index] = counts
# multiplier *= 64
multiplier <<= 6
end
# Make bounds cumulative
bounds = cumsum(bounds)
return DiscreteDistributionTable(table, bounds)
end
##CHUNK 3
end
return DiscreteDistributionTable(table, bounds)
end
end
# Fill tables
multiplier = 1
for index in 9:-1:1
counts = Vector{Int64}()
for i in 1:n
digit = mod(vals[i], 64)
# vals[i] = fld(vals[i], 64)
vals[i] >>= 6
bounds[index] += digit
for itr in 1:digit
push!(counts, i)
end
end
bounds[index] *= multiplier
table[index] = counts
##CHUNK 4
vals = Vector{Int64}(undef, n)
for i in 1:n
vals[i] = round(Int, probs[i] * 64^9)
end
# Allocate digit table and digit sums as table bounds
table = Vector{Vector{Int64}}(undef, 9)
bounds = zeros(Int64, 9)
# Special case for deterministic distributions
for i in 1:n
if vals[i] == 64^9
table[1] = Vector{Int64}(undef, 64)
for j in 1:64
table[1][j] = i
end
bounds[1] = 64^9
for j in 2:9
table[j] = Vector{Int64}()
bounds[j] = 64^9
|
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, Poisson(d.μ1)) - rand(rng, Poisson(d.μ2))
#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.ξ * log(u)) / d.ξ
end
return d.μ + d.σ * rd
end
#FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
end
# From Knuth
function rand(rng::AbstractRNG, s::BetaSampler)
if s.γ
g1 = rand(rng, s.s1)
g2 = rand(rng, s.s2)
return g1 / (g1 + g2)
else
iα = s.iα
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)
return x / (x + y)
else
#FILE: Distributions.jl/src/samplers/vonmises.jl
##CHUNK 1
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)
if d + e <= 0.25
t = d / e
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) + 1 >= c
break
end
#FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
i = j
x[m] = s
end
j = n + 1
k = j - i
if k > 1
s += T(rand(rng, GammaMTSampler(Gamma{T}(T(k), T(1)))))
else
s += randexp(rng, T)
end
x .= Base.Fix1(quantile, d.dist).(x ./ s)
end
return x
end
#CURRENT 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
# Naive sampler by counting exp variables
#
# Suitable for small μ
#
struct PoissonCountSampler{T<:Real} <: Sampleable{Univariate,Discrete}
μ::T
end
PoissonCountSampler(d::Poisson) = PoissonCountSampler(rate(d))
##CHUNK 2
# Naive sampler by counting exp variables
#
# Suitable for small μ
#
struct PoissonCountSampler{T<:Real} <: Sampleable{Univariate,Discrete}
μ::T
end
PoissonCountSampler(d::Poisson) = PoissonCountSampler(rate(d))
# Algorithm from:
#
# J.H. Ahrens, U. Dieter (1982)
# "Computer Generation of Poisson Deviates from Modified Normal Distributions"
# ACM Transactions on Mathematical Software, 8(2):163-179
#
# For μ sufficiently large, (i.e. >= 10.0)
#
##CHUNK 3
s = sqrt(μ)
d = 6 * μ^2
L = floor(Int, μ - 1.1484)
PoissonADSampler(promote(μ, s, d)..., L)
end
function rand(rng::AbstractRNG, sampler::PoissonADSampler)
μ = sampler.μ
s = sampler.s
d = sampler.d
L = sampler.L
μType = typeof(μ)
# Step N
G = μ + s * randn(rng, μType)
if G >= zero(G)
K = floor(Int, G)
# Step I
##CHUNK 4
struct PoissonADSampler{T<:Real} <: Sampleable{Univariate,Discrete}
μ::T
s::T
d::T
L::Int
end
PoissonADSampler(d::Poisson) = PoissonADSampler(rate(d))
function PoissonADSampler(μ::Real)
s = sqrt(μ)
d = 6 * μ^2
L = floor(Int, μ - 1.1484)
PoissonADSampler(promote(μ, s, d)..., L)
end
function rand(rng::AbstractRNG, sampler::PoissonADSampler)
μ = sampler.μ
s = sampler.s
##CHUNK 5
d = sampler.d
L = sampler.L
μType = typeof(μ)
# Step N
G = μ + s * randn(rng, μType)
if G >= zero(G)
K = floor(Int, G)
# Step I
if K >= L
return K
end
# Step S
U = rand(rng, μType)
if d * U >= (μ - K)^3
return K
end
|
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
px = -μ
py = μ^K/factorial(K)
else
δ = 0.08333333333333333/K
δ -= 4.8*δ^3
V = (μ-K)/K
px = K*log1pmx(V) - δ # avoids need for table
py = 0.3989422804014327/sqrt(K)
end
X = (K-μ+0.5)/s
X2 = X^2
fx = -X2 / 2 # missing negation in pseudo-algorithm, but appears in fortran code.
fy = ω*(((c3*X2+c2)*X2+c1)*X2+c0)
return px,py,fx,fy
end | 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
px = -μ
py = μ^K/factorial(K)
else
δ = 0.08333333333333333/K
δ -= 4.8*δ^3
V = (μ-K)/K
px = K*log1pmx(V) - δ # avoids need for table
py = 0.3989422804014327/sqrt(K)
end
X = (K-μ+0.5)/s
X2 = X^2
fx = -X2 / 2 # missing negation in pseudo-algorithm, but appears in fortran code.
fy = ω*(((c3*X2+c2)*X2+c1)*X2+c0)
return px,py,fx,fy
end | [
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
px = -μ
py = μ^K/factorial(K)
else
δ = 0.08333333333333333/K
δ -= 4.8*δ^3
V = (μ-K)/K
px = K*log1pmx(V) - δ # avoids need for table
py = 0.3989422804014327/sqrt(K)
end
X = (K-μ+0.5)/s
X2 = X^2
fx = -X2 / 2 # missing negation in pseudo-algorithm, but appears in fortran code.
fy = ω*(((c3*X2+c2)*X2+c1)*X2+c0)
return px,py,fx,fy
end | 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
px = -μ
py = μ^K/factorial(K)
else
δ = 0.08333333333333333/K
δ -= 4.8*δ^3
V = (μ-K)/K
px = K*log1pmx(V) - δ # avoids need for table
py = 0.3989422804014327/sqrt(K)
end
X = (K-μ+0.5)/s
X2 = X^2
fx = -X2 / 2 # missing negation in pseudo-algorithm, but appears in fortran code.
fy = ω*(((c3*X2+c2)*X2+c1)*X2+c0)
return px,py,fx,fy
end | 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
return 12sqrt(6) * zeta(3) / pi ^ 3 * one(T)
elseif ξ < 1/3
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
return sign(ξ) * (g3 - 3g1 * g2 + 2g1^3) / (g2 - g1^2) ^ (3/2)
else
return T(Inf)
end
end
##CHUNK 2
function kurtosis(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return T(12)/5
elseif ξ < 1 / 4
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
g4 = g(d, 4)
return (g4 - 4g1 * g3 + 6g2 * g1^2 - 3 * g1^4) / (g2 - g1^2)^2 - 3
else
return T(Inf)
end
end
function entropy(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
return log(σ) + MathConstants.γ * ξ + (1 + MathConstants.γ)
##CHUNK 3
return 12sqrt(6) * zeta(3) / pi ^ 3 * one(T)
elseif ξ < 1/3
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
return sign(ξ) * (g3 - 3g1 * g2 + 2g1^3) / (g2 - g1^2) ^ (3/2)
else
return T(Inf)
end
end
function kurtosis(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return T(12)/5
elseif ξ < 1 / 4
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
#FILE: Distributions.jl/src/samplers/gamma.jl
##CHUNK 1
else
b = 1.77
σ = 0.75
c = 0.1515/s
end
GammaGDSampler(T(a), T(s2), T(s), T(i2s), T(d), T(q0), T(b), T(σ), T(c), scale(g))
end
function calc_q(s::GammaGDSampler, t)
v = t*s.i2s
if abs(v) > 0.25
return s.q0 - s.s*t + 0.25*t*t + 2.0*s.s2*log1p(v)
else
return s.q0 + 0.5*t*t*(v*@horner(v,
0.333333333,
-0.249999949,
0.199999867,
-0.1666774828,
0.142873973,
##CHUNK 2
ia = 1.0/a
q0 = ia*@horner(ia,
0.0416666664,
0.0208333723,
0.0079849875,
0.0015746717,
-0.0003349403,
0.0003340332,
0.0006053049,
-0.0004701849,
0.0001710320)
if a <= 3.686
b = 0.463 + s + 0.178s2
σ = 1.235
c = 0.195/s - 0.079 + 0.16s
elseif a <= 13.022
b = 1.654 + 0.0076s2
σ = 1.68/s + 0.275
c = 0.062/s + 0.024
#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 + θ^2 - π/8 * exp(-θ^2 / 2) * ((2 + θ^2) * besseli(0, θ^2 / 4) + θ^2 * besseli(1, θ^2 / 4))^2
g(θ) = sqrt(ξ(θ) * (1+r^2) - 2)
θ = g(1)
for j in 1:maxiters
θ⁻ = θ
θ = g(θ)
abs(θ - θ⁻) < tol && break
end
ξθ = ξ(θ)
σ = convert(float(T), sqrt(μ₂ / ξθ))
ν = convert(float(T), sqrt(μ₁^2 + (ξθ - 2) * σ^2))
end
#FILE: Distributions.jl/src/truncated/normal.jl
##CHUNK 1
lower, upper = extrema(d)
a = (lower - μ) / σ
b = (upper - μ) / σ
return T(_tnvar(a, b) * σ^2)
end
end
function entropy(d::Truncated{<:Normal{<:Real},Continuous})
d0 = d.untruncated
z = d.tp
μ = mean(d0)
σ = std(d0)
lower, upper = extrema(d)
a = (lower - μ) / σ
b = (upper - μ) / σ
aφa = isinf(a) ? 0.0 : a * normpdf(a)
bφb = isinf(b) ? 0.0 : b * normpdf(b)
0.5 * (log2π + 1.) + log(σ * z) + (aφa - bφb) / (2.0 * z)
end
#FILE: Distributions.jl/src/univariate/continuous/biweight.jl
##CHUNK 1
u ≥ 1 ? one(T) :
(u + 1)^3/16 * @horner(u, 8, -9, 3)
end
@quantile_newton Biweight
function mgf(d::Biweight{T}, t::Real) where T<:Real
a = d.σ*t
a2 = a^2
a == 0 ? one(T) :
15exp(d.μ * t) * (-3cosh(a) + (a + 3/a) * sinh(a)) / (a2^2)
end
function cf(d::Biweight{T}, t::Real) where T<:Real
a = d.σ * t
a2 = a^2
a == 0 ? one(T)+zero(T)*im :
-15cis(d.μ * t) * (3cos(a) + (a - 3/a) * sin(a)) / (a2^2)
end
#FILE: Distributions.jl/test/univariate/continuous/skewedexponentialpower.jl
##CHUNK 1
1.0526316 0.070717323 0.92258764;
1.7894737 0.031620241 0.95773428;
2.5263158 0.016507946 0.97472202;
3.2631579 0.009427166 0.98399211;
4.0000000 0.005718906 0.98942757;
]
d = SkewedExponentialPower(0, 1, 0.5, 0.7)
for t in eachrow(test)
@test @inferred(pdf(d, t[1])) ≈ t[2] rtol=1e-5
@test @inferred(logpdf(d, t[1])) ≈ log(t[2]) rtol=1e-5
@test @inferred(cdf(d, t[1])) ≈ t[3] rtol=1e-3
@test @inferred(logcdf(d, t[1])) ≈ log(t[3]) rtol=1e-3
end
test_distr(d, 10^6)
# relationship between sepd(μ, σ, p, α) and
# sepd(μ, σ, p, 1-α)
d1 = SkewedExponentialPower(0, 1, 0.1, 0.7)
d2 = SkewedExponentialPower(0, 1, 0.1, 0.3)
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end
#CURRENT FILE: Distributions.jl/src/samplers/poisson.jl |
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)
if d + e <= 0.25
t = d / e
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) + 1 >= c
break
end
end
acf = acos(f)
x = s.μ + (rand(rng, Bool) ? acf : -acf)
end
return x
end | 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)
if d + e <= 0.25
t = d / e
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) + 1 >= c
break
end
end
acf = acos(f)
x = s.μ + (rand(rng, Bool) ? acf : -acf)
end
return x
end | [
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)
if d + e <= 0.25
t = d / e
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) + 1 >= c
break
end
end
acf = acos(f)
x = s.μ + (rand(rng, Bool) ? acf : -acf)
end
return x
end | 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)
if d + e <= 0.25
t = d / e
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) + 1 >= c
break
end
end
acf = acos(f)
x = s.μ + (rand(rng, Bool) ? acf : -acf)
end
return x
end | 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)
a = (-ub + sqrt(ub^2 + 4.0)) / 2.0
while true
r = rand(rng, Exponential(1.0 / a)) - ub
u = rand(rng)
if u < exp(-0.5 * (r - a)^2) && r < -lb
return -r
end
end
else
while true
r = lb + rand(rng) * (ub - lb)
u = rand(rng)
if lb > 0
rho = exp((lb^2 - r^2) * 0.5)
#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::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 - b) * z)
end
return w::Float64
end
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end
#FILE: Distributions.jl/src/samplers/poisson.jl
##CHUNK 1
while true
# Step E
E = randexp(rng, μType)
U = 2 * rand(rng, μType) - one(μType)
T = 1.8 + copysign(E, U)
if T <= -0.6744
continue
end
K = floor(Int, μ + s * T)
px, py, fx, fy = procf(μ, K, s)
c = 0.1069 / μ
# Step H
if c*abs(U) <= py*exp(px + E) - fy*exp(fx + E)
return K
end
end
end
##CHUNK 2
# Procedure F
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
px = -μ
py = μ^K/factorial(K)
else
δ = 0.08333333333333333/K
δ -= 4.8*δ^3
V = (μ-K)/K
px = K*log1pmx(V) - δ # avoids need for table
py = 0.3989422804014327/sqrt(K)
#FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
g4 = g(d, 4)
return (g4 - 4g1 * g3 + 6g2 * g1^2 - 3 * g1^4) / (g2 - g1^2)^2 - 3
else
return T(Inf)
end
end
function entropy(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
return log(σ) + MathConstants.γ * ξ + (1 + MathConstants.γ)
end
function quantile(d::GeneralizedExtremeValue, p::Real)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * (-log(-log(p)))
else
return μ + σ * ((-log(p))^(-ξ) - 1) / ξ
end
##CHUNK 2
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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
##CHUNK 3
g(d::GeneralizedExtremeValue, k::Real) = gamma(1 - k * d.ξ) # This should not be exported.
function median(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps() # ξ == 0
return μ - σ * log(log(2))
else
return μ + σ * (log(2) ^ (- ξ) - 1) / ξ
end
end
function mean(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * MathConstants.γ
elseif ξ < 1
return μ + σ * (gamma(1 - ξ) - 1) / ξ
else
#FILE: Distributions.jl/src/pdfnorm.jl
##CHUNK 1
return d.ν > 0.5 ? z : oftype(z, Inf)
end
function pdfsquaredL2norm(d::Chisq)
ν = d.ν
z = gamma(d.ν - 1) / (gamma(d.ν / 2) ^ 2 * 2 ^ d.ν)
# L2 norm of the pdf converges only for ν > 1
return ν > 1 ? z : oftype(z, Inf)
end
pdfsquaredL2norm(d::DiscreteUniform) = 1 / (d.b - d.a + 1)
pdfsquaredL2norm(d::Exponential) = 1 / (2 * d.θ)
function pdfsquaredL2norm(d::Gamma)
α, θ = params(d)
z = (2^(1 - 2 * α) * gamma(2 * α - 1)) / (gamma(α) ^ 2 * θ)
# L2 norm of the pdf converges only for α > 0.5
return α > 0.5 ? z : oftype(z, Inf)
end
#FILE: Distributions.jl/src/samplers/gamma.jl
##CHUNK 1
while true
e = randexp(rng)
u = 2.0rand(rng) - 1.0
t = s.b + e*s.σ*sign(u)
# Step 9
t ≥ -0.718_744_837_717_19 && break
end
# Step 10
q = calc_q(s, t)
# Step 11
(q > 0.0) && (s.c*abs(u) ≤ expm1(q)*exp(e-0.5t*t)) && break
end
# Step 12
x = s.s+0.5t
return x*x*s.scale
end
#CURRENT FILE: Distributions.jl/src/samplers/vonmises.jl |
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
x[i] *= r
end
return _vmf_rot!(spl.v, x)
end | 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
x[i] *= r
end
return _vmf_rot!(spl.v, x)
end | [
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
x[i] *= r
end
return _vmf_rot!(spl.v, x)
end | 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
x[i] *= r
end
return _vmf_rot!(spl.v, x)
end | _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(μ)
μ = μ ./ κ
s = Distributions.VonMisesFisherSampler(μ, κ)
v = μ - vcat(1, zeros(p-1))
H = I - 2*v*v'/(v'*v)
@test Distributions._vmf_rot!(s.v, copy(x)) ≈ (H*x)
##CHUNK 2
x = randn(rng, p)
end
κ = norm(μ)
μ = μ ./ κ
s = Distributions.VonMisesFisherSampler(μ, κ)
v = μ - vcat(1, zeros(p-1))
H = I - 2*v*v'/(v'*v)
@test Distributions._vmf_rot!(s.v, copy(x)) ≈ (H*x)
end
function test_genw3(κ::Real, ns::Int, rng::Union{AbstractRNG, Missing} = missing)
p = 3
if ismissing(rng)
μ = randn(p)
##CHUNK 3
function gen_vmf_tdata(n::Int, p::Int,
rng::Union{AbstractRNG, Missing} = missing)
if ismissing(rng)
X = randn(p, n)
else
X = randn(rng, p, n)
end
for i = 1:n
X[:,i] = X[:,i] ./ norm(X[:,i])
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)
##CHUNK 4
end
function test_genw3(κ::Real, ns::Int, rng::Union{AbstractRNG, Missing} = missing)
p = 3
if ismissing(rng)
μ = randn(p)
else
μ = randn(rng, p)
end
μ = μ ./ norm(μ)
s = Distributions.VonMisesFisherSampler(μ, float(κ))
genw3_res = [Distributions._vmf_genw3(rng, s.p, s.b, s.x0, s.c, s.κ) for _ in 1:ns]
genwp_res = [Distributions._vmf_genwp(rng, s.p, s.b, s.x0, s.c, s.κ) for _ in 1:ns]
#FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
return A
end
#FILE: Distributions.jl/src/univariate/continuous/vonmises.jl
##CHUNK 1
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
#### Sampling
rand(rng::AbstractRNG, d::VonMises) = rand(rng, sampler(d))
sampler(d::VonMises) = VonMisesSampler(d.μ, d.κ)
#FILE: Distributions.jl/src/samplers/multinomial.jl
##CHUNK 1
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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
#CURRENT FILE: Distributions.jl/src/samplers/vonmisesfisher.jl
##CHUNK 1
return _vmf_genwp(rng, p, b, x0, c, κ)
end
end
_vmf_genw(rng::AbstractRNG, s::VonMisesFisherSampler) =
_vmf_genw(rng, s.p, s.b, s.x0, s.c, s.κ)
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
##CHUNK 2
@inline function _vmf_rot!(v::AbstractVector, x::AbstractVector)
# rotate
scale = 2.0 * (v' * x)
@. x -= (scale * v)
return x
end
### Core computation
_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
##CHUNK 3
function VonMisesFisherSampler(μ::Vector{Float64}, κ::Float64)
p = length(μ)
b = _vmf_bval(p, κ)
x0 = (1.0 - b) / (1.0 + b)
c = κ * x0 + (p - 1) * log1p(-abs2(x0))
v = _vmf_householder_vec(μ)
VonMisesFisherSampler(p, κ, b, x0, c, v)
end
Base.length(s::VonMisesFisherSampler) = length(s.v)
@inline function _vmf_rot!(v::AbstractVector, x::AbstractVector)
# rotate
scale = 2.0 * (v' * x)
@. x -= (scale * v)
return x
end
|
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 - b) * z)
end
return w::Float64
end | 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 - b) * z)
end
return w::Float64
end | [
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 - b) * z)
end
return w::Float64
end | 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 - b) * z)
end
return w::Float64
end | _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
logX -= logM
logY -= logM
return exp(logX - log(exp(logX) + exp(logY)))
end
end
end
else
g1 = rand(rng, Gamma(α, one(T)))
g2 = rand(rng, Gamma(β, one(T)))
return g1 / (g1 + g2)
end
end
##CHUNK 2
end
function rand(rng::AbstractRNG, d::Beta{T}) where T
(α, β) = params(d)
if (α ≤ 1.0) && (β ≤ 1.0)
while true
u = rand(rng)
v = rand(rng)
x = u^inv(α)
y = v^inv(β)
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
logX -= logM
logY -= logM
return exp(logX - log(exp(logX) + exp(logY)))
#FILE: Distributions.jl/src/univariate/continuous/kumaraswamy.jl
##CHUNK 1
a, b = params(d)
H = digamma(b + 1) + eulergamma
return (1 - inv(b)) + (1 - inv(a)) * H - log(a) - log(b)
end
function gradlogpdf(d::Kumaraswamy, x::Real)
a, b = params(d)
_x = clamp(x, 0, 1)
_xᵃ = _x^a
y = (a * (b * _xᵃ - 1) + (1 - _xᵃ)) / (_x * (_xᵃ - 1))
return x < 0 || x > 1 ? oftype(y, -Inf) : y
end
### Sampling
# `rand`: Uses fallback inversion sampling method
### Statistics
_kumomentaswamy(a, b, n) = b * beta(1 + n / a, b)
#FILE: Distributions.jl/src/samplers/vonmises.jl
##CHUNK 1
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)
if d + e <= 0.25
t = d / e
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) + 1 >= c
break
end
##CHUNK 2
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) + 1 >= c
break
end
end
acf = acos(f)
x = s.μ + (rand(rng, Bool) ? acf : -acf)
end
return x
end
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
2(α + s) / (β - 3) * sqrt((β - 2) / (α * s))
else
return T(NaN)
end
end
#### Evaluation
function logpdf(d::BetaPrime, x::Real)
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
#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)
a = (-ub + sqrt(ub^2 + 4.0)) / 2.0
while true
r = rand(rng, Exponential(1.0 / a)) - ub
u = rand(rng)
if u < exp(-0.5 * (r - a)^2) && r < -lb
return -r
end
end
else
while true
r = lb + rand(rng) * (ub - lb)
u = rand(rng)
if lb > 0
rho = exp((lb^2 - r^2) * 0.5)
#FILE: Distributions.jl/src/univariate/continuous/lindley.jl
##CHUNK 1
# upper bound on the error for this algorithm is (1/2)^(2^n), where n is the number of
# recursion steps. The default here is set such that this error is less than `eps()`.
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
### Sampling
# Ghitany, M. E., Atieh, B., & Nadarajah, S. (2008). Lindley distribution and its
#CURRENT 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
# generate the W value -- the key step in simulating vMF
#
# following movMF's document for the p != 3 case
# and Wenzel Jakob's document for the p == 3 case
function _vmf_genw(rng::AbstractRNG, p, b, x0, c, κ)
if p == 3
return _vmf_genw3(rng, p, b, x0, c, κ)
else
return _vmf_genwp(rng, p, b, x0, c, κ)
end
end
##CHUNK 2
r = sqrt((1.0 - abs2(w)) / s)
@inbounds for i = 2:p
x[i] *= r
end
return _vmf_rot!(spl.v, x)
end
### Core computation
_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
# generate the W value -- the key step in simulating vMF
|
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
end | 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
end | [
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
end | 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
end | _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(μ)
μ = μ ./ κ
s = Distributions.VonMisesFisherSampler(μ, κ)
v = μ - vcat(1, zeros(p-1))
H = I - 2*v*v'/(v'*v)
@test Distributions._vmf_rot!(s.v, copy(x)) ≈ (H*x)
##CHUNK 2
μ = μ ./ norm(μ)
d = VonMisesFisher(μ, κ)
@test length(d) == p
@test meandir(d) == μ
@test concentration(d) == κ
@test partype(d) == Float64
# conversions
@test convert(VonMisesFisher{partype(d)}, d) === d
for d32 in (convert(VonMisesFisher{Float32}, d), convert(VonMisesFisher{Float32}, d.μ, d.κ, d.logCκ))
@test d32 isa VonMisesFisher{Float32}
@test params(d32) == (map(Float32, μ), Float32(κ))
end
θ = κ * μ
d2 = VonMisesFisher(θ)
@test length(d2) == p
@test meandir(d2) ≈ μ
@test concentration(d2) ≈ κ
##CHUNK 3
x = randn(rng, p)
end
κ = norm(μ)
μ = μ ./ κ
s = Distributions.VonMisesFisherSampler(μ, κ)
v = μ - vcat(1, zeros(p-1))
H = I - 2*v*v'/(v'*v)
@test Distributions._vmf_rot!(s.v, copy(x)) ≈ (H*x)
end
function test_genw3(κ::Real, ns::Int, rng::Union{AbstractRNG, Missing} = missing)
p = 3
if ismissing(rng)
μ = randn(p)
##CHUNK 4
end
function test_vonmisesfisher(p::Int, κ::Real, n::Int, ns::Int,
rng::Union{AbstractRNG, Missing} = missing)
if ismissing(rng)
μ = randn(p)
else
μ = randn(rng, p)
end
μ = μ ./ norm(μ)
d = VonMisesFisher(μ, κ)
@test length(d) == p
@test meandir(d) == μ
@test concentration(d) == κ
@test partype(d) == Float64
# conversions
@test convert(VonMisesFisher{partype(d)}, d) === d
#FILE: Distributions.jl/src/utils.jl
##CHUNK 1
end
##### Utility functions
isunitvec(v::AbstractVector) = (norm(v) - 1.0) < 1.0e-12
isprobvec(p::AbstractVector{<:Real}) =
all(x -> x ≥ zero(x), p) && isapprox(sum(p), one(eltype(p)))
sqrt!!(x::AbstractVector{<:Real}) = map(sqrt, x)
function sqrt!!(x::Vector{<:Real})
for i in eachindex(x)
x[i] = sqrt(x[i])
end
return x
end
# get a type wide enough to represent all a distributions's parameters
# (if the distribution is parametric)
# if the distribution is not parametric, we need this to be a float so that
#FILE: Distributions.jl/src/univariate/continuous/ksdist.jl
##CHUNK 1
H[i,j] /= ℯ
end
Q = H^n
s = Q[k,k]
s*stirling(n)
end
# Miller (1956) approximation
function ccdf_miller(d::KSDist, x::Real)
2*ccdf(KSOneSided(d.n),x)
end
## these functions are used in durbin and pomeranz algorithms
# calculate exact remainders the easy way
function floor_rems_mult(n,x)
t = big(x)*big(n)
fl = floor(t)
lrem = t - fl
urem = (fl+one(fl)) - t
return convert(typeof(n),fl), convert(typeof(x),lrem), convert(typeof(x),urem)
#FILE: Distributions.jl/src/univariate/continuous/normal.jl
##CHUNK 1
@inbounds wi = w[i]
@inbounds s += wi * x[i]
tw += wi
end
m = s / tw
# compute s2
s2 = zero(m)
for i in eachindex(x, w)
@inbounds s2 += w[i] * abs2(x[i] - m)
end
NormalStats(s, m, s2, tw)
end
# Cases where μ or σ is known
struct NormalKnownMu <: IncompleteDistribution
μ::Float64
end
#FILE: Distributions.jl/src/multivariate/vonmisesfisher.jl
##CHUNK 1
ρ2 = abs2(ρ)
κ = ρ * (p - ρ2) / (1 - ρ2)
i = 0
while i < maxiter
i += 1
κ_prev = κ
a = (ρ / _vmfA(half_p, κ))
# println("i = $i, a = $a, abs(a - 1) = $(abs(a - 1))")
κ *= a
if abs(a - 1.0) < 1.0e-12
break
end
end
return κ
end
_vmfA(half_p::Float64, κ::Float64) = besselix(half_p, κ) / besselix(half_p - 1.0, κ)
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
function rand(rng::AbstractRNG, d::InverseGaussian)
μ, λ = params(d)
z = randn(rng)
v = z * z
w = μ * v
x1 = μ + μ / (2λ) * (w - sqrt(w * (4λ + w)))
p1 = μ / (μ + x1)
u = rand(rng)
u >= p1 ? μ^2 / x1 : x1
end
#### Fit model
"""
Sufficient statistics for `InverseGaussian`, containing the weighted
sum of observations, the weighted sum of inverse points and sum of weights.
"""
struct InverseGaussianStats <: SufficientStats
sx::Float64 # (weighted) sum of x
sinvx::Float64 # (weighted) sum of 1/x
#CURRENT FILE: Distributions.jl/src/samplers/vonmisesfisher.jl
##CHUNK 1
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
x[i] *= r
end
return _vmf_rot!(spl.v, x)
end
### Core computation
|
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 * invsqrt2
if a ≤ 0 ≤ b
m = expm1(-Δ) * exp(-a^2 / 2) / erf(b′, a′)
elseif 0 < a < b
z = exp(-Δ) * erfcx(b′) - erfcx(a′)
iszero(z) && return mid
m = expm1(-Δ) / z
end
return clamp(m / sqrthalfπ, a, b)
end | 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 * invsqrt2
if a ≤ 0 ≤ b
m = expm1(-Δ) * exp(-a^2 / 2) / erf(b′, a′)
elseif 0 < a < b
z = exp(-Δ) * erfcx(b′) - erfcx(a′)
iszero(z) && return mid
m = expm1(-Δ) / z
end
return clamp(m / sqrthalfπ, a, b)
end | [
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 * invsqrt2
if a ≤ 0 ≤ b
m = expm1(-Δ) * exp(-a^2 / 2) / erf(b′, a′)
elseif 0 < a < b
z = exp(-Δ) * erfcx(b′) - erfcx(a′)
iszero(z) && return mid
m = expm1(-Δ) / z
end
return clamp(m / sqrthalfπ, a, b)
end | 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 * invsqrt2
if a ≤ 0 ≤ b
m = expm1(-Δ) * exp(-a^2 / 2) / erf(b′, a′)
elseif 0 < a < b
z = exp(-Δ) * erfcx(b′) - erfcx(a′)
iszero(z) && return mid
m = expm1(-Δ) / z
end
return clamp(m / sqrthalfπ, a, b)
end | _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)
(a, b, c) = params(d)
c_m_a = c - a
b_m_a = b - a
rl = c_m_a / b_m_a
p <= rl ? a + sqrt(b_m_a * c_m_a * p) :
b - sqrt(b_m_a * (b - c) * (1 - p))
end
"""
_phi2(x::Real)
##CHUNK 2
# Handle x == c separately to avoid `NaN` if `c == a` or `c == b`
oftype(x - a, 2) / (b - a)
end
return insupport(d, x) ? res : zero(res)
end
logpdf(d::TriangularDist, x::Real) = log(pdf(d, x))
function cdf(d::TriangularDist, x::Real)
a, b, c = params(d)
if x < c
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)
(a, b, c) = params(d)
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end
##CHUNK 2
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 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
#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 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end
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
#CURRENT FILE: Distributions.jl/src/truncated/normal.jl
##CHUNK 1
elseif abs(a) > abs(b)
return _tnmom2(-b, -a)
elseif isinf(a) && isinf(b)
return one(mid)
elseif isinf(b)
return 1 + a / erfcx(a * invsqrt2) / sqrthalfπ
end
a′ = a * invsqrt2
b′ = b * invsqrt2
if a ≤ 0 ≤ b
eb_ea = sqrthalfπ * erf(a′, b′)
fb_fa = eb_ea + a * exp(-a^2 / 2) - b * exp(-b^2 / 2)
return fb_fa / eb_ea
else # 0 ≤ a ≤ b
exΔ = exp((a - b) * mid)
ea = sqrthalfπ * erfcx(a′)
eb = sqrthalfπ * erfcx(b′)
fa = ea + a
fb = eb + b
return (fa - fb * exΔ) / (ea - eb * exΔ)
##CHUNK 2
eb_ea = sqrthalfπ * erf(a′, b′)
fb_fa = eb_ea + a * exp(-a^2 / 2) - b * exp(-b^2 / 2)
return fb_fa / eb_ea
else # 0 ≤ a ≤ b
exΔ = exp((a - b) * mid)
ea = sqrthalfπ * erfcx(a′)
eb = sqrthalfπ * erfcx(b′)
fa = ea + a
fb = eb + b
return (fa - fb * exΔ) / (ea - eb * exΔ)
end
end
# do not export. Used in var
function _tnvar(a::Real, b::Real)
if a == b
return zero(middle(a, b))
elseif a < b
m1 = _tnmom1(a, b)
m2 = √_tnmom2(a, b)
##CHUNK 3
# computes mean of standard normal distribution truncated to [a, b]
# do not export. Used in var
# computes 2nd moment of standard normal distribution truncated to [a, b]
function _tnmom2(a::Real, b::Real)
mid = float(middle(a, b))
if !(a ≤ b)
return oftype(mid, NaN)
elseif a == b
return mid^2
elseif abs(a) > abs(b)
return _tnmom2(-b, -a)
elseif isinf(a) && isinf(b)
return one(mid)
elseif isinf(b)
return 1 + a / erfcx(a * invsqrt2) / sqrthalfπ
end
a′ = a * invsqrt2
b′ = b * invsqrt2
if a ≤ 0 ≤ b
##CHUNK 4
return (m2 - m1) * (m2 + m1)
else
return oftype(middle(a, b), NaN)
end
end
function mean(d::Truncated{<:Normal{<:Real},Continuous,T}) where {T<:Real}
d0 = d.untruncated
μ = mean(d0)
σ = std(d0)
if iszero(σ)
return mode(d)
else
lower, upper = extrema(d)
a = (lower - μ) / σ
b = (upper - μ) / σ
return T(μ + _tnmom1(a, b) * σ)
end
end
##CHUNK 5
return T(_tnvar(a, b) * σ^2)
end
end
function entropy(d::Truncated{<:Normal{<:Real},Continuous})
d0 = d.untruncated
z = d.tp
μ = mean(d0)
σ = std(d0)
lower, upper = extrema(d)
a = (lower - μ) / σ
b = (upper - μ) / σ
aφa = isinf(a) ? 0.0 : a * normpdf(a)
bφb = isinf(b) ? 0.0 : b * normpdf(b)
0.5 * (log2π + 1.) + log(σ * z) + (aφa - bφb) / (2.0 * z)
end
### sampling
|
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 #newton method
t+=1
temp1 = digamma(θ[1]+θ[2])
temp2 = trigamma(θ[1]+θ[2])
grad = [g₁+temp1-digamma(θ[1])
temp1+g₂-digamma(θ[2])]
hess = [temp2-trigamma(θ[1]) temp2
temp2 temp2-trigamma(θ[2])]
Δθ = hess\grad #newton step
θ .-= Δθ
converged = dot(Δθ,Δθ) < 2*tol #stopping criterion
end
return Beta(θ[1], θ[2])
end | 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 #newton method
t+=1
temp1 = digamma(θ[1]+θ[2])
temp2 = trigamma(θ[1]+θ[2])
grad = [g₁+temp1-digamma(θ[1])
temp1+g₂-digamma(θ[2])]
hess = [temp2-trigamma(θ[1]) temp2
temp2 temp2-trigamma(θ[2])]
Δθ = hess\grad #newton step
θ .-= Δθ
converged = dot(Δθ,Δθ) < 2*tol #stopping criterion
end
return Beta(θ[1], θ[2])
end | [
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 #newton method
t+=1
temp1 = digamma(θ[1]+θ[2])
temp2 = trigamma(θ[1]+θ[2])
grad = [g₁+temp1-digamma(θ[1])
temp1+g₂-digamma(θ[2])]
hess = [temp2-trigamma(θ[1]) temp2
temp2 temp2-trigamma(θ[2])]
Δθ = hess\grad #newton step
θ .-= Δθ
converged = dot(Δθ,Δθ) < 2*tol #stopping criterion
end
return Beta(θ[1], θ[2])
end | 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 #newton method
t+=1
temp1 = digamma(θ[1]+θ[2])
temp2 = trigamma(θ[1]+θ[2])
grad = [g₁+temp1-digamma(θ[1])
temp1+g₂-digamma(θ[2])]
hess = [temp2-trigamma(θ[1]) temp2
temp2 temp2-trigamma(θ[2])]
Δθ = hess\grad #newton step
θ .-= Δθ
converged = dot(Δθ,Δθ) < 2*tol #stopping criterion
end
return Beta(θ[1], θ[2])
end | 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 + θ^2 - π/8 * exp(-θ^2 / 2) * ((2 + θ^2) * besseli(0, θ^2 / 4) + θ^2 * besseli(1, θ^2 / 4))^2
g(θ) = sqrt(ξ(θ) * (1+r^2) - 2)
θ = g(1)
for j in 1:maxiters
θ⁻ = θ
θ = g(θ)
abs(θ - θ⁻) < tol && break
end
ξθ = ξ(θ)
σ = convert(float(T), sqrt(μ₂ / ξθ))
ν = convert(float(T), sqrt(μ₁^2 + (ξθ - 2) * σ^2))
end
#FILE: Distributions.jl/src/univariate/continuous/laplace.jl
##CHUNK 1
#### Statistics
mean(d::Laplace) = d.μ
median(d::Laplace) = d.μ
mode(d::Laplace) = d.μ
var(d::Laplace) = 2d.θ^2
std(d::Laplace) = sqrt2 * d.θ
skewness(d::Laplace{T}) where {T<:Real} = zero(T)
kurtosis(d::Laplace{T}) where {T<:Real} = 3one(T)
entropy(d::Laplace) = log(2d.θ) + 1
function kldivergence(p::Laplace, q::Laplace)
pμ, pθ = params(p)
qμ, qθ = params(q)
r = abs(pμ - qμ)
return (pθ * exp(-r / pθ) + r) / qθ + log(qθ / pθ) - 1
end
#FILE: Distributions.jl/src/univariate/continuous/gamma.jl
##CHUNK 1
function fit_mle(::Type{<:Gamma}, ss::GammaStats;
alpha0::Float64=NaN, maxiter::Int=1000, tol::Float64=1e-16)
mx = ss.sx / ss.tw
logmx = log(mx)
mlogx = ss.slogx / ss.tw
a::Float64 = isnan(alpha0) ? (logmx - mlogx)/2 : alpha0
converged = false
t = 0
while !converged && t < maxiter
t += 1
a_old = a
a = gamma_mle_update(logmx, mlogx, a)
converged = abs(a - a_old) <= tol
end
Gamma(a, mx / a)
end
##CHUNK 2
end
GammaStats(sx, slogx, tw)
end
function gamma_mle_update(logmx::Float64, mlogx::Float64, a::Float64)
ia = 1 / a
z = ia + (mlogx - logmx + log(a) - digamma(a)) / (abs2(a) * (ia - trigamma(a)))
1 / z
end
function fit_mle(::Type{<:Gamma}, ss::GammaStats;
alpha0::Float64=NaN, maxiter::Int=1000, tol::Float64=1e-16)
mx = ss.sx / ss.tw
logmx = log(mx)
mlogx = ss.slogx / ss.tw
a::Float64 = isnan(alpha0) ? (logmx - mlogx)/2 : alpha0
converged = false
##CHUNK 3
α >= 1 ? θ * (α - 1) : error("Gamma has no mode when shape < 1")
end
function entropy(d::Gamma)
(α, θ) = params(d)
α + loggamma(α) + (1 - α) * digamma(α) + log(θ)
end
mgf(d::Gamma, t::Real) = (1 - t * d.θ)^(-d.α)
function cgf(d::Gamma, t)
α, θ = params(d)
return α * cgf(Exponential{typeof(θ)}(θ), t)
end
cf(d::Gamma, t::Real) = (1 - im * t * d.θ)^(-d.α)
function kldivergence(p::Gamma, q::Gamma)
# We use the parametrization with the scale θ
αp, θp = params(p)
αq, θq = params(q)
#FILE: Distributions.jl/src/univariate/continuous/normal.jl
##CHUNK 1
# `logerf(...)` is more accurate for arguments in the tails than `logsubexp(logcdf(...), logcdf(...))`
function logdiffcdf(d::Normal, x::Real, y::Real)
x < y && throw(ArgumentError("requires x >= y."))
μ, σ = params(d)
_x, _y, _μ, _σ = promote(x, y, μ, σ)
s = sqrt2 * _σ
return logerf((_y - _μ) / s, (_x - _μ) / s) - logtwo
end
gradlogpdf(d::Normal, x::Real) = (d.μ - x) / d.σ^2
mgf(d::Normal, t::Real) = exp(t * d.μ + d.σ^2 / 2 * t^2)
function cgf(d::Normal, t)
μ,σ = params(d)
t*μ + (σ*t)^2/2
end
cf(d::Normal, t::Real) = exp(im * t * d.μ - d.σ^2 / 2 * t^2)
#### Affine transformations
#FILE: Distributions.jl/src/univariate/continuous/logistic.jl
##CHUNK 1
invlogcdf(d::Logistic, lp::Real) = xval(d, -logexpm1(-lp))
invlogccdf(d::Logistic, lp::Real) = xval(d, logexpm1(-lp))
function gradlogpdf(d::Logistic, x::Real)
e = exp(-zval(d, x))
((2e) / (1 + e) - 1) / d.θ
end
mgf(d::Logistic, t::Real) = exp(t * d.μ) / sinc(d.θ * t)
function cgf(d::Logistic, t)
μ, θ = params(d)
t*μ - log(sinc(θ*t))
end
function cf(d::Logistic, t::Real)
a = (π * t) * d.θ
a == zero(a) ? complex(one(a)) : cis(t * d.μ) * (a / sinh(a))
end
#FILE: Distributions.jl/src/univariate/continuous/levy.jl
##CHUNK 1
μ, σ = params(d)
if x <= μ
return zero(T)
end
z = x - μ
(sqrt(σ) / sqrt2π) * exp((-σ) / (2z)) / z^(3//2)
end
function logpdf(d::Levy{T}, x::Real) where T<:Real
μ, σ = params(d)
if x <= μ
return T(-Inf)
end
z = x - μ
(log(σ) - log2π - σ / z - 3log(z))/2
end
cdf(d::Levy{T}, x::Real) where {T<:Real} = x <= d.μ ? zero(T) : erfc(sqrt(d.σ / (2(x - d.μ))))
ccdf(d::Levy{T}, x::Real) where {T<:Real} = x <= d.μ ? one(T) : erf(sqrt(d.σ / (2(x - d.μ))))
#FILE: Distributions.jl/src/univariate/continuous/weibull.jl
##CHUNK 1
alpha0::Real = 1, maxiter::Int = 1000, tol::Real = 1e-16)
Compute the maximum likelihood estimate of the [`Weibull`](@ref) distribution with Newton's method.
"""
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(xpow0)
dot_xpowlnx0 = dot(xpow0, lnx)
fx = dot_xpowlnx0 / sum_xpow0 - mean_lnx - 1 / alpha0
#CURRENT FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
(s - 2) * digamma(s)
end
function kldivergence(p::Beta, q::Beta)
αp, βp = params(p)
αq, βq = params(q)
return logbeta(αq, βq) - logbeta(αp, βp) + (αp - αq) * digamma(αp) +
(βp - βq) * digamma(βp) + (αq - αp + βq - βp) * digamma(αp + βp)
end
#### Evaluation
@_delegate_statsfuns Beta beta α β
gradlogpdf(d::Beta{T}, x::Real) where {T<:Real} =
((α, β) = params(d); 0 <= x <= 1 ? (α - 1) / x - (β - 1) / (1 - x) : zero(T))
#### Sampling
|
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.353308035220429;
0.3 -0.2751512847290148;
0.4 -0.13319637678583637;
0.5 0.0;
0.6 0.13319637678583637;
0.7 0.2751512847290147;
0.75 0.353308035220429;
0.8 0.4398276660488655;
0.9 0.6642351964332931;
0.95 0.8450811886357724;
0.975 0.9981810946684272;
0.99 1.17153434157313;
1.0 Inf
]
(0.0 <= tau && tau <= 1.0) || throw(DomainError(tau, "illegal value of tau"))
present = searchsortedfirst(precomputedquants[:, 1], tau)
if present <= size(precomputedquants, 1)
if tau == precomputedquants[present, 1]
return precomputedquants[present, 2]
end
end
# one good approximation of the quantiles can be computed using Normal(0.0, stdapprox) with stdapprox = 0.52
stdapprox = 0.52
dnorm = Normal(0.0, 1.0)
if tau < 0.001
return -newton(x -> tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, 1.0 - tau)*stdapprox)
end
if tau > 0.999
return newton(x -> 1.0 - tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox)
end
return newton(x -> ChernoffComputations._cdf(x) - tau, ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox) # should consider replacing x-> construct for speed
end | 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.353308035220429;
0.3 -0.2751512847290148;
0.4 -0.13319637678583637;
0.5 0.0;
0.6 0.13319637678583637;
0.7 0.2751512847290147;
0.75 0.353308035220429;
0.8 0.4398276660488655;
0.9 0.6642351964332931;
0.95 0.8450811886357724;
0.975 0.9981810946684272;
0.99 1.17153434157313;
1.0 Inf
]
(0.0 <= tau && tau <= 1.0) || throw(DomainError(tau, "illegal value of tau"))
present = searchsortedfirst(precomputedquants[:, 1], tau)
if present <= size(precomputedquants, 1)
if tau == precomputedquants[present, 1]
return precomputedquants[present, 2]
end
end
# one good approximation of the quantiles can be computed using Normal(0.0, stdapprox) with stdapprox = 0.52
stdapprox = 0.52
dnorm = Normal(0.0, 1.0)
if tau < 0.001
return -newton(x -> tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, 1.0 - tau)*stdapprox)
end
if tau > 0.999
return newton(x -> 1.0 - tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox)
end
return newton(x -> ChernoffComputations._cdf(x) - tau, ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox) # should consider replacing x-> construct for speed
end | [
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.353308035220429;
0.3 -0.2751512847290148;
0.4 -0.13319637678583637;
0.5 0.0;
0.6 0.13319637678583637;
0.7 0.2751512847290147;
0.75 0.353308035220429;
0.8 0.4398276660488655;
0.9 0.6642351964332931;
0.95 0.8450811886357724;
0.975 0.9981810946684272;
0.99 1.17153434157313;
1.0 Inf
]
(0.0 <= tau && tau <= 1.0) || throw(DomainError(tau, "illegal value of tau"))
present = searchsortedfirst(precomputedquants[:, 1], tau)
if present <= size(precomputedquants, 1)
if tau == precomputedquants[present, 1]
return precomputedquants[present, 2]
end
end
# one good approximation of the quantiles can be computed using Normal(0.0, stdapprox) with stdapprox = 0.52
stdapprox = 0.52
dnorm = Normal(0.0, 1.0)
if tau < 0.001
return -newton(x -> tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, 1.0 - tau)*stdapprox)
end
if tau > 0.999
return newton(x -> 1.0 - tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox)
end
return newton(x -> ChernoffComputations._cdf(x) - tau, ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox) # should consider replacing x-> construct for speed
end | 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.353308035220429;
0.3 -0.2751512847290148;
0.4 -0.13319637678583637;
0.5 0.0;
0.6 0.13319637678583637;
0.7 0.2751512847290147;
0.75 0.353308035220429;
0.8 0.4398276660488655;
0.9 0.6642351964332931;
0.95 0.8450811886357724;
0.975 0.9981810946684272;
0.99 1.17153434157313;
1.0 Inf
]
(0.0 <= tau && tau <= 1.0) || throw(DomainError(tau, "illegal value of tau"))
present = searchsortedfirst(precomputedquants[:, 1], tau)
if present <= size(precomputedquants, 1)
if tau == precomputedquants[present, 1]
return precomputedquants[present, 2]
end
end
# one good approximation of the quantiles can be computed using Normal(0.0, stdapprox) with stdapprox = 0.52
stdapprox = 0.52
dnorm = Normal(0.0, 1.0)
if tau < 0.001
return -newton(x -> tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, 1.0 - tau)*stdapprox)
end
if tau > 0.999
return newton(x -> 1.0 - tau - ChernoffComputations._cdfbar(x), ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox)
end
return newton(x -> ChernoffComputations._cdf(x) - tau, ChernoffComputations._pdf, quantile(dnorm, tau)*stdapprox) # should consider replacing x-> construct for speed
end | 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 = [
-10.0000000 0.004770878 0.02119061;
-9.2631579 0.005831228 0.02508110;
-8.5263158 0.007185598 0.02985598;
-7.7894737 0.008936705 0.03576749;
-7.0526316 0.011232802 0.04315901;
-6.3157895 0.014293449 0.05250781;
-5.5789474 0.018454000 0.06449163;
-4.8421053 0.024246394 0.08010122;
-4.1052632 0.032555467 0.10083623;
-3.3684211 0.044947194 0.12906978;
-2.6315789 0.064438597 0.16879238;
-1.8947368 0.097617334 0.22732053;
-1.1578947 0.162209719 0.32007314;
-0.4210526 0.333932302 0.49013645;
0.3157895 0.234346966 0.82757893;
##CHUNK 2
-6.3157895 0.014293449 0.05250781;
-5.5789474 0.018454000 0.06449163;
-4.8421053 0.024246394 0.08010122;
-4.1052632 0.032555467 0.10083623;
-3.3684211 0.044947194 0.12906978;
-2.6315789 0.064438597 0.16879238;
-1.8947368 0.097617334 0.22732053;
-1.1578947 0.162209719 0.32007314;
-0.4210526 0.333932302 0.49013645;
0.3157895 0.234346966 0.82757893;
1.0526316 0.070717323 0.92258764;
1.7894737 0.031620241 0.95773428;
2.5263158 0.016507946 0.97472202;
3.2631579 0.009427166 0.98399211;
4.0000000 0.005718906 0.98942757;
]
d = SkewedExponentialPower(0, 1, 0.5, 0.7)
for t in eachrow(test)
@test @inferred(pdf(d, t[1])) ≈ t[2] rtol=1e-5
##CHUNK 3
1.0526316 0.070717323 0.92258764;
1.7894737 0.031620241 0.95773428;
2.5263158 0.016507946 0.97472202;
3.2631579 0.009427166 0.98399211;
4.0000000 0.005718906 0.98942757;
]
d = SkewedExponentialPower(0, 1, 0.5, 0.7)
for t in eachrow(test)
@test @inferred(pdf(d, t[1])) ≈ t[2] rtol=1e-5
@test @inferred(logpdf(d, t[1])) ≈ log(t[2]) rtol=1e-5
@test @inferred(cdf(d, t[1])) ≈ t[3] rtol=1e-3
@test @inferred(logcdf(d, t[1])) ≈ log(t[3]) rtol=1e-3
end
test_distr(d, 10^6)
# relationship between sepd(μ, σ, p, α) and
# sepd(μ, σ, p, 1-α)
d1 = SkewedExponentialPower(0, 1, 0.1, 0.7)
d2 = SkewedExponentialPower(0, 1, 0.1, 0.3)
##CHUNK 4
dn = Normal(0, 1)
@test @inferred mean(d) ≈ mean(dn)
@test @inferred var(d) ≈ var(dn)
@test @inferred skewness(d) ≈ skewness(dn)
@test @inferred isapprox(kurtosis(d), kurtosis(dn), atol = 1/10^10)
@test @inferred pdf(d, 0.5) ≈ pdf(dn, 0.5)
@test @inferred cdf(d, 0.5) ≈ cdf(dn, 0.5)
@test @inferred quantile(d, 0.5) ≈ quantile(dn, 0.5)
test_distr(d, 10^6)
end
@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 = [
-10.0000000 0.004770878 0.02119061;
-9.2631579 0.005831228 0.02508110;
-8.5263158 0.007185598 0.02985598;
-7.7894737 0.008936705 0.03576749;
-7.0526316 0.011232802 0.04315901;
#FILE: Distributions.jl/test/univariate/continuous/chernoff.jl
##CHUNK 1
0.865 0.9540476043275662;
0.875 0.9559822554235589;
0.885 0.9578534391151732;
0.895 0.9596624048960603;
0.905 0.9614104126081986;
0.915 0.9630987307693821;
0.925 0.9647286349803182;
0.935 0.9663014063237074;
0.945 0.9678183298266878;
0.955 0.9692806929171217;
0.965 0.9706897839442293;
0.975 0.9720468907261572;
0.985 0.9733532991278337;
0.995 0.9746102916986603
]
pdftest = [
0.000 0.758345;
0.050 0.755123;
0.100 0.745532;
##CHUNK 2
0.965 0.9706897839442293;
0.975 0.9720468907261572;
0.985 0.9733532991278337;
0.995 0.9746102916986603
]
pdftest = [
0.000 0.758345;
0.050 0.755123;
0.100 0.745532;
0.150 0.729792;
0.200 0.708260;
0.250 0.681422;
0.300 0.649874;
0.350 0.614303;
0.400 0.575464;
0.450 0.534159;
0.500 0.491208;
0.550 0.447424;
0.600 0.403594;
#FILE: Distributions.jl/src/samplers/gamma.jl
##CHUNK 1
ia = 1.0/a
q0 = ia*@horner(ia,
0.0416666664,
0.0208333723,
0.0079849875,
0.0015746717,
-0.0003349403,
0.0003340332,
0.0006053049,
-0.0004701849,
0.0001710320)
if a <= 3.686
b = 0.463 + s + 0.178s2
σ = 1.235
c = 0.195/s - 0.079 + 0.16s
elseif a <= 13.022
b = 1.654 + 0.0076s2
σ = 1.68/s + 0.275
c = 0.062/s + 0.024
#FILE: Distributions.jl/test/truncate.jl
##CHUNK 1
# prior to patch #1727 this was offering 1.0000000000000002 > 1.
@test quantile(d, 1) ≤ d.upper && quantile(d, 1) ≈ d.upper
@test isa(quantile(d, ForwardDiff.Dual(1.,0.)), ForwardDiff.Dual)
end
@testset "cdf outside of [0, 1] (#1854)" begin
dist = truncated(Normal(2.5, 0.2); lower=0.0)
@test @inferred(cdf(dist, 3.741058503233821e-17)) === 0.0
@test @inferred(ccdf(dist, 3.741058503233821e-17)) === 1.0
@test @inferred(cdf(dist, 1.4354474178676617e-18)) === 0.0
@test @inferred(ccdf(dist, 1.4354474178676617e-18)) === 1.0
@test @inferred(cdf(dist, 8.834854780587132e-18)) === 0.0
@test @inferred(ccdf(dist, 8.834854780587132e-18)) === 1.0
dist = truncated(
Normal(2.122039143928797, 0.07327367710864985);
lower = 1.9521656132878236,
upper = 2.8274429454898398,
#FILE: Distributions.jl/test/truncated/normal.jl
##CHUNK 1
using Test
using Distributions, Random
rng = MersenneTwister(123)
@testset "Truncated normal, mean and variance" begin
@test mean(truncated(Normal(0,1),100,115)) ≈ 100.00999800099926070518490239457545847490332879043
@test mean(truncated(Normal(-2,3),50,70)) ≈ 50.171943499898757645751683644632860837133138152489
@test mean(truncated(Normal(0,2),-100,0)) ≈ -1.59576912160573071175978423973752747390343452465973
@test mean(truncated(Normal(0,1))) == 0
@test mean(truncated(Normal(0,1); lower=-Inf, upper=Inf)) == 0
@test mean(truncated(Normal(0,1); lower=0)) ≈ +√(2/π)
@test mean(truncated(Normal(0,1); lower=0, upper=Inf)) ≈ +√(2/π)
@test mean(truncated(Normal(0,1); upper=0)) ≈ -√(2/π)
@test mean(truncated(Normal(0,1); lower=-Inf, upper=0)) ≈ -√(2/π)
@test var(truncated(Normal(0,1),50,70)) ≈ 0.00039904318680389954790992722653605933053648912703600
@test var(truncated(Normal(-2,3); lower=50, upper=70)) ≈ 0.029373438107168350377591231295634273607812172191712
@test var(truncated(Normal(0,1))) == 1
@test var(truncated(Normal(0,1); lower=-Inf, upper=Inf)) == 1
@test var(truncated(Normal(0,1); lower=0)) ≈ 1 - 2/π
#CURRENT FILE: Distributions.jl/src/univariate/continuous/chernoff.jl
##CHUNK 1
### Random number generation
rand(d::Chernoff) = rand(default_rng(), d)
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
1.164660153310361
1.1191528874523227
1.0782281238946987
1.0406685077375248
1.0056599129954287
0.9726255909850547
0.9411372703351518
0.910863725882819
0.8815390956471935
|
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
1.164660153310361
1.1191528874523227
1.0782281238946987
1.0406685077375248
1.0056599129954287
0.9726255909850547
0.9411372703351518
0.910863725882819
0.8815390956471935
0.8529422519848634
0.8248826278765808
0.7971898990526088
0.769705944382039
0.7422780374708061
0.7147524811697309
0.6869679724643997
0.6587479056872714
0.6298905501492661
0.6001554584431008
0.5692432986584453
0.5367639126935895
0.5021821750911241
0.4647187417226889
0.42314920361072667
0.37533885097957154
0.31692143952775814
0.2358977457249061
1.0218214689661219e-7
]
y=[
0.02016386420423385
0.042162593823411566
0.06607475557706186
0.09147489698007219
0.11817165794330549
0.14606157249935905
0.17508555351826158
0.20521115629454248
0.2364240467790298
0.26872350680813245
0.3021199879039766
0.3366338395880132
0.37229479658922043
0.4091420247190392
0.4472246406136998
0.48660269400571066
0.5273486595545326
0.5695495447104147
0.6133097942704644
0.6587552778727138
0.7060388099508409
0.7553479187650504
0.8069160398536568
0.8610391369707446
0.9181013320624011
0.97861633948841
1.0432985878313983
1.113195213997703
1.1899583790598025
1.2764995726449935
1.3789927085182485
1.516689116183566
]
n = length(x)
i = rand(rng, 0:n-1)
r = (2.0*rand(rng)-1) * ((i>0) ? x[i] : A/y[1])
rabs = abs(r)
if rabs < x[i+1]
return r
end
s = (i>0) ? (y[i]+rand(rng)*(y[i+1]-y[i])) : rand(rng)*y[1]
if s < 2.0*ChernoffComputations._pdf(rabs)
return r
end
if i > 0
return rand(rng, d)
end
F0 = ChernoffComputations._cdf(A/y[1])
tau = 2.0*rand(rng)-1 # ~ U(-1,1)
tauabs = abs(tau)
return quantile(d, tauabs + (1-tauabs)*F0) * sign(tau)
end | 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
1.164660153310361
1.1191528874523227
1.0782281238946987
1.0406685077375248
1.0056599129954287
0.9726255909850547
0.9411372703351518
0.910863725882819
0.8815390956471935
0.8529422519848634
0.8248826278765808
0.7971898990526088
0.769705944382039
0.7422780374708061
0.7147524811697309
0.6869679724643997
0.6587479056872714
0.6298905501492661
0.6001554584431008
0.5692432986584453
0.5367639126935895
0.5021821750911241
0.4647187417226889
0.42314920361072667
0.37533885097957154
0.31692143952775814
0.2358977457249061
1.0218214689661219e-7
]
y=[
0.02016386420423385
0.042162593823411566
0.06607475557706186
0.09147489698007219
0.11817165794330549
0.14606157249935905
0.17508555351826158
0.20521115629454248
0.2364240467790298
0.26872350680813245
0.3021199879039766
0.3366338395880132
0.37229479658922043
0.4091420247190392
0.4472246406136998
0.48660269400571066
0.5273486595545326
0.5695495447104147
0.6133097942704644
0.6587552778727138
0.7060388099508409
0.7553479187650504
0.8069160398536568
0.8610391369707446
0.9181013320624011
0.97861633948841
1.0432985878313983
1.113195213997703
1.1899583790598025
1.2764995726449935
1.3789927085182485
1.516689116183566
]
n = length(x)
i = rand(rng, 0:n-1)
r = (2.0*rand(rng)-1) * ((i>0) ? x[i] : A/y[1])
rabs = abs(r)
if rabs < x[i+1]
return r
end
s = (i>0) ? (y[i]+rand(rng)*(y[i+1]-y[i])) : rand(rng)*y[1]
if s < 2.0*ChernoffComputations._pdf(rabs)
return r
end
if i > 0
return rand(rng, d)
end
F0 = ChernoffComputations._cdf(A/y[1])
tau = 2.0*rand(rng)-1 # ~ U(-1,1)
tauabs = abs(tau)
return quantile(d, tauabs + (1-tauabs)*F0) * sign(tau)
end | [
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
1.164660153310361
1.1191528874523227
1.0782281238946987
1.0406685077375248
1.0056599129954287
0.9726255909850547
0.9411372703351518
0.910863725882819
0.8815390956471935
0.8529422519848634
0.8248826278765808
0.7971898990526088
0.769705944382039
0.7422780374708061
0.7147524811697309
0.6869679724643997
0.6587479056872714
0.6298905501492661
0.6001554584431008
0.5692432986584453
0.5367639126935895
0.5021821750911241
0.4647187417226889
0.42314920361072667
0.37533885097957154
0.31692143952775814
0.2358977457249061
1.0218214689661219e-7
]
y=[
0.02016386420423385
0.042162593823411566
0.06607475557706186
0.09147489698007219
0.11817165794330549
0.14606157249935905
0.17508555351826158
0.20521115629454248
0.2364240467790298
0.26872350680813245
0.3021199879039766
0.3366338395880132
0.37229479658922043
0.4091420247190392
0.4472246406136998
0.48660269400571066
0.5273486595545326
0.5695495447104147
0.6133097942704644
0.6587552778727138
0.7060388099508409
0.7553479187650504
0.8069160398536568
0.8610391369707446
0.9181013320624011
0.97861633948841
1.0432985878313983
1.113195213997703
1.1899583790598025
1.2764995726449935
1.3789927085182485
1.516689116183566
]
n = length(x)
i = rand(rng, 0:n-1)
r = (2.0*rand(rng)-1) * ((i>0) ? x[i] : A/y[1])
rabs = abs(r)
if rabs < x[i+1]
return r
end
s = (i>0) ? (y[i]+rand(rng)*(y[i+1]-y[i])) : rand(rng)*y[1]
if s < 2.0*ChernoffComputations._pdf(rabs)
return r
end
if i > 0
return rand(rng, d)
end
F0 = ChernoffComputations._cdf(A/y[1])
tau = 2.0*rand(rng)-1 # ~ U(-1,1)
tauabs = abs(tau)
return quantile(d, tauabs + (1-tauabs)*F0) * sign(tau)
end | 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
1.164660153310361
1.1191528874523227
1.0782281238946987
1.0406685077375248
1.0056599129954287
0.9726255909850547
0.9411372703351518
0.910863725882819
0.8815390956471935
0.8529422519848634
0.8248826278765808
0.7971898990526088
0.769705944382039
0.7422780374708061
0.7147524811697309
0.6869679724643997
0.6587479056872714
0.6298905501492661
0.6001554584431008
0.5692432986584453
0.5367639126935895
0.5021821750911241
0.4647187417226889
0.42314920361072667
0.37533885097957154
0.31692143952775814
0.2358977457249061
1.0218214689661219e-7
]
y=[
0.02016386420423385
0.042162593823411566
0.06607475557706186
0.09147489698007219
0.11817165794330549
0.14606157249935905
0.17508555351826158
0.20521115629454248
0.2364240467790298
0.26872350680813245
0.3021199879039766
0.3366338395880132
0.37229479658922043
0.4091420247190392
0.4472246406136998
0.48660269400571066
0.5273486595545326
0.5695495447104147
0.6133097942704644
0.6587552778727138
0.7060388099508409
0.7553479187650504
0.8069160398536568
0.8610391369707446
0.9181013320624011
0.97861633948841
1.0432985878313983
1.113195213997703
1.1899583790598025
1.2764995726449935
1.3789927085182485
1.516689116183566
]
n = length(x)
i = rand(rng, 0:n-1)
r = (2.0*rand(rng)-1) * ((i>0) ? x[i] : A/y[1])
rabs = abs(r)
if rabs < x[i+1]
return r
end
s = (i>0) ? (y[i]+rand(rng)*(y[i+1]-y[i])) : rand(rng)*y[1]
if s < 2.0*ChernoffComputations._pdf(rabs)
return r
end
if i > 0
return rand(rng, d)
end
F0 = ChernoffComputations._cdf(A/y[1])
tau = 2.0*rand(rng)-1 # ~ U(-1,1)
tauabs = abs(tau)
return quantile(d, tauabs + (1-tauabs)*F0) * sign(tau)
end | 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 = [
-10.0000000 0.004770878 0.02119061;
-9.2631579 0.005831228 0.02508110;
-8.5263158 0.007185598 0.02985598;
-7.7894737 0.008936705 0.03576749;
-7.0526316 0.011232802 0.04315901;
-6.3157895 0.014293449 0.05250781;
-5.5789474 0.018454000 0.06449163;
-4.8421053 0.024246394 0.08010122;
-4.1052632 0.032555467 0.10083623;
-3.3684211 0.044947194 0.12906978;
-2.6315789 0.064438597 0.16879238;
-1.8947368 0.097617334 0.22732053;
-1.1578947 0.162209719 0.32007314;
-0.4210526 0.333932302 0.49013645;
0.3157895 0.234346966 0.82757893;
##CHUNK 2
-6.3157895 0.014293449 0.05250781;
-5.5789474 0.018454000 0.06449163;
-4.8421053 0.024246394 0.08010122;
-4.1052632 0.032555467 0.10083623;
-3.3684211 0.044947194 0.12906978;
-2.6315789 0.064438597 0.16879238;
-1.8947368 0.097617334 0.22732053;
-1.1578947 0.162209719 0.32007314;
-0.4210526 0.333932302 0.49013645;
0.3157895 0.234346966 0.82757893;
1.0526316 0.070717323 0.92258764;
1.7894737 0.031620241 0.95773428;
2.5263158 0.016507946 0.97472202;
3.2631579 0.009427166 0.98399211;
4.0000000 0.005718906 0.98942757;
]
d = SkewedExponentialPower(0, 1, 0.5, 0.7)
for t in eachrow(test)
@test @inferred(pdf(d, t[1])) ≈ t[2] rtol=1e-5
#FILE: Distributions.jl/test/univariate/continuous/chernoff.jl
##CHUNK 1
0.665 0.9002661976867428;
0.675 0.9037015359952119;
0.685 0.9070532266935508;
0.695 0.9103219523993228;
0.705 0.9135084400870754;
0.715 0.9166134594908737;
0.725 0.9196378215191889;
0.735 0.9225823766240466;
0.745 0.9254480131350427;
0.755 0.928235655591972;
0.765 0.9309462630294286;
0.775 0.9335808272718444;
0.785 0.9361403712094327;
0.795 0.9386259470397855;
0.805 0.9410386345416801;
0.815 0.9433795393000659;
0.825 0.9456497909787722;
0.835 0.9478505415455782;
0.845 0.9499829635303033;
0.855 0.9520482483056357;
##CHUNK 2
0.765 0.9309462630294286;
0.775 0.9335808272718444;
0.785 0.9361403712094327;
0.795 0.9386259470397855;
0.805 0.9410386345416801;
0.815 0.9433795393000659;
0.825 0.9456497909787722;
0.835 0.9478505415455782;
0.845 0.9499829635303033;
0.855 0.9520482483056357;
0.865 0.9540476043275662;
0.875 0.9559822554235589;
0.885 0.9578534391151732;
0.895 0.9596624048960603;
0.905 0.9614104126081986;
0.915 0.9630987307693821;
0.925 0.9647286349803182;
0.935 0.9663014063237074;
0.945 0.9678183298266878;
0.955 0.9692806929171217;
##CHUNK 3
0.865 0.9540476043275662;
0.875 0.9559822554235589;
0.885 0.9578534391151732;
0.895 0.9596624048960603;
0.905 0.9614104126081986;
0.915 0.9630987307693821;
0.925 0.9647286349803182;
0.935 0.9663014063237074;
0.945 0.9678183298266878;
0.955 0.9692806929171217;
0.965 0.9706897839442293;
0.975 0.9720468907261572;
0.985 0.9733532991278337;
0.995 0.9746102916986603
]
pdftest = [
0.000 0.758345;
0.050 0.755123;
0.100 0.745532;
##CHUNK 4
0.165 0.6232176009794599;
0.175 0.6304360010992436;
0.185 0.6376113008624671;
0.195 0.6447412908097765;
0.205 0.6518238023240649;
0.215 0.6588567094682105;
0.225 0.6658379307650819;
0.235 0.6727654309193446;
0.245 0.6796372224828434;
0.255 0.6864513674498119;
0.265 0.6932059787930698;
0.275 0.6998992219329853;
0.285 0.7065293161345655;
0.295 0.7130945358373242;
0.305 0.7195932119132353;
0.315 0.7260237328492151;
0.325 0.7323845458573087;
0.335 0.7386741579064688;
0.345 0.7448911366812273;
0.355 0.7510341114556635;
#CURRENT FILE: Distributions.jl/src/univariate/continuous/chernoff.jl
##CHUNK 1
-5.520559828095551
-6.786708090071759
-7.944133587120853
-9.02265085334098
-10.040174341558085
-11.008524303733262
-11.936015563236262
-12.828776752865757
-13.691489035210719
-14.527829951775335
-15.340755135977997
-16.132685156945772
-16.90563399742994
-17.66130010569706
]
const airyai_prime=[
0.7012108227206906
-0.8031113696548534
0.865204025894141
-0.9108507370495821
##CHUNK 2
1.063018673013022e-17
-1.26451831871265e-19
1.2954000902764143e-21
-1.1437790369170514e-23
8.543413293195206e-26
-5.05879944592705e-28
]
const airyai_roots=[
-2.338107410459767
-4.08794944413097
-5.520559828095551
-6.786708090071759
-7.944133587120853
-9.02265085334098
-10.040174341558085
-11.008524303733262
-11.936015563236262
-12.828776752865757
-13.691489035210719
-14.527829951775335
##CHUNK 3
-15.340755135977997
-16.132685156945772
-16.90563399742994
-17.66130010569706
]
const airyai_prime=[
0.7012108227206906
-0.8031113696548534
0.865204025894141
-0.9108507370495821
0.9473357094415571
-0.9779228085695176
1.0043701226603126
-1.0277386888207862
1.0487206485881893
-1.0677938591574279
1.0853028313507
-1.1015045702774968
1.1165961779326556
-1.1307323104931881
##CHUNK 4
0.6666666666666666
0.021164021164021163
-0.0007893341226674574
1.9520978781876193e-5
-3.184888134149933e-7
2.4964953625552273e-9
3.6216439304006735e-11
-1.874438299727797e-12
4.393984966701305e-14
-7.57237085924526e-16
1.063018673013022e-17
-1.26451831871265e-19
1.2954000902764143e-21
-1.1437790369170514e-23
8.543413293195206e-26
-5.05879944592705e-28
]
const airyai_roots=[
-2.338107410459767
-4.08794944413097
|
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 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end
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
##CHUNK 2
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 = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
##CHUNK 3
elseif ξ < 0
# y(x) = y(μ - σ / ξ) = -1 if x > μ - σ / ξ (upper bound)
-log1p(max(z * ξ, -1)) / ξ
else
-log1p(z * ξ) / ξ
end
end
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
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 / ξ : T(Inf)
elseif 0 < p < 1
##CHUNK 4
end
return p
end
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)) / ξ
else
-log1p(z * ξ) / ξ
end
end
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# 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 / μ
#CURRENT 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(t) - t
end
end
end
end
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
##CHUNK 2
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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
##CHUNK 3
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
end
##CHUNK 4
end
#### Support
insupport(d::GeneralizedExtremeValue, x::Real) = minimum(d) <= x <= maximum(d)
#### Evaluation
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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
##CHUNK 5
end
function quantile(d::GeneralizedExtremeValue, p::Real)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * (-log(-log(p)))
else
return μ + σ * ((-log(p))^(-ξ) - 1) / ξ
end
end
#### Support
insupport(d::GeneralizedExtremeValue, x::Real) = minimum(d) <= x <= maximum(d)
#### Evaluation
|
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
end | 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
end | [
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
end | 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
end | 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.ξ * log(u)) / d.ξ
end
return d.μ + d.σ * rd
end
##CHUNK 2
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
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()
##CHUNK 3
return T(Inf)
end
end
function var(d::GeneralizedPareto{T}) where {T<:Real}
if d.ξ < 0.5
return d.σ^2 / ((1 - d.ξ)^2 * (1 - 2 * d.ξ))
else
return T(Inf)
end
end
function skewness(d::GeneralizedPareto{T}) where {T<:Real}
(μ, σ, ξ) = params(d)
if ξ < (1/3)
return 2(1 + ξ) * sqrt(1 - 2ξ) / (1 - 3ξ)
else
return T(Inf)
end
#FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
end
function rand(rng::AbstractRNG, d::Beta{T}) where T
(α, β) = params(d)
if (α ≤ 1.0) && (β ≤ 1.0)
while true
u = rand(rng)
v = rand(rng)
x = u^inv(α)
y = v^inv(β)
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
logX -= logM
logY -= logM
return exp(logX - log(exp(logX) + exp(logY)))
#CURRENT 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(t) - t
end
end
end
end
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
##CHUNK 2
end
function mean(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * MathConstants.γ
elseif ξ < 1
return μ + σ * (gamma(1 - ξ) - 1) / ξ
else
return T(Inf)
end
end
function mode(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ
else
##CHUNK 3
return T(Inf)
end
end
function mode(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ
else
return μ + σ * ((1 + ξ) ^ (-ξ) - 1) / ξ
end
end
function var(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return σ ^2 * π^2 / 6
elseif ξ < 1/2
##CHUNK 4
return μ + σ * ((1 + ξ) ^ (-ξ) - 1) / ξ
end
end
function var(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return σ ^2 * π^2 / 6
elseif ξ < 1/2
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
##CHUNK 5
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
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)
##CHUNK 6
g(d::GeneralizedExtremeValue, k::Real) = gamma(1 - k * d.ξ) # This should not be exported.
function median(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps() # ξ == 0
return μ - σ * log(log(2))
else
return μ + σ * (log(2) ^ (- ξ) - 1) / ξ
end
end
function mean(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * MathConstants.γ
elseif ξ < 1
return μ + σ * (gamma(1 - ξ) - 1) / ξ
else
|
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 = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end | 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 = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end | [
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 = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end | 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 = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end | 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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
##CHUNK 2
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
end
##CHUNK 3
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
##CHUNK 4
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
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)
##CHUNK 5
end
#### Support
insupport(d::GeneralizedExtremeValue, x::Real) = minimum(d) <= x <= maximum(d)
#### Evaluation
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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
2(α + s) / (β - 3) * sqrt((β - 2) / (α * s))
else
return T(NaN)
end
end
#### Evaluation
function logpdf(d::BetaPrime, x::Real)
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
#FILE: Distributions.jl/src/univariate/continuous/cosine.jl
##CHUNK 1
logpdf(d::Cosine, x::Real) = log(pdf(d, x))
function cdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return zero(T)
end
if x > d.μ + d.σ
return one(T)
end
z = (x - d.μ) / d.σ
(1 + z + sinpi(z) * invπ) / 2
end
function ccdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return one(T)
end
if x > d.μ + d.σ
return zero(T)
end
#CURRENT FILE: Distributions.jl/src/univariate/continuous/generalizedpareto.jl
##CHUNK 1
return T(Inf)
end
end
#### Evaluation
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)) / ξ
else
-log1p(z * ξ) / ξ
end
end
##CHUNK 2
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)) / ξ
else
-log1p(z * ξ) / ξ
end
end
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
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)
##CHUNK 3
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
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 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
|
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)) / ξ
else
-log1p(z * ξ) / ξ
end
end | 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)) / ξ
else
-log1p(z * ξ) / ξ
end
end | [
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)) / ξ
else
-log1p(z * ξ) / ξ
end
end | 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)) / ξ
else
-log1p(z * ξ) / ξ
end
end | 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 (t^(ξ + 1) * exp(- t)) / σ
end
end
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)
##CHUNK 2
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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
##CHUNK 3
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
end
##CHUNK 4
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
##CHUNK 5
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
cdf(d::GeneralizedExtremeValue, x::Real) = exp(logcdf(d, x))
ccdf(d::GeneralizedExtremeValue, x::Real) = - expm1(logcdf(d, x))
logccdf(d::GeneralizedExtremeValue, x::Real) = log1mexp(logcdf(d, x))
#### Sampling
##CHUNK 6
g(d::GeneralizedExtremeValue, k::Real) = gamma(1 - k * d.ξ) # This should not be exported.
function median(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps() # ξ == 0
return μ - σ * log(log(2))
else
return μ + σ * (log(2) ^ (- ξ) - 1) / ξ
end
end
function mean(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * MathConstants.γ
elseif ξ < 1
return μ + σ * (gamma(1 - ξ) - 1) / ξ
else
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
2(α + s) / (β - 3) * sqrt((β - 2) / (α * s))
else
return T(NaN)
end
end
#### Evaluation
function logpdf(d::BetaPrime, x::Real)
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
#CURRENT 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 = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
##CHUNK 2
# 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 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
logcdf(d::GeneralizedPareto, x::Real) = log1mexp(logccdf(d, x))
##CHUNK 3
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)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
end
|
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)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
end | 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)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
end | [
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)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
end | 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)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
end | 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(t) - t
end
end
end
end
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
##CHUNK 2
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
end
##CHUNK 3
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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
##CHUNK 4
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
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)
##CHUNK 5
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
end
##CHUNK 6
return T(Inf)
end
end
function mode(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ
else
return μ + σ * ((1 + ξ) ^ (-ξ) - 1) / ξ
end
end
function var(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return σ ^2 * π^2 / 6
elseif ξ < 1/2
#CURRENT 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 = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
##CHUNK 2
return T(Inf)
end
end
function var(d::GeneralizedPareto{T}) where {T<:Real}
if d.ξ < 0.5
return d.σ^2 / ((1 - d.ξ)^2 * (1 - 2 * d.ξ))
else
return T(Inf)
end
end
function skewness(d::GeneralizedPareto{T}) where {T<:Real}
(μ, σ, ξ) = params(d)
if ξ < (1/3)
return 2(1 + ξ) * sqrt(1 - 2ξ) / (1 - 3ξ)
else
return T(Inf)
end
##CHUNK 3
# 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 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end
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
##CHUNK 4
end
function kurtosis(d::GeneralizedPareto{T}) where T<:Real
(μ, σ, ξ) = params(d)
if ξ < 0.25
k1 = (1 - 2ξ) * (2ξ^2 + ξ + 3)
k2 = (1 - 3ξ) * (1 - 4ξ)
return 3k1 / k2 - 3
else
return T(Inf)
end
end
#### Evaluation
function logpdf(d::GeneralizedPareto{T}, x::Real) where T<:Real
(μ, σ, ξ) = params(d)
|
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))
else
rd = expm1(- ξ * log(- log(u))) / ξ
end
return μ + σ * rd
end
##CHUNK 2
- y^(-1/ξ)
end
end
cdf(d::GeneralizedExtremeValue, x::Real) = exp(logcdf(d, x))
ccdf(d::GeneralizedExtremeValue, x::Real) = - expm1(logcdf(d, x))
logccdf(d::GeneralizedExtremeValue, x::Real) = log1mexp(logcdf(d, x))
#### Sampling
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))) / ξ
#FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
end
# From Knuth
function rand(rng::AbstractRNG, s::BetaSampler)
if s.γ
g1 = rand(rng, s.s1)
g2 = rand(rng, s.s2)
return g1 / (g1 + g2)
else
iα = s.iα
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)
return x / (x + y)
else
##CHUNK 2
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)
return x / (x + y)
else
logX = log(u) * iα
logY = log(v) * iβ
logM = logX > logY ? logX : logY
logX -= logM
logY -= logM
return exp(logX - log(exp(logX) + exp(logY)))
end
end
end
end
#FILE: Distributions.jl/src/samplers/vonmises.jl
##CHUNK 1
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)
if d + e <= 0.25
t = d / e
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) + 1 >= c
break
end
#CURRENT 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 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
##CHUNK 2
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 = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
##CHUNK 3
"""
GeneralizedPareto(μ, σ, ξ)
The *Generalized Pareto distribution* (GPD) with shape parameter `ξ`, scale `σ` and location `μ` has probability density function
```math
f(x; \\mu, \\sigma, \\xi) = \\begin{cases}
\\frac{1}{\\sigma}(1 + \\xi \\frac{x - \\mu}{\\sigma} )^{-\\frac{1}{\\xi} - 1} & \\text{for } \\xi \\neq 0 \\\\
\\frac{1}{\\sigma} e^{-\\frac{\\left( x - \\mu \\right) }{\\sigma}} & \\text{for } \\xi = 0
\\end{cases}~,
##CHUNK 4
return T(Inf)
end
end
function var(d::GeneralizedPareto{T}) where {T<:Real}
if d.ξ < 0.5
return d.σ^2 / ((1 - d.ξ)^2 * (1 - 2 * d.ξ))
else
return T(Inf)
end
end
function skewness(d::GeneralizedPareto{T}) where {T<:Real}
(μ, σ, ξ) = params(d)
if ξ < (1/3)
return 2(1 + ξ) * sqrt(1 - 2ξ) / (1 - 3ξ)
else
return T(Inf)
end
##CHUNK 5
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
end
#### Sampling
|
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end | 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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end | [
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end | 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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end | 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 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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
##CHUNK 2
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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
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 μ + copysign(z, r)
#FILE: Distributions.jl/src/univariate/continuous/cosine.jl
##CHUNK 1
logpdf(d::Cosine, x::Real) = log(pdf(d, x))
function cdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return zero(T)
end
if x > d.μ + d.σ
return one(T)
end
z = (x - d.μ) / d.σ
(1 + z + sinpi(z) * invπ) / 2
end
function ccdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return one(T)
end
if x > d.μ + d.σ
return zero(T)
end
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
2(α + s) / (β - 3) * sqrt((β - 2) / (α * s))
else
return T(NaN)
end
end
#### Evaluation
function logpdf(d::BetaPrime, x::Real)
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
#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 = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
#CURRENT FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# 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)
##CHUNK 2
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end
##CHUNK 3
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : 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
@quantile_newton InverseGaussian
##CHUNK 4
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 logccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
##CHUNK 5
μ, λ = params(d)
return sqrt(λ / (twoπ * x^3)) * exp(-λ * (x - μ)^2 / (2μ^2 * x))
else
return zero(T)
end
end
function logpdf(d::InverseGaussian{T}, x::Real) where T<:Real
if x > 0
μ, λ = params(d)
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
function ccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
|
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | 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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | [
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | 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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end | 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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
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 μ + copysign(z, r)
##CHUNK 2
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 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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
#FILE: Distributions.jl/src/univariate/continuous/cosine.jl
##CHUNK 1
logpdf(d::Cosine, x::Real) = log(pdf(d, x))
function cdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return zero(T)
end
if x > d.μ + d.σ
return one(T)
end
z = (x - d.μ) / d.σ
(1 + z + sinpi(z) * invπ) / 2
end
function ccdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return one(T)
end
if x > d.μ + d.σ
return zero(T)
end
#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 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
##CHUNK 2
elseif ξ < 0
# y(x) = y(μ - σ / ξ) = -1 if x > μ - σ / ξ (upper bound)
-log1p(max(z * ξ, -1)) / ξ
else
-log1p(z * ξ) / ξ
end
end
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
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 / ξ : T(Inf)
elseif 0 < p < 1
#CURRENT FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(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)
##CHUNK 2
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : 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
@quantile_newton InverseGaussian
##CHUNK 3
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 logccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
##CHUNK 4
μ, λ = params(d)
return sqrt(λ / (twoπ * x^3)) * exp(-λ * (x - μ)^2 / (2μ^2 * x))
else
return zero(T)
end
end
function logpdf(d::InverseGaussian{T}, x::Real) where T<:Real
if x > 0
μ, λ = params(d)
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
function cdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
##CHUNK 5
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
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 = clamp(normcdf(u * (v - 1)) + exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? one(z) : z
end
|
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 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
#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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
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 μ + copysign(z, r)
##CHUNK 2
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 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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
##CHUNK 3
end
function logpdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
return log(p / (2 * α)) - loggamma(1 / p) - (abs(x - μ) / α)^p
end
# To determine the CDF, the incomplete gamma function is required.
# The CDF of the Gamma distribution provides this, with the necessary 1/Γ(a) normalization.
function cdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
return _normcdf_pgeneralizedgaussian(p, (x - μ) / α)
end
function ccdf(d::PGeneralizedGaussian, x::Real)
μ, α, p = params(d)
return _normcdf_pgeneralizedgaussian(p, (μ - x) / α)
end
function _normcdf_pgeneralizedgaussian(p::Real, z::Real)
r = abs(z)^p
d = Gamma(inv(p), 1)
if z < 0
#FILE: Distributions.jl/src/univariate/continuous/weibull.jl
##CHUNK 1
end
#### Evaluation
function pdf(d::Weibull, x::Real)
α, θ = params(d)
z = abs(x) / θ
res = (α / θ) * z^(α - 1) * exp(-z^α)
x < 0 || isinf(x) ? zero(res) : res
end
function logpdf(d::Weibull, x::Real)
α, θ = params(d)
z = abs(x) / θ
res = log(α / θ) + xlogy(α - 1, z) - z^α
x < 0 || isinf(x) ? oftype(res, -Inf) : res
end
zval(d::Weibull, x::Real) = (max(x, 0) / d.θ) ^ d.α
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
return isinf(x) && x > 0 ? oftype(z, Inf) : z
end
xval(::BetaPrime, z::Real) = z / (1 - z)
for f in (:cdf, :ccdf, :logcdf, :logccdf)
@eval $f(d::BetaPrime, x::Real) = $f(Beta(d.α, d.β; check_args=false), zval(d, x))
end
for f in (:quantile, :cquantile, :invlogcdf, :invlogccdf)
@eval $f(d::BetaPrime, p::Real) = xval(d, $f(Beta(d.α, d.β; check_args=false), p))
#CURRENT FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : z
end
function logccdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
v = y / μ
##CHUNK 2
# otherwise `NaN` is returned for `+Inf`
return isinf(x) && x > 0 ? zero(z) : 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
@quantile_newton InverseGaussian
##CHUNK 3
μ, λ = params(d)
return sqrt(λ / (twoπ * x^3)) * exp(-λ * (x - μ)^2 / (2μ^2 * x))
else
return zero(T)
end
end
function logpdf(d::InverseGaussian{T}, x::Real) where T<:Real
if x > 0
μ, λ = params(d)
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
function cdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
##CHUNK 4
μ, λ = params(d)
r = μ / λ
μ * (sqrt(1 + (3r/2)^2) - (3r/2))
end
#### Evaluation
function pdf(d::InverseGaussian{T}, x::Real) where T<:Real
if x > 0
μ, λ = params(d)
return sqrt(λ / (twoπ * x^3)) * exp(-λ * (x - μ)^2 / (2μ^2 * x))
else
return zero(T)
end
end
function logpdf(d::InverseGaussian{T}, x::Real) where T<:Real
if x > 0
μ, λ = params(d)
|
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 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
##CHUNK 2
elseif ξ < 0
# y(x) = y(μ - σ / ξ) = -1 if x > μ - σ / ξ (upper bound)
-log1p(max(z * ξ, -1)) / ξ
else
-log1p(z * ξ) / ξ
end
end
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
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 / ξ : T(Inf)
elseif 0 < p < 1
#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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
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 μ + copysign(z, r)
##CHUNK 2
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 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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
return isinf(x) && x > 0 ? oftype(z, Inf) : z
end
xval(::BetaPrime, z::Real) = z / (1 - z)
for f in (:cdf, :ccdf, :logcdf, :logccdf)
@eval $f(d::BetaPrime, x::Real) = $f(Beta(d.α, d.β; check_args=false), zval(d, x))
end
for f in (:quantile, :cquantile, :invlogcdf, :invlogccdf)
@eval $f(d::BetaPrime, p::Real) = xval(d, $f(Beta(d.α, d.β; check_args=false), p))
##CHUNK 2
2(α + s) / (β - 3) * sqrt((β - 2) / (α * s))
else
return T(NaN)
end
end
#### Evaluation
function logpdf(d::BetaPrime, x::Real)
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
#FILE: Distributions.jl/src/univariate/continuous/kumaraswamy.jl
##CHUNK 1
function logpdf(d::Kumaraswamy, x::Real)
a, b = params(d)
_x = clamp(x, 0, 1) # Ensures we can still get a value when outside the support
y = log(a) + log(b) + xlogy(a - 1, _x) + xlog1py(b - 1, -_x^a)
return x < 0 || x > 1 ? oftype(y, -Inf) : y
end
function ccdf(d::Kumaraswamy, x::Real)
a, b = params(d)
y = (1 - clamp(x, 0, 1)^a)^b
return x < 0 ? one(y) : (x > 1 ? zero(y) : y)
end
cdf(d::Kumaraswamy, x::Real) = 1 - ccdf(d, x)
function logccdf(d::Kumaraswamy, x::Real)
a, b = params(d)
y = b * log1p(-clamp(x, 0, 1)^a)
return x < 0 ? zero(y) : (x > 1 ? oftype(y, -Inf) : y)
#CURRENT FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
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 = clamp(normccdf(u * (v - 1)) - exp(2λ / μ + normlogcdf(-u * (v + 1))), 0, 1)
# 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 / μ
##CHUNK 2
# 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
@quantile_newton InverseGaussian
##CHUNK 3
μ, λ = params(d)
return sqrt(λ / (twoπ * x^3)) * exp(-λ * (x - μ)^2 / (2μ^2 * x))
else
return zero(T)
end
end
function logpdf(d::InverseGaussian{T}, x::Real) where T<:Real
if x > 0
μ, λ = params(d)
return (log(λ) - (log2π + 3log(x)) - λ * (x - μ)^2 / (μ^2 * x))/2
else
return -T(Inf)
end
end
function cdf(d::InverseGaussian, x::Real)
μ, λ = params(d)
y = max(x, 0)
u = sqrt(λ / y)
|
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)
return x / (x + y)
else
logX = log(u) * iα
logY = log(v) * iβ
logM = logX > logY ? logX : logY
logX -= logM
logY -= logM
return exp(logX - log(exp(logX) + exp(logY)))
end
end
end
end
##CHUNK 2
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
logX -= logM
logY -= logM
return exp(logX - log(exp(logX) + exp(logY)))
end
end
end
else
g1 = rand(rng, Gamma(α, one(T)))
g2 = rand(rng, Gamma(β, one(T)))
return g1 / (g1 + g2)
end
end
##CHUNK 3
end
function rand(rng::AbstractRNG, d::Beta{T}) where T
(α, β) = params(d)
if (α ≤ 1.0) && (β ≤ 1.0)
while true
u = rand(rng)
v = rand(rng)
x = u^inv(α)
y = v^inv(β)
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
logX -= logM
logY -= logM
return exp(logX - log(exp(logX) + exp(logY)))
#FILE: Distributions.jl/src/univariate/continuous/ksdist.jl
##CHUNK 1
return exp(logfactorial(n)+n*(log(2*b-1)-log(n)))
elseif x >= 1
return 1.0
elseif b >= n-1
return 1 - 2*(1-x)^n
end
a = b*x
if a >= 18
return 1.0
elseif n <= 10_000
if a <= 4
return cdf_durbin(d,x)
else
return 1 - ccdf_miller(d,x)
end
else
return cdf(Kolmogorov(),sqrt(a))
end
end
##CHUNK 2
function ccdf(d::KSDist,x::Float64)
n = d.n
b = x*n
# Ruben and Gambino (1982) known exact values
if b <= 0.5
return 1.0
elseif b <= 1
return 1-exp(logfactorial(n)+n*(log(2*b-1)-log(n)))
elseif x >= 1
return 0.0
elseif b >= n-1
return 2*(1-x)^n
end
a = b*x
if a >= 370
return 0.0
elseif a >= 4 || (n > 140 && a >= 2.2)
return ccdf_miller(d,x)
#FILE: Distributions.jl/src/univariate/continuous/lognormal.jl
##CHUNK 1
function pdf(d::LogNormal, x::Real)
if x ≤ zero(x)
logx = log(zero(x))
x = one(x)
else
logx = log(x)
end
return pdf(Normal(d.μ, d.σ), logx) / x
end
function logpdf(d::LogNormal, x::Real)
if x ≤ zero(x)
logx = log(zero(x))
b = zero(logx)
else
logx = log(x)
b = logx
end
return logpdf(Normal(d.μ, d.σ), logx) - b
end
#FILE: Distributions.jl/src/univariate/continuous/kolmogorov.jl
##CHUNK 1
if x <= 0
return 0.0
elseif x <= 1
c = π/(2*x)
s = 0.0
for i = 1:20
k = ((2i - 1)*c)^2
s += (k - 1)*exp(-k/2)
end
return sqrt2π*s/x^2
else
s = 0.0
for i = 1:20
s += (iseven(i) ? -1 : 1)*i^2*exp(-2(i*x)^2)
end
return 8*x*s
end
end
logpdf(d::Kolmogorov, x::Real) = log(pdf(d, x))
#FILE: Distributions.jl/src/univariate/continuous/logitnormal.jl
##CHUNK 1
#### Evaluation
#TODO check pd and logpdf
function pdf(d::LogitNormal{T}, x::Real) where T<:Real
if zero(x) < x < one(x)
return normpdf(d.μ, d.σ, logit(x)) / (x * (1-x))
else
return T(0)
end
end
function logpdf(d::LogitNormal{T}, x::Real) where T<:Real
if zero(x) < x < one(x)
lx = logit(x)
return normlogpdf(d.μ, d.σ, lx) - log(x) - log1p(-x)
else
return -T(Inf)
end
end
#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(t) - t
end
end
end
end
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
#CURRENT FILE: Distributions.jl/src/univariate/continuous/lindley.jl
##CHUNK 1
cdf(d::Lindley, y::Real) = 1 - ccdf(d, y)
logcdf(d::Lindley, y::Real) = log1mexp(logccdf(d, y))
# Jodrá, P. (2010). Computer generation of random variables with Lindley or
# Poisson–Lindley distribution via the Lambert W function. Mathematics and Computers
# in Simulation, 81(4), 851–859.
#
# Only the -1 branch of the Lambert W functions is required since the argument is
# in (-1/e, 0) for all θ > 0 and 0 < q < 1.
function quantile(d::Lindley, q::Real)
θ = shape(d)
return -(1 + (1 + _lambertwm1((1 + θ) * (q - 1) / exp(1 + θ))) / θ)
end
# Lóczi, L. (2022). Guaranteed- and high-precision evaluation of the Lambert W function.
# Applied Mathematics and Computation, 433, 127406.
#
# Compute W₋₁(x) for x ∈ (-1/e, 0) using formula (27) in Lóczi. By Theorem 2.23, the
|
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 Pareto(α, θ)
end | 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 Pareto(α, θ)
end | [
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 Pareto(α, θ)
end | 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 Pareto(α, θ)
end | 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 = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
##CHUNK 2
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 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
#FILE: Distributions.jl/src/univariate/continuous/frechet.jl
##CHUNK 1
end
function entropy(d::Frechet)
1 + MathConstants.γ / d.α + MathConstants.γ + log(d.θ / d.α)
end
#### Evaluation
function logpdf(d::Frechet{T}, x::Real) where T<:Real
(α, θ) = params(d)
if x > 0
z = θ / x
return log(α / θ) + (1 + α) * log(z) - z^α
else
return -T(Inf)
end
end
zval(d::Frechet, x::Real) = (d.θ / max(x, 0))^d.α
#FILE: Distributions.jl/src/univariate/continuous/weibull.jl
##CHUNK 1
invlogccdf(d::Weibull, lp::Real) = xval(d, -lp)
function gradlogpdf(d::Weibull{T}, x::Real) where T<:Real
if insupport(Weibull, x)
α, θ = params(d)
(α - 1) / x - α * x^(α - 1) / (θ^α)
else
zero(T)
end
end
#### Sampling
rand(rng::AbstractRNG, d::Weibull) = xval(d, randexp(rng))
#### Fit model
"""
fit_mle(::Type{<:Weibull}, x::AbstractArray{<:Real};
#CURRENT FILE: Distributions.jl/src/univariate/continuous/pareto.jl
##CHUNK 1
params(d::Pareto) = (d.α, d.θ)
@inline partype(d::Pareto{T}) where {T<:Real} = T
#### Statistics
function mean(d::Pareto{T}) where T<:Real
(α, θ) = params(d)
α > 1 ? α * θ / (α - 1) : T(Inf)
end
median(d::Pareto) = ((α, θ) = params(d); θ * 2^(1/α))
mode(d::Pareto) = d.θ
function var(d::Pareto{T}) where T<:Real
(α, θ) = params(d)
α > 2 ? (θ^2 * α) / ((α - 1)^2 * (α - 2)) : T(Inf)
end
function skewness(d::Pareto{T}) where T<:Real
##CHUNK 2
α = shape(d)
α > 3 ? ((2(1 + α)) / (α - 3)) * sqrt((α - 2) / α) : T(NaN)
end
function kurtosis(d::Pareto{T}) where T<:Real
α = shape(d)
α > 4 ? (6(α^3 + α^2 - 6α - 2)) / (α * (α - 3) * (α - 4)) : T(NaN)
end
entropy(d::Pareto) = ((α, θ) = params(d); log(θ / α) + 1 / α + 1)
#### Evaluation
function pdf(d::Pareto{T}, x::Real) where T<:Real
(α, θ) = params(d)
x >= θ ? α * (θ / x)^α * (1/x) : zero(T)
end
function logpdf(d::Pareto{T}, x::Real) where T<:Real
##CHUNK 3
"""
Pareto(α,θ)
The *Pareto distribution* with shape `α` and scale `θ` has probability density function
```math
f(x; \\alpha, \\theta) = \\frac{\\alpha \\theta^\\alpha}{x^{\\alpha + 1}}, \\quad x \\ge \\theta
```
```julia
##CHUNK 4
Pareto() # Pareto distribution with unit shape and unit scale, i.e. Pareto(1, 1)
Pareto(α) # Pareto distribution with shape α and unit scale, i.e. Pareto(α, 1)
Pareto(α, θ) # Pareto distribution with shape α and scale θ
params(d) # Get the parameters, i.e. (α, θ)
shape(d) # Get the shape parameter, i.e. α
scale(d) # Get the scale parameter, i.e. θ
```
External links
* [Pareto distribution on Wikipedia](http://en.wikipedia.org/wiki/Pareto_distribution)
"""
struct Pareto{T<:Real} <: ContinuousUnivariateDistribution
α::T
θ::T
Pareto{T}(α::T, θ::T) where {T} = new{T}(α, θ)
end
function Pareto(α::T, θ::T; check_args::Bool=true) where {T <: Real}
##CHUNK 5
#### Evaluation
function pdf(d::Pareto{T}, x::Real) where T<:Real
(α, θ) = params(d)
x >= θ ? α * (θ / x)^α * (1/x) : zero(T)
end
function logpdf(d::Pareto{T}, x::Real) where T<:Real
(α, θ) = params(d)
x >= θ ? log(α) + α * log(θ) - (α + 1) * log(x) : -T(Inf)
end
function ccdf(d::Pareto, x::Real)
α, θ = params(d)
return (θ / max(x, θ))^α
end
cdf(d::Pareto, x::Real) = 1 - ccdf(d, x)
##CHUNK 6
* [Pareto distribution on Wikipedia](http://en.wikipedia.org/wiki/Pareto_distribution)
"""
struct Pareto{T<:Real} <: ContinuousUnivariateDistribution
α::T
θ::T
Pareto{T}(α::T, θ::T) where {T} = new{T}(α, θ)
end
function Pareto(α::T, θ::T; check_args::Bool=true) where {T <: Real}
@check_args Pareto (α, α > zero(α)) (θ, θ > zero(θ))
return Pareto{T}(α, θ)
end
Pareto(α::Real, θ::Real; check_args::Bool=true) = Pareto(promote(α, θ)...; check_args=check_args)
Pareto(α::Integer, θ::Integer; check_args::Bool=true) = Pareto(float(α), float(θ); check_args=check_args)
Pareto(α::Real; check_args::Bool=true) = Pareto(α, one(α); check_args=check_args)
Pareto() = Pareto{Float64}(1.0, 1.0)
@distr_support Pareto d.θ Inf
|
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
return insupport(d, x) ? res : zero(res)
end | 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
return insupport(d, x) ? res : zero(res)
end | [
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
return insupport(d, x) ? res : zero(res)
end | 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
return insupport(d, x) ? res : zero(res)
end | 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::Real)
(a, b) = params(d)
u = (b - a) * t / 2
u == zero(u) && return one(u)
v = (a + b) * t / 2
exp(v) * (sinh(u) / u)
end
function cgf_uniform_around_zero_kernel(x)
# taylor series of (exp(x) - x - 1) / x
T = typeof(x)
##CHUNK 2
function mgf(d::Uniform, t::Real)
(a, b) = params(d)
u = (b - a) * t / 2
u == zero(u) && return one(u)
v = (a + b) * t / 2
exp(v) * (sinh(u) / u)
end
function cgf_uniform_around_zero_kernel(x)
# taylor series of (exp(x) - x - 1) / x
T = typeof(x)
a0 = inv(T(2))
a1 = inv(T(6))
a2 = inv(T(24))
a3 = inv(T(120))
x*@evalpoly(x, a0, a1, a2, a3)
end
function cgf(d::Uniform, t)
# log((exp(t*b) - exp(t*a))/ (t*(b-a)))
a,b = params(d)
#FILE: Distributions.jl/src/univariate/continuous/inversegaussian.jl
##CHUNK 1
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 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
#FILE: Distributions.jl/test/univariate/continuous/triangular.jl
##CHUNK 1
@test logpdf(d, x) == log(pdf(d, x))
@test cdf(d, x) == (x - a)^2 / ((b - a) * (c - a))
end
# x = c
@test pdf(d, c) == (a == b ? Inf : 2 / (b - a))
@test logpdf(d, c) == log(pdf(d, c))
@test cdf(d, c) == (c == b ? 1 : (c - a) / (b - a))
# c < x < b
if c < b
x = (c + b) / 2
@test pdf(d, x) == 2 * (b - x) / ((b - a) * (b - c))
@test logpdf(d, x) == log(pdf(d, x))
@test cdf(d, x) == 1 - (b - x)^2 / ((b - a) * (b - c))
end
# x = b
@test pdf(d, b) == (b == a ? Inf : (b == c ? 2 / (b - a) : 0))
@test logpdf(d, b) == log(pdf(d, b))
@test cdf(d, b) == 1
# x > b
for x in (b + 1, b + 3)
##CHUNK 2
@test cdf(d, x) == 0
end
# x = a
@test pdf(d, a) == (a == b ? Inf : (a == c ? 2 / (b - a) : 0))
@test logpdf(d, a) == log(pdf(d, a))
@test cdf(d, a) == (a == b ? 1 : 0)
# a < x < c
if a < c
x = (a + c) / 2
@test pdf(d, x) == 2 * (x - a) / ((b - a) * (c - a))
@test logpdf(d, x) == log(pdf(d, x))
@test cdf(d, x) == (x - a)^2 / ((b - a) * (c - a))
end
# x = c
@test pdf(d, c) == (a == b ? Inf : 2 / (b - a))
@test logpdf(d, c) == log(pdf(d, c))
@test cdf(d, c) == (c == b ? 1 : (c - a) / (b - a))
# c < x < b
if c < b
x = (c + b) / 2
#FILE: Distributions.jl/src/univariate/continuous/rician.jl
##CHUNK 1
d = a + (b - a) / ϕ
while abs(b - a) > tol
if f(c) < f(d)
b = d
else
a = c
end
c = b - (b - a) / ϕ
d = a + (b - a) / ϕ
end
(b + a) / 2
end
#### PDF/CDF/quantile delegated to NoncentralChisq
function quantile(d::Rician, x::Real)
ν, σ = params(d)
return sqrt(quantile(NoncentralChisq(2, (ν / σ)^2), x)) * σ
end
#FILE: Distributions.jl/src/truncated/normal.jl
##CHUNK 1
return zero(mid)
end
Δ = (b - a) * mid
a′ = a * invsqrt2
b′ = b * invsqrt2
if a ≤ 0 ≤ b
m = expm1(-Δ) * exp(-a^2 / 2) / erf(b′, a′)
elseif 0 < a < b
z = exp(-Δ) * erfcx(b′) - erfcx(a′)
iszero(z) && return mid
m = expm1(-Δ) / z
end
return clamp(m / sqrthalfπ, a, b)
end
# do not export. Used in var
# computes 2nd moment of standard normal distribution truncated to [a, b]
function _tnmom2(a::Real, b::Real)
mid = float(middle(a, b))
if !(a ≤ b)
#FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
end
#CURRENT FILE: Distributions.jl/src/univariate/continuous/triangular.jl
##CHUNK 1
2 (exp(x) - 1 - x) / x^2
```
with the correct limit at ``x = 0``.
"""
function _phi2(x::Real)
res = 2 * (expm1(x) - x) / x^2
return iszero(x) ? one(res) : res
end
function mgf(d::TriangularDist, t::Real)
a, b, c = params(d)
# In principle, only two branches (degenerate + non-degenerate case) are needed
# But writing out all four cases will avoid unnecessary computations
if a < c
if c < b
# Case: a < c < b
return exp(c * t) * ((c - a) * _phi2((a - c) * t) + (b - c) * _phi2((b - c) * t)) / (b - a)
else
# Case: a < c = b
return exp(c * t) * _phi2((a - c) * t)
end
##CHUNK 2
#### Evaluation
logpdf(d::TriangularDist, x::Real) = log(pdf(d, x))
function cdf(d::TriangularDist, x::Real)
a, b, c = params(d)
if x < c
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)
(a, b, c) = params(d)
c_m_a = c - a
b_m_a = b - a
|
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::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 - b) * z)
end
return w::Float64
end
##CHUNK 2
r = sqrt((1.0 - abs2(w)) / s)
@inbounds for i = 2:p
x[i] *= r
end
return _vmf_rot!(spl.v, x)
end
### Core computation
_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::AbstractRNG, p, b, x0, c, κ)
r = (p - 1) / 2.0
#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 abs(ξ) < eps(one(ξ)) # ξ == 0
t = z
return -log(σ) - t - exp(-t)
else
if z * ξ == -1 # Otherwise, would compute zero to the power something.
return -T(Inf)
else
t = (1 + z * ξ) ^ (-1/ξ)
return - log(σ) + (ξ + 1) * log(t) - t
end
end
end
end
##CHUNK 2
function pdf(d::GeneralizedExtremeValue{T}, x::Real) where T<:Real
if x == -Inf || x == Inf || ! insupport(d, x)
return zero(T)
else
(μ, σ, ξ) = params(d)
z = (x - μ) / σ # Normalise x.
if abs(ξ) < eps(one(ξ)) # ξ == 0
t = exp(-z)
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
end
##CHUNK 3
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 (t^(ξ + 1) * exp(- t)) / σ
end
end
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)
#FILE: Distributions.jl/src/univariate/continuous/kolmogorov.jl
##CHUNK 1
if x <= 0
return 0.0
elseif x <= 1
c = π/(2*x)
s = 0.0
for i = 1:20
k = ((2i - 1)*c)^2
s += (k - 1)*exp(-k/2)
end
return sqrt2π*s/x^2
else
s = 0.0
for i = 1:20
s += (iseven(i) ? -1 : 1)*i^2*exp(-2(i*x)^2)
end
return 8*x*s
end
end
logpdf(d::Kolmogorov, x::Real) = log(pdf(d, x))
#FILE: Distributions.jl/src/univariate/continuous/cosine.jl
##CHUNK 1
logpdf(d::Cosine, x::Real) = log(pdf(d, x))
function cdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return zero(T)
end
if x > d.μ + d.σ
return one(T)
end
z = (x - d.μ) / d.σ
(1 + z + sinpi(z) * invπ) / 2
end
function ccdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return one(T)
end
if x > d.μ + d.σ
return zero(T)
end
##CHUNK 2
(1 + z + sinpi(z) * invπ) / 2
end
function ccdf(d::Cosine{T}, x::Real) where T<:Real
if x < d.μ - d.σ
return one(T)
end
if x > d.μ + d.σ
return zero(T)
end
nz = (d.μ - x) / d.σ
(1 + nz + sinpi(nz) * invπ) / 2
end
quantile(d::Cosine, p::Real) = quantile_bisect(d, p)
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
2(α + s) / (β - 3) * sqrt((β - 2) / (α * s))
else
return T(NaN)
end
end
#### Evaluation
function logpdf(d::BetaPrime, x::Real)
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
#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 / ξ) * log1p(z * ξ) - log(σ)
end
end
return p
end
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
#CURRENT FILE: Distributions.jl/src/univariate/continuous/vonmises.jl |
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(xpow0)
dot_xpowlnx0 = dot(xpow0, lnx)
fx = dot_xpowlnx0 / sum_xpow0 - mean_lnx - 1 / alpha0
∂fx = (-dot_xpowlnx0^2 + sum_xpow0 * dot(lnxsq, xpow0)) / (sum_xpow0^2) + 1 / alpha0^2
Δα = fx / ∂fx
α = alpha0 - Δα
ϵ = abs(Δα)
N += 1
while ϵ > tol && N < maxiter
xpow = x.^α
sum_xpow = sum(xpow)
dot_xpowlnx = dot(xpow, lnx)
fx = dot_xpowlnx / sum_xpow - mean_lnx - 1 / α
∂fx = (-dot_xpowlnx^2 + sum_xpow * dot(lnxsq, xpow)) / (sum_xpow^2) + 1 / α^2
Δα = fx / ∂fx
α -= Δα
ϵ = abs(Δα)
N += 1
end
θ = mean(x.^α)^(1 / α)
return Weibull(α, θ)
end | 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(xpow0)
dot_xpowlnx0 = dot(xpow0, lnx)
fx = dot_xpowlnx0 / sum_xpow0 - mean_lnx - 1 / alpha0
∂fx = (-dot_xpowlnx0^2 + sum_xpow0 * dot(lnxsq, xpow0)) / (sum_xpow0^2) + 1 / alpha0^2
Δα = fx / ∂fx
α = alpha0 - Δα
ϵ = abs(Δα)
N += 1
while ϵ > tol && N < maxiter
xpow = x.^α
sum_xpow = sum(xpow)
dot_xpowlnx = dot(xpow, lnx)
fx = dot_xpowlnx / sum_xpow - mean_lnx - 1 / α
∂fx = (-dot_xpowlnx^2 + sum_xpow * dot(lnxsq, xpow)) / (sum_xpow^2) + 1 / α^2
Δα = fx / ∂fx
α -= Δα
ϵ = abs(Δα)
N += 1
end
θ = mean(x.^α)^(1 / α)
return Weibull(α, θ)
end | [
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(xpow0)
dot_xpowlnx0 = dot(xpow0, lnx)
fx = dot_xpowlnx0 / sum_xpow0 - mean_lnx - 1 / alpha0
∂fx = (-dot_xpowlnx0^2 + sum_xpow0 * dot(lnxsq, xpow0)) / (sum_xpow0^2) + 1 / alpha0^2
Δα = fx / ∂fx
α = alpha0 - Δα
ϵ = abs(Δα)
N += 1
while ϵ > tol && N < maxiter
xpow = x.^α
sum_xpow = sum(xpow)
dot_xpowlnx = dot(xpow, lnx)
fx = dot_xpowlnx / sum_xpow - mean_lnx - 1 / α
∂fx = (-dot_xpowlnx^2 + sum_xpow * dot(lnxsq, xpow)) / (sum_xpow^2) + 1 / α^2
Δα = fx / ∂fx
α -= Δα
ϵ = abs(Δα)
N += 1
end
θ = mean(x.^α)^(1 / α)
return Weibull(α, θ)
end | 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(xpow0)
dot_xpowlnx0 = dot(xpow0, lnx)
fx = dot_xpowlnx0 / sum_xpow0 - mean_lnx - 1 / alpha0
∂fx = (-dot_xpowlnx0^2 + sum_xpow0 * dot(lnxsq, xpow0)) / (sum_xpow0^2) + 1 / alpha0^2
Δα = fx / ∂fx
α = alpha0 - Δα
ϵ = abs(Δα)
N += 1
while ϵ > tol && N < maxiter
xpow = x.^α
sum_xpow = sum(xpow)
dot_xpowlnx = dot(xpow, lnx)
fx = dot_xpowlnx / sum_xpow - mean_lnx - 1 / α
∂fx = (-dot_xpowlnx^2 + sum_xpow * dot(lnxsq, xpow)) / (sum_xpow^2) + 1 / α^2
Δα = fx / ∂fx
α -= Δα
ϵ = abs(Δα)
N += 1
end
θ = mean(x.^α)^(1 / α)
return Weibull(α, θ)
end | 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 + θ^2 - π/8 * exp(-θ^2 / 2) * ((2 + θ^2) * besseli(0, θ^2 / 4) + θ^2 * besseli(1, θ^2 / 4))^2
g(θ) = sqrt(ξ(θ) * (1+r^2) - 2)
θ = g(1)
for j in 1:maxiters
θ⁻ = θ
θ = g(θ)
abs(θ - θ⁻) < tol && break
end
ξθ = ξ(θ)
σ = convert(float(T), sqrt(μ₂ / ξθ))
ν = convert(float(T), sqrt(μ₁^2 + (ξθ - 2) * σ^2))
end
#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::SkewedExponentialPower) = d.α > 1//2 ? -1 : 1
mean(d::SkewedExponentialPower) = d.α == 1//2 ? float(d.μ) : sgn(d)*exp(m_k(d, 1)) + d.μ
mode(d::SkewedExponentialPower) = mean(d)
var(d::SkewedExponentialPower) = exp(m_k(d, 2)) - exp(2*m_k(d, 1))
skewness(d::SkewedExponentialPower) = d.α == 1//2 ? float(zero(partype(d))) : sgn(d)*exp(m_k(d, 3)) / (std(d))^3
kurtosis(d::SkewedExponentialPower) = exp(m_k(d, 4))/var(d)^2 - 3
function logpdf(d::SkewedExponentialPower, x::Real)
μ, σ, p, α = params(d)
a = x < μ ? α : 1 - α
inv_p = inv(p)
return -(logtwo + log(σ) + loggamma(inv_p) + ((1 - p) * log(p) + (abs(μ - x) / (2 * σ * a))^p) / p)
end
##CHUNK 2
function logcdf(d::SkewedExponentialPower, x::Real)
μ, σ, p, α = params(d)
inv_p = inv(p)
if x <= μ
log(α) + logccdf(Gamma(inv_p), inv_p * (abs((x-μ)/σ) / (2*α))^p)
else
log1mexp(log1p(-α) + logccdf(Gamma(inv_p), inv_p * (abs((x-μ)/σ) / (2*(1-α)))^p))
end
end
function quantile(d::SkewedExponentialPower, p::Real)
μ, σ, _, α = params(d)
inv_p = inv(d.p)
if p <= α
μ - 2*α*σ * (d.p * quantile(Gamma(inv_p), (α-p)/α))^inv_p
else
μ + 2*(1-α)*σ * (d.p * quantile(Gamma(inv_p), (p-α)/(1-α)))^inv_p
end
end
#FILE: Distributions.jl/src/univariate/continuous/chi.jl
##CHUNK 1
function kldivergence(p::Chi, q::Chi)
pν = dof(p)
qν = dof(q)
pν2 = pν / 2
return loggamma(qν / 2) - loggamma(pν2) + (pν - qν) * digamma(pν2) / 2
end
#### Evaluation
function logpdf(d::Chi, x::Real)
ν, _x = promote(d.ν, x)
xsq = _x^2
val = (xlogy(ν - 1, xsq / 2) - xsq + logtwo) / 2 - loggamma(ν / 2)
return x < zero(x) ? oftype(val, -Inf) : val
end
gradlogpdf(d::Chi{T}, x::Real) where {T<:Real} = x >= 0 ? (d.ν - 1) / x - x : zero(T)
#FILE: Distributions.jl/src/truncated/normal.jl
##CHUNK 1
lower, upper = extrema(d)
a = (lower - μ) / σ
b = (upper - μ) / σ
return T(_tnvar(a, b) * σ^2)
end
end
function entropy(d::Truncated{<:Normal{<:Real},Continuous})
d0 = d.untruncated
z = d.tp
μ = mean(d0)
σ = std(d0)
lower, upper = extrema(d)
a = (lower - μ) / σ
b = (upper - μ) / σ
aφa = isinf(a) ? 0.0 : a * normpdf(a)
bφb = isinf(b) ? 0.0 : b * normpdf(b)
0.5 * (log2π + 1.) + log(σ * z) + (aφa - bφb) / (2.0 * z)
end
#FILE: Distributions.jl/src/univariate/continuous/pareto.jl
##CHUNK 1
(α, θ) = params(d)
x >= θ ? log(α) + α * log(θ) - (α + 1) * log(x) : -T(Inf)
end
function ccdf(d::Pareto, x::Real)
α, θ = params(d)
return (θ / max(x, θ))^α
end
cdf(d::Pareto, x::Real) = 1 - ccdf(d, x)
function logccdf(d::Pareto, x::Real)
α, θ = params(d)
return xlogy(α, θ / max(x, θ))
end
logcdf(d::Pareto, x::Real) = log1mexp(logccdf(d, x))
cquantile(d::Pareto, p::Real) = d.θ / p^(1 / d.α)
quantile(d::Pareto, p::Real) = cquantile(d, 1 - p)
#FILE: Distributions.jl/src/univariate/continuous/johnsonsu.jl
##CHUNK 1
end
#### Evaluation
yval(d::JohnsonSU, x::Real) = (x - d.ξ) / d.λ
zval(d::JohnsonSU, x::Real) = d.γ + d.δ * asinh(yval(d, x))
xval(d::JohnsonSU, x::Real) = d.λ * sinh((x - d.γ) / d.δ) + d.ξ
pdf(d::JohnsonSU, x::Real) = d.δ / (d.λ * hypot(1, yval(d, x))) * normpdf(zval(d, x))
logpdf(d::JohnsonSU, x::Real) = log(d.δ) - log(d.λ) - log1psq(yval(d, x)) / 2 + normlogpdf(zval(d, x))
cdf(d::JohnsonSU, x::Real) = normcdf(zval(d, x))
logcdf(d::JohnsonSU, x::Real) = normlogcdf(zval(d, x))
ccdf(d::JohnsonSU, x::Real) = normccdf(zval(d, x))
logccdf(d::JohnsonSU, x::Real) = normlogccdf(zval(d, x))
quantile(d::JohnsonSU, q::Real) = xval(d, norminvcdf(q))
cquantile(d::JohnsonSU, p::Real) = xval(d, norminvccdf(p))
invlogcdf(d::JohnsonSU, lp::Real) = xval(d, norminvlogcdf(lp))
invlogccdf(d::JohnsonSU, lq::Real) = xval(d, norminvlogccdf(lq))
#FILE: Distributions.jl/src/univariate/continuous/normal.jl
##CHUNK 1
μq = mean(q)
σ²q = var(q)
σ²p_over_σ²q = σ²p / σ²q
return (abs2(μp - μq) / σ²q - logmxp1(σ²p_over_σ²q)) / 2
end
#### Evaluation
# Use Julia implementations in StatsFuns
@_delegate_statsfuns Normal norm μ σ
# `logerf(...)` is more accurate for arguments in the tails than `logsubexp(logcdf(...), logcdf(...))`
function logdiffcdf(d::Normal, x::Real, y::Real)
x < y && throw(ArgumentError("requires x >= y."))
μ, σ = params(d)
_x, _y, _μ, _σ = promote(x, y, μ, σ)
s = sqrt2 * _σ
return logerf((_y - _μ) / s, (_x - _μ) / s) - logtwo
end
#FILE: Distributions.jl/src/univariate/continuous/generalizedpareto.jl
##CHUNK 1
end
return p
end
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)) / ξ
else
-log1p(z * ξ) / ξ
end
end
ccdf(d::GeneralizedPareto, x::Real) = exp(logccdf(d, x))
cdf(d::GeneralizedPareto, x::Real) = -expm1(logccdf(d, x))
#CURRENT FILE: Distributions.jl/src/univariate/continuous/weibull.jl
##CHUNK 1
end
function logpdf(d::Weibull, x::Real)
α, θ = params(d)
z = abs(x) / θ
res = log(α / θ) + xlogy(α - 1, z) - z^α
x < 0 || isinf(x) ? oftype(res, -Inf) : res
end
zval(d::Weibull, x::Real) = (max(x, 0) / d.θ) ^ d.α
xval(d::Weibull, z::Real) = d.θ * z ^ (1 / d.α)
cdf(d::Weibull, x::Real) = -expm1(- zval(d, x))
ccdf(d::Weibull, x::Real) = exp(- zval(d, x))
logcdf(d::Weibull, x::Real) = log1mexp(- zval(d, x))
logccdf(d::Weibull, x::Real) = - zval(d, x)
quantile(d::Weibull, p::Real) = xval(d, -log1p(-p))
cquantile(d::Weibull, p::Real) = xval(d, -log(p))
invlogcdf(d::Weibull, lp::Real) = xval(d, -log1mexp(lp))
|
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 / denominator
right = (alpha_beta_sum) * (alpha_beta_sum - 1 + 6n) + 3*alpha_beta_product * (n - 2) + 6n^2
right -= (3*alpha_beta_product * n * (6 - n)) / alpha_beta_sum
right -= (18*alpha_beta_product * n^2) / (alpha_beta_sum)^2
return (left * right) - 3
end | 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 / denominator
right = (alpha_beta_sum) * (alpha_beta_sum - 1 + 6n) + 3*alpha_beta_product * (n - 2) + 6n^2
right -= (3*alpha_beta_product * n * (6 - n)) / alpha_beta_sum
right -= (18*alpha_beta_product * n^2) / (alpha_beta_sum)^2
return (left * right) - 3
end | [
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 / denominator
right = (alpha_beta_sum) * (alpha_beta_sum - 1 + 6n) + 3*alpha_beta_product * (n - 2) + 6n^2
right -= (3*alpha_beta_product * n * (6 - n)) / alpha_beta_sum
right -= (18*alpha_beta_product * n^2) / (alpha_beta_sum)^2
return (left * right) - 3
end | 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 / denominator
right = (alpha_beta_sum) * (alpha_beta_sum - 1 + 6n) + 3*alpha_beta_product * (n - 2) + 6n^2
right -= (3*alpha_beta_product * n * (6 - n)) / alpha_beta_sum
right -= (18*alpha_beta_product * n^2) / (alpha_beta_sum)^2
return (left * right) - 3
end | 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::SkewedExponentialPower) = d.α > 1//2 ? -1 : 1
mean(d::SkewedExponentialPower) = d.α == 1//2 ? float(d.μ) : sgn(d)*exp(m_k(d, 1)) + d.μ
mode(d::SkewedExponentialPower) = mean(d)
var(d::SkewedExponentialPower) = exp(m_k(d, 2)) - exp(2*m_k(d, 1))
skewness(d::SkewedExponentialPower) = d.α == 1//2 ? float(zero(partype(d))) : sgn(d)*exp(m_k(d, 3)) / (std(d))^3
kurtosis(d::SkewedExponentialPower) = exp(m_k(d, 4))/var(d)^2 - 3
function logpdf(d::SkewedExponentialPower, x::Real)
μ, σ, p, α = params(d)
a = x < μ ? α : 1 - α
inv_p = inv(p)
return -(logtwo + log(σ) + loggamma(inv_p) + ((1 - p) * log(p) + (abs(μ - x) / (2 * σ * a))^p) / p)
end
##CHUNK 2
function logcdf(d::SkewedExponentialPower, x::Real)
μ, σ, p, α = params(d)
inv_p = inv(p)
if x <= μ
log(α) + logccdf(Gamma(inv_p), inv_p * (abs((x-μ)/σ) / (2*α))^p)
else
log1mexp(log1p(-α) + logccdf(Gamma(inv_p), inv_p * (abs((x-μ)/σ) / (2*(1-α)))^p))
end
end
function quantile(d::SkewedExponentialPower, p::Real)
μ, σ, _, α = params(d)
inv_p = inv(d.p)
if p <= α
μ - 2*α*σ * (d.p * quantile(Gamma(inv_p), (α-p)/α))^inv_p
else
μ + 2*(1-α)*σ * (d.p * quantile(Gamma(inv_p), (p-α)/(1-α)))^inv_p
end
end
#FILE: Distributions.jl/src/univariate/continuous/beta.jl
##CHUNK 1
α, β = params(d)
s = α + β
p = α * β
6(abs2(α - β) * (s + 1) - p * (s + 2)) / (p * (s + 2) * (s + 3))
end
function entropy(d::Beta)
α, β = params(d)
s = α + β
logbeta(α, β) - (α - 1) * digamma(α) - (β - 1) * digamma(β) +
(s - 2) * digamma(s)
end
function kldivergence(p::Beta, q::Beta)
αp, βp = params(p)
αq, βq = params(q)
return logbeta(αq, βq) - logbeta(αp, βp) + (αp - αq) * digamma(αp) +
(βp - βq) * digamma(βp) + (αq - αp + βq - βp) * digamma(αp + βp)
end
#FILE: Distributions.jl/src/matrix/matrixbeta.jl
##CHUNK 1
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*(-(2/n)*Ω[i,j]*Ω[k,l] + Ω[j,l]*Ω[i,k] + Ω[i,l]*Ω[k,j])
end
function var(d::MatrixBeta, i::Integer, j::Integer)
p, n1, n2 = params(d)
n = n1 + n2
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*((1 - (2/n))*Ω[i,j]^2 + Ω[j,j]*Ω[i,i])
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function matrixbeta_logc0(p::Int, n1::Real, n2::Real)
# returns the natural log of the normalizing constant for the pdf
return -logmvbeta(p, n1 / 2, n2 / 2)
end
#FILE: Distributions.jl/test/univariate/continuous/skewedexponentialpower.jl
##CHUNK 1
@inferred -mean(d1) ≈ mean(d2)
@inferred var(d1) ≈ var(d2)
@inferred -skewness(d1) ≈ skewness(d2)
@inferred kurtosis(d1) ≈ kurtosis(d2)
α, p = rand(2)
d = SkewedExponentialPower(0, 1, p, α)
# moments of the standard SEPD, Equation 18 in Zhy, D. and V. Zinde-Walsh (2009)
moments = [(2*p^(1/p))^k * ((-1)^k*α^(1+k) + (1-α)^(1+k)) * gamma((1+k)/p)/gamma(1/p) for k ∈ 1:4]
@inferred var(d) ≈ moments[2] - moments[1]^2
@inferred skewness(d) ≈ moments[3] / (√(moments[2] - moments[1]^2))^3
@inferred kurtosis(d) ≈ (moments[4] / ((moments[2] - moments[1]^2))^2 - 3)
test_distr(d, 10^6)
end
end
#FILE: Distributions.jl/src/univariate/continuous/normalinversegaussian.jl
##CHUNK 1
var(d::NormalInverseGaussian) = d.δ * d.α^2 / d.γ^3
skewness(d::NormalInverseGaussian) = 3d.β / (d.α * sqrt(d.δ * d.γ))
kurtosis(d::NormalInverseGaussian) = 3 * (1 + 4*d.β^2/d.α^2) / (d.δ * d.γ)
function pdf(d::NormalInverseGaussian, x::Real)
μ, α, β, δ = params(d)
α * δ * besselk(1, α*sqrt(δ^2+(x - μ)^2)) / (π*sqrt(δ^2 + (x - μ)^2)) * exp(δ * d.γ + β*(x - μ))
end
function logpdf(d::NormalInverseGaussian, x::Real)
μ, α, β, δ = params(d)
log(α*δ) + log(besselk(1, α*sqrt(δ^2+(x-μ)^2))) - log(π*sqrt(δ^2+(x-μ)^2)) + δ*d.γ + β*(x-μ)
end
#### Sampling
# The Normal Inverse Gaussian distribution is a normal variance-mean
# mixture with an inverse Gaussian as mixing distribution.
#
#FILE: Distributions.jl/src/univariate/continuous/skewnormal.jl
##CHUNK 1
mean_z(d::SkewNormal) = √(2/π) * delta(d)
std_z(d::SkewNormal) = 1 - (2/π) * delta(d)^2
mean(d::SkewNormal) = d.ξ + d.ω * mean_z(d)
var(d::SkewNormal) = abs2(d.ω) * (1 - mean_z(d)^2)
std(d::SkewNormal) = √var(d)
skewness(d::SkewNormal) = ((4 - π)/2) * (mean_z(d)^3/(1 - mean_z(d)^2)^(3/2))
kurtosis(d::SkewNormal) = 2 * (π-3) * ((delta(d) * sqrt(2/π))^4/(1-2 * (delta(d)^2)/π)^2)
# no analytic expression for max m_0(d) but accurate numerical approximation
m_0(d::SkewNormal) = mean_z(d) - (skewness(d) * std_z(d))/2 - (sign(d.α)/2) * exp(-2π/abs(d.α))
mode(d::SkewNormal) = d.ξ + d.ω * m_0(d)
#### Evaluation
pdf(d::SkewNormal, x::Real) = (2/d.ω) * normpdf((x-d.ξ)/d.ω) * normcdf(d.α * (x-d.ξ)/d.ω)
logpdf(d::SkewNormal, x::Real) = log(2) - log(d.ω) + normlogpdf((x-d.ξ) / d.ω) + normlogcdf(d.α * (x-d.ξ) / d.ω)
#cdf requires Owen's T function.
#cdf/quantile etc
mgf(d::SkewNormal, t::Real) = 2 * exp(d.ξ * t + (d.ω^2 * t^2)/2 ) * normcdf(d.ω * delta(d) * t)
#FILE: Distributions.jl/src/edgeworth.jl
##CHUNK 1
s = skewness(d)
k = kurtosis(d)
z = quantile(Normal(0,1),p)
z2 = z*z
z + s*(z2-1)/6.0 + k*z*(z2-3)/24.0 - s*s/36.0*z*(2.0*z2-5.0)
end
function cquantile(d::EdgeworthZ, p::Float64)
s = skewness(d)
k = kurtosis(d)
z = cquantile(Normal(0,1),p)
z2 = z*z
z + s*(z2-1)/6.0 + k*z*(z2-3)/24.0 - s*s/36.0*z*(2.0*z2-5.0)
end
# Edgeworth approximation of the sum
struct EdgeworthSum{D<:UnivariateDistribution} <: EdgeworthAbstract
dist::D
#CURRENT FILE: Distributions.jl/src/univariate/discrete/betabinomial.jl
##CHUNK 1
params(d::BetaBinomial) = (d.n, d.α, d.β)
partype(::BetaBinomial{T}) where {T} = T
#### Properties
mean(d::BetaBinomial) = (d.n * d.α) / (d.α + d.β)
function var(d::BetaBinomial)
n, α, β = d.n, d.α, d.β
numerator = n * α * β * (α + β + n)
denominator = (α + β)^2 * (α + β + 1)
return numerator / denominator
end
function skewness(d::BetaBinomial)
n, α, β = d.n, d.α, d.β
t1 = (α + β + 2n) * (β - α) / (α + β + 2)
t2 = sqrt((1 + α +β) / (n * α * β * (n + α + β)))
return t1 * t2
end
##CHUNK 2
denominator = (α + β)^2 * (α + β + 1)
return numerator / denominator
end
function skewness(d::BetaBinomial)
n, α, β = d.n, d.α, d.β
t1 = (α + β + 2n) * (β - α) / (α + β + 2)
t2 = sqrt((1 + α +β) / (n * α * β * (n + α + β)))
return t1 * t2
end
function logpdf(d::BetaBinomial, k::Real)
n, α, β = d.n, d.α, d.β
_insupport = insupport(d, k)
_k = _insupport ? round(Int, k) : 0
logbinom = - log1p(n) - logbeta(_k + 1, n - _k + 1)
lognum = logbeta(_k + α, n - _k + β)
logdenom = logbeta(α, β)
result = logbinom + lognum - logdenom
|
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)
end
end
fm1 = vfirst - 1
for v = vl:vr
r[v - fm1] = p[v]
end
if vr < vlast
for i = (vr - vfirst + 2):length(rgn)
r[i] = zero(T)
end
end
return r
end | 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)
end
end
fm1 = vfirst - 1
for v = vl:vr
r[v - fm1] = p[v]
end
if vr < vlast
for i = (vr - vfirst + 2):length(rgn)
r[i] = zero(T)
end
end
return r
end | [
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)
end
end
fm1 = vfirst - 1
for v = vl:vr
r[v - fm1] = p[v]
end
if vr < vlast
for i = (vr - vfirst + 2):length(rgn)
r[i] = zero(T)
end
end
return r
end | 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)
end
end
fm1 = vfirst - 1
for v = vl:vr
r[v - fm1] = p[v]
end
if vr < vlast
for i = (vr - vfirst + 2):length(rgn)
r[i] = zero(T)
end
end
return r
end | _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_outside!(r, d, X)
# fill central part: with non-zero pdf
if vl <= vr
fm1 = vfirst - 1
r[vl - fm1] = pv = pdf(d, vl)
for v = (vl+1):vr
r[v - fm1] = pv = nextpdf(rpe, pv, v)
end
end
##CHUNK 2
fm1 = vfirst - 1
for v = vl:vr
r[v - fm1] = pdf(d, v)
end
# fill right part
if vr < vlast
for i = (vr-vfirst+2):n
r[i] = 0.0
end
end
return vl, vr, vfirst, vlast
end
function _pdf!(r::AbstractArray{<:Real}, d::DiscreteUnivariateDistribution, X::UnitRange)
vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X)
# fill central part: with non-zero pdf
fm1 = vfirst - 1
for v = vl:vr
##CHUNK 3
end
# fill left part
if vl > vfirst
for i = 1:(vl - vfirst)
r[i] = 0.0
end
end
# fill central part: with non-zero pdf
fm1 = vfirst - 1
for v = vl:vr
r[v - fm1] = pdf(d, v)
end
# fill right part
if vr < vlast
for i = (vr-vfirst+2):n
r[i] = 0.0
end
##CHUNK 4
end
return vl, vr, vfirst, vlast
end
function _pdf!(r::AbstractArray{<:Real}, d::DiscreteUnivariateDistribution, X::UnitRange)
vl,vr, vfirst, vlast = _pdf_fill_outside!(r, d, X)
# fill central part: with non-zero pdf
fm1 = vfirst - 1
for v = vl:vr
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_outside!(r, d, X)
##CHUNK 5
# fill central part: with non-zero pdf
if vl <= vr
fm1 = vfirst - 1
r[vl - fm1] = pv = pdf(d, vl)
for v = (vl+1):vr
r[v - fm1] = pv = nextpdf(rpe, pv, v)
end
end
return r
end
### special definitions for distributions with integer-valued support
function cdf_int(d::DiscreteUnivariateDistribution, x::Real)
# handle `NaN` and `±Inf` which can't be truncated to `Int`
isfinite_x = isfinite(x)
_x = isfinite_x ? x : zero(x)
c = float(cdf(d, floor(Int, _x)))
#FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
end
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, component(d, i)).(x)
else
pdf!(t, component(d, i), x)
end
axpy!(pi, t, r)
end
end
return r
end
#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(pdf(d, x)) isa T
if length(r) == 1
@test logpdf(d, x) ≈ logpdf(OrderStatistic(dist, n, r[1]), x[1])
@test pdf(d, x) ≈ pdf(OrderStatistic(dist, n, r[1]), x[1])
elseif length(r) == 2
i, j = r
xi, xj = x
lc = T(
logfactorial(n) - logfactorial(i - 1) - logfactorial(n - j) -
logfactorial(j - i - 1),
)
lp = (
lc +
#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)
end
qsum, i = zero(T), 0
while qsum < q
i += 1
qsum += pdf(d, range[i])
end
range[i]
end
end
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
# determine the range of values to examine
vmin = minimum(distr)
vmax = maximum(distr)
rmin = floor(Int,quantile(distr, 0.00001))::Int
rmax = floor(Int,quantile(distr, 0.99999))::Int
m = rmax - rmin + 1 # length of the range
p0 = map(Base.Fix1(pdf, distr), rmin:rmax) # reference probability masses
@assert length(p0) == m
# determine confidence intervals for counts:
# with probability q, the count will be out of this interval.
#
clb = Vector{Int}(undef, m)
cub = Vector{Int}(undef, m)
for i = 1:m
bp = Binomial(n, p0[i])
clb[i] = floor(Int,quantile(bp, q/2))
cub[i] = ceil(Int,cquantile(bp, q/2))
#FILE: Distributions.jl/src/multivariate/jointorderstatistics.jl
##CHUNK 1
Base.eltype(::Type{<:JointOrderStatistics{D}}) where {D} = Base.eltype(D)
Base.eltype(d::JointOrderStatistics) = eltype(d.dist)
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)
if i > 1 # _marginalize_range(d.dist, 0, i, -Inf, xᵢ, T)
lp += (i - 1) * logcdf(d.dist, xᵢ) - loggamma(T(i))
end
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
#CURRENT FILE: Distributions.jl/src/univariate/discrete/categorical.jl |
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, 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]
#FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
function cdf(d::UnivariateMixture, x::Real)
p = probs(d)
r = sum(pi * cdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return r
end
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
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
#FILE: Distributions.jl/src/samplers/multinomial.jl
##CHUNK 1
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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
#CURRENT FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
while cp < q && i < k #Note: is i < k necessary?
i += 1
@inbounds cp += p[i]
end
x[i]
end
minimum(d::DiscreteNonParametric) = first(support(d))
maximum(d::DiscreteNonParametric) = last(support(d))
insupport(d::DiscreteNonParametric, x::Real) =
length(searchsorted(support(d), x)) > 0
##CHUNK 2
end
return s
end
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
##CHUNK 3
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
while cp < q && i < k #Note: is i < k necessary?
i += 1
##CHUNK 4
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
s = 1 - s
##CHUNK 5
ps = probs(d)
if idx <= length(ps) && s[idx] == x
return ps[idx]
else
return zero(eltype(ps))
end
end
logpdf(d::DiscreteNonParametric, x::Real) = log(pdf(d, x))
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)
##CHUNK 6
s = zero(P)
if stop_idx < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
s = 1 - s
end
return s
end
function ccdf(d::DiscreteNonParametric, x::Real)
ps = probs(d)
P = float(eltype(ps))
# trivial cases
##CHUNK 7
# an evenly-spaced integer support
get_evalsamples(d::DiscreteNonParametric, ::Float64) = support(d)
# Evaluation
pdf(d::DiscreteNonParametric) = copy(probs(d))
function pdf(d::DiscreteNonParametric, x::Real)
s = support(d)
idx = searchsortedfirst(s, x)
ps = probs(d)
if idx <= length(ps) && s[idx] == x
return ps[idx]
else
return zero(eltype(ps))
end
end
logpdf(d::DiscreteNonParametric, x::Real) = log(pdf(d, x))
function cdf(d::DiscreteNonParametric, x::Real)
|
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
s = 1 - s
end
return s
end | 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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
s = 1 - s
end
return s
end | [
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
s = 1 - s
end
return s
end | 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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
s = 1 - s
end
return s
end | 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)
end
qsum, i = zero(T), 0
while qsum < q
i += 1
qsum += pdf(d, range[i])
end
range[i]
end
end
#FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
elseif isnan(x)
oftype(c, NaN)
elseif x < 0
zero(c)
else
oftype(c, -Inf)
end
end
# implementation of the cdf for distributions whose support is a unitrange of integers
# note: incorrect for discrete distributions whose support includes non-integer numbers
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.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? zero(c) : c
else
c = 1 - sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
#FILE: Distributions.jl/perf/mixtures.jl
##CHUNK 1
function indexed_boolprod_noinbound(d, x)
ps = probs(d)
cs = components(d)
return sum((ps[i] > 0) * (ps[i] * pdf(cs[i], x)) for i in eachindex(ps))
end
function sumcomp_cond(d, x)
ps = probs(d)
cs = components(d)
s = zero(eltype(ps))
@inbounds sum(ps[i] * pdf(cs[i], x) for i in eachindex(ps) if ps[i] > 0)
end
distributions = [
Normal(-1.0, 0.3),
Normal(0.0, 0.5),
Normal(3.0, 1.0),
]
#CURRENT FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
##CHUNK 2
s = support(d)
idx = searchsortedfirst(s, x)
ps = probs(d)
if idx <= length(ps) && s[idx] == x
return ps[idx]
else
return zero(eltype(ps))
end
end
logpdf(d::DiscreteNonParametric, x::Real) = log(pdf(d, x))
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)
##CHUNK 3
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
##CHUNK 4
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
while cp < q && i < k #Note: is i < k necessary?
i += 1
@inbounds cp += p[i]
end
x[i]
##CHUNK 5
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
while cp < q && i < k #Note: is i < k necessary?
i += 1
@inbounds cp += p[i]
end
x[i]
end
minimum(d::DiscreteNonParametric) = first(support(d))
maximum(d::DiscreteNonParametric) = last(support(d))
insupport(d::DiscreteNonParametric, x::Real) =
length(searchsorted(support(d), x)) > 0
mean(d::DiscreteNonParametric) = dot(probs(d), support(d))
function var(d::DiscreteNonParametric)
##CHUNK 6
# Override the method in testutils.jl since it assumes
# an evenly-spaced integer support
get_evalsamples(d::DiscreteNonParametric, ::Float64) = support(d)
# Evaluation
pdf(d::DiscreteNonParametric) = copy(probs(d))
function pdf(d::DiscreteNonParametric, x::Real)
s = support(d)
idx = searchsortedfirst(s, x)
ps = probs(d)
if idx <= length(ps) && s[idx] == x
return ps[idx]
else
return zero(eltype(ps))
end
end
logpdf(d::DiscreteNonParametric, x::Real) = log(pdf(d, x))
##CHUNK 7
end
minimum(d::DiscreteNonParametric) = first(support(d))
maximum(d::DiscreteNonParametric) = last(support(d))
insupport(d::DiscreteNonParametric, x::Real) =
length(searchsorted(support(d), x)) > 0
mean(d::DiscreteNonParametric) = dot(probs(d), support(d))
function var(d::DiscreteNonParametric)
x = support(d)
p = probs(d)
return var(x, Weights(p, one(eltype(p))); corrected=false)
end
function skewness(d::DiscreteNonParametric)
x = support(d)
p = probs(d)
return skewness(x, Weights(p, one(eltype(p))))
end
|
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end | 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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end | [
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end | 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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end | 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) = ccdf_int(d, x)
cdf(d::Categorical, x::Int) = integerunitrange_cdf(d, x)
ccdf(d::Categorical, x::Int) = integerunitrange_ccdf(d, x)
function pdf(d::Categorical, x::Real)
ps = probs(d)
return insupport(d, x) ? ps[round(Int, x)] : zero(eltype(ps))
end
#FILE: Distributions.jl/src/censored.jl
##CHUNK 1
lower = d.lower
upper = d.upper
px = float(pdf(d0, x))
return if _in_open_interval(x, lower, upper)
px
elseif x == lower
x == upper ? one(px) : oftype(px, cdf(d0, x))
elseif x == upper
if value_support(typeof(d0)) === Discrete
oftype(px, ccdf(d0, x) + px)
else
oftype(px, ccdf(d0, x))
end
else # not in support
zero(px)
end
end
function logpdf(d::Censored, x::Real)
d0 = d.uncensored
#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, xs)
T = typeof(x)
if 0 < p < 1
x0 = T(xs)
while abs(x-x0) > max(abs(x),abs(x0)) * tol
x0 = x
x = x0 + (ccdf(d, x0)-p) / pdf(d, x0)
end
return x
elseif p == 1
return T(minimum(d))
##CHUNK 2
x = xs + (p - cdf(d, xs)) / pdf(d, xs)
T = typeof(x)
if 0 < p < 1
x0 = T(xs)
while abs(x-x0) > max(abs(x),abs(x0)) * tol
x0 = x
x = x0 + (p - cdf(d, x0)) / pdf(d, x0)
end
return x
elseif p == 0
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, xs)
#CURRENT FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
##CHUNK 2
s = support(d)
idx = searchsortedfirst(s, x)
ps = probs(d)
if idx <= length(ps) && s[idx] == x
return ps[idx]
else
return zero(eltype(ps))
end
end
logpdf(d::DiscreteNonParametric, x::Real) = log(pdf(d, x))
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)
##CHUNK 3
n = length(ps)
stop_idx = searchsortedlast(support(d), x)
s = zero(P)
if stop_idx < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
s = 1 - s
end
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
##CHUNK 4
end
s = 1 - s
end
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
while cp < q && i < k #Note: is i < k necessary?
i += 1
@inbounds cp += p[i]
end
x[i]
##CHUNK 5
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
while cp < q && i < k #Note: is i < k necessary?
i += 1
@inbounds cp += p[i]
end
x[i]
end
minimum(d::DiscreteNonParametric) = first(support(d))
maximum(d::DiscreteNonParametric) = last(support(d))
insupport(d::DiscreteNonParametric, x::Real) =
length(searchsorted(support(d), x)) > 0
mean(d::DiscreteNonParametric) = dot(probs(d), support(d))
function var(d::DiscreteNonParametric)
##CHUNK 6
# Override the method in testutils.jl since it assumes
# an evenly-spaced integer support
get_evalsamples(d::DiscreteNonParametric, ::Float64) = support(d)
# Evaluation
pdf(d::DiscreteNonParametric) = copy(probs(d))
function pdf(d::DiscreteNonParametric, x::Real)
s = support(d)
idx = searchsortedfirst(s, x)
ps = probs(d)
if idx <= length(ps) && s[idx] == x
return ps[idx]
else
return zero(eltype(ps))
end
end
logpdf(d::DiscreteNonParametric, x::Real) = log(pdf(d, x))
|
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
else
q = 1.0 - p
a = p / q
@inbounds pv[1] = pk = q ^ n
for k = 1:n
@inbounds pv[k+1] = (pk *= ((n - k + 1) / k) * a)
end
end
return pv
end
#FILE: Distributions.jl/src/univariate/continuous/triangular.jl
##CHUNK 1
# Handle x == c separately to avoid `NaN` if `c == a` or `c == b`
oftype(x - a, 2) / (b - a)
end
return insupport(d, x) ? res : zero(res)
end
logpdf(d::TriangularDist, x::Real) = log(pdf(d, x))
function cdf(d::TriangularDist, x::Real)
a, b, c = params(d)
if x < c
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)
(a, b, c) = params(d)
#FILE: Distributions.jl/src/truncate.jl
##CHUNK 1
result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper !== nothing && x >= d.upper
zero(result)
else
result
end
end
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)
elseif d.upper !== nothing && x > d.upper
zero(result)
else
result
end
##CHUNK 2
return if d.lower !== nothing && x < d.lower
zero(result)
elseif d.upper !== nothing && x >= d.upper
one(result)
else
result
end
end
function logcdf(d::Truncated, x::Real)
result = logsubexp(logcdf(d.untruncated, x), d.loglcdf) - d.logtp
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper !== nothing && x >= d.upper
zero(result)
else
result
end
end
#FILE: Distributions.jl/src/univariates.jl
##CHUNK 1
x >= maximum_d ? one(c) : c
end
return result
end
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(Base.Fix1(pdf, d), minimum_d:(max(x, minimum_d)))
x < minimum_d ? one(c) : c
else
c = sum(Base.Fix1(pdf, d), (min(x + 1, maximum_d)):maximum_d)
x >= maximum_d ? zero(c) : c
end
return result
end
#FILE: Distributions.jl/src/censored.jl
##CHUNK 1
elseif upper === nothing || x < upper
result
else
one(result)
end
end
function logcdf(d::Censored, x::Real)
lower = d.lower
upper = d.upper
result = logcdf(d.uncensored, x)
return if d.lower !== nothing && x < d.lower
oftype(result, -Inf)
elseif d.upper === nothing || x < d.upper
result
else
zero(result)
end
end
#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::Real)
(a, b) = params(d)
u = (b - a) * t / 2
u == zero(u) && return one(u)
v = (a + b) * t / 2
exp(v) * (sinh(u) / u)
end
function cgf_uniform_around_zero_kernel(x)
# taylor series of (exp(x) - x - 1) / x
T = typeof(x)
#FILE: Distributions.jl/src/samplers/gamma.jl
##CHUNK 1
q = calc_q(s, t)
# Step 7
log1p(-u) <= q && return x*x*s.scale
end
# Step 8
t = 0.0
while true
e = 0.0
u = 0.0
while true
e = randexp(rng)
u = 2.0rand(rng) - 1.0
t = s.b + e*s.σ*sign(u)
# Step 9
t ≥ -0.718_744_837_717_19 && break
end
# Step 10
q = calc_q(s, t)
#CURRENT FILE: Distributions.jl/src/univariate/discrete/discreteuniform.jl
##CHUNK 1
"""
DiscreteUniform(a,b)
A *Discrete uniform distribution* is a uniform distribution over a consecutive sequence of integers between `a` and `b`, inclusive.
```math
P(X = k) = 1 / (b - a + 1) \\quad \\text{for } k = a, a+1, \\ldots, b.
```
```julia
DiscreteUniform(a, b) # a uniform distribution over {a, a+1, ..., b}
params(d) # Get the parameters, i.e. (a, b)
span(d) # Get the span of the support, i.e. (b - a + 1)
probval(d) # Get the probability value, i.e. 1 / (b - a + 1)
minimum(d) # Return a
maximum(d) # Return b
```
External links
##CHUNK 2
DiscreteUniform(a, b) # a uniform distribution over {a, a+1, ..., b}
params(d) # Get the parameters, i.e. (a, b)
span(d) # Get the span of the support, i.e. (b - a + 1)
probval(d) # Get the probability value, i.e. 1 / (b - a + 1)
minimum(d) # Return a
maximum(d) # Return b
```
External links
* [Discrete uniform distribution on Wikipedia](http://en.wikipedia.org/wiki/Uniform_distribution_(discrete))
"""
struct DiscreteUniform <: DiscreteUnivariateDistribution
a::Int
b::Int
pv::Float64 # individual probabilities
function DiscreteUniform(a::Real, b::Real; check_args::Bool=true)
@check_args DiscreteUniform (a <= b)
|
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
return z
end
return insupport(d, k) ? z - log(k + r) - logbeta(r, k + 1) : oftype(z, -Inf)
end | 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
return z
end
return insupport(d, k) ? z - log(k + r) - logbeta(r, k + 1) : oftype(z, -Inf)
end | [
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
return z
end
return insupport(d, k) ? z - log(k + r) - logbeta(r, k + 1) : oftype(z, -Inf)
end | 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
return z
end
return insupport(d, k) ? z - log(k + r) - logbeta(r, k + 1) : oftype(z, -Inf)
end | 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 `logpdf(d, k)` above)
r, p = params(d)
z = StatsFuns.xlogy(r, p) + StatsFuns.xlog1py(k, -p)
if iszero(k)
Ω = z
∂r = oftype(z, log(p))
∂p = oftype(z, r/p)
elseif insupport(d, k)
Ω = z - log(k + r) - SpecialFunctions.logbeta(r, k + 1)
∂r = oftype(z, log(p) - inv(k + r) - SpecialFunctions.digamma(r) + SpecialFunctions.digamma(r + k + 1))
∂p = oftype(z, r/p - k / (1 - p))
else
Ω = oftype(z, -Inf)
∂r = oftype(z, NaN)
∂p = oftype(z, NaN)
end
#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 = (x - μ) / σ
if abs(ξ) < eps()
p = -z - log(σ)
elseif ξ > 0 || (ξ < 0 && x < maximum(d))
p = (-1 - 1 / ξ) * log1p(z * ξ) - log(σ)
end
##CHUNK 2
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 / ξ : T(Inf)
elseif 0 < p < 1
if abs(ξ) < eps()
z = -log1p(-p)
else
z = expm1(-ξ * log1p(-p)) / ξ
end
else
z = T(NaN)
end
return μ + σ * z
#FILE: Distributions.jl/src/univariate/continuous/kumaraswamy.jl
##CHUNK 1
function logpdf(d::Kumaraswamy, x::Real)
a, b = params(d)
_x = clamp(x, 0, 1) # Ensures we can still get a value when outside the support
y = log(a) + log(b) + xlogy(a - 1, _x) + xlog1py(b - 1, -_x^a)
return x < 0 || x > 1 ? oftype(y, -Inf) : y
end
function ccdf(d::Kumaraswamy, x::Real)
a, b = params(d)
y = (1 - clamp(x, 0, 1)^a)^b
return x < 0 ? one(y) : (x > 1 ? zero(y) : y)
end
cdf(d::Kumaraswamy, x::Real) = 1 - ccdf(d, x)
function logccdf(d::Kumaraswamy, x::Real)
a, b = params(d)
y = b * log1p(-clamp(x, 0, 1)^a)
return x < 0 ? zero(y) : (x > 1 ? oftype(y, -Inf) : y)
#FILE: Distributions.jl/src/univariate/continuous/betaprime.jl
##CHUNK 1
2(α + s) / (β - 3) * sqrt((β - 2) / (α * s))
else
return T(NaN)
end
end
#### Evaluation
function logpdf(d::BetaPrime, x::Real)
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
##CHUNK 2
α, β = params(d)
_x = max(0, x)
z = xlogy(α - 1, _x) - (α + β) * log1p(_x) - logbeta(α, β)
return x < 0 ? oftype(z, -Inf) : z
end
function zval(::BetaPrime, x::Real)
y = max(x, 0)
z = y / (1 + y)
# map `Inf` to `Inf` (otherwise it returns `NaN`)
return isinf(x) && x > 0 ? oftype(z, Inf) : z
end
xval(::BetaPrime, z::Real) = z / (1 - z)
for f in (:cdf, :ccdf, :logcdf, :logccdf)
@eval $f(d::BetaPrime, x::Real) = $f(Beta(d.α, d.β; check_args=false), zval(d, x))
end
for f in (:quantile, :cquantile, :invlogcdf, :invlogccdf)
@eval $f(d::BetaPrime, p::Real) = xval(d, $f(Beta(d.α, d.β; check_args=false), p))
#FILE: Distributions.jl/src/univariate/continuous/logitnormal.jl
##CHUNK 1
#### Evaluation
#TODO check pd and logpdf
function pdf(d::LogitNormal{T}, x::Real) where T<:Real
if zero(x) < x < one(x)
return normpdf(d.μ, d.σ, logit(x)) / (x * (1-x))
else
return T(0)
end
end
function logpdf(d::LogitNormal{T}, x::Real) where T<:Real
if zero(x) < x < one(x)
lx = logit(x)
return normlogpdf(d.μ, d.σ, lx) - log(x) - log1p(-x)
else
return -T(Inf)
end
end
#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 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), 1)
if z < 0
return logccdf(d, r) - logtwo
else
#FILE: Distributions.jl/src/univariate/discrete/skellam.jl
##CHUNK 1
#### Evaluation
function logpdf(d::Skellam, x::Real)
μ1, μ2 = params(d)
if insupport(d, x)
return - (μ1 + μ2) + (x/2) * log(μ1/μ2) + log(besseli(x, 2*sqrt(μ1)*sqrt(μ2)))
else
return one(x) / 2 * log(zero(μ1/μ2))
end
end
function mgf(d::Skellam, t::Real)
μ1, μ2 = params(d)
exp(μ1 * (exp(t) - 1) + μ2 * (exp(-t) - 1))
end
function cf(d::Skellam, t::Real)
μ1, μ2 = params(d)
#FILE: Distributions.jl/src/univariate/discrete/betabinomial.jl
##CHUNK 1
right -= (18*alpha_beta_product * n^2) / (alpha_beta_sum)^2
return (left * right) - 3
end
function logpdf(d::BetaBinomial, k::Real)
n, α, β = d.n, d.α, d.β
_insupport = insupport(d, k)
_k = _insupport ? round(Int, k) : 0
logbinom = - log1p(n) - logbeta(_k + 1, n - _k + 1)
lognum = logbeta(_k + α, n - _k + β)
logdenom = logbeta(α, β)
result = logbinom + lognum - logdenom
return _insupport ? result : oftype(result, -Inf)
end
# sum values of the probability mass function
cdf(d::BetaBinomial, k::Int) = integerunitrange_cdf(d, k)
for f in (:ccdf, :logcdf, :logccdf)
@eval begin
#CURRENT FILE: Distributions.jl/src/univariate/discrete/negativebinomial.jl |
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.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
return fₖ/s
end | 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.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
return fₖ/s
end | [
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.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
return fₖ/s
end | 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.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
return fₖ/s
end | 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 + θ^2 - π/8 * exp(-θ^2 / 2) * ((2 + θ^2) * besseli(0, θ^2 / 4) + θ^2 * besseli(1, θ^2 / 4))^2
g(θ) = sqrt(ξ(θ) * (1+r^2) - 2)
θ = g(1)
for j in 1:maxiters
θ⁻ = θ
θ = g(θ)
abs(θ - θ⁻) < tol && break
end
ξθ = ξ(θ)
σ = convert(float(T), sqrt(μ₂ / ξθ))
ν = convert(float(T), sqrt(μ₁^2 + (ξθ - 2) * σ^2))
end
#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
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end
#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
return 12sqrt(6) * zeta(3) / pi ^ 3 * one(T)
elseif ξ < 1/3
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
return sign(ξ) * (g3 - 3g1 * g2 + 2g1^3) / (g2 - g1^2) ^ (3/2)
else
return T(Inf)
end
end
#CURRENT FILE: Distributions.jl/src/univariate/discrete/noncentralhypergeometric.jl
##CHUNK 1
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
##CHUNK 2
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
##CHUNK 3
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
return m/s
##CHUNK 4
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
##CHUNK 5
return Fₖ/s
end
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
##CHUNK 6
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 in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
##CHUNK 7
# Noncentral Hypergeometric Distribution. The American Statistician, 55(4), 366–369.
# doi:10.1198/000313001753272547
#
# but the rule for terminating the summation has been slightly modified.
logpdf(d::FisherNoncentralHypergeometric, k::Real) = log(pdf(d, k))
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(ω)
|
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 in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
return Fₖ/s
end | 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 in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
return Fₖ/s
end | [
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 in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
return Fₖ/s
end | 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 in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
return Fₖ/s
end | 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 + θ^2 - π/8 * exp(-θ^2 / 2) * ((2 + θ^2) * besseli(0, θ^2 / 4) + θ^2 * besseli(1, θ^2 / 4))^2
g(θ) = sqrt(ξ(θ) * (1+r^2) - 2)
θ = g(1)
for j in 1:maxiters
θ⁻ = θ
θ = g(θ)
abs(θ - θ⁻) < tol && break
end
ξθ = ξ(θ)
σ = convert(float(T), sqrt(μ₂ / ξθ))
ν = convert(float(T), sqrt(μ₁^2 + (ξθ - 2) * σ^2))
end
#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
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end
#FILE: Distributions.jl/src/samplers/poisson.jl
##CHUNK 1
# Procedure F
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
px = -μ
py = μ^K/factorial(K)
else
δ = 0.08333333333333333/K
δ -= 4.8*δ^3
V = (μ-K)/K
px = K*log1pmx(V) - δ # avoids need for table
py = 0.3989422804014327/sqrt(K)
#FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
g(d::GeneralizedExtremeValue, k::Real) = gamma(1 - k * d.ξ) # This should not be exported.
function median(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
if abs(ξ) < eps() # ξ == 0
return μ - σ * log(log(2))
else
return μ + σ * (log(2) ^ (- ξ) - 1) / ξ
end
end
function mean(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return μ + σ * MathConstants.γ
elseif ξ < 1
return μ + σ * (gamma(1 - ξ) - 1) / ξ
else
#CURRENT FILE: Distributions.jl/src/univariate/discrete/noncentralhypergeometric.jl
##CHUNK 1
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
return fₖ/s
end
##CHUNK 2
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
##CHUNK 3
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
return m/s
##CHUNK 4
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
##CHUNK 5
logpdf(d::FisherNoncentralHypergeometric, k::Real) = log(pdf(d, k))
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
##CHUNK 6
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
|
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
return m/s
end | 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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
return m/s
end | [
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
return m/s
end | 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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s
break
end
s = sfᵢ
m += f(i)*fᵢ
end
return m/s
end | _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 + θ^2 - π/8 * exp(-θ^2 / 2) * ((2 + θ^2) * besseli(0, θ^2 / 4) + θ^2 * besseli(1, θ^2 / 4))^2
g(θ) = sqrt(ξ(θ) * (1+r^2) - 2)
θ = g(1)
for j in 1:maxiters
θ⁻ = θ
θ = g(θ)
abs(θ - θ⁻) < tol && break
end
ξθ = ξ(θ)
σ = convert(float(T), sqrt(μ₂ / ξθ))
ν = convert(float(T), sqrt(μ₁^2 + (ξθ - 2) * σ^2))
end
#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
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end
#FILE: Distributions.jl/src/univariate/continuous/generalizedextremevalue.jl
##CHUNK 1
function kurtosis(d::GeneralizedExtremeValue{T}) where T<:Real
(μ, σ, ξ) = params(d)
if abs(ξ) < eps(one(ξ)) # ξ == 0
return T(12)/5
elseif ξ < 1 / 4
g1 = g(d, 1)
g2 = g(d, 2)
g3 = g(d, 3)
g4 = g(d, 4)
return (g4 - 4g1 * g3 + 6g2 * g1^2 - 3 * g1^4) / (g2 - g1^2)^2 - 3
else
return T(Inf)
end
end
function entropy(d::GeneralizedExtremeValue)
(μ, σ, ξ) = params(d)
return log(σ) + MathConstants.γ * ξ + (1 + MathConstants.γ)
#CURRENT FILE: Distributions.jl/src/univariate/discrete/noncentralhypergeometric.jl
##CHUNK 1
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
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 terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
##CHUNK 2
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
return fₖ/s
end
##CHUNK 3
end
η = mode(d)
s = one(ω)
fᵢ = one(ω)
Fₖ = k >= η ? one(ω) : zero(ω)
for i in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
##CHUNK 4
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
return Fₖ/s
end
mean(d::FisherNoncentralHypergeometric) = _expectation(identity, d)
##CHUNK 5
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i == k
fₖ = fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
##CHUNK 6
logpdf(d::FisherNoncentralHypergeometric, k::Real) = log(pdf(d, k))
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 in (η + 1):u
rᵢ = (d.ns - i + 1)*ω/(i*(d.nf - d.n + i))*(d.n - i + 1)
fᵢ *= rᵢ
# break if terms no longer contribute to s
##CHUNK 7
sfᵢ = s + fᵢ
if sfᵢ == s && i > k
break
end
s = sfᵢ
if i <= k
Fₖ += fᵢ
end
end
fᵢ = one(ω)
for i in (η - 1):-1:l
rᵢ₊ = (d.ns - i)*ω/((i + 1)*(d.nf - d.n + i + 1))*(d.n - i)
fᵢ /= rᵢ₊
# break if terms no longer contribute to s
sfᵢ = s + fᵢ
if sfᵢ == s && i < k
break
end
s = sfᵢ
|
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",
),
)
return new{T,typeof(p)}(p, nothing)
end | 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",
),
)
return new{T,typeof(p)}(p, nothing)
end | [
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",
),
)
return new{T,typeof(p)}(p, nothing)
end | 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",
),
)
return new{T,typeof(p)}(p, nothing)
end | 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)
"""
struct NegativeBinomial{T<:Real} <: DiscreteUnivariateDistribution
r::T
p::T
function NegativeBinomial{T}(r::T, p::T) where {T <: Real}
return new{T}(r, p)
end
end
function NegativeBinomial(r::T, p::T; check_args::Bool=true) where {T <: Real}
@check_args NegativeBinomial (r, r > zero(r)) (p, zero(p) < p <= one(p))
return NegativeBinomial{T}(r, p)
#FILE: Distributions.jl/src/univariate/discrete/binomial.jl
##CHUNK 1
end
Binomial() = Binomial{Float64}(1, 0.5)
@distr_support Binomial 0 d.n
#### Conversions
function convert(::Type{Binomial{T}}, n::Int, p::Real) where T<:Real
return Binomial(n, T(p))
end
function Base.convert(::Type{Binomial{T}}, d::Binomial) where {T<:Real}
return Binomial{T}(d.n, T(d.p))
end
Base.convert(::Type{Binomial{T}}, d::Binomial{T}) where {T<:Real} = d
#### Parameters
ntrials(d::Binomial) = d.n
succprob(d::Binomial) = d.p
failprob(d::Binomial{T}) where {T} = one(T) - d.p
##CHUNK 2
Binomial() # Binomial distribution with n = 1 and p = 0.5
Binomial(n) # Binomial distribution for n trials with success rate p = 0.5
Binomial(n, p) # Binomial distribution for n trials with success rate p
params(d) # Get the parameters, i.e. (n, p)
ntrials(d) # Get the number of trials, i.e. n
succprob(d) # Get the success rate, i.e. p
failprob(d) # Get the failure rate, i.e. 1 - p
```
External links:
* [Binomial distribution on Wikipedia](http://en.wikipedia.org/wiki/Binomial_distribution)
"""
struct Binomial{T<:Real} <: DiscreteUnivariateDistribution
n::Int
p::T
Binomial{T}(n, p) where {T <: Real} = new{T}(n, p)
end
#FILE: Distributions.jl/src/multivariate/multinomial.jl
##CHUNK 1
"""
struct Multinomial{T<:Real, TV<:AbstractVector{T}} <: DiscreteMultivariateDistribution
n::Int
p::TV
Multinomial{T, TV}(n::Int, p::TV) where {T <: Real, TV <: AbstractVector{T}} = new{T, TV}(n, p)
end
function Multinomial(n::Integer, p::AbstractVector{T}; check_args::Bool=true) where {T<:Real}
@check_args(
Multinomial,
(n, n >= 0),
(p, isprobvec(p), "p is not a probability vector."),
)
return Multinomial{T,typeof(p)}(n, p)
end
function Multinomial(n::Integer, k::Integer; check_args::Bool=true)
@check_args Multinomial (n, n >= 0) (k, k >= 1)
return Multinomial{Float64, Vector{Float64}}(round(Int, n), fill(1.0 / k, k))
end
#CURRENT FILE: Distributions.jl/src/univariate/discrete/poissonbinomial.jl
##CHUNK 1
@distr_support PoissonBinomial 0 length(d.p)
#### Conversions
function PoissonBinomial(::Type{PoissonBinomial{T}}, p::AbstractVector{S}) where {T, S}
return PoissonBinomial(AbstractVector{T}(p))
end
function PoissonBinomial(::Type{PoissonBinomial{T}}, d::PoissonBinomial{S}) where {T, S}
return PoissonBinomial(AbstractVector{T}(d.p), check_args=false)
end
#### Parameters
ntrials(d::PoissonBinomial) = length(d.p)
succprob(d::PoissonBinomial) = d.p
failprob(d::PoissonBinomial{T}) where {T} = one(T) .- d.p
params(d::PoissonBinomial) = (d.p,)
partype(::PoissonBinomial{T}) where {T} = T
##CHUNK 2
function PoissonBinomial(p::AbstractVector{T}; check_args::Bool=true) where {T<:Real}
return PoissonBinomial{T}(p; check_args=check_args)
end
function Base.getproperty(d::PoissonBinomial, x::Symbol)
if x === :pmf
z = getfield(d, :pmf)
if z === nothing
y = poissonbinomial_pdf(d.p)
isprobvec(y) || error("probability mass function is not normalized")
setfield!(d, :pmf, y)
return y
else
return z
end
else
return getfield(d, x)
end
end
##CHUNK 3
where ``F_k`` is the set of all subsets of ``k`` integers that can be selected from ``\\{1,2,3,...,K\\}``.
```julia
PoissonBinomial(p) # Poisson Binomial distribution with success rate vector p
params(d) # Get the parameters, i.e. (p,)
succprob(d) # Get the vector of success rates, i.e. p
failprob(d) # Get the vector of failure rates, i.e. 1-p
```
External links:
* [Poisson-binomial distribution on Wikipedia](http://en.wikipedia.org/wiki/Poisson_binomial_distribution)
"""
mutable struct PoissonBinomial{T<:Real,P<:AbstractVector{T}} <: DiscreteUnivariateDistribution
p::P
pmf::Union{Nothing,Vector{T}} # lazy computation of the probability mass function
end
##CHUNK 4
isprobvec(y) || error("probability mass function is not normalized")
setfield!(d, :pmf, y)
return y
else
return z
end
else
return getfield(d, x)
end
end
@distr_support PoissonBinomial 0 length(d.p)
#### Conversions
function PoissonBinomial(::Type{PoissonBinomial{T}}, p::AbstractVector{S}) where {T, S}
return PoissonBinomial(AbstractVector{T}(p))
end
function PoissonBinomial(::Type{PoissonBinomial{T}}, d::PoissonBinomial{S}) where {T, S}
return PoissonBinomial(AbstractVector{T}(d.p), check_args=false)
##CHUNK 5
External links:
* [Poisson-binomial distribution on Wikipedia](http://en.wikipedia.org/wiki/Poisson_binomial_distribution)
"""
mutable struct PoissonBinomial{T<:Real,P<:AbstractVector{T}} <: DiscreteUnivariateDistribution
p::P
pmf::Union{Nothing,Vector{T}} # lazy computation of the probability mass function
end
function PoissonBinomial(p::AbstractVector{T}; check_args::Bool=true) where {T<:Real}
return PoissonBinomial{T}(p; check_args=check_args)
end
function Base.getproperty(d::PoissonBinomial, x::Symbol)
if x === :pmf
z = getfield(d, :pmf)
if z === nothing
y = poissonbinomial_pdf(d.p)
##CHUNK 6
end
#### Parameters
ntrials(d::PoissonBinomial) = length(d.p)
succprob(d::PoissonBinomial) = d.p
failprob(d::PoissonBinomial{T}) where {T} = one(T) .- d.p
params(d::PoissonBinomial) = (d.p,)
partype(::PoissonBinomial{T}) where {T} = T
#### Properties
mean(d::PoissonBinomial) = sum(succprob(d))
var(d::PoissonBinomial) = sum(p * (1 - p) for p in succprob(d))
function skewness(d::PoissonBinomial{T}) where {T}
v = zero(T)
s = zero(T)
p, = params(d)
|
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.jl/src/multivariate/multinomial.jl
##CHUNK 1
@inbounds p_i = p[i]
v[i] = n * p_i * (1 - p_i)
end
v
end
function cov(d::Multinomial{T}) where T<:Real
p = probs(d)
k = length(p)
n = ntrials(d)
C = Matrix{T}(undef, k, k)
for j = 1:k
pj = p[j]
for i = 1:j-1
@inbounds C[i,j] = - n * p[i] * pj
end
@inbounds C[j,j] = n * pj * (1-pj)
end
##CHUNK 2
p = probs(d)
n = ntrials(d)
s = zero(Complex{T})
for i in 1:length(p)
s += p[i] * exp(im * t[i])
end
return s^n
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
##CHUNK 3
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, 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]
#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
else
q = 1.0 - p
a = p / q
@inbounds pv[1] = pk = q ^ n
for k = 1:n
@inbounds pv[k+1] = (pk *= ((n - k + 1) / k) * a)
end
end
return pv
end
##CHUNK 2
# 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
#FILE: Distributions.jl/src/univariate/discrete/discretenonparametric.jl
##CHUNK 1
@inbounds for i in 1:stop_idx
s += ps[i]
end
s = 1 - s
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
end
end
return s
end
function quantile(d::DiscreteNonParametric, q::Real)
0 <= q <= 1 || throw(DomainError())
x = support(d)
p = probs(d)
k = length(x)
i = 1
cp = p[1]
##CHUNK 2
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 < div(n, 2)
@inbounds for i in 1:stop_idx
s += ps[i]
end
else
@inbounds for i in (stop_idx + 1):n
s += ps[i]
#FILE: Distributions.jl/src/samplers/multinomial.jl
##CHUNK 1
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 if needed)
i = 0
km1 = k - 1
while i < km1 && n > 0
i += 1
@inbounds pi = p[i]
if pi < rp
xi = rand(rng, Binomial(n, Float64(pi / rp)))
@inbounds x[i] = xi
n -= xi
rp -= pi
else
# In this case, we don't even have to sample
#FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
function cdf(d::UnivariateMixture, x::Real)
p = probs(d)
r = sum(pi * cdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
return r
end
function _mixpdf1(d::AbstractMixtureModel, x)
p = probs(d)
return sum(pi * pdf(component(d, i), x) for (i, pi) in enumerate(p) if !iszero(pi))
end
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
#CURRENT FILE: Distributions.jl/src/univariate/discrete/poissonbinomial.jl |
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 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
for j in 1:(i-1)
A[j, end] *= pi
end
for j in (i+1):n
A[j, end] *= pi
end
end
@inbounds for j in 1:n, i in 1:n
A[i, j] -= A[i, j+1]
end
return A
end | 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 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
for j in 1:(i-1)
A[j, end] *= pi
end
for j in (i+1):n
A[j, end] *= pi
end
end
@inbounds for j in 1:n, i in 1:n
A[i, j] -= A[i, j+1]
end
return A
end | [
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 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
for j in 1:(i-1)
A[j, end] *= pi
end
for j in (i+1):n
A[j, end] *= pi
end
end
@inbounds for j in 1:n, i in 1:n
A[i, j] -= A[i, j+1]
end
return A
end | 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 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
for j in 1:(i-1)
A[j, end] *= pi
end
for j in (i+1):n
A[j, end] *= pi
end
end
@inbounds for j in 1:n, i in 1:n
A[i, j] -= A[i, j+1]
end
return A
end | 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
for (j, xⱼ) in Iterators.drop(zip(ranks, x), 1)
xⱼ < xᵢ && return oftype(lp, -Inf)
lp += _marginalize_range(d.dist, i, j, xᵢ, xⱼ, T)
i = j
xᵢ = xⱼ
end
if i < n # _marginalize_range(d.dist, i, n + 1, xᵢ, Inf, T)
lp += (n - i) * logccdf(d.dist, xᵢ) - loggamma(T(n - i + 1))
end
return lp
end
#FILE: Distributions.jl/src/univariate/continuous/ksdist.jl
##CHUNK 1
H[i,1] = H[m,m-i+1] = ch*r
r += h^i
end
H[m,1] += h <= 0.5 ? -h^m : -h^m+(h-ch)
for i = 1:m, j = 1:m
for g = 1:max(i-j+1,0)
H[i,j] /= g
end
# we can avoid keeping track of the exponent by dividing by e
# (from Stirling's approximation)
H[i,j] /= ℯ
end
Q = H^n
s = Q[k,k]
s*stirling(n)
end
# Miller (1956) approximation
function ccdf_miller(d::KSDist, x::Real)
2*ccdf(KSOneSided(d.n),x)
#FILE: Distributions.jl/src/cholesky/lkjcholesky.jl
##CHUNK 1
A[2, 1] = w0
else
A[1, 2] = w0
end
@inbounds A[2, 2] = sqrt(1 - w0^2)
# 2. Loop, each iteration k adds row/column k+1
for k in 2:(d - 1)
# (a)
β -= 1//2
# (b)
y = rand(rng, Beta(k//2, β))
# (c)-(e)
# w is directionally uniform vector of length √y
@inbounds w = @views uplo === :L ? A[k + 1, 1:k] : A[1:k, k + 1]
Random.randn!(rng, w)
rmul!(w, sqrt(y) / norm(w))
# normalize so new row/column has unit norm
@inbounds A[k + 1, k + 1] = sqrt(1 - y)
end
# 3.
#FILE: Distributions.jl/src/matrix/matrixbeta.jl
##CHUNK 1
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*(-(2/n)*Ω[i,j]*Ω[k,l] + Ω[j,l]*Ω[i,k] + Ω[i,l]*Ω[k,j])
end
function var(d::MatrixBeta, i::Integer, j::Integer)
p, n1, n2 = params(d)
n = n1 + n2
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*((1 - (2/n))*Ω[i,j]^2 + Ω[j,j]*Ω[i,i])
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function matrixbeta_logc0(p::Int, n1::Real, n2::Real)
# returns the natural log of the normalizing constant for the pdf
return -logmvbeta(p, n1 / 2, n2 / 2)
end
##CHUNK 2
params(d::MatrixBeta) = (size(d, 1), d.W1.df, d.W2.df)
mean(d::MatrixBeta) = ((p, n1, n2) = params(d); Matrix((n1 / (n1 + n2)) * I, p, p))
@inline partype(d::MatrixBeta{T}) where {T <: Real} = T
# Konno (1988 JJSS) Corollary 3.3.i
function cov(d::MatrixBeta, i::Integer, j::Integer, k::Integer, l::Integer)
p, n1, n2 = params(d)
n = n1 + n2
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*(-(2/n)*Ω[i,j]*Ω[k,l] + Ω[j,l]*Ω[i,k] + Ω[i,l]*Ω[k,j])
end
function var(d::MatrixBeta, i::Integer, j::Integer)
p, n1, n2 = params(d)
n = n1 + n2
Ω = Matrix{partype(d)}(I, p, p)
n1*n2*inv(n*(n - 1)*(n + 2))*((1 - (2/n))*Ω[i,j]^2 + Ω[j,j]*Ω[i,i])
end
#FILE: Distributions.jl/src/matrix/wishart.jl
##CHUNK 1
df = oftype(logdet_S, d.df)
for i in 0:(p - 1)
v += digamma((df - i) / 2)
end
return d.singular ? oftype(v, -Inf) : v
end
function entropy(d::Wishart)
d.singular && throw(ArgumentError("entropy not defined for singular Wishart."))
p = size(d, 1)
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
##CHUNK 2
df = d.df
return -d.logc0 - ((df - p - 1) * meanlogdet(d) - df * p) / 2
end
# Gupta/Nagar (1999) Theorem 3.3.15.i
function cov(d::Wishart, i::Integer, j::Integer, k::Integer, l::Integer)
S = d.S
return d.df * (S[i, k] * S[j, l] + S[i, l] * S[j, k])
end
function var(d::Wishart, i::Integer, j::Integer)
S = d.S
return d.df * (S[i, i] * S[j, j] + S[i, j] ^ 2)
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
function wishart_logc0(df::T, S::AbstractPDMat{T}, rnk::Integer) where {T<:Real}
#FILE: Distributions.jl/src/mixtures/mixturemodel.jl
##CHUNK 1
if lp_i[j] > m[j]
m[j] = lp_i[j]
end
end
end
end
fill!(r, 0.0)
@inbounds for i = 1:K
if p[i] > 0.0
lp_i = view(Lp, :, i)
for j = 1:n
r[j] += exp(lp_i[j] - m[j])
end
end
end
@inbounds for j = 1:n
r[j] = log(r[j]) + m[j]
end
#FILE: Distributions.jl/test/testutils.jl
##CHUNK 1
cc = Vector{Float64}(undef, nv)
lp = Vector{Float64}(undef, nv)
lc = Vector{Float64}(undef, nv)
lcc = Vector{Float64}(undef, nv)
ci = 0.
for (i, v) in enumerate(vs)
p[i] = pdf(d, v)
c[i] = cdf(d, v)
cc[i] = ccdf(d, v)
lp[i] = logpdf(d, v)
lc[i] = logcdf(d, v)
lcc[i] = logccdf(d, v)
@assert p[i] >= 0.0
@assert (i == 1 || c[i] >= c[i-1])
ci += p[i]
@test ci ≈ c[i]
@test isapprox(c[i] + cc[i], 1.0 , atol=1.0e-12)
#FILE: Distributions.jl/src/matrix/matrixfdist.jl
##CHUNK 1
n1, n2, PDB = params(d)
n2 > p + 3 || throw(ArgumentError("cov only defined for df2 > dim + 3"))
n = n1 + n2
B = Matrix(PDB)
n1*(n - p - 1)*inv((n2 - p)*(n2 - p - 1)*(n2 - p - 3))*(2inv(n2 - p - 1)*B[i,j]*B[k,l] + B[j,l]*B[i,k] + B[i,l]*B[k,j])
end
function var(d::MatrixFDist, i::Integer, j::Integer)
p = size(d, 1)
n1, n2, PDB = params(d)
n2 > p + 3 || throw(ArgumentError("var only defined for df2 > dim + 3"))
n = n1 + n2
B = Matrix(PDB)
n1*(n - p - 1)*inv((n2 - p)*(n2 - p - 1)*(n2 - p - 3))*((2inv(n2 - p - 1) + 1)*B[i,j]^2 + B[j,j]*B[i,i])
end
# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
#CURRENT FILE: Distributions.jl/src/univariate/discrete/poissonbinomial.jl |
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 = [arma.theta; zeros(impulse_length - arma.q)]
psi_zero = 1.0
psi = Vector{Float64}(undef, impulse_length)
for j = 1:impulse_length
psi[j] = theta[j]
for i = 1:min(j, arma.p)
psi[j] += arma.phi[i] * (j-i > 0 ? psi[j-i] : psi_zero)
end
end
return [psi_zero; psi[1:end-1]]
end | 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 = [arma.theta; zeros(impulse_length - arma.q)]
psi_zero = 1.0
psi = Vector{Float64}(undef, impulse_length)
for j = 1:impulse_length
psi[j] = theta[j]
for i = 1:min(j, arma.p)
psi[j] += arma.phi[i] * (j-i > 0 ? psi[j-i] : psi_zero)
end
end
return [psi_zero; psi[1:end-1]]
end | [
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 = [arma.theta; zeros(impulse_length - arma.q)]
psi_zero = 1.0
psi = Vector{Float64}(undef, impulse_length)
for j = 1:impulse_length
psi[j] = theta[j]
for i = 1:min(j, arma.p)
psi[j] += arma.phi[i] * (j-i > 0 ? psi[j-i] : psi_zero)
end
end
return [psi_zero; psi[1:end-1]]
end | 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 = [arma.theta; zeros(impulse_length - arma.q)]
psi_zero = 1.0
psi = Vector{Float64}(undef, impulse_length)
for j = 1:impulse_length
psi[j] = theta[j]
for i = 1:min(j, arma.p)
psi[j] += arma.phi[i] * (j-i > 0 ? psi[j-i] : psi_zero)
end
end
return [psi_zero; psi[1:end-1]]
end | 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_resp = impulse_response(lp, impulse_length=75)
@test length(imp_resp) == 75
@testset "test constructors" begin
phi = 0.5
theta = 0.4
sigma = 0.15
##CHUNK 2
@test length(sim) == 250
# test impulse response
imp_resp = impulse_response(lp, impulse_length=75)
@test length(imp_resp) == 75
@testset "test constructors" begin
phi = 0.5
theta = 0.4
sigma = 0.15
a1 = ARMA(phi, theta, sigma)
a2 = ARMA([phi;], theta, sigma)
a3 = ARMA(phi, [theta;], sigma)
for nm in fieldnames(typeof(a1))
@test getfield(a1, nm) == getfield(a2, nm)
@test getfield(a1, nm) == getfield(a3, nm)
end
end
##CHUNK 3
@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)
#CURRENT FILE: QuantEcon.jl/src/arma.jl
##CHUNK 1
"""
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
X[t] = dot(epsilon[t:J+t-1], psi)
end
return X
end
##CHUNK 2
##### Arguments
- `arma::ARMA`: Instance of `ARMA` type
- `;ts_length::Integer(90)`: Length of simulation
- `;impulse_length::Integer(30)`: Horizon for calculating impulse response
(see also docstring for `impulse_response`)
##### Returns
- `X::Vector{Float64}`: Simulation of the ARMA model `arma`
"""
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
##CHUNK 3
"""
function autocovariance(arma::ARMA; num_autocov::Integer=16)
# Compute the autocovariance function associated with ARMA process arma
# Computation is via the spectral density and inverse FFT
(w, spect) = spectral_density(arma)
acov = real(ifft(spect))
# num_autocov should be <= len(acov) / 2
return acov[1:num_autocov]
end
@doc doc"""
Get the impulse response corresponding to our model.
##### Arguments
- `arma::ARMA`: Instance of `ARMA` type
- `;impulse_length::Integer(30)`: Length of horizon for calcluating impulse reponse. Must be at least as long as the `p` fields of `arma`
##CHUNK 4
@doc doc"""
Get the impulse response corresponding to our model.
##### Arguments
- `arma::ARMA`: Instance of `ARMA` type
- `;impulse_length::Integer(30)`: Length of horizon for calcluating impulse reponse. Must be at least as long as the `p` fields of `arma`
##### Returns
- `psi::Vector{Float64}`: `psi[j]` is the response at lag j of the impulse
response. We take `psi[1]` as unity.
"""
"""
Compute a simulated sample path assuming Gaussian shocks.
##CHUNK 5
If ``\phi`` and ``\theta`` are arrays or sequences,
then the interpretation is the ARMA(p, q) model
```math
X_t = \phi_1 X_{t-1} + ... + \phi_p X_{t-p} +
\epsilon_t + \theta_1 \epsilon_{t-1} + \ldots +
\theta_q \epsilon_{t-q}
```
where
* ``\phi = (\phi_1, \phi_2, \ldots , \phi_p)``
* ``\theta = (\theta_1, \theta_2, \ldots , \theta_q)``
* ``\sigma`` is a scalar, the standard deviation of the white noise
##### Fields
- `phi::Vector` : AR parameters ``\phi_1, \ldots, \phi_p``
- `theta::Vector` : MA parameters ``\theta_1, \ldots, \theta_q``
- `p::Integer` : Number of AR coefficients
##CHUNK 6
ARMA(phi::Vector, theta::Real, sigma::Real) = ARMA(phi, [theta;], sigma)
function ARMA(phi::AbstractVector, theta::AbstractVector=[0.0], sigma::Real=1.0)
# == Record dimensions == #
p = length(phi)
q = length(theta)
# == Build filtering representation of polynomials == #
ma_poly = [1.0; theta]
ar_poly = [1.0; -phi]
return ARMA(phi, theta, p, q, sigma, ma_poly, ar_poly)
end
@doc doc"""
Compute the spectral density function.
The spectral density is the discrete time Fourier transform of the
autocovariance function. In particular,
```math
##CHUNK 7
##### Returns
- `psi::Vector{Float64}`: `psi[j]` is the response at lag j of the impulse
response. We take `psi[1]` as unity.
"""
"""
Compute a simulated sample path assuming Gaussian shocks.
##### Arguments
- `arma::ARMA`: Instance of `ARMA` type
- `;ts_length::Integer(90)`: Length of simulation
- `;impulse_length::Integer(30)`: Horizon for calculating impulse response
(see also docstring for `impulse_response`)
##### Returns
- `X::Vector{Float64}`: Simulation of the ARMA model `arma`
|
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
X[t] = dot(epsilon[t:J+t-1], psi)
end
return X
end | 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
X[t] = dot(epsilon[t:J+t-1], psi)
end
return X
end | [
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
X[t] = dot(epsilon[t:J+t-1], psi)
end
return X
end | 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
X[t] = dot(epsilon[t:J+t-1], psi)
end
return X
end | 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_resp = impulse_response(lp, impulse_length=75)
@test length(imp_resp) == 75
@testset "test constructors" begin
phi = 0.5
theta = 0.4
sigma = 0.15
##CHUNK 2
@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)
##CHUNK 3
@test length(sim) == 250
# test impulse response
imp_resp = impulse_response(lp, impulse_length=75)
@test length(imp_resp) == 75
@testset "test constructors" begin
phi = 0.5
theta = 0.4
sigma = 0.15
a1 = ARMA(phi, theta, sigma)
a2 = ARMA([phi;], theta, sigma)
a3 = ARMA(phi, [theta;], sigma)
for nm in fieldnames(typeof(a1))
@test getfield(a1, nm) == getfield(a2, nm)
@test getfield(a1, nm) == getfield(a3, nm)
end
end
#FILE: QuantEcon.jl/src/lss.jl
##CHUNK 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, y
end
@doc doc"""
Simulate `num_reps` observations of ``x_T`` and ``y_T`` given ``x_0 \sim N(\mu_0, \Sigma_0)``.
#### Arguments
- `lss::LSS` An instance of the Gaussian linear state space model.
- `t::Int = 10` The period that we want to replicate values for.
- `num_reps::Int = 100` The number of replications we want
#### Returns
#CURRENT FILE: QuantEcon.jl/src/arma.jl
##CHUNK 1
# == Pad theta with zeros at the end == #
theta = [arma.theta; zeros(impulse_length - arma.q)]
psi_zero = 1.0
psi = Vector{Float64}(undef, impulse_length)
for j = 1:impulse_length
psi[j] = theta[j]
for i = 1:min(j, arma.p)
psi[j] += arma.phi[i] * (j-i > 0 ? psi[j-i] : psi_zero)
end
end
return [psi_zero; psi[1:end-1]]
end
"""
Compute a simulated sample path assuming Gaussian shocks.
##### Arguments
- `arma::ARMA`: Instance of `ARMA` type
- `;ts_length::Integer(90)`: Length of simulation
##CHUNK 2
@doc doc"""
Get the impulse response corresponding to our model.
##### Arguments
- `arma::ARMA`: Instance of `ARMA` type
- `;impulse_length::Integer(30)`: Length of horizon for calcluating impulse reponse. Must be at least as long as the `p` fields of `arma`
##### Returns
- `psi::Vector{Float64}`: `psi[j]` is the response at lag j of the impulse
response. We take `psi[1]` as unity.
"""
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
##CHUNK 3
return [psi_zero; psi[1:end-1]]
end
"""
Compute a simulated sample path assuming Gaussian shocks.
##### Arguments
- `arma::ARMA`: Instance of `ARMA` type
- `;ts_length::Integer(90)`: Length of simulation
- `;impulse_length::Integer(30)`: Horizon for calculating impulse response
(see also docstring for `impulse_response`)
##### Returns
- `X::Vector{Float64}`: Simulation of the ARMA model `arma`
"""
##CHUNK 4
References
----------
https://lectures.quantecon.org/jl/arma.html
=#
@doc doc"""
Represents a scalar ARMA(p, q) process
If ``\phi`` and ``\theta`` are scalars, then the model is
understood to be
```math
X_t = \phi X_{t-1} + \epsilon_t + \theta \epsilon_{t-1}
```
where ``\epsilon_t`` is a white noise process with standard
deviation sigma.
##CHUNK 5
##### Returns
- `psi::Vector{Float64}`: `psi[j]` is the response at lag j of the impulse
response. We take `psi[1]` as unity.
"""
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 = [arma.theta; zeros(impulse_length - arma.q)]
psi_zero = 1.0
psi = Vector{Float64}(undef, impulse_length)
for j = 1:impulse_length
psi[j] = theta[j]
for i = 1:min(j, arma.p)
psi[j] += arma.phi[i] * (j-i > 0 ? psi[j-i] : psi_zero)
end
end
##CHUNK 6
If ``\phi`` and ``\theta`` are scalars, then the model is
understood to be
```math
X_t = \phi X_{t-1} + \epsilon_t + \theta \epsilon_{t-1}
```
where ``\epsilon_t`` is a white noise process with standard
deviation sigma.
If ``\phi`` and ``\theta`` are arrays or sequences,
then the interpretation is the ARMA(p, q) model
```math
X_t = \phi_1 X_{t-1} + ... + \phi_p X_{t-p} +
\epsilon_t + \theta_1 \epsilon_{t-1} + \ldots +
\theta_q \epsilon_{t-q}
```
where
|
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 should be 0, 1 or 2"))
end
iterate = 0
err = err_tol + 1
while iterate < max_iter && err > err_tol
new_v = T(v)::TV
iterate += 1
err = Base.maximum(abs, new_v - v)
if verbose == 2
if iterate % print_skip == 0
println("Compute iterate $iterate with error $err")
end
end
v = new_v
end
if verbose >= 1
if err > err_tol
@warn("max_iter attained in compute_fixed_point")
elseif verbose == 2
println("Converged in $iterate steps")
end
end
return v
end | 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 should be 0, 1 or 2"))
end
iterate = 0
err = err_tol + 1
while iterate < max_iter && err > err_tol
new_v = T(v)::TV
iterate += 1
err = Base.maximum(abs, new_v - v)
if verbose == 2
if iterate % print_skip == 0
println("Compute iterate $iterate with error $err")
end
end
v = new_v
end
if verbose >= 1
if err > err_tol
@warn("max_iter attained in compute_fixed_point")
elseif verbose == 2
println("Converged in $iterate steps")
end
end
return v
end | [
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 should be 0, 1 or 2"))
end
iterate = 0
err = err_tol + 1
while iterate < max_iter && err > err_tol
new_v = T(v)::TV
iterate += 1
err = Base.maximum(abs, new_v - v)
if verbose == 2
if iterate % print_skip == 0
println("Compute iterate $iterate with error $err")
end
end
v = new_v
end
if verbose >= 1
if err > err_tol
@warn("max_iter attained in compute_fixed_point")
elseif verbose == 2
println("Converged in $iterate steps")
end
end
return v
end | 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 should be 0, 1 or 2"))
end
iterate = 0
err = err_tol + 1
while iterate < max_iter && err > err_tol
new_v = T(v)::TV
iterate += 1
err = Base.maximum(abs, new_v - v)
if verbose == 2
if iterate % print_skip == 0
println("Compute iterate $iterate with error $err")
end
end
v = new_v
end
if verbose >= 1
if err > err_tol
@warn("max_iter attained in compute_fixed_point")
elseif verbose == 2
println("Converged in $iterate steps")
end
end
return v
end | 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]
# arguments for compute_fixed_point
kwargs = Dict{Symbol,Any}(:err_tol => 1e-5, :max_iter => 200,
:verbose => true, :print_skip => 30)
rough_kwargs = Dict{Symbol,Any}(:atol => 1e-4)
T(x, mu) = 4.0 * mu * x * (1.0 - x)
# shorthand
#FILE: QuantEcon.jl/src/markov/ddp.jl
##CHUNK 1
old_sigma = copy(ddpr.sigma)
tol = beta > 0 ? epsilon * (1-beta) / beta : Inf
for i in 1:max_iter
bellman_operator!(ddp, ddpr) # updates Tv, sigma inplace
dif = ddpr.Tv - ddpr.v
ddpr.num_iter += 1
# check convergence
if span(dif) < tol
ddpr.v = ddpr.Tv .+ midrange(dif) * beta / (1-beta)
break
end
# now update v to use the output of the bellman step when entering
# policy loop
copyto!(ddpr.v, ddpr.Tv)
##CHUNK 2
throw(ArgumentError("method invalid for beta = 1"))
else
tol = epsilon * (1-ddp.beta) / (2*ddp.beta)
end
for i in 1:max_iter
# updates Tv in place
bellman_operator!(ddp, ddpr)
# compute error and update the v inside ddpr
err = maximum(abs, ddpr.Tv .- ddpr.v)
copyto!(ddpr.v, ddpr.Tv)
ddpr.num_iter += 1
if err < tol
break
end
end
ddpr
#FILE: QuantEcon.jl/other/ddpsolve.jl
##CHUNK 1
for it = 1:maxit
vold = v
xold = x
v, x = valmax(v, f, P, delta)
pstar, fstar, ind = valpol(x, f, P)
v = (speye(n)-diagmult(delta[ind], pstar)) \ fstar
err = norm(v - vold)
println("it: $it\terr: $err")
if x == xold
break
end
end
return v, x, pstar
end
#FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
##CHUNK 2
p1 = fill!(similar(z), one(eltype(z)))
p2 = fill!(similar(z), one(eltype(z)))
for j = 1:n
p3 = p2
p2 = p1
p1 = ((2 * j - 1) * z .* p2 - (j - 1) * p3) ./ j
end
# p1 is now a vector of Legendre polynomials of degree 1..n
# pp will be the deriative of each p1 at the nth zero of each
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
#FILE: QuantEcon.jl/test/test_ddp.jl
##CHUNK 1
# just test that we can call the method and the result is
# deterministic
@test bellman_operator!(ddp, v, s) == bellman_operator!(ddp, v, s)
end
for T in int_types
s = T[1, 1]
@test isapprox(evaluate_policy(ddp, s), v_star)
end
end
end
@testset "compute_greedy! changes ddpr.v" begin
res = solve(ddp0, VFI)
res.Tv[:] .= 500.0
compute_greedy!(ddp0, res)
@test maximum(abs, res.Tv .- 500.0) > 0
end
@testset "value_iteration" begin
#FILE: QuantEcon.jl/src/robustlq.jl
##CHUNK 1
"""
function robust_rule_simple(rlq::RBLQ,
P::Matrix=zeros(Float64, rlq.n, rlq.n);
max_iter=80,
tol=1e-8)
# Simplify notation
A, B, C, Q, R = rlq.A, rlq.B, rlq.C, rlq.Q, rlq.R
bet, theta, k, j = rlq.bet, rlq.theta, rlq.k, rlq.j
iterate, e = 0, tol + 1.0
F = similar(P) # instantiate so available after loop
while iterate <= max_iter && e > tol
F, new_P = b_operator(rlq, d_operator(rlq, P))
e = sqrt(sum((new_P - P).^2))
iterate += 1
copyto!(P, new_P)
end
#CURRENT FILE: QuantEcon.jl/src/compute_fp.jl
##CHUNK 1
err_tol` or `max_iter` iterations has been exceeded.
Provided that ``T`` is a contraction mapping or similar, the return value will
be an approximation to the fixed point of ``T``.
##### Arguments
* `T`: A function representing the operator ``T``
* `v::TV`: The initial condition. An object of type ``TV``
* `;err_tol(1e-3)`: Stopping tolerance for iterations
* `;max_iter(50)`: Maximum number of iterations
* `;verbose(2)`: Level of feedback (0 for no output, 1 for warnings only, 2
for warning and convergence messages during iteration)
* `;print_skip(10)` : if `verbose == 2`, how many iterations to apply between
print messages
##### Returns
---
* '::TV': The fixed point of the operator ``T``. Has type ``TV``
##CHUNK 2
* `;max_iter(50)`: Maximum number of iterations
* `;verbose(2)`: Level of feedback (0 for no output, 1 for warnings only, 2
for warning and convergence messages during iteration)
* `;print_skip(10)` : if `verbose == 2`, how many iterations to apply between
print messages
##### Returns
---
* '::TV': The fixed point of the operator ``T``. Has type ``TV``
##### Example
```julia
using QuantEcon
T(x, μ) = 4.0 * μ * x * (1.0 - x)
x_star = compute_fixed_point(x->T(x, 0.3), 0.4) # (4μ - 1)/(4μ)
```
"""
|
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)
window_len += 1
println("Window length must be odd, reset to $window_len")
end
windows = Dict("hanning" => DSP.hanning,
"hamming" => DSP.hamming,
"bartlett" => DSP.bartlett,
"blackman" => DSP.blackman,
"flat" => DSP.rect # moving average
)
# Reflect x around x[0] and x[-1] prior to convolution
k = ceil(Int, window_len / 2)
xb = x[1:k] # First k elements
xt = x[end-k+1:end] # Last k elements
s = [reverse(xb); x; reverse(xt)]
# === Select window values === #
if !haskey(windows, window)
msg = "Unrecognized window type '$window'"
print(msg * " Defaulting to hanning")
window = "hanning"
end
w = windows[window](window_len)
return conv(w ./ sum(w), s)[window_len+1:end-window_len]
end | 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)
window_len += 1
println("Window length must be odd, reset to $window_len")
end
windows = Dict("hanning" => DSP.hanning,
"hamming" => DSP.hamming,
"bartlett" => DSP.bartlett,
"blackman" => DSP.blackman,
"flat" => DSP.rect # moving average
)
# Reflect x around x[0] and x[-1] prior to convolution
k = ceil(Int, window_len / 2)
xb = x[1:k] # First k elements
xt = x[end-k+1:end] # Last k elements
s = [reverse(xb); x; reverse(xt)]
# === Select window values === #
if !haskey(windows, window)
msg = "Unrecognized window type '$window'"
print(msg * " Defaulting to hanning")
window = "hanning"
end
w = windows[window](window_len)
return conv(w ./ sum(w), s)[window_len+1:end-window_len]
end | [
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)
window_len += 1
println("Window length must be odd, reset to $window_len")
end
windows = Dict("hanning" => DSP.hanning,
"hamming" => DSP.hamming,
"bartlett" => DSP.bartlett,
"blackman" => DSP.blackman,
"flat" => DSP.rect # moving average
)
# Reflect x around x[0] and x[-1] prior to convolution
k = ceil(Int, window_len / 2)
xb = x[1:k] # First k elements
xt = x[end-k+1:end] # Last k elements
s = [reverse(xb); x; reverse(xt)]
# === Select window values === #
if !haskey(windows, window)
msg = "Unrecognized window type '$window'"
print(msg * " Defaulting to hanning")
window = "hanning"
end
w = windows[window](window_len)
return conv(w ./ sum(w), s)[window_len+1:end-window_len]
end | 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)
window_len += 1
println("Window length must be odd, reset to $window_len")
end
windows = Dict("hanning" => DSP.hanning,
"hamming" => DSP.hamming,
"bartlett" => DSP.bartlett,
"blackman" => DSP.blackman,
"flat" => DSP.rect # moving average
)
# Reflect x around x[0] and x[-1] prior to convolution
k = ceil(Int, window_len / 2)
xb = x[1:k] # First k elements
xt = x[end-k+1:end] # Last k elements
s = [reverse(xb); x; reverse(xt)]
# === Select window values === #
if !haskey(windows, window)
msg = "Unrecognized window type '$window'"
print(msg * " Defaulting to hanning")
window = "hanning"
end
w = windows[window](window_len)
return conv(w ./ sum(w), s)[window_len+1:end-window_len]
end | 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)
# when x is even we get 10 elements back
@test n_w == (iseven(n_x) ? floor(Int, n_x / 2) : floor(Int, n_x / 2 + 1))
@test n_Iw == (iseven(n_x) ? floor(Int, n_x / 2) : floor(Int, n_x / 2 + 1))
end
end # teset set
@testset "testing `smooth` function options" begin
# window length must be between 3 and length(x)
@test_throws ArgumentError smooth(x_20, window_len=25)
@test_throws ArgumentError smooth(x_20, window_len=2)
# test hanning is default
##CHUNK 2
@test n_Iw == (iseven(n_x) ? floor(Int, n_x / 2) : floor(Int, n_x / 2 + 1))
end
end # teset set
@testset "testing `smooth` function options" begin
# window length must be between 3 and length(x)
@test_throws ArgumentError smooth(x_20, window_len=25)
@test_throws ArgumentError smooth(x_20, window_len=2)
# test hanning is default
out = smooth(x_20, window="foobar")
@test out == smooth(x_20, window="hanning")
# test window_len must be odd
@test length(smooth(x_20, window_len=6)) == length(smooth(x_20, window_len=7))
end # @testset
@testset "issue from http://discourse.quantecon.org/t/question-about-estspec-jl/61" begin
##CHUNK 3
out = smooth(x_20, window="foobar")
@test out == smooth(x_20, window="hanning")
# test window_len must be odd
@test length(smooth(x_20, window_len=6)) == length(smooth(x_20, window_len=7))
end # @testset
@testset "issue from http://discourse.quantecon.org/t/question-about-estspec-jl/61" begin
T = 150
rho = -0.9
e = randn(T)
x = [e[1]]
tmp = e[1]
for t = 2:T
tmp = rho*tmp+e[t]
push!(x,tmp)
end
#FILE: QuantEcon.jl/src/markov/markov_approx.jl
##CHUNK 1
Nm::Integer,
n_moments::Integer=2,
method::VAREstimationMethod=Even(),
n_sigmas::Real=sqrt(Nm-1))
# b = zeros(2)
# A = [0.9809 0.0028; 0.041 0.9648]
# Sigma = [7.569e-5 0.0; 0.0 0.00068644]
# N = 9
# n_moments = nMoments
# method = Quantile()
# b, B, Psi, Nm = (zeros(2), A, Sigma, N, nMoments, Quantile())
M, M_ = size(B, 1), size(B, 2)
# Check size restrictions on matrices
M == M_ || throw(ArgumentError("B must be a scalar or square matrix"))
M == length(b) || throw(ArgumentError("b must have the same number of rows as B"))
#% Check that Psi is a valid covariance matrix
isposdef(Psi) || throw(ArgumentError("Psi must be a positive definite matrix"))
#CURRENT FILE: QuantEcon.jl/src/estspec.jl
##CHUNK 1
- `x::Array`: An array containing the data to smooth
- `window_len::Int(7)`: An odd integer giving the length of the window
- `window::AbstractString("hanning")`: A string giving the window type.
Possible values are `flat`, `hanning`, `hamming`, `bartlett`, or `blackman`
##### Returns
- `out::Array`: The array of smoothed data
"""
"Version of `smooth` where `window_len` and `window` are keyword arguments"
function smooth(x::Array; window_len::Int=7, window::AbstractString="hanning")
smooth(x, window_len, window)
end
function periodogram(x::Vector)
n = length(x)
I_w = abs.(fft(x)).^2 ./ n
w = 2pi * (0:n-1) ./ n # Fourier frequencies
##CHUNK 2
https://lectures.quantecon.org/jl/estspec.html
=#
using DSP
"""
Smooth the data in x using convolution with a window of requested size and type.
##### Arguments
- `x::Array`: An array containing the data to smooth
- `window_len::Int(7)`: An odd integer giving the length of the window
- `window::AbstractString("hanning")`: A string giving the window type.
Possible values are `flat`, `hanning`, `hamming`, `bartlett`, or `blackman`
##### Returns
- `out::Array`: The array of smoothed data
"""
##CHUNK 3
"Version of `smooth` where `window_len` and `window` are keyword arguments"
function smooth(x::Array; window_len::Int=7, window::AbstractString="hanning")
smooth(x, window_len, window)
end
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, n / 2)
w, I_w = w[1:ind], I_w[1:ind]
return w, I_w
end
function periodogram(x::Vector, window::AbstractString, window_len::Int=7)
w, I_w = periodogram(x)
##CHUNK 4
at the Fourier frequences ``w_j := 2 \frac{\pi j}{n}, j = 0, \ldots, n - 1``, using the fast
Fourier transform. Only the frequences ``w_j`` in ``[0, \pi]`` and corresponding values
``I(w_j)`` are returned. If a window type is given then smoothing is performed.
##### Arguments
- `x::Array`: An array containing the data to smooth
- `window_len::Int(7)`: An odd integer giving the length of the window
- `window::AbstractString("hanning")`: A string giving the window type. Possible values
are `flat`, `hanning`, `hamming`, `bartlett`, or `blackman`
##### Returns
- `w::Array{Float64}`: Fourier frequencies at which the periodogram is evaluated
- `I_w::Array{Float64}`: The periodogram at frequences `w`
"""
periodogram
##CHUNK 5
"""
Compute periodogram from data `x`, using prewhitening, smoothing and recoloring.
The data is fitted to an AR(1) model for prewhitening, and the residuals are
used to compute a first-pass periodogram with smoothing. The fitted
coefficients are then used for recoloring.
##### Arguments
- `x::Array`: An array containing the data to smooth
- `window_len::Int(7)`: An odd integer giving the length of the window
- `window::AbstractString("hanning")`: A string giving the window type. Possible values
are `flat`, `hanning`, `hamming`, `bartlett`, or `blackman`
##### 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)
##CHUNK 6
I_w = smooth(I_w, window_len=window_len, window=window)
return w, I_w
end
@doc doc"""
Computes the periodogram
```math
I(w) = \frac{1}{n} | \sum_{t=0}^{n-1} x_t e^{itw} |^2
```
at the Fourier frequences ``w_j := 2 \frac{\pi j}{n}, j = 0, \ldots, n - 1``, using the fast
Fourier transform. Only the frequences ``w_j`` in ``[0, \pi]`` and corresponding values
``I(w_j)`` are returned. If a window type is given then smoothing is performed.
##### Arguments
- `x::Array`: An array containing the data to smooth
- `window_len::Int(7)`: An odd integer giving the length of the window
- `window::AbstractString("hanning")`: A string giving the window type. Possible values
|
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, n / 2)
w, I_w = w[1:ind], I_w[1:ind]
return w, I_w
end | 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, n / 2)
w, I_w = w[1:ind], I_w[1:ind]
return w, I_w
end | [
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, n / 2)
w, I_w = w[1:ind], I_w[1:ind]
return w, I_w
end | 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, n / 2)
w, I_w = w[1:ind], I_w[1:ind]
return w, I_w
end | 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]
w, I_w = periodogram(x)
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)
# when x is even we get 10 elements back
@test n_w == (iseven(n_x) ? floor(Int, n_x / 2) : floor(Int, n_x / 2 + 1))
##CHUNK 2
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)
# when x is even we get 10 elements back
@test n_w == (iseven(n_x) ? floor(Int, n_x / 2) : floor(Int, n_x / 2 + 1))
@test n_Iw == (iseven(n_x) ? floor(Int, n_x / 2) : floor(Int, n_x / 2 + 1))
end
end # teset set
@testset "testing `smooth` function options" begin
# window length must be between 3 and length(x)
@test_throws ArgumentError smooth(x_20, window_len=25)
@test_throws ArgumentError smooth(x_20, window_len=2)
# test hanning is default
#FILE: QuantEcon.jl/src/zeros.jl
##CHUNK 1
##### Returns
- `x1b::Vector{T}`: `Vector` of lower borders of bracketing intervals
- `x2b::Vector{T}`: `Vector` of upper borders of bracketing intervals
##### References
This is `zbrack` from Numerical Recepies Recepies in C++
"""
function divide_bracket(f::Function, x1::T, x2::T, n::Int=50) where T<:Number
x1 <= x2 || throw(ArgumentError("x1 must be less than x2"))
xs = range(x1, stop=x2, length=n)
dx = xs[2] - xs[1]
x1b = T[]
x2b = T[]
f1 = f(x1)
#FILE: QuantEcon.jl/src/arma.jl
##CHUNK 1
if false and ``[0, 2 \pi]`` otherwise.
- `;res(1200)` : If `res` is a scalar then the spectral density is computed at
`res` frequencies evenly spaced around the unit circle, but if `res` is an array
then the function computes the response at the frequencies given by the array
##### Returns
- `w::Vector{Float64}`: The normalized frequencies at which h was computed, in
radians/sample
- `spect::Vector{Float64}` : The frequency response
"""
function spectral_density(arma::ARMA; res=1200, two_pi::Bool=true)
# Compute the spectral density associated with ARMA process arma
wmax = two_pi ? 2pi : pi
w = range(0, stop=wmax, length=res)
tf = PolynomialRatio(reverse(arma.ma_poly), reverse(arma.ar_poly))
h = freqresp(tf, w)
spect = arma.sigma.^2 .* abs.(h).^2
return w, spect
end
#FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
"""
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([2.0, 4.0], Int((n + 1) / 2))
weights = weights[1:n]
##CHUNK 2
length of either `n` and/or `mu` (which ever is a vector).
If all 3 are scalars, then 1d nodes are computed. `mu` and `sig2` are treated as
the mean and variance of a 1d normal distribution
$(qnw_refs)
"""
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.85575 * ((2n + 1).^(-1 / 6))
#CURRENT FILE: QuantEcon.jl/src/estspec.jl
##CHUNK 1
smooth(x, window_len, window)
end
function periodogram(x::Vector, window::AbstractString, window_len::Int=7)
w, I_w = periodogram(x)
I_w = smooth(I_w, window_len=window_len, window=window)
return w, I_w
end
@doc doc"""
Computes the periodogram
```math
I(w) = \frac{1}{n} | \sum_{t=0}^{n-1} x_t e^{itw} |^2
```
at the Fourier frequences ``w_j := 2 \frac{\pi j}{n}, j = 0, \ldots, n - 1``, using the fast
Fourier transform. Only the frequences ``w_j`` in ``[0, \pi]`` and corresponding values
##CHUNK 2
@doc doc"""
Computes the periodogram
```math
I(w) = \frac{1}{n} | \sum_{t=0}^{n-1} x_t e^{itw} |^2
```
at the Fourier frequences ``w_j := 2 \frac{\pi j}{n}, j = 0, \ldots, n - 1``, using the fast
Fourier transform. Only the frequences ``w_j`` in ``[0, \pi]`` and corresponding values
``I(w_j)`` are returned. If a window type is given then smoothing is performed.
##### Arguments
- `x::Array`: An array containing the data to smooth
- `window_len::Int(7)`: An odd integer giving the length of the window
- `window::AbstractString("hanning")`: A string giving the window type. Possible values
are `flat`, `hanning`, `hamming`, `bartlett`, or `blackman`
##### Returns
##CHUNK 3
window = "hanning"
end
w = windows[window](window_len)
return conv(w ./ sum(w), s)[window_len+1:end-window_len]
end
"Version of `smooth` where `window_len` and `window` are keyword arguments"
function smooth(x::Array; window_len::Int=7, window::AbstractString="hanning")
smooth(x, window_len, window)
end
function periodogram(x::Vector, window::AbstractString, window_len::Int=7)
w, I_w = periodogram(x)
I_w = smooth(I_w, window_len=window_len, window=window)
return w, I_w
end
##CHUNK 4
# Reflect x around x[0] and x[-1] prior to convolution
k = ceil(Int, window_len / 2)
xb = x[1:k] # First k elements
xt = x[end-k+1:end] # Last k elements
s = [reverse(xb); x; reverse(xt)]
# === Select window values === #
if !haskey(windows, window)
msg = "Unrecognized window type '$window'"
print(msg * " Defaulting to hanning")
window = "hanning"
end
w = windows[window](window_len)
return conv(w ./ sum(w), s)[window_len+1:end-window_len]
end
"Version of `smooth` where `window_len` and `window` are keyword arguments"
function smooth(x::Array; window_len::Int=7, window::AbstractString="hanning")
|
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_lagged), one(eltype(x_lagged))) x_lagged] * coefs
e_hat = x_current - est
phi = coefs[2]
# compute periodogram on residuals
w, I_w = periodogram(e_hat, window, window_len)
# recolor and return
I_w = I_w ./ abs.(1 .- phi .* exp.(im.*w)).^2
return w, I_w
end | 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_lagged), one(eltype(x_lagged))) x_lagged] * coefs
e_hat = x_current - est
phi = coefs[2]
# compute periodogram on residuals
w, I_w = periodogram(e_hat, window, window_len)
# recolor and return
I_w = I_w ./ abs.(1 .- phi .* exp.(im.*w)).^2
return w, I_w
end | [
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_lagged), one(eltype(x_lagged))) x_lagged] * coefs
e_hat = x_current - est
phi = coefs[2]
# compute periodogram on residuals
w, I_w = periodogram(e_hat, window, window_len)
# recolor and return
I_w = I_w ./ abs.(1 .- phi .* exp.(im.*w)).^2
return w, I_w
end | 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_lagged), one(eltype(x_lagged))) x_lagged] * coefs
e_hat = x_current - est
phi = coefs[2]
# compute periodogram on residuals
w, I_w = periodogram(e_hat, window, window_len)
# recolor and return
I_w = I_w ./ abs.(1 .- phi .* exp.(im.*w)).^2
return w, I_w
end | 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)
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] = y[p+h:T] - X*b
y_trend = vcat(fill(NaN, p+h-1), X*b)
return y_cycle, y_trend
end
#FILE: QuantEcon.jl/src/lss.jl
##CHUNK 1
mu_0::Vector=zeros(size(G, 2)),
Sigma_0::Matrix=zeros(size(G, 2), size(G, 2)))
return LSS(A, C, G, H, mu_0, Sigma_0)
end
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, y
end
@doc doc"""
##CHUNK 2
- `x::Matrix` An `n x num_reps` matrix, where the j-th column is the j_th
observation of ``x_T``
- `y::Matrix` An `k x num_reps` matrix, where the j-th column is the j_th
observation of ``y_T``
"""
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(lss::LSS; t::Integer=10, num_reps::Integer=100) =
replicate(lss, t, num_reps)
#FILE: QuantEcon.jl/src/robustlq.jl
##CHUNK 1
"""
function robust_rule_simple(rlq::RBLQ,
P::Matrix=zeros(Float64, rlq.n, rlq.n);
max_iter=80,
tol=1e-8)
# Simplify notation
A, B, C, Q, R = rlq.A, rlq.B, rlq.C, rlq.Q, rlq.R
bet, theta, k, j = rlq.bet, rlq.theta, rlq.k, rlq.j
iterate, e = 0, tol + 1.0
F = similar(P) # instantiate so available after loop
while iterate <= max_iter && e > tol
F, new_P = b_operator(rlq, d_operator(rlq, P))
e = sqrt(sum((new_P - P).^2))
iterate += 1
copyto!(P, new_P)
end
#FILE: QuantEcon.jl/src/markov/ddp.jl
##CHUNK 1
function solve(ddp::DiscreteDP{T}, v_init::AbstractVector{T},
method::Type{Algo}=VFI; max_iter::Integer=250,
epsilon::Real=1e-3, k::Integer=20) where {Algo<:DDPAlgorithm,T}
ddpr = DPSolveResult{Algo,T}(ddp, v_init)
_solve!(ddp, ddpr, max_iter, epsilon, k)
ddpr.mc = MarkovChain(ddp, ddpr)
ddpr
end
"""
backward_induction(ddp, J[, v_term=zeros(num_states(ddp))])
Solve by backward induction a ``J``-period finite horizon discrete dynamic
program with stationary reward ``r`` and transition probability functions ``q``
and discount factor ``\\beta \\in [0, 1]``.
The optimal value functions ``v^{\\ast}_1, \\ldots, v^{\\ast}_{J+1}`` and
policy functions ``\\sigma^{\\ast}_1, \\ldots, \\sigma^{\\ast}_J`` are obtained
by ``v^{\\ast}_{J+1} = v_{J+1}``, and
#FILE: QuantEcon.jl/src/arma.jl
##CHUNK 1
##### Returns
- `psi::Vector{Float64}`: `psi[j]` is the response at lag j of the impulse
response. We take `psi[1]` as unity.
"""
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 = [arma.theta; zeros(impulse_length - arma.q)]
psi_zero = 1.0
psi = Vector{Float64}(undef, impulse_length)
for j = 1:impulse_length
psi[j] = theta[j]
for i = 1:min(j, arma.p)
psi[j] += arma.phi[i] * (j-i > 0 ? psi[j-i] : psi_zero)
end
end
#FILE: QuantEcon.jl/test/test_lss.jl
##CHUNK 1
xval3, yval3 = replicate(ss1; t=100, num_reps=5000)
for (x, y) in [(xval1, yval1), (xval2, yval2), (xval3, yval3)]
@test isapprox(x , y; rough_kwargs...)
@test abs(mean(x)) <= 0.05
end
end
@testset "test convergence error" begin
@test_throws ErrorException stationary_distributions(ss; max_iter=1, tol=eps())
end
@testset "test geometric_sums" begin
β = 0.98
xs = rand(10)
for x in xs
gsum_x, gsum_y = QuantEcon.geometric_sums(ss, β, [x])
@test isapprox(gsum_x, ([x/(1-β *ss.A[1])]))
@test isapprox(gsum_y, ([ss.G[1]*x/(1-β *ss.A[1])]))
#CURRENT FILE: QuantEcon.jl/src/estspec.jl
##CHUNK 1
ind = iseven(n) ? round(Int, n / 2 + 1) : ceil(Int, n / 2)
w, I_w = w[1:ind], I_w[1:ind]
return w, I_w
end
function periodogram(x::Vector, window::AbstractString, window_len::Int=7)
w, I_w = periodogram(x)
I_w = smooth(I_w, window_len=window_len, window=window)
return w, I_w
end
@doc doc"""
Computes the periodogram
```math
I(w) = \frac{1}{n} | \sum_{t=0}^{n-1} x_t e^{itw} |^2
```
at the Fourier frequences ``w_j := 2 \frac{\pi j}{n}, j = 0, \ldots, n - 1``, using the fast
##CHUNK 2
smooth(x, window_len, window)
end
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, n / 2)
w, I_w = w[1:ind], I_w[1:ind]
return w, I_w
end
function periodogram(x::Vector, window::AbstractString, window_len::Int=7)
w, I_w = periodogram(x)
I_w = smooth(I_w, window_len=window_len, window=window)
return w, I_w
##CHUNK 3
end
@doc doc"""
Computes the periodogram
```math
I(w) = \frac{1}{n} | \sum_{t=0}^{n-1} x_t e^{itw} |^2
```
at the Fourier frequences ``w_j := 2 \frac{\pi j}{n}, j = 0, \ldots, n - 1``, using the fast
Fourier transform. Only the frequences ``w_j`` in ``[0, \pi]`` and corresponding values
``I(w_j)`` are returned. If a window type is given then smoothing is performed.
##### Arguments
- `x::Array`: An array containing the data to smooth
- `window_len::Int(7)`: An odd integer giving the length of the window
- `window::AbstractString("hanning")`: A string giving the window type. Possible values
are `flat`, `hanning`, `hamming`, `bartlett`, or `blackman`
|
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 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
2 => fill(λ, N-2))
y_trend = float(H) \ y
y_cyclical = y - y_trend
return y_cyclical, y_trend
end | 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 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
2 => fill(λ, N-2))
y_trend = float(H) \ y
y_cyclical = y - y_trend
return y_cyclical, y_trend
end | [
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 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
2 => fill(λ, N-2))
y_trend = float(H) \ y
y_cyclical = y - y_trend
return y_cyclical, y_trend
end | 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 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
2 => fill(λ, N-2))
y_trend = float(H) \ y
y_cyclical = y - y_trend
return y_cyclical, y_trend
end | 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
a_bar = n_std * sqrt(σ^2 / (1 - ρ^2))
y = range(-a_bar, stop=a_bar, length=N)
d = y[2] - y[1]
# Get transition probabilities
Π = zeros(promote_type(T1, T2), N, N)
for row = 1:N
# Do end points first
Π[row, 1] = std_norm_cdf((y[1] - ρ*y[row] + d/2) / σ)
Π[row, N] = 1 - std_norm_cdf((y[N] - ρ*y[row] - d/2) / σ)
# fill in the middle columns
for col = 2:N-1
##CHUNK 2
end
function _rouwenhorst(p::Real, q::Real, m::Real, Δ::Real, n::Integer)
if n == 2
return [m-Δ, m+Δ], [p 1-p; 1-q q]
else
_, θ_nm1 = _rouwenhorst(p, q, m, Δ, n-1)
θN = p *[θ_nm1 zeros(n-1, 1); zeros(1, n)] +
(1-p)*[zeros(n-1, 1) θ_nm1; zeros(1, n)] +
q *[zeros(1, n); zeros(n-1, 1) θ_nm1] +
(1-q)*[zeros(1, n); θ_nm1 zeros(n-1, 1)]
θN[2:end-1, :] ./= 2
return range(m-Δ, stop=m+Δ, length=n), θN
end
end
# These are to help me order types other than vectors
#FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
# In each node, a pair of random variables (p,q) takes either values
# (1,1) or (1,-1) or (-1,1) or (-1,-1), and all other variables take
# value 0. For example, for N = 2, `z2 = [1 1; 1 -1; -1 1; -1 1]`
for p = 1:n - 1
for q = p + 1:n
i += 1
z2[4 * (i - 1) + 1:4 * i, p] = [1, -1, 1, -1]
z2[4 * (i - 1) + 1:4 * i, q] = [1, 1, -1, -1]
end
end
sqrt_vcv = cholesky(vcv).U
R = sqrt(n + 2) .* sqrt_vcv
S = sqrt((n + 2) / 2) * sqrt_vcv
ϵj = [z0; z1 * R; z2 * S]
ωj = vcat(2 / (n + 2) * ones(size(z0, 1)),
(4 - n) / (2 * (n + 2)^2) * ones(size(z1, 1)),
1 / (n + 2)^2 * ones(size(z2, 1)))
return ϵj, ωj
end
#FILE: QuantEcon.jl/test/test_mc_tools.jl
##CHUNK 1
((i/(n-1) > p) + (i/(n-1) == p)/2))
P[i+1, i+1] = 1 - P[i+1, i] - P[i+1, i+2]
end
P[end, end-1], P[end, end] = ε/2, 1 - ε/2
return P
end
function Base.isapprox(x::Vector{Vector{<:Real}},
y::Vector{Vector{<:Real}})
length(x) == length(y) || return false
return all(xy -> isapprox(x, y), zip(x, y))
end
@testset "Testing mc_tools.jl" begin
# Matrix with two recurrent classes [1, 2] and [4, 5, 6],
# which have periods 2 and 3, respectively
Q = [0 1 0 0 0 0
1 0 0 0 0 0
##CHUNK 2
kmr_markov_matrix_sequential is contributed from https://github.com/oyamad
"""
function kmr_markov_matrix_sequential(n::Integer, p::T, ε::T) where T<:Real
P = zeros(T, n+1, n+1)
P[1, 1], P[1, 2] = 1 - ε/2, ε/2
@inbounds for i = 1:n-1
P[i+1, i] = (i/n) * (ε/2 + (1 - ε) *
(((i-1)/(n-1) < p) + ((i-1)/(n-1) == p)/2))
P[i+1, i+2] = ((n-i)/n) * (ε/2 + (1 - ε) *
((i/(n-1) > p) + (i/(n-1) == p)/2))
P[i+1, i+1] = 1 - P[i+1, i] - P[i+1, i+2]
end
P[end, end-1], P[end, end] = ε/2, 1 - ε/2
return P
end
function Base.isapprox(x::Vector{Vector{<:Real}},
y::Vector{Vector{<:Real}})
#FILE: QuantEcon.jl/test/test_kalman.jl
##CHUNK 1
@test isapprox(-12.7076583170714, logL)
set_state!(kn, zeros(2,1), cov_init)
@test isapprox(-12.7076583170714, compute_loglikelihood(kn, y))
# test a case where the number of state is larger than the number of observation
# ```matlab
# A= [0.5 0.4;
# 0.3 0.2];
# B_sigma=[0.5 0.3;
# 0.1 0.4];
# C=[0.5 0.4];
# D = 0.05;
# y=[1; 2; 3; 4];
# Mdl = ssm(A,B_sigma,C,D);
# [x_matlab, logL_matlab] = smooth(Mdl, y)
# ```
A = [.5 .4;
.3 .2]
Q = [.34 .17;
##CHUNK 2
# 0.1 0.4];
# C=[0.5 0.4];
# D = 0.05;
# y=[1; 2; 3; 4];
# Mdl = ssm(A,B_sigma,C,D);
# [x_matlab, logL_matlab] = smooth(Mdl, y)
# ```
A = [.5 .4;
.3 .2]
Q = [.34 .17;
.17 .17]
G = [.5 .4]
R = [.05^2]
y = [1. 2. 3. 4.]
k = Kalman(A, G, Q, R)
cov_init = [0.722222222222222 0.386904761904762;
0.386904761904762 0.293154761904762]
set_state!(k, zeros(2), cov_init)
x_smoothed, logL, P_smoothed = smooth(k, y)
x_matlab = [1.36158275104493 2.68312458668362 4.04291315305382 5.36947053521018;
#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
0 d[1, 2]/2.]
m2 = copy(m1)
# build model and solve it
f1, f2, p1, p2 = nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2)
#FILE: QuantEcon.jl/test/test_lss.jl
##CHUNK 1
@test size(rand(lss_psd.dist,10)) == (4,10)
end
@testset "test stability checks: unstable systems" begin
phi_0, phi_1, phi_2 = 1.1, 1.8, -1.8
A = [1.0 0.0 0
phi_0 phi_1 phi_2
0.0 1.0 0.0]
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
@test_throws ErrorException stationary_distributions(sys)
#CURRENT FILE: QuantEcon.jl/src/filter.jl
##CHUNK 1
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] = y[p+h:T] - X*b
y_trend = vcat(fill(NaN, p+h-1), X*b)
return y_cycle, y_trend
end
@doc doc"""
This function applies "Hamilton filter" to `<:AbstractVector`
|
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] = y[p+h:T] - X*b
y_trend = vcat(fill(NaN, p+h-1), X*b)
return y_cycle, y_trend
end | 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] = y[p+h:T] - X*b
y_trend = vcat(fill(NaN, p+h-1), X*b)
return y_cycle, y_trend
end | [
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] = y[p+h:T] - X*b
y_trend = vcat(fill(NaN, p+h-1), X*b)
return y_cycle, y_trend
end | 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] = y[p+h:T] - X*b
y_trend = vcat(fill(NaN, p+h-1), X*b)
return y_cycle, y_trend
end | 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_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_lagged), one(eltype(x_lagged))) x_lagged] * coefs
e_hat = x_current - est
phi = coefs[2]
# compute periodogram on residuals
##CHUNK 2
coefs = hcat(ones(size(x_lagged, 1)), x_lagged) \ x_current
# get estimated values and compute residual
est = [fill!(similar(x_lagged), one(eltype(x_lagged))) x_lagged] * coefs
e_hat = x_current - est
phi = coefs[2]
# compute periodogram on residuals
w, I_w = periodogram(e_hat, window, window_len)
# recolor and return
I_w = I_w ./ abs.(1 .- phi .* exp.(im.*w)).^2
return w, I_w
end
#FILE: QuantEcon.jl/src/kalman.jl
##CHUNK 1
##### Arguments
- `kn::Kalman`: `Kalman` specifying the model. Current values must be the
forecast for period ``t`` observation conditional on ``t-1``
observation.
- `y::AbstractVector`: Respondentbservations at period ``t``
##### Returns
- `logL::Real`: log-likelihood of observations at period ``t``
"""
function log_likelihood(k::Kalman, y::AbstractVector)
eta = y - k.G*k.cur_x_hat # forecast error
P = k.G*k.cur_sigma*k.G' + k.R # covariance matrix of forecast error
logL = - (length(y)*log(2pi) + logdet(P) .+ eta'/P*eta)[1]/2
return logL
end
"""
computes log-likelihood of entire observations
##CHUNK 2
function log_likelihood(k::Kalman, y::AbstractVector)
eta = y - k.G*k.cur_x_hat # forecast error
P = k.G*k.cur_sigma*k.G' + k.R # covariance matrix of forecast error
logL = - (length(y)*log(2pi) + logdet(P) .+ eta'/P*eta)[1]/2
return logL
end
"""
computes log-likelihood of entire observations
##### Arguments
- `kn::Kalman`: `Kalman` specifying the model. Initial value must be the prior
for t=1 period observation, i.e. ``x_{1|0}``.
- `y::AbstractMatrix`: `n x T` matrix of observed data.
`n` is the number of observed variables in one period.
Each column is a vector of observations at each period.
##### Returns
- `logL::Real`: log-likelihood of all observations
"""
#CURRENT FILE: QuantEcon.jl/src/filter.jl
##CHUNK 1
##### Arguments
- `y::AbstractVector` : data to be filtered
- `h::Integer` : Time horizon that we are likely to predict incorrectly.
Original paper recommends 2 for annual data, 8 for quarterly data,
24 for monthly data.
Note: For seasonal data, it's desirable for `h` to be an integer multiple
of the number of obsevations in a year.
e.g. For quarterly data, `h = 8` is recommended.
##### Returns
- `y_cycle::Vector` : cyclical component
- `y_trend::Vector` : trend component
"""
function hamilton_filter(y::AbstractVector, h::Integer)
y = Vector(y)
T = length(y)
y_cycle = fill(NaN, T)
y_cycle[h+1:T] = y[h+1:T] - y[1:T-h]
y_trend = y - y_cycle
return y_cycle, y_trend
end
##CHUNK 2
y_trend = float(H) \ y
y_cyclical = y - y_trend
return y_cyclical, y_trend
end
@doc doc"""
This function applies "Hamilton filter" to `AbstractVector`.
http://econweb.ucsd.edu/~jhamilto/hp.pdf
##### Arguments
- `y::AbstractVector` : data to be filtered
- `h::Integer` : Time horizon that we are likely to predict incorrectly.
Original paper recommends 2 for annual data, 8 for quarterly data,
24 for monthly data.
- `p::Integer` : Number of lags in regression. Must be greater than `h`.
Note: For seasonal data, it's desirable for `p` and `h` to be integer multiples
of the number of obsevations in a year.
e.g. For quarterly data, `h = 8` and `p = 4` are recommended.
##### Returns
##CHUNK 3
@doc doc"""
apply Hodrick-Prescott filter to `AbstractVector`.
##### Arguments
- `y::AbstractVector` : data to be detrended
- `λ::Real` : penalty on variation in trend
##### Returns
- `y_cyclical::Vector`: cyclical component
- `y_trend::Vector`: trend component
"""
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 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
2 => fill(λ, N-2))
##CHUNK 4
- `y_cycle::Vector` : cyclical component
- `y_trend::Vector` : trend component
"""
@doc doc"""
This function applies "Hamilton filter" to `<:AbstractVector`
under random walk assumption.
http://econweb.ucsd.edu/~jhamilto/hp.pdf
##### Arguments
- `y::AbstractVector` : data to be filtered
- `h::Integer` : Time horizon that we are likely to predict incorrectly.
Original paper recommends 2 for annual data, 8 for quarterly data,
24 for monthly data.
Note: For seasonal data, it's desirable for `h` to be an integer multiple
of the number of obsevations in a year.
e.g. For quarterly data, `h = 8` is recommended.
##### Returns
- `y_cycle::Vector` : cyclical component
##CHUNK 5
##### Arguments
- `y::AbstractVector` : data to be filtered
- `h::Integer` : Time horizon that we are likely to predict incorrectly.
Original paper recommends 2 for annual data, 8 for quarterly data,
24 for monthly data.
- `p::Integer` : Number of lags in regression. Must be greater than `h`.
Note: For seasonal data, it's desirable for `p` and `h` to be integer multiples
of the number of obsevations in a year.
e.g. For quarterly data, `h = 8` and `p = 4` are recommended.
##### Returns
- `y_cycle::Vector` : cyclical component
- `y_trend::Vector` : trend component
"""
@doc doc"""
This function applies "Hamilton filter" to `<:AbstractVector`
under random walk assumption.
http://econweb.ucsd.edu/~jhamilto/hp.pdf
##CHUNK 6
"""
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 => vcat(-2λ, fill(-4λ, N - 3), -2λ),
2 => fill(λ, N-2))
y_trend = float(H) \ y
y_cyclical = y - y_trend
return y_cyclical, y_trend
end
@doc doc"""
This function applies "Hamilton filter" to `AbstractVector`.
http://econweb.ucsd.edu/~jhamilto/hp.pdf
|
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 = logL + log_likelihood(kn, y[:, t])
prior_to_filtered!(kn, y[:, t])
x_filtered[:, t], sigma_filtered[:, :, t] = kn.cur_x_hat, kn.cur_sigma
filtered_to_forecast!(kn)
sigma_forecast[:, :, t] = kn.cur_sigma
end
# smoothing
x_smoothed = copy(x_filtered)
sigma_smoothed = copy(sigma_filtered)
for t in (T-1):-1:1
x_smoothed[:, t], sigma_smoothed[:, :, t] =
go_backward(kn, x_filtered[:, t], sigma_filtered[:, :, t],
sigma_forecast[:, :, t], x_smoothed[:, t+1],
sigma_smoothed[:, :, t+1])
end
return x_smoothed, logL, sigma_smoothed
end | 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 = logL + log_likelihood(kn, y[:, t])
prior_to_filtered!(kn, y[:, t])
x_filtered[:, t], sigma_filtered[:, :, t] = kn.cur_x_hat, kn.cur_sigma
filtered_to_forecast!(kn)
sigma_forecast[:, :, t] = kn.cur_sigma
end
# smoothing
x_smoothed = copy(x_filtered)
sigma_smoothed = copy(sigma_filtered)
for t in (T-1):-1:1
x_smoothed[:, t], sigma_smoothed[:, :, t] =
go_backward(kn, x_filtered[:, t], sigma_filtered[:, :, t],
sigma_forecast[:, :, t], x_smoothed[:, t+1],
sigma_smoothed[:, :, t+1])
end
return x_smoothed, logL, sigma_smoothed
end | [
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 = logL + log_likelihood(kn, y[:, t])
prior_to_filtered!(kn, y[:, t])
x_filtered[:, t], sigma_filtered[:, :, t] = kn.cur_x_hat, kn.cur_sigma
filtered_to_forecast!(kn)
sigma_forecast[:, :, t] = kn.cur_sigma
end
# smoothing
x_smoothed = copy(x_filtered)
sigma_smoothed = copy(sigma_filtered)
for t in (T-1):-1:1
x_smoothed[:, t], sigma_smoothed[:, :, t] =
go_backward(kn, x_filtered[:, t], sigma_filtered[:, :, t],
sigma_forecast[:, :, t], x_smoothed[:, t+1],
sigma_smoothed[:, :, t+1])
end
return x_smoothed, logL, sigma_smoothed
end | 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 = logL + log_likelihood(kn, y[:, t])
prior_to_filtered!(kn, y[:, t])
x_filtered[:, t], sigma_filtered[:, :, t] = kn.cur_x_hat, kn.cur_sigma
filtered_to_forecast!(kn)
sigma_forecast[:, :, t] = kn.cur_sigma
end
# smoothing
x_smoothed = copy(x_filtered)
sigma_smoothed = copy(sigma_filtered)
for t in (T-1):-1:1
x_smoothed[:, t], sigma_smoothed[:, :, t] =
go_backward(kn, x_filtered[:, t], sigma_filtered[:, :, t],
sigma_forecast[:, :, t], x_smoothed[:, t+1],
sigma_smoothed[:, :, t+1])
end
return x_smoothed, logL, sigma_smoothed
end | 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_sigma = A * curr_sigma * A' - curr_k * G * curr_sigma * A' + Q
new_xhat = A * curr_x + curr_k * (y_observed - G * curr_x)
@test isapprox(kf.cur_sigma, new_sigma; rough_kwargs...)
@test isapprox(kf.cur_x_hat, new_xhat; rough_kwargs...)
# test smooth
A = [.5 .3;
.1 .6]
Q = [1 .1;
.1 .8]
G = A
R = Q/10
kn = Kalman(A, G, Q, R)
cov_init = [1.76433188153014 0.657255445961981
##CHUNK 2
@test isapprox(sig_inf, sig_recursion; rough_kwargs...)
@test isapprox(kal_gain, kal_recursion; rough_kwargs...)
# test_update_using_stationary
set_state!(kf, [0.0 0.0]', sig_inf)
update!(kf, [0.0 0.0]')
@test isapprox(kf.cur_sigma, sig_inf; rough_kwargs...)
@test isapprox(kf.cur_x_hat, [0.0 0.0]'; rough_kwargs...)
# test update nonstationary
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_sigma = A * curr_sigma * A' - curr_k * G * curr_sigma * A' + Q
new_xhat = A * curr_x + curr_k * (y_observed - G * curr_x)
@test isapprox(kf.cur_sigma, new_sigma; rough_kwargs...)
@test isapprox(kf.cur_x_hat, new_xhat; rough_kwargs...)
#CURRENT FILE: QuantEcon.jl/src/kalman.jl
##CHUNK 1
- `sigma_fi::Matrix`: filtered covariance matrix of state for period ``t``
- `sigma_fo::Matrix`: forecast of covariance matrix of state for period ``t+1``
conditional on period ``t`` observations
- `x_s1::Vector`: smoothed mean of state for period ``t+1``
- `sigma_s1::Matrix`: smoothed covariance of state for period ``t+1``
##### Returns
- `x_s1::Vector`: smoothed mean of state for period ``t``
- `sigma_s1::Matrix`: smoothed covariance of state for period ``t``
"""
function go_backward(k::Kalman, x_fi::Vector,
sigma_fi::Matrix, sigma_fo::Matrix,
x_s1::Vector, sigma_s1::Matrix)
A = k.A
temp = sigma_fi*A'/sigma_fo
x_s = x_fi + temp*(x_s1-A*x_fi)
sigma_s = sigma_fi + temp*(sigma_s1-sigma_fo)*temp'
return x_s, sigma_s
end
##CHUNK 2
- `y` The current measurement
"""
function prior_to_filtered!(k::Kalman, y)
# simplify notation
G, R = k.G, k.R
x_hat, Sigma = k.cur_x_hat, k.cur_sigma
# and then update
if k.k > 1
reshape(y, k.k, 1)
end
A = Sigma * G'
B = G * Sigma * G' + R
M = A / B
k.cur_x_hat = x_hat + M * (y .- G * x_hat)
k.cur_sigma = Sigma - M * G * Sigma
Nothing
end
##CHUNK 3
"""
Updates the moments of the time ``t`` filtering distribution to the
moments of the predictive distribution, which becomes the time
``t+1`` prior
#### Arguments
- `k::Kalman` An instance of the Kalman filter
"""
function filtered_to_forecast!(k::Kalman)
# simplify notation
A, Q = k.A, k.Q
x_hat, Sigma = k.cur_x_hat, k.cur_sigma
# and then update
k.cur_x_hat = A * x_hat
k.cur_sigma = A * Sigma * A' + Q
Nothing
end
##CHUNK 4
- `x_smoothed::AbstractMatrix`: `k x T` matrix of smoothed mean of states.
`k` is the number of states.
- `logL::Real`: log-likelihood of all observations
- `sigma_smoothed::AbstractArray` `k x k x T` array of smoothed covariance matrix of states.
"""
"""
##### Arguments
- `kn::Kalman`: `Kalman` specifying the model.
- `x_fi::Vector`: filtered mean of state for period ``t``
- `sigma_fi::Matrix`: filtered covariance matrix of state for period ``t``
- `sigma_fo::Matrix`: forecast of covariance matrix of state for period ``t+1``
conditional on period ``t`` observations
- `x_s1::Vector`: smoothed mean of state for period ``t+1``
- `sigma_s1::Matrix`: smoothed covariance of state for period ``t+1``
##### Returns
- `x_s1::Vector`: smoothed mean of state for period ``t``
- `sigma_s1::Matrix`: smoothed covariance of state for period ``t``
"""
##CHUNK 5
"""
##### Arguments
- `kn::Kalman`: `Kalman` specifying the model. Initial value must be the prior
for t=1 period observation, i.e. ``x_{1|0}``.
- `y::AbstractMatrix`: `n x T` matrix of observed data.
`n` is the number of observed variables in one period.
Each column is a vector of observations at each period.
##### Returns
- `x_smoothed::AbstractMatrix`: `k x T` matrix of smoothed mean of states.
`k` is the number of states.
- `logL::Real`: log-likelihood of all observations
- `sigma_smoothed::AbstractArray` `k x k x T` array of smoothed covariance matrix of states.
"""
"""
##### Arguments
- `kn::Kalman`: `Kalman` specifying the model.
- `x_fi::Vector`: filtered mean of state for period ``t``
##CHUNK 6
##### Arguments
- `kn::Kalman`: `Kalman` specifying the model. Current values must be the
forecast for period ``t`` observation conditional on ``t-1``
observation.
- `y::AbstractVector`: Respondentbservations at period ``t``
##### Returns
- `logL::Real`: log-likelihood of observations at period ``t``
"""
function log_likelihood(k::Kalman, y::AbstractVector)
eta = y - k.G*k.cur_x_hat # forecast error
P = k.G*k.cur_sigma*k.G' + k.R # covariance matrix of forecast error
logL = - (length(y)*log(2pi) + logdet(P) .+ eta'/P*eta)[1]/2
return logL
end
"""
computes log-likelihood of entire observations
##CHUNK 7
function log_likelihood(k::Kalman, y::AbstractVector)
eta = y - k.G*k.cur_x_hat # forecast error
P = k.G*k.cur_sigma*k.G' + k.R # covariance matrix of forecast error
logL = - (length(y)*log(2pi) + logdet(P) .+ eta'/P*eta)[1]/2
return logL
end
"""
computes log-likelihood of entire observations
##### Arguments
- `kn::Kalman`: `Kalman` specifying the model. Initial value must be the prior
for t=1 period observation, i.e. ``x_{1|0}``.
- `y::AbstractMatrix`: `n x T` matrix of observed data.
`n` is the number of observed variables in one period.
Each column is a vector of observations at each period.
##### Returns
- `logL::Real`: log-likelihood of all observations
"""
##CHUNK 8
function update!(k::Kalman, y)
prior_to_filtered!(k, y)
filtered_to_forecast!(k)
Nothing
end
function stationary_values(k::Kalman)
# simplify notation
A, Q, G, R = k.A, k.Q, k.G, k.R
# solve Riccati equation, obtain Kalman gain
Sigma_inf = solve_discrete_riccati(A', G', Q, R)
K_inf = A * Sigma_inf * G' * inv(G * Sigma_inf * G' .+ R)
return Sigma_inf, K_inf
end
"""
computes log-likelihood of period ``t``
|
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, _lq.F, _lq.d
end | 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, _lq.F, _lq.d
end | [
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, _lq.F, _lq.d
end | 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, _lq.F, _lq.d
end | 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 robust_rule(rlq::RBLQ)
A, B, C, Q, R = rlq.A, rlq.B, rlq.C, rlq.Q, rlq.R
bet, theta, k, j = rlq.bet, rlq.theta, rlq.k, rlq.j
# Set up LQ version
# I = eye(j)
Z = zeros(k, j)
Ba = [B C]
Qa = [Q Z
Z' -bet.*I.*theta]
lq = QuantEcon.LQ(Qa, R, A, Ba, bet=bet)
# Solve and convert back to robust problem
P, f, d = stationary_values(lq)
##CHUNK 2
- `K::Matrix{Float64}` : Agent's best cost minimizing response corresponding to ``F``
- `P::Matrix{Float64}` : The value function corresponding to ``F``
"""
function F_to_K(rlq::RBLQ, F::Matrix)
# simplify notation
R, Q, A, B, C = rlq.R, rlq.Q, rlq.A, rlq.B, rlq.C
bet, theta = rlq.bet, rlq.theta
# set up lq
Q2 = bet * theta
R2 = - R - F'*Q*F
A2 = A - B*F
B2 = C
lq = QuantEcon.LQ(Q2, R2, A2, B2, bet=bet)
neg_P, neg_K, d = stationary_values(lq)
return -neg_K, -neg_P
end
##CHUNK 3
- `F::Matrix{Float64}` : Agent's best cost minimizing response corresponding to ``K``
- `P::Matrix{Float64}` : The value function corresponding to ``K``
"""
function K_to_F(rlq::RBLQ, K::Matrix)
R, Q, A, B, C = rlq.R, rlq.Q, rlq.A, rlq.B, rlq.C
bet, theta = rlq.bet, rlq.theta
A1, B1, Q1, R1 = A+C*K, B, Q, R-bet*theta.*K'*K
lq = QuantEcon.LQ(Q1, R1, A1, B1, bet=bet)
P, F, d = stationary_values(lq)
return F, P
end
@doc doc"""
Given ``K`` and ``F``, compute the value of deterministic entropy, which is
``\sum_t \beta^t x_t' K'K x_t`` with ``x_{t+1} = (A - BF + CK) x_t``.
##CHUNK 4
# Set up LQ version
# I = eye(j)
Z = zeros(k, j)
Ba = [B C]
Qa = [Q Z
Z' -bet.*I.*theta]
lq = QuantEcon.LQ(Qa, R, A, Ba, bet=bet)
# Solve and convert back to robust problem
P, f, d = stationary_values(lq)
F = f[1:k, :]
K = -f[k+1:end, :]
return F, K, P
end
@doc doc"""
Solve the robust LQ problem
##CHUNK 5
Q2 = bet * theta
R2 = - R - F'*Q*F
A2 = A - B*F
B2 = C
lq = QuantEcon.LQ(Q2, R2, A2, B2, bet=bet)
neg_P, neg_K, d = stationary_values(lq)
return -neg_K, -neg_P
end
@doc doc"""
Compute agent 1's best cost-minimizing response ``K``, given ``F``.
##### Arguments
- `rlq::RBLQ`: Instance of `RBLQ` type
- `K::Matrix{Float64}`: A `k x n` array representing the worst case matrix
##### Returns
#FILE: QuantEcon.jl/test/test_lqcontrol.jl
##CHUNK 1
c = .05
β = .95
n = 0.
capT = 1
lq_scalar = QuantEcon.LQ(q, r, a, b, c, n, bet=β, capT=capT, rf=rf)
Q = [0. 0.; 0. 1]
R = [1. 0.; 0. 0]
rf = I * 100
A = fill(0.95, 2, 2)
B = fill(-1.0, 2, 2)
lq_mat = QuantEcon.LQ(Q, R, A, B, bet=β, capT=capT, rf=rf)
@testset "Test scalar sequences with exact by hand solution" begin
x0 = 2.0
x_seq, u_seq, w_seq = compute_sequence(lq_scalar, x0)
# solve by hand
u_0 = (-2 .*lq_scalar.A*lq_scalar.B*lq_scalar.bet*lq_scalar.rf) /
(2 .*lq_scalar.Q+lq_scalar.bet*lq_scalar.rf*2lq_scalar.B^2)*x0
x_1 = lq_scalar.A * x0 + lq_scalar.B * u_0 + w_seq[end]
#CURRENT FILE: QuantEcon.jl/src/lqcontrol.jl
##CHUNK 1
- `lq::LQ` : instance of `LQ` type
##### Returns
- `P::ScalarOrArray` : n x n matrix in value function representation ``V(x) = x'Px + d``
- `d::Real` : Constant in value function representation
- `F::ScalarOrArray` : Policy rule that specifies optimal control in each period
##### Notes
This function updates the `P`, `d`, and `F` fields on the `lq` instance in
addition to returning them
"""
function stationary_values!(lq::LQ)
# simplify notation
Q, R, A, B, N, C = lq.Q, lq.R, lq.A, lq.B, lq.N, lq.C
# solve Riccati equation, obtain P
##CHUNK 2
- `lq::LQ` : instance of `LQ` type
##### Returns
- `P::ScalarOrArray` : `n x n` matrix in value function representation
``V(x) = x'Px + d``
- `d::Real` : Constant in value function representation
##### Notes
This function updates the `P` and `d` fields on the `lq` instance in addition to
returning them
"""
function update_values!(lq::LQ)
# Simplify notation
Q, R, A, B, N, C, P, d = lq.Q, lq.R, lq.A, lq.B, lq.N, lq.C, lq.P, lq.d
# Some useful matrices
s1 = Q + lq.bet * (B'P*B)
##CHUNK 3
if isa(lq.capT, Nothing)
stationary_values!(lq)
policies = fill(lq.F, ts_length)
else
capT = min(ts_length, lq.capT)
policies = Vector{typeof(lq.F)}(undef, capT)
for t = capT:-1:1
update_values!(lq)
policies[t] = lq.F
end
end
_compute_sequence(lq, x0, policies)
end
##CHUNK 4
This function updates the `P`, `d`, and `F` fields on the `lq` instance in
addition to returning them
"""
function stationary_values!(lq::LQ)
# simplify notation
Q, R, A, B, N, C = lq.Q, lq.R, lq.A, lq.B, lq.N, lq.C
# solve Riccati equation, obtain P
A0, B0 = sqrt(lq.bet) * A, sqrt(lq.bet) * B
P = solve_discrete_riccati(A0, B0, R, Q, N)
# Compute F
s1 = Q .+ lq.bet * (B' * P * B)
s2 = lq.bet * (B' * P * A) .+ N
F = s1 \ s2
# Compute d
d = lq.bet * tr(P * C * C') / (1 - lq.bet)
|
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 what we want.
# if b1/b2 has 1 dimension size(b, 2) returns a 1, so it is also
# what we want
k_1 = size(b1, 2)
k_2 = size(b2, 2)
# initial values
v1 = Matrix(I, k_1, k_1)
v2 = Matrix(I, k_2, k_2)
p1 = zeros(n, n)
p2 = zeros(n, n)
f1 = randn(k_1, n)
f2 = randn(k_2, n)
while dd > tol
# update
f10 = f1
f20 = f2
g2 = (b2'*p2*b2 .+ q2)\v2
g1 = (b1'*p1*b1 .+ q1)\v1
h2 = Matrix(g2) * Matrix(b2') * p2
h1 = Matrix(g1) * Matrix(b1') * p1
# Break up computation of f1 and f2
f_1_left = v1 .- (h1*b2 .+ g1*m1')*(h2*b1 .+ g2*m2')
f_1_right = h1*a .+ g1*w1' .- (h1*b2 .+ g1*m1')*(h2*a .+ g2*w2')
f1 = f_1_left\f_1_right
f2 = h2*a .+ g2*w2' .- (h2*b1 .+ g2*m2')*f1
a2 = a .- b2*f2
a1 = a .- b1*f1
p1 = (a2'*p1*a2) .+ r1 .+ (f2'*s1*f2) .- (a2'*p1*b1 .+ w1 .- f2'*m1)*f1
p2 = (a1'*p2*a1) .+ r2 .+ (f1'*s2*f1) .- (a1'*p2*b2 .+ w2 .- f1'*m2)*f2
dd = maximum(abs.(f10 .- f1) + abs.(f20 .- f2))
its = its + 1
if its > max_iter
error("Reached max iterations, no convergence")
end
end
return f1, f2, p1, p2
end | 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 what we want.
# if b1/b2 has 1 dimension size(b, 2) returns a 1, so it is also
# what we want
k_1 = size(b1, 2)
k_2 = size(b2, 2)
# initial values
v1 = Matrix(I, k_1, k_1)
v2 = Matrix(I, k_2, k_2)
p1 = zeros(n, n)
p2 = zeros(n, n)
f1 = randn(k_1, n)
f2 = randn(k_2, n)
while dd > tol
# update
f10 = f1
f20 = f2
g2 = (b2'*p2*b2 .+ q2)\v2
g1 = (b1'*p1*b1 .+ q1)\v1
h2 = Matrix(g2) * Matrix(b2') * p2
h1 = Matrix(g1) * Matrix(b1') * p1
# Break up computation of f1 and f2
f_1_left = v1 .- (h1*b2 .+ g1*m1')*(h2*b1 .+ g2*m2')
f_1_right = h1*a .+ g1*w1' .- (h1*b2 .+ g1*m1')*(h2*a .+ g2*w2')
f1 = f_1_left\f_1_right
f2 = h2*a .+ g2*w2' .- (h2*b1 .+ g2*m2')*f1
a2 = a .- b2*f2
a1 = a .- b1*f1
p1 = (a2'*p1*a2) .+ r1 .+ (f2'*s1*f2) .- (a2'*p1*b1 .+ w1 .- f2'*m1)*f1
p2 = (a1'*p2*a1) .+ r2 .+ (f1'*s2*f1) .- (a1'*p2*b2 .+ w2 .- f1'*m2)*f2
dd = maximum(abs.(f10 .- f1) + abs.(f20 .- f2))
its = its + 1
if its > max_iter
error("Reached max iterations, no convergence")
end
end
return f1, f2, p1, p2
end | [
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 what we want.
# if b1/b2 has 1 dimension size(b, 2) returns a 1, so it is also
# what we want
k_1 = size(b1, 2)
k_2 = size(b2, 2)
# initial values
v1 = Matrix(I, k_1, k_1)
v2 = Matrix(I, k_2, k_2)
p1 = zeros(n, n)
p2 = zeros(n, n)
f1 = randn(k_1, n)
f2 = randn(k_2, n)
while dd > tol
# update
f10 = f1
f20 = f2
g2 = (b2'*p2*b2 .+ q2)\v2
g1 = (b1'*p1*b1 .+ q1)\v1
h2 = Matrix(g2) * Matrix(b2') * p2
h1 = Matrix(g1) * Matrix(b1') * p1
# Break up computation of f1 and f2
f_1_left = v1 .- (h1*b2 .+ g1*m1')*(h2*b1 .+ g2*m2')
f_1_right = h1*a .+ g1*w1' .- (h1*b2 .+ g1*m1')*(h2*a .+ g2*w2')
f1 = f_1_left\f_1_right
f2 = h2*a .+ g2*w2' .- (h2*b1 .+ g2*m2')*f1
a2 = a .- b2*f2
a1 = a .- b1*f1
p1 = (a2'*p1*a2) .+ r1 .+ (f2'*s1*f2) .- (a2'*p1*b1 .+ w1 .- f2'*m1)*f1
p2 = (a1'*p2*a1) .+ r2 .+ (f1'*s2*f1) .- (a1'*p2*b2 .+ w2 .- f1'*m2)*f2
dd = maximum(abs.(f10 .- f1) + abs.(f20 .- f2))
its = its + 1
if its > max_iter
error("Reached max iterations, no convergence")
end
end
return f1, f2, p1, p2
end | 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 what we want.
# if b1/b2 has 1 dimension size(b, 2) returns a 1, so it is also
# what we want
k_1 = size(b1, 2)
k_2 = size(b2, 2)
# initial values
v1 = Matrix(I, k_1, k_1)
v2 = Matrix(I, k_2, k_2)
p1 = zeros(n, n)
p2 = zeros(n, n)
f1 = randn(k_1, n)
f2 = randn(k_2, n)
while dd > tol
# update
f10 = f1
f20 = f2
g2 = (b2'*p2*b2 .+ q2)\v2
g1 = (b1'*p1*b1 .+ q1)\v1
h2 = Matrix(g2) * Matrix(b2') * p2
h1 = Matrix(g1) * Matrix(b1') * p1
# Break up computation of f1 and f2
f_1_left = v1 .- (h1*b2 .+ g1*m1')*(h2*b1 .+ g2*m2')
f_1_right = h1*a .+ g1*w1' .- (h1*b2 .+ g1*m1')*(h2*a .+ g2*w2')
f1 = f_1_left\f_1_right
f2 = h2*a .+ g2*w2' .- (h2*b1 .+ g2*m2')*f1
a2 = a .- b2*f2
a1 = a .- b1*f1
p1 = (a2'*p1*a2) .+ r1 .+ (f2'*s1*f2) .- (a2'*p1*b1 .+ w1 .- f2'*m1)*f1
p2 = (a1'*p2*a1) .+ r2 .+ (f1'*s2*f1) .- (a1'*p2*b2 .+ w2 .- f1'*m2)*f2
dd = maximum(abs.(f10 .- f1) + abs.(f20 .- f2))
its = its + 1
if its > max_iter
error("Reached max iterations, no convergence")
end
end
return f1, f2, p1, p2
end | 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
0 d[1, 2]/2.]
m2 = copy(m1)
# build model and solve it
f1, f2, p1, p2 = nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2)
##CHUNK 2
w2 = [0 0
0 0
-0.5*e2[2] B[2]/2.]
m1 = [0 0
0 d[1, 2]/2.]
m2 = copy(m1)
# build model and solve it
f1, f2, p1, p2 = nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2)
aaa = a - b1*f1 - b2*f2
aa = aaa[1:2, 1:2]
tf = I - aa
tfi = inv(tf)
xbar = tfi*aaa[1:2, 3]
# Define answers from matlab. TODO: this is ghetto
f1_ml = [0.243666582208565 0.027236062661951 -6.827882928738190
0.392370733875639 0.139696450885998 -37.734107291009138]
#FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
# In each node, a pair of random variables (p,q) takes either values
# (1,1) or (1,-1) or (-1,1) or (-1,-1), and all other variables take
# value 0. For example, for N = 2, `z2 = [1 1; 1 -1; -1 1; -1 1]`
for p = 1:n - 1
for q = p + 1:n
i += 1
z2[4 * (i - 1) + 1:4 * i, p] = [1, -1, 1, -1]
z2[4 * (i - 1) + 1:4 * i, q] = [1, 1, -1, -1]
end
end
sqrt_vcv = cholesky(vcv).U
R = sqrt(n + 2) .* sqrt_vcv
S = sqrt((n + 2) / 2) * sqrt_vcv
ϵj = [z0; z1 * R; z2 * S]
ωj = vcat(2 / (n + 2) * ones(size(z0, 1)),
(4 - n) / (2 * (n + 2)^2) * ones(size(z1, 1)),
1 / (n + 2)^2 * ones(size(z2, 1)))
return ϵj, ωj
end
#FILE: QuantEcon.jl/src/markov/markov_approx.jl
##CHUNK 1
end
function _rouwenhorst(p::Real, q::Real, m::Real, Δ::Real, n::Integer)
if n == 2
return [m-Δ, m+Δ], [p 1-p; 1-q q]
else
_, θ_nm1 = _rouwenhorst(p, q, m, Δ, n-1)
θN = p *[θ_nm1 zeros(n-1, 1); zeros(1, n)] +
(1-p)*[zeros(n-1, 1) θ_nm1; zeros(1, n)] +
q *[zeros(1, n); zeros(n-1, 1) θ_nm1] +
(1-q)*[zeros(1, n); θ_nm1 zeros(n-1, 1)]
θN[2:end-1, :] ./= 2
return range(m-Δ, stop=m+Δ, length=n), θN
end
end
# These are to help me order types other than vectors
#FILE: QuantEcon.jl/other/quadrature.jl
##CHUNK 1
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
x[i] = z
w[i] = temp / (pp * p2)
end
x = (1 - x) ./ 2
w = w * exp(gammaln(a + n) +
gammaln(b + n) -
gammaln(n + 1) -
gammaln(n + ab + 1))
##CHUNK 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
#FILE: QuantEcon.jl/other/regression.jl
##CHUNK 1
X1, Y1 = normalize_data(X, Y)
U, S, V = svd(X1; thin=true)
r = sum((maximum(S)./ S) .<= 10.0^penalty)
Sr_inv = zeros(Float64, n1, n1)
Sr_inv[1:r, 1:r] = diagm(1./ S[1:r])
B1 = V*Sr_inv*U'*Y1
B = de_normalize(X, Y, B1)
return B
end
function RLAD_PP(X, Y, penalty=7)
# TODO: There is a bug here. linprog returns wrong answer, even when
# MATLAB gets it right (lame)
T, n1 = size(X)
N = size(Y, 2)
n1 -= 1
X1, Y1 = normalize_data(X, Y)
##CHUNK 2
# B1 = inv(X1' * X1 + T / n1 * eye(n1) * 10.0^ penalty) * X1' * Y1
B1 = inv(X1' * X1 + T / n1 * I * 10.0^ penalty) * X1' * Y1
B = de_normalize(X, Y, B1)
return B
end
function RLS_TSVD(X, Y, penalty=7)
T, n = size(X)
n1 = n - 1
X1, Y1 = normalize_data(X, Y)
U, S, V = svd(X1; thin=true)
r = sum((maximum(S)./ S) .<= 10.0^penalty)
Sr_inv = zeros(Float64, n1, n1)
Sr_inv[1:r, 1:r] = diagm(1./ S[1:r])
B1 = V*Sr_inv*U'*Y1
B = de_normalize(X, Y, B1)
return B
end
#FILE: QuantEcon.jl/test/test_mc_tools.jl
##CHUNK 1
kmr_markov_matrix_sequential is contributed from https://github.com/oyamad
"""
function kmr_markov_matrix_sequential(n::Integer, p::T, ε::T) where T<:Real
P = zeros(T, n+1, n+1)
P[1, 1], P[1, 2] = 1 - ε/2, ε/2
@inbounds for i = 1:n-1
P[i+1, i] = (i/n) * (ε/2 + (1 - ε) *
(((i-1)/(n-1) < p) + ((i-1)/(n-1) == p)/2))
P[i+1, i+2] = ((n-i)/n) * (ε/2 + (1 - ε) *
((i/(n-1) > p) + (i/(n-1) == p)/2))
P[i+1, i+1] = 1 - P[i+1, i] - P[i+1, i+2]
end
P[end, end-1], P[end, end] = ε/2, 1 - ε/2
return P
end
function Base.isapprox(x::Vector{Vector{<:Real}},
y::Vector{Vector{<:Real}})
#FILE: QuantEcon.jl/test/test_quad.jl
##CHUNK 1
# 3-d parameters -- just some random numbers
a_3 = [-1.0, -2.0, 1.0]
b_3 = [1.0, 12.0, 1.5]
n_3 = [7, 5, 9]
mu_3d = [1.0, 2.0, 2.5]
sigma2_3d = [1.0 0.1 0.0; 0.1 1.0 0.0; 0.0 0.0 1.2]
# 1-d nodes and weights
x_cheb_1, w_cheb_1 = qnwcheb(n, a, b)
x_equiN_1, w_equiN_1 = qnwequi(n, a, b, "N")
x_equiW_1, w_equiW_1 = qnwequi(n, a, b, "W")
x_equiH_1, w_equiH_1 = qnwequi(n, a, b, "H")
x_lege_1, w_lege_1 = qnwlege(n, a, b)
x_norm_1, w_norm_1 = qnwnorm(n, a, b)
x_logn_1, w_logn_1 = qnwlogn(n, a, b)
x_simp_1, w_simp_1 = qnwsimp(n, a, b)
x_trap_1, w_trap_1 = qnwtrap(n, a, b)
x_unif_1, w_unif_1 = qnwunif(n, a, b)
x_beta_1, w_beta_1 = qnwbeta(n, b, b + 1)
#CURRENT FILE: QuantEcon.jl/src/lqnash.jl |
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, y
end | 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, y
end | [
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, y
end | 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, y
end | 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.0 1.0 0.0]
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
##CHUNK 2
@test size(rand(lss_psd.dist,10)) == (4,10)
end
@testset "test stability checks: unstable systems" begin
phi_0, phi_1, phi_2 = 1.1, 1.8, -1.8
A = [1.0 0.0 0
phi_0 phi_1 phi_2
0.0 1.0 0.0]
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
@test_throws ErrorException stationary_distributions(sys)
##CHUNK 3
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
@test_throws ErrorException stationary_distributions(sys)
@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
##CHUNK 4
@test_throws ErrorException stationary_distributions(ss; max_iter=1, tol=eps())
end
@testset "test geometric_sums" begin
β = 0.98
xs = rand(10)
for x in xs
gsum_x, gsum_y = QuantEcon.geometric_sums(ss, β, [x])
@test isapprox(gsum_x, ([x/(1-β *ss.A[1])]))
@test isapprox(gsum_y, ([ss.G[1]*x/(1-β *ss.A[1])]))
end
end
@testset "test constructors" begin
# kwarg version
other_ss = LSS(A, C, G; H=H, mu_0=[mu_0;])
for nm in fieldnames(typeof(ss))
@test getfield(ss, nm) == getfield(other_ss, nm)
end
end
##CHUNK 5
phi_0 phi_1 phi_2
0.0 1.0 0.0]
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) == true
end
end
end # @testset
##CHUNK 6
@testset "Testing lss.jl" begin
rough_kwargs = Dict(:atol => 1e-7, :rtol => 1e-7)
# set up
A = .95
C = .05
G = 1.
H = 0
mu_0 = [.75;]
Sigma_0 = fill(0.000001, 1, 1)
ss = LSS(A, C, G, H, mu_0)
ss1 = LSS(A, C, G, H, mu_0, Sigma_0)
vals = stationary_distributions(ss, max_iter=1000, tol=1e-9)
@testset "test stationarity" begin
vals = stationary_distributions(ss, max_iter=1000, tol=1e-9)
ssmux, ssmuy, sssigx, sssigy = vals
#FILE: QuantEcon.jl/src/markov/random_mc.jl
##CHUNK 1
k == 1 && return ones((k, m))
# if k >= 2
x = Matrix{Float64}(undef, k, m)
r = rand(rng, k-1, m)
x[1:end .- 1, :] = sort(r, dims = 1)
for j in 1:m
x[end, j] = 1 - x[end-1, j]
for i in k-1:-1:2
x[i, j] -= x[i-1, j]
end
end
return x
end
random_probvec(k::Integer, m::Integer) = random_probvec(Random.GLOBAL_RNG, k, m)
#CURRENT FILE: QuantEcon.jl/src/lss.jl
##CHUNK 1
- `y::Matrix` An `k x num_reps` matrix, where the j-th column is the j_th
observation of ``y_T``
"""
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(lss::LSS; t::Integer=10, num_reps::Integer=100) =
replicate(lss, t, num_reps)
struct LSSMoments
##CHUNK 2
#### Arguments
- `lss::LSS` An instance of the Gaussian linear state space model.
- `t::Int = 10` The period that we want to replicate values for.
- `num_reps::Int = 100` The number of replications we want
#### Returns
- `x::Matrix` An `n x num_reps` matrix, where the j-th column is the j_th
observation of ``x_T``
- `y::Matrix` An `k x num_reps` matrix, where the j-th column is the j_th
observation of ``y_T``
"""
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]
##CHUNK 3
end
y = lss.G * x + lss.H * v
return x, y
end
replicate(lss::LSS; t::Integer=10, num_reps::Integer=100) =
replicate(lss, t, num_reps)
struct LSSMoments
lss::LSS
end
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'
|
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.0 1.0 0.0]
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
##CHUNK 2
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
@test_throws ErrorException stationary_distributions(sys)
@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
##CHUNK 3
@test size(rand(lss_psd.dist,10)) == (4,10)
end
@testset "test stability checks: unstable systems" begin
phi_0, phi_1, phi_2 = 1.1, 1.8, -1.8
A = [1.0 0.0 0
phi_0 phi_1 phi_2
0.0 1.0 0.0]
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
@test_throws ErrorException stationary_distributions(sys)
##CHUNK 4
Sigma_0 = fill(0.000001, 1, 1)
ss = LSS(A, C, G, H, mu_0)
ss1 = LSS(A, C, G, H, mu_0, Sigma_0)
vals = stationary_distributions(ss, max_iter=1000, tol=1e-9)
@testset "test stationarity" begin
vals = stationary_distributions(ss, max_iter=1000, tol=1e-9)
ssmux, ssmuy, sssigx, sssigy = vals
@test isapprox(ssmux, ssmuy; rough_kwargs...)
@test isapprox(sssigx, sssigy; rough_kwargs...)
@test isapprox(ssmux, [0.0]; rough_kwargs...)
@test isapprox(sssigx, ss.C.^2 ./ (1 .- ss.A .^2); rough_kwargs...)
end
@testset "test replicate" begin
xval1, yval1 = replicate(ss, 100, 5000)
xval2, yval2 = replicate(ss; t=100, num_reps=5000)
##CHUNK 5
@testset "Testing lss.jl" begin
rough_kwargs = Dict(:atol => 1e-7, :rtol => 1e-7)
# set up
A = .95
C = .05
G = 1.
H = 0
mu_0 = [.75;]
Sigma_0 = fill(0.000001, 1, 1)
ss = LSS(A, C, G, H, mu_0)
ss1 = LSS(A, C, G, H, mu_0, Sigma_0)
vals = stationary_distributions(ss, max_iter=1000, tol=1e-9)
@testset "test stationarity" begin
vals = stationary_distributions(ss, max_iter=1000, tol=1e-9)
ssmux, ssmuy, sssigx, sssigy = vals
#CURRENT FILE: QuantEcon.jl/src/lss.jl
##CHUNK 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, y
end
@doc doc"""
Simulate `num_reps` observations of ``x_T`` and ``y_T`` given ``x_0 \sim N(\mu_0, \Sigma_0)``.
#### Arguments
- `lss::LSS` An instance of the Gaussian linear state space model.
- `t::Int = 10` The period that we want to replicate values for.
- `num_reps::Int = 100` The number of replications we want
#### Returns
##CHUNK 2
mu_0::Vector=zeros(size(G, 2)),
Sigma_0::Matrix=zeros(size(G, 2), size(G, 2)))
return LSS(A, C, G, H, mu_0, Sigma_0)
end
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, y
end
@doc doc"""
##CHUNK 3
- `x::Matrix` An `n x num_reps` matrix, where the j-th column is the j_th
observation of ``x_T``
- `y::Matrix` An `k x num_reps` matrix, where the j-th column is the j_th
observation of ``y_T``
"""
replicate(lss::LSS; t::Integer=10, num_reps::Integer=100) =
replicate(lss, t, num_reps)
struct LSSMoments
lss::LSS
end
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'
##CHUNK 4
Simulate `num_reps` observations of ``x_T`` and ``y_T`` given ``x_0 \sim N(\mu_0, \Sigma_0)``.
#### Arguments
- `lss::LSS` An instance of the Gaussian linear state space model.
- `t::Int = 10` The period that we want to replicate values for.
- `num_reps::Int = 100` The number of replications we want
#### Returns
- `x::Matrix` An `n x num_reps` matrix, where the j-th column is the j_th
observation of ``x_T``
- `y::Matrix` An `k x num_reps` matrix, where the j-th column is the j_th
observation of ``y_T``
"""
replicate(lss::LSS; t::Integer=10, num_reps::Integer=100) =
replicate(lss, t, num_reps)
##CHUNK 5
mu_0 = reshape([mu_0;], n)
dist = MVNSampler(mu_0,Sigma_0)
LSS(A, C, G, H, k, n, m, l, mu_0, Sigma_0, dist)
end
# make kwarg version
function LSS(A::ScalarOrArray, C::ScalarOrArray, G::ScalarOrArray;
H::ScalarOrArray=zeros(size(G, 1)),
mu_0::Vector=zeros(size(G, 2)),
Sigma_0::Matrix=zeros(size(G, 2), size(G, 2)))
return LSS(A, C, G, H, mu_0, Sigma_0)
end
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)
|
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_x2 = A * Sigma_x * A' + C * C'
return ((mu_x, mu_y, Sigma_x, Sigma_y), (mu_x2, Sigma_x2))
end | 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_x2 = A * Sigma_x * A' + C * C'
return ((mu_x, mu_y, Sigma_x, Sigma_y), (mu_x2, Sigma_x2))
end | [
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_x2 = A * Sigma_x * A' + C * C'
return ((mu_x, mu_y, Sigma_x, Sigma_y), (mu_x2, Sigma_x2))
end | 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_x2 = A * Sigma_x * A' + C * C'
return ((mu_x, mu_y, Sigma_x, Sigma_y), (mu_x2, Sigma_x2))
end | 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 Kalman(A, G, Q, R, k, n, xhat, Sigma)
end
function set_state!(k::Kalman, x_hat, Sigma)
k.cur_x_hat = x_hat
##CHUNK 2
- `y` The current measurement
"""
function prior_to_filtered!(k::Kalman, y)
# simplify notation
G, R = k.G, k.R
x_hat, Sigma = k.cur_x_hat, k.cur_sigma
# and then update
if k.k > 1
reshape(y, k.k, 1)
end
A = Sigma * G'
B = G * Sigma * G' + R
M = A / B
k.cur_x_hat = x_hat + M * (y .- G * x_hat)
k.cur_sigma = Sigma - M * G * Sigma
Nothing
end
##CHUNK 3
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 Kalman(A, G, Q, R, k, n, xhat, Sigma)
end
function set_state!(k::Kalman, x_hat, Sigma)
k.cur_x_hat = x_hat
k.cur_sigma = Sigma
Nothing
end
@doc doc"""
Updates the moments (`cur_x_hat`, `cur_sigma`) of the time ``t`` prior to the
time ``t`` filtering distribution, using current measurement ``y_t``.
The updates are according to
```math
#FILE: QuantEcon.jl/src/markov/markov_approx.jl
##CHUNK 1
- `Sigma::AbstractMatrix` : variance-covariance matrix of the standardized VAR(1) process
"""
function standardize_var(b::AbstractVector, B::AbstractMatrix,
Psi::AbstractMatrix, M::Integer)
C1 = cholesky(Psi).L
mu = ((I - B)\ I)*b
A1 = C1\(B*C1)
# unconditional variance
Sigma1 = reshape(((I-kron(A1,A1))\I)*vec(Matrix(I, M, M)),M,M)
U, _ = min_var_trace(Sigma1)
A = U'*A1*U
Sigma = U'*Sigma1*U
C = C1*U
return A, C, mu, Sigma
end
"""
construct prior guess for evenly spaced grid method
#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_sigma = A * curr_sigma * A' - curr_k * G * curr_sigma * A' + Q
new_xhat = A * curr_x + curr_k * (y_observed - G * curr_x)
@test isapprox(kf.cur_sigma, new_sigma; rough_kwargs...)
@test isapprox(kf.cur_x_hat, new_xhat; rough_kwargs...)
# test smooth
A = [.5 .3;
.1 .6]
Q = [1 .1;
.1 .8]
G = A
R = Q/10
kn = Kalman(A, G, Q, R)
cov_init = [1.76433188153014 0.657255445961981
#FILE: QuantEcon.jl/src/robustlq.jl
##CHUNK 1
function evaluate_F(rlq::RBLQ, F::Matrix)
R, Q, A, B, C = rlq.R, rlq.Q, rlq.A, rlq.B, rlq.C
bet, theta, j = rlq.bet, rlq.theta, rlq.j
# Solve for policies and costs using agent 2's problem
K_F, P_F = F_to_K(rlq, F)
# I = eye(j)
H = inv(I - C'*P_F*C./theta)
d_F = log(det(H))
# compute O_F and o_F
sig = -1.0 / theta
AO = sqrt(bet) .* (A - B*F + C*K_F)
O_F = solve_discrete_lyapunov(AO', bet*K_F'*K_F)
ho = (tr(H .- 1) - d_F) / 2.0
trace = tr(O_F*C*H*C')
o_F = (ho + bet*trace) / (1 - bet)
return K_F, P_F, d_F, O_F, o_F
end
#CURRENT FILE: QuantEcon.jl/src/lss.jl
##CHUNK 1
mu_0::Vector=zeros(size(G, 2)),
Sigma_0::Matrix=zeros(size(G, 2), size(G, 2)))
return LSS(A, C, G, H, mu_0, Sigma_0)
end
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, y
end
@doc doc"""
##CHUNK 2
mu_0 = reshape([mu_0;], n)
dist = MVNSampler(mu_0,Sigma_0)
LSS(A, C, G, H, k, n, m, l, mu_0, Sigma_0, dist)
end
# make kwarg version
function LSS(A::ScalarOrArray, C::ScalarOrArray, G::ScalarOrArray;
H::ScalarOrArray=zeros(size(G, 1)),
mu_0::Vector=zeros(size(G, 2)),
Sigma_0::Matrix=zeros(size(G, 2), size(G, 2)))
return LSS(A, C, G, H, mu_0, Sigma_0)
end
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)
##CHUNK 3
# return here because of how scoping works in loops.
return mu_x1, mu_y, Sigma_x1, Sigma_y
end
end
end
function geometric_sums(lss::LSS, bet, x_t)
!is_stable(lss) ? error("Cannot compute geometric sum because the system is not stable.") : nothing
# I = eye(lss.n)
S_x = (I - bet .* lss.A) \ x_t
S_y = lss.G * S_x
return S_x, S_y
end
@doc doc"""
Test for stability of linear state space system.
First removes the constant row and column.
#### Arguments
##CHUNK 4
"""
function stationary_distributions(lss::LSS; max_iter=200, tol=1e-5)
!is_stable(lss) ? error("Cannot compute stationary distribution because the system is not stable.") : nothing
# Initialize iteration
m = moment_sequence(lss)
mu_x, mu_y, Sigma_x, Sigma_y = first(m)
i = 0
err = tol + 1.0
for (mu_x1, mu_y, Sigma_x1, Sigma_y) in m
i > max_iter && error("Convergence failed after $i iterations")
i += 1
err_mu = maximum(abs, mu_x1 - mu_x)
err_Sigma = maximum(abs, Sigma_x1 - Sigma_x)
err = max(err_Sigma, err_mu)
mu_x, Sigma_x = mu_x1, Sigma_x1
if err < tol && i > 1
|
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_one = map(i->abs(A[i, i] - 1.0) < 1e-14, 1:n)
not_constant_index = .!(row_sums_to_one .& is_ii_one)
return A[not_constant_index, not_constant_index]
end | 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_one = map(i->abs(A[i, i] - 1.0) < 1e-14, 1:n)
not_constant_index = .!(row_sums_to_one .& is_ii_one)
return A[not_constant_index, not_constant_index]
end | [
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_one = map(i->abs(A[i, i] - 1.0) < 1e-14, 1:n)
not_constant_index = .!(row_sums_to_one .& is_ii_one)
return A[not_constant_index, not_constant_index]
end | 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_one = map(i->abs(A[i, i] - 1.0) < 1e-14, 1:n)
not_constant_index = .!(row_sums_to_one .& is_ii_one)
return A[not_constant_index, not_constant_index]
end | 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
@test_throws ErrorException stationary_distributions(sys)
@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
##CHUNK 2
@test size(rand(lss_psd.dist,10)) == (4,10)
end
@testset "test stability checks: unstable systems" begin
phi_0, phi_1, phi_2 = 1.1, 1.8, -1.8
A = [1.0 0.0 0
phi_0 phi_1 phi_2
0.0 1.0 0.0]
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
@test_throws ErrorException stationary_distributions(sys)
##CHUNK 3
@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.0 1.0 0.0]
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
##CHUNK 4
phi_0 phi_1 phi_2
0.0 1.0 0.0]
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) == true
end
end
end # @testset
##CHUNK 5
@test_throws ErrorException stationary_distributions(ss; max_iter=1, tol=eps())
end
@testset "test geometric_sums" begin
β = 0.98
xs = rand(10)
for x in xs
gsum_x, gsum_y = QuantEcon.geometric_sums(ss, β, [x])
@test isapprox(gsum_x, ([x/(1-β *ss.A[1])]))
@test isapprox(gsum_y, ([ss.G[1]*x/(1-β *ss.A[1])]))
end
end
@testset "test constructors" begin
# kwarg version
other_ss = LSS(A, C, G; H=H, mu_0=[mu_0;])
for nm in fieldnames(typeof(ss))
@test getfield(ss, nm) == getfield(other_ss, nm)
end
end
#FILE: QuantEcon.jl/src/markov/markov_approx.jl
##CHUNK 1
cond_mean = A*D
# probability transition matrix
P = ones(Nm^M, Nm^M)
# normalizing constant for maximum entropy computations
scaling_factor = y1D[:, end]
# used to store some intermediate calculations
temp = Matrix{Float64}(undef, Nm, M)
# store optimized values of lambda (2 moments) to improve initial guesses
lambda_bar = zeros(2*M, Nm^M)
# small positive constant for numerical stability
kappa = 1e-8
for ii = 1:(Nm^M)
# Construct prior guesses for maximum entropy optimizations
q = construct_prior_guess(cond_mean[:, ii], Nm, y1D, y1Dhelper, method)
# Make sure all elements of the prior are stricly positive
q[q.<kappa] .= kappa
#FILE: QuantEcon.jl/src/matrix_eqn.jl
##CHUNK 1
- `gamma1::Matrix{Float64}` Represents the value ``X``
"""
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(eltype(alpha0)))
gamma1 = fill!(similar(gamma0), zero(eltype(gamma0)))
diff = 5
n_its = 1
while diff > 1e-15
#FILE: QuantEcon.jl/test/test_sampler.jl
##CHUNK 1
c = rand(mvns)-mvns.mu
@test all(broadcast(isapprox,c[1],c))
end
@testset "check positive semi-definite 1 and -1/(n-1)" begin
Sigma = -1/(n-1)*ones(n, n) + n/(n-1)*Matrix(Matrix(I, n, n))
mvns = MVNSampler(mu, Sigma)
@test isapprox(sum(rand(mvns)) , sum(mu), atol=1e-4, rtol=1e-4)
end
@testset "check non-positive definite" begin
Sigma = [2.0 1.0 3.0 1.0;
1.0 2.0 1.0 1.0;
3.0 1.0 2.0 1.0;
1.0 1.0 1.0 1.0]
@test_throws ArgumentError MVNSampler(mu, Sigma)
end
@testset "check availability of rank deficient matrix" begin
A = randn(n,n)
#FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
function qnwmonomial1(vcv::AbstractMatrix)
n = size(vcv, 1)
@assert n == size(vcv, 2) "Variance covariance matrix must be square"
n_nodes = 2n
z1 = zeros(n_nodes, n)
# In each node, random variable i takes value either 1 or -1, and
# all other variables take value 0. For example, for N = 2,
# z1 = [1 0; -1 0; 0 1; 0 -1]
for i = 1:n
z1[2 * (i - 1) + 1:2 * i, i] = [1, -1]
end
sqrt_vcv = cholesky(vcv).U
R = sqrt(n) .* sqrt_vcv
ϵj = z1 * R
ωj = ones(n_nodes) ./ n_nodes
ϵj, ωj
##CHUNK 2
# z1 = [1 0; -1 0; 0 1; 0 -1]
for i = 1:n
z1[2 * (i - 1) + 1:2 * i, i] = [1, -1]
end
sqrt_vcv = cholesky(vcv).U
R = sqrt(n) .* sqrt_vcv
ϵj = z1 * R
ωj = ones(n_nodes) ./ n_nodes
ϵj, ωj
end
function qnwmonomial2(vcv::AbstractMatrix)
n = size(vcv, 1)
@assert n == size(vcv, 2) "Variance covariance matrix must be square"
n_nodes = 2n^2 + 1
z0 = zeros(1, n)
z1 = zeros(2n, n)
#CURRENT FILE: QuantEcon.jl/src/lss.jl |
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(eltype(alpha0)))
gamma1 = fill!(similar(gamma0), zero(eltype(gamma0)))
diff = 5
n_its = 1
while diff > 1e-15
alpha1 = alpha0*alpha0
gamma1 = gamma0 + alpha0*gamma0*alpha0'
diff = maximum(abs, gamma1 - gamma0)
alpha0 = alpha1
gamma0 = gamma1
n_its += 1
if n_its > max_it
error("Exceeded maximum iterations, check input matrices")
end
end
return gamma1
end | 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(eltype(alpha0)))
gamma1 = fill!(similar(gamma0), zero(eltype(gamma0)))
diff = 5
n_its = 1
while diff > 1e-15
alpha1 = alpha0*alpha0
gamma1 = gamma0 + alpha0*gamma0*alpha0'
diff = maximum(abs, gamma1 - gamma0)
alpha0 = alpha1
gamma0 = gamma1
n_its += 1
if n_its > max_it
error("Exceeded maximum iterations, check input matrices")
end
end
return gamma1
end | [
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(eltype(alpha0)))
gamma1 = fill!(similar(gamma0), zero(eltype(gamma0)))
diff = 5
n_its = 1
while diff > 1e-15
alpha1 = alpha0*alpha0
gamma1 = gamma0 + alpha0*gamma0*alpha0'
diff = maximum(abs, gamma1 - gamma0)
alpha0 = alpha1
gamma0 = gamma1
n_its += 1
if n_its > max_it
error("Exceeded maximum iterations, check input matrices")
end
end
return gamma1
end | 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(eltype(alpha0)))
gamma1 = fill!(similar(gamma0), zero(eltype(gamma0)))
diff = 5
n_its = 1
while diff > 1e-15
alpha1 = alpha0*alpha0
gamma1 = gamma0 + alpha0*gamma0*alpha0'
diff = maximum(abs, gamma1 - gamma0)
alpha0 = alpha1
gamma0 = gamma1
n_its += 1
if n_its > max_it
error("Exceeded maximum iterations, check input matrices")
end
end
return gamma1
end | 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 = reshape([x0;], n)
# solve system
Q = solve_discrete_lyapunov(sqrt(bet) .* A', H)
cq = C'*Q*C
v = tr(cq) * bet / (1 - bet)
q0 = x0'*Q*x0 + v
return q0[1]
end
#FILE: QuantEcon.jl/src/robustlq.jl
##CHUNK 1
"""
function robust_rule_simple(rlq::RBLQ,
P::Matrix=zeros(Float64, rlq.n, rlq.n);
max_iter=80,
tol=1e-8)
# Simplify notation
A, B, C, Q, R = rlq.A, rlq.B, rlq.C, rlq.Q, rlq.R
bet, theta, k, j = rlq.bet, rlq.theta, rlq.k, rlq.j
iterate, e = 0, tol + 1.0
F = similar(P) # instantiate so available after loop
while iterate <= max_iter && e > tol
F, new_P = b_operator(rlq, d_operator(rlq, P))
e = sqrt(sum((new_P - P).^2))
iterate += 1
copyto!(P, new_P)
end
#FILE: QuantEcon.jl/other/regression.jl
##CHUNK 1
X1, Y1 = normalize_data(X, Y)
U, S, V = svd(X1; thin=true)
r = sum((maximum(S)./ S) .<= 10.0^penalty)
Sr_inv = zeros(Float64, n1, n1)
Sr_inv[1:r, 1:r] = diagm(1./ S[1:r])
B1 = V*Sr_inv*U'*Y1
B = de_normalize(X, Y, B1)
return B
end
function RLAD_PP(X, Y, penalty=7)
# TODO: There is a bug here. linprog returns wrong answer, even when
# MATLAB gets it right (lame)
T, n1 = size(X)
N = size(Y, 2)
n1 -= 1
X1, Y1 = normalize_data(X, Y)
##CHUNK 2
# B1 = inv(X1' * X1 + T / n1 * eye(n1) * 10.0^ penalty) * X1' * Y1
B1 = inv(X1' * X1 + T / n1 * I * 10.0^ penalty) * X1' * Y1
B = de_normalize(X, Y, B1)
return B
end
function RLS_TSVD(X, Y, penalty=7)
T, n = size(X)
n1 = n - 1
X1, Y1 = normalize_data(X, Y)
U, S, V = svd(X1; thin=true)
r = sum((maximum(S)./ S) .<= 10.0^penalty)
Sr_inv = zeros(Float64, n1, n1)
Sr_inv[1:r, 1:r] = diagm(1./ S[1:r])
B1 = V*Sr_inv*U'*Y1
B = de_normalize(X, Y, B1)
return B
end
#FILE: QuantEcon.jl/test/test_lss.jl
##CHUNK 1
@test size(rand(lss_psd.dist,10)) == (4,10)
end
@testset "test stability checks: unstable systems" begin
phi_0, phi_1, phi_2 = 1.1, 1.8, -1.8
A = [1.0 0.0 0
phi_0 phi_1 phi_2
0.0 1.0 0.0]
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
@test_throws ErrorException stationary_distributions(sys)
#FILE: QuantEcon.jl/test/test_matrix_eqn.jl
##CHUNK 1
@testset "scalars lyap" begin
a, b = 0.5, 0.75
sol = solve_discrete_lyapunov(a, b)
@test sol == ones(1, 1)
end
@testset "testing ricatti golden_num_float" begin
val = solve_discrete_riccati(1.0, 1.0, 1.0, 1.0)
gold_ratio = (1 + sqrt(5)) / 2.
@test isapprox(val[1], gold_ratio; rough_kwargs...)
end
@testset "testing ricatti golden_num_2d" begin
If64 = Matrix{Float64}(I, 2, 2)
A, B, R, Q = If64, If64, If64, If64
gold_diag = If64 .* (1 + sqrt(5)) ./ 2.
val = solve_discrete_riccati(A, B, Q, R)
@test isapprox(val, gold_diag; rough_kwargs...)
end
#FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
- `b::Union{Real, Vector{Real}}` : Scale parameter of the gamma distribution,
along each dimension. Must be positive. Default is 1
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
"""
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 = zeros(n)
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
##CHUNK 2
p1 = fill!(similar(z), one(eltype(z)))
p2 = fill!(similar(z), one(eltype(z)))
for j = 1:n
p3 = p2
p2 = p1
p1 = ((2 * j - 1) * z .* p2 - (j - 1) * p3) ./ j
end
# p1 is now a vector of Legendre polynomials of degree 1..n
# pp will be the deriative of each p1 at the nth zero of each
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
#CURRENT FILE: QuantEcon.jl/src/matrix_eqn.jl
##CHUNK 1
msg = "Unable to initialize routine due to ill conditioned args"
error(msg)
end
gamma = best_gamma
R_hat = R .+ gamma .* BB
# Initial conditions
Q_tilde = -Q .+ N' * (R_hat\(N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (R_hat\B')
A0 = (Im .- gamma .* G0) * A .- B * (R_hat\N)
H0 = gamma .* A'*A0 .- Q_tilde
i = 1
# Main loop
while dist > tolerance
if i > max_it
msg = "Maximum Iterations reached $i"
error(msg)
##CHUNK 2
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,
max_it::Int=50)
# Set up
dist = tolerance + 1
best_gamma = 0.0
n = size(R, 1)
k = size(Q, 1)
Im = Matrix{Float64}(I, k, k)
current_min = Inf
candidates = [0.01, 0.1, 0.25, 0.5, 1.0, 2.0, 10.0, 100.0, 10e5]
BB = B' * B
BTA = B' * A
for gamma in candidates
|
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,
max_it::Int=50)
# Set up
dist = tolerance + 1
best_gamma = 0.0
n = size(R, 1)
k = size(Q, 1)
Im = Matrix{Float64}(I, k, k)
current_min = Inf
candidates = [0.01, 0.1, 0.25, 0.5, 1.0, 2.0, 10.0, 100.0, 10e5]
BB = B' * B
BTA = B' * A
for gamma in candidates
Z = getZ(R, gamma, BB)
cn = cond(Z)
if cn * eps() < 1
Q_tilde = -Q .+ N' * (Z \ (N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (Z \ B')
A0 = (Im .- gamma .* G0) * A .- B * (Z \ N)
H0 = gamma .* (A' * A0) - Q_tilde
f1 = cond(Z, Inf)
f2 = gamma .* f1
f3 = cond(Im + G0 * H0)
f_gamma = max(f1, f2, f3)
if f_gamma < current_min
best_gamma = gamma
current_min = f_gamma
end
end
end
if isinf(current_min)
msg = "Unable to initialize routine due to ill conditioned args"
error(msg)
end
gamma = best_gamma
R_hat = R .+ gamma .* BB
# Initial conditions
Q_tilde = -Q .+ N' * (R_hat\(N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (R_hat\B')
A0 = (Im .- gamma .* G0) * A .- B * (R_hat\N)
H0 = gamma .* A'*A0 .- Q_tilde
i = 1
# Main loop
while dist > tolerance
if i > max_it
msg = "Maximum Iterations reached $i"
error(msg)
end
A1 = A0 * ((Im .+ G0 * H0)\A0)
G1 = G0 .+ A0 * G0 * ((Im .+ H0 * G0)\A0')
H1 = H0 .+ A0' * ((Im .+ H0*G0)\(H0*A0))
dist = maximum(abs, H1 - H0)
A0 = A1
G0 = G1
H0 = H1
i += 1
end
return H0 + gamma .* Im # Return X
end | 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,
max_it::Int=50)
# Set up
dist = tolerance + 1
best_gamma = 0.0
n = size(R, 1)
k = size(Q, 1)
Im = Matrix{Float64}(I, k, k)
current_min = Inf
candidates = [0.01, 0.1, 0.25, 0.5, 1.0, 2.0, 10.0, 100.0, 10e5]
BB = B' * B
BTA = B' * A
for gamma in candidates
Z = getZ(R, gamma, BB)
cn = cond(Z)
if cn * eps() < 1
Q_tilde = -Q .+ N' * (Z \ (N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (Z \ B')
A0 = (Im .- gamma .* G0) * A .- B * (Z \ N)
H0 = gamma .* (A' * A0) - Q_tilde
f1 = cond(Z, Inf)
f2 = gamma .* f1
f3 = cond(Im + G0 * H0)
f_gamma = max(f1, f2, f3)
if f_gamma < current_min
best_gamma = gamma
current_min = f_gamma
end
end
end
if isinf(current_min)
msg = "Unable to initialize routine due to ill conditioned args"
error(msg)
end
gamma = best_gamma
R_hat = R .+ gamma .* BB
# Initial conditions
Q_tilde = -Q .+ N' * (R_hat\(N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (R_hat\B')
A0 = (Im .- gamma .* G0) * A .- B * (R_hat\N)
H0 = gamma .* A'*A0 .- Q_tilde
i = 1
# Main loop
while dist > tolerance
if i > max_it
msg = "Maximum Iterations reached $i"
error(msg)
end
A1 = A0 * ((Im .+ G0 * H0)\A0)
G1 = G0 .+ A0 * G0 * ((Im .+ H0 * G0)\A0')
H1 = H0 .+ A0' * ((Im .+ H0*G0)\(H0*A0))
dist = maximum(abs, H1 - H0)
A0 = A1
G0 = G1
H0 = H1
i += 1
end
return H0 + gamma .* Im # Return X
end | [
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,
max_it::Int=50)
# Set up
dist = tolerance + 1
best_gamma = 0.0
n = size(R, 1)
k = size(Q, 1)
Im = Matrix{Float64}(I, k, k)
current_min = Inf
candidates = [0.01, 0.1, 0.25, 0.5, 1.0, 2.0, 10.0, 100.0, 10e5]
BB = B' * B
BTA = B' * A
for gamma in candidates
Z = getZ(R, gamma, BB)
cn = cond(Z)
if cn * eps() < 1
Q_tilde = -Q .+ N' * (Z \ (N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (Z \ B')
A0 = (Im .- gamma .* G0) * A .- B * (Z \ N)
H0 = gamma .* (A' * A0) - Q_tilde
f1 = cond(Z, Inf)
f2 = gamma .* f1
f3 = cond(Im + G0 * H0)
f_gamma = max(f1, f2, f3)
if f_gamma < current_min
best_gamma = gamma
current_min = f_gamma
end
end
end
if isinf(current_min)
msg = "Unable to initialize routine due to ill conditioned args"
error(msg)
end
gamma = best_gamma
R_hat = R .+ gamma .* BB
# Initial conditions
Q_tilde = -Q .+ N' * (R_hat\(N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (R_hat\B')
A0 = (Im .- gamma .* G0) * A .- B * (R_hat\N)
H0 = gamma .* A'*A0 .- Q_tilde
i = 1
# Main loop
while dist > tolerance
if i > max_it
msg = "Maximum Iterations reached $i"
error(msg)
end
A1 = A0 * ((Im .+ G0 * H0)\A0)
G1 = G0 .+ A0 * G0 * ((Im .+ H0 * G0)\A0')
H1 = H0 .+ A0' * ((Im .+ H0*G0)\(H0*A0))
dist = maximum(abs, H1 - H0)
A0 = A1
G0 = G1
H0 = H1
i += 1
end
return H0 + gamma .* Im # Return X
end | 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,
max_it::Int=50)
# Set up
dist = tolerance + 1
best_gamma = 0.0
n = size(R, 1)
k = size(Q, 1)
Im = Matrix{Float64}(I, k, k)
current_min = Inf
candidates = [0.01, 0.1, 0.25, 0.5, 1.0, 2.0, 10.0, 100.0, 10e5]
BB = B' * B
BTA = B' * A
for gamma in candidates
Z = getZ(R, gamma, BB)
cn = cond(Z)
if cn * eps() < 1
Q_tilde = -Q .+ N' * (Z \ (N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (Z \ B')
A0 = (Im .- gamma .* G0) * A .- B * (Z \ N)
H0 = gamma .* (A' * A0) - Q_tilde
f1 = cond(Z, Inf)
f2 = gamma .* f1
f3 = cond(Im + G0 * H0)
f_gamma = max(f1, f2, f3)
if f_gamma < current_min
best_gamma = gamma
current_min = f_gamma
end
end
end
if isinf(current_min)
msg = "Unable to initialize routine due to ill conditioned args"
error(msg)
end
gamma = best_gamma
R_hat = R .+ gamma .* BB
# Initial conditions
Q_tilde = -Q .+ N' * (R_hat\(N .+ gamma .* BTA)) .+ gamma .* Im
G0 = B * (R_hat\B')
A0 = (Im .- gamma .* G0) * A .- B * (R_hat\N)
H0 = gamma .* A'*A0 .- Q_tilde
i = 1
# Main loop
while dist > tolerance
if i > max_it
msg = "Maximum Iterations reached $i"
error(msg)
end
A1 = A0 * ((Im .+ G0 * H0)\A0)
G1 = G0 .+ A0 * G0 * ((Im .+ H0 * G0)\A0')
H1 = H0 .+ A0' * ((Im .+ H0*G0)\(H0*A0))
dist = maximum(abs, H1 - H0)
A0 = A1
G0 = G1
H0 = H1
i += 1
end
return H0 + gamma .* Im # Return X
end | 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 = [1.0+r -c_bar+mu;
0.0 1.0]
B = [-1.0, 0.0]
C = [sigma, 0.0]
# == Compute solutions and simulate == #
lq = QuantEcon.LQ(Q, R, A, B, C; bet=bet, capT=t, rf=Rf)
x0 = [0.0, 1.0]
#FILE: QuantEcon.jl/test/test_kalman.jl
##CHUNK 1
@testset "Testing kalman.jl" begin
# set up
A = [.95 0; 0. .95]
Q = Matrix(I, 2, 2) .* 0.5
G = Matrix(I, 2, 2) .* 0.5
R = Matrix(I, 2, 2) .* 0.2
kf = Kalman(A, G, Q, R)
rough_kwargs = Dict(:atol => 1e-2, :rtol => 1e-4)
sig_inf, kal_gain = stationary_values(kf)
# Compute the Kalman gain and sigma infinity according to the
# recursive equations and compare
mat_inv = inv(G * sig_inf * G' + R)
kal_recursion = A * sig_inf * (G') * mat_inv
sig_recursion = A * sig_inf * A' - kal_recursion * G * sig_inf * A' + Q
# test stationary
##CHUNK 2
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_sigma = A * curr_sigma * A' - curr_k * G * curr_sigma * A' + Q
new_xhat = A * curr_x + curr_k * (y_observed - G * curr_x)
@test isapprox(kf.cur_sigma, new_sigma; rough_kwargs...)
@test isapprox(kf.cur_x_hat, new_xhat; rough_kwargs...)
# test smooth
A = [.5 .3;
.1 .6]
Q = [1 .1;
.1 .8]
G = A
R = Q/10
kn = Kalman(A, G, Q, R)
cov_init = [1.76433188153014 0.657255445961981
#FILE: QuantEcon.jl/src/lqcontrol.jl
##CHUNK 1
This function updates the `P`, `d`, and `F` fields on the `lq` instance in
addition to returning them
"""
function stationary_values!(lq::LQ)
# simplify notation
Q, R, A, B, N, C = lq.Q, lq.R, lq.A, lq.B, lq.N, lq.C
# solve Riccati equation, obtain P
A0, B0 = sqrt(lq.bet) * A, sqrt(lq.bet) * B
P = solve_discrete_riccati(A0, B0, R, Q, N)
# Compute F
s1 = Q .+ lq.bet * (B' * P * B)
s2 = lq.bet * (B' * P * A) .+ N
F = s1 \ s2
# Compute d
d = lq.bet * tr(P * C * C') / (1 - lq.bet)
#FILE: QuantEcon.jl/test/test_robustlq.jl
##CHUNK 1
A = [1. 0. 0.
0. 1. 0.
0. 0. ρ]
B = [0.0 1.0 0.0]'
C = [0.0 0.0 sigma_d]'
rblq = RBLQ(Q, R, A, B, C, β, θ)
lq = QuantEcon.LQ(Q, R, A, B, C, β)
Fr, Kr, Pr = robust_rule(rblq)
# test stuff
@testset "test robust vs simple" begin
Fs, Ks, Ps = robust_rule_simple(rblq, Pr; tol=1e-12)
@test isapprox(Fr, Fs; rough_kwargs...)
@test isapprox(Kr, Ks; rough_kwargs...)
@test isapprox(Pr, Ps; rough_kwargs...)
##CHUNK 2
γ = 50.0
θ = 0.002
ac = (a_0 - c) / 2.0
R = [0 ac 0
ac -a_1 0.5
0. 0.5 0]
R = -R
Q = γ / 2
A = [1. 0. 0.
0. 1. 0.
0. 0. ρ]
B = [0.0 1.0 0.0]'
C = [0.0 0.0 sigma_d]'
rblq = RBLQ(Q, R, A, B, C, β, θ)
lq = QuantEcon.LQ(Q, R, A, B, C, β)
#FILE: QuantEcon.jl/src/robustlq.jl
##CHUNK 1
"""
function robust_rule_simple(rlq::RBLQ,
P::Matrix=zeros(Float64, rlq.n, rlq.n);
max_iter=80,
tol=1e-8)
# Simplify notation
A, B, C, Q, R = rlq.A, rlq.B, rlq.C, rlq.Q, rlq.R
bet, theta, k, j = rlq.bet, rlq.theta, rlq.k, rlq.j
iterate, e = 0, tol + 1.0
F = similar(P) # instantiate so available after loop
while iterate <= max_iter && e > tol
F, new_P = b_operator(rlq, d_operator(rlq, P))
e = sqrt(sum((new_P - P).^2))
iterate += 1
copyto!(P, new_P)
end
#FILE: QuantEcon.jl/other/regression.jl
##CHUNK 1
function RLAD_PP(X, Y, penalty=7)
# TODO: There is a bug here. linprog returns wrong answer, even when
# MATLAB gets it right (lame)
T, n1 = size(X)
N = size(Y, 2)
n1 -= 1
X1, Y1 = normalize_data(X, Y)
LB = 0.0 # lower bound is 0
UB = Inf # no upper bound
f = [10.0^penalty*ones(n1*2)*T/n1; ones(2*T)]
# Aeq = [X1 -X1 eye(T, T) -eye(T,T)]
Aeq = [X1 -X1 I -I]
B1 = zeros(size(X1, 2), N)
#FILE: QuantEcon.jl/test/test_matrix_eqn.jl
##CHUNK 1
@test isapprox(val[1], gold_ratio; rough_kwargs...)
end
@testset "testing ricatti golden_num_2d" begin
If64 = Matrix{Float64}(I, 2, 2)
A, B, R, Q = If64, If64, If64, If64
gold_diag = If64 .* (1 + sqrt(5)) ./ 2.
val = solve_discrete_riccati(A, B, Q, R)
@test isapprox(val, gold_diag; rough_kwargs...)
end
@testset "test tjm 1" begin
A = [0.0 0.1 0.0
0.0 0.0 0.1
0.0 0.0 0.0]
B = [1.0 0.0
0.0 0.0
0.0 1.0]
Q = [10^5 0.0 0.0
0.0 10^3 0.0
#FILE: QuantEcon.jl/test/test_lqnash.jl
##CHUNK 1
w2 = [0 0
0 0
-0.5*e2[2] B[2]/2.]
m1 = [0 0
0 d[1, 2]/2.]
m2 = copy(m1)
# build model and solve it
f1, f2, p1, p2 = nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2)
aaa = a - b1*f1 - b2*f2
aa = aaa[1:2, 1:2]
tf = I - aa
tfi = inv(tf)
xbar = tfi*aaa[1:2, 3]
# Define answers from matlab. TODO: this is ghetto
f1_ml = [0.243666582208565 0.027236062661951 -6.827882928738190
0.392370733875639 0.139696450885998 -37.734107291009138]
#CURRENT FILE: QuantEcon.jl/src/matrix_eqn.jl |
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)
its = 0
for its = 1:maxit
p1 = fill!(similar(z), one(eltype(z)))
p2 = fill!(similar(z), one(eltype(z)))
for j = 1:n
p3 = p2
p2 = p1
p1 = ((2 * j - 1) * z .* p2 - (j - 1) * p3) ./ j
end
# p1 is now a vector of Legendre polynomials of degree 1..n
# pp will be the deriative of each p1 at the nth zero of each
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
return nodes, weights
end | 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)
its = 0
for its = 1:maxit
p1 = fill!(similar(z), one(eltype(z)))
p2 = fill!(similar(z), one(eltype(z)))
for j = 1:n
p3 = p2
p2 = p1
p1 = ((2 * j - 1) * z .* p2 - (j - 1) * p3) ./ j
end
# p1 is now a vector of Legendre polynomials of degree 1..n
# pp will be the deriative of each p1 at the nth zero of each
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
return nodes, weights
end | [
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)
its = 0
for its = 1:maxit
p1 = fill!(similar(z), one(eltype(z)))
p2 = fill!(similar(z), one(eltype(z)))
for j = 1:n
p3 = p2
p2 = p1
p1 = ((2 * j - 1) * z .* p2 - (j - 1) * p3) ./ j
end
# p1 is now a vector of Legendre polynomials of degree 1..n
# pp will be the deriative of each p1 at the nth zero of each
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
return nodes, weights
end | 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)
its = 0
for its = 1:maxit
p1 = fill!(similar(z), one(eltype(z)))
p2 = fill!(similar(z), one(eltype(z)))
for j = 1:n
p3 = p2
p2 = p1
p1 = ((2 * j - 1) * z .* p2 - (j - 1) * p3) ./ j
end
# p1 is now a vector of Legendre polynomials of degree 1..n
# pp will be the deriative of each p1 at the nth zero of each
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
return nodes, weights
end | 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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
##CHUNK 2
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
x[i] = z
w[i] = temp / (pp * p2)
end
x = (1 - x) ./ 2
w = w * exp(gammaln(a + n) +
gammaln(b + n) -
gammaln(n + 1) -
gammaln(n + ab + 1))
#FILE: QuantEcon.jl/test/test_mc_tools.jl
##CHUNK 1
((i/(n-1) > p) + (i/(n-1) == p)/2))
P[i+1, i+1] = 1 - P[i+1, i] - P[i+1, i+2]
end
P[end, end-1], P[end, end] = ε/2, 1 - ε/2
return P
end
function Base.isapprox(x::Vector{Vector{<:Real}},
y::Vector{Vector{<:Real}})
length(x) == length(y) || return false
return all(xy -> isapprox(x, y), zip(x, y))
end
@testset "Testing mc_tools.jl" begin
# Matrix with two recurrent classes [1, 2] and [4, 5, 6],
# which have periods 2 and 3, respectively
Q = [0 1 0 0 0 0
1 0 0 0 0 0
#FILE: QuantEcon.jl/src/robustlq.jl
##CHUNK 1
"""
function robust_rule_simple(rlq::RBLQ,
P::Matrix=zeros(Float64, rlq.n, rlq.n);
max_iter=80,
tol=1e-8)
# Simplify notation
A, B, C, Q, R = rlq.A, rlq.B, rlq.C, rlq.Q, rlq.R
bet, theta, k, j = rlq.bet, rlq.theta, rlq.k, rlq.j
iterate, e = 0, tol + 1.0
F = similar(P) # instantiate so available after loop
while iterate <= max_iter && e > tol
F, new_P = b_operator(rlq, d_operator(rlq, P))
e = sqrt(sum((new_P - P).^2))
iterate += 1
copyto!(P, new_P)
end
#CURRENT FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
aa = 2 * j * (j + ab) * (temp - 2)
bb = (temp - 1) * (a * a - b * b + temp * (temp - 2) * z)
c = 2 * (j - 1 + a) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta")
end
x[i] = z
w[i] = temp / (pp * p2)
end
##CHUNK 2
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)
weights[n + 1 - i] = weights[i]
end
weights = weights ./ sqrt(pi)
nodes = sqrt(2) .* nodes
return nodes, weights
end
##CHUNK 3
# In each node, a pair of random variables (p,q) takes either values
# (1,1) or (1,-1) or (-1,1) or (-1,-1), and all other variables take
# value 0. For example, for N = 2, `z2 = [1 1; 1 -1; -1 1; -1 1]`
for p = 1:n - 1
for q = p + 1:n
i += 1
z2[4 * (i - 1) + 1:4 * i, p] = [1, -1, 1, -1]
z2[4 * (i - 1) + 1:4 * i, q] = [1, 1, -1, -1]
end
end
sqrt_vcv = cholesky(vcv).U
R = sqrt(n + 2) .* sqrt_vcv
S = sqrt((n + 2) / 2) * sqrt_vcv
ϵj = [z0; z1 * R; z2 * S]
ωj = vcat(2 / (n + 2) * ones(size(z0, 1)),
(4 - n) / (2 * (n + 2)^2) * ones(size(z1, 1)),
1 / (n + 2)^2 * ones(size(z2, 1)))
return ϵj, ωj
end
##CHUNK 4
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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
##CHUNK 5
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28 + a ) * n * n))
z = z + (z - x[n - 2]) * r1 * r2 * r3
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
##CHUNK 6
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
|
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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
# root finding iterations
it = 0
pp = 0.0 # initialize pp so it is available outside while
while it < maxit
it += 1
p1 = pim4
p2 = 0.0
for j = 1:n
p3 = p2
p2 = p1
p1 = z .* sqrt(2 / j) .* p2 - sqrt((j - 1) / j) .* p3
end
# p1 now contains degree n Hermite polynomial
# pp is derivative of p1 at the n'th zero of p1
pp = sqrt(2n) .* p2
z1 = z
z = z1 - p1 ./ pp # newton step
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)
weights[n + 1 - i] = weights[i]
end
weights = weights ./ sqrt(pi)
nodes = sqrt(2) .* nodes
return nodes, weights
end | 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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
# root finding iterations
it = 0
pp = 0.0 # initialize pp so it is available outside while
while it < maxit
it += 1
p1 = pim4
p2 = 0.0
for j = 1:n
p3 = p2
p2 = p1
p1 = z .* sqrt(2 / j) .* p2 - sqrt((j - 1) / j) .* p3
end
# p1 now contains degree n Hermite polynomial
# pp is derivative of p1 at the n'th zero of p1
pp = sqrt(2n) .* p2
z1 = z
z = z1 - p1 ./ pp # newton step
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)
weights[n + 1 - i] = weights[i]
end
weights = weights ./ sqrt(pi)
nodes = sqrt(2) .* nodes
return nodes, weights
end | [
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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
# root finding iterations
it = 0
pp = 0.0 # initialize pp so it is available outside while
while it < maxit
it += 1
p1 = pim4
p2 = 0.0
for j = 1:n
p3 = p2
p2 = p1
p1 = z .* sqrt(2 / j) .* p2 - sqrt((j - 1) / j) .* p3
end
# p1 now contains degree n Hermite polynomial
# pp is derivative of p1 at the n'th zero of p1
pp = sqrt(2n) .* p2
z1 = z
z = z1 - p1 ./ pp # newton step
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)
weights[n + 1 - i] = weights[i]
end
weights = weights ./ sqrt(pi)
nodes = sqrt(2) .* nodes
return nodes, weights
end | 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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
# root finding iterations
it = 0
pp = 0.0 # initialize pp so it is available outside while
while it < maxit
it += 1
p1 = pim4
p2 = 0.0
for j = 1:n
p3 = p2
p2 = p1
p1 = z .* sqrt(2 / j) .* p2 - sqrt((j - 1) / j) .* p3
end
# p1 now contains degree n Hermite polynomial
# pp is derivative of p1 at the n'th zero of p1
pp = sqrt(2n) .* p2
z1 = z
z = z1 - p1 ./ pp # newton step
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)
weights[n + 1 - i] = weights[i]
end
weights = weights ./ sqrt(pi)
nodes = sqrt(2) .* nodes
return nodes, weights
end | 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28+ a ) * n * n))
z = z + (z - x[n-2]) * r1 * r2 * r3
else
z = 3 * x[i-1] - 3 * x[i-2] + x[i-3]
end
ab = a + b
for its = 1:maxit
temp = 2 + ab
p1 = (a - b + temp * z) / 2
##CHUNK 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
##CHUNK 3
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.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) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
#CURRENT FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
# rootfinding iterations
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
for j in 1:n
# Recurrance relation for Laguerre polynomials
p3 = p2
p2 = p1
##CHUNK 2
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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28 + a ) * n * n))
z = z + (z - x[n - 2]) * r1 * r2 * r3
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
##CHUNK 3
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
##CHUNK 4
p1 = fill!(similar(z), one(eltype(z)))
p2 = fill!(similar(z), one(eltype(z)))
for j = 1:n
p3 = p2
p2 = p1
p1 = ((2 * j - 1) * z .* p2 - (j - 1) * p3) ./ j
end
# p1 is now a vector of Legendre polynomials of degree 1..n
# pp will be the deriative of each p1 at the nth zero of each
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
##CHUNK 5
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
##CHUNK 6
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
for j in 1:n
# Recurrance relation for Laguerre polynomials
p3 = p2
p2 = p1
p1 = ((2j - 1 + a - z) * p2 - (j - 1 + a) * p3) ./ j
end
pp = (n * p1 - (n + a) * p2) ./ z
z1 = z
z = z1 - p1 ./ pp
err = abs(z - z1)
if err < 3e-14
break
end
##CHUNK 7
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
|
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([2.0, 4.0], Int((n + 1) / 2))
weights = weights[1:n]
weights[1] = 1
weights[end] = 1
weights = (dx / 3) * weights
return nodes, weights
end | 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([2.0, 4.0], Int((n + 1) / 2))
weights = weights[1:n]
weights[1] = 1
weights[end] = 1
weights = (dx / 3) * weights
return nodes, weights
end | [
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([2.0, 4.0], Int((n + 1) / 2))
weights = weights[1:n]
weights[1] = 1
weights[end] = 1
weights = (dx / 3) * weights
return nodes, weights
end | 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([2.0, 4.0], Int((n + 1) / 2))
weights = weights[1:n]
weights[1] = 1
weights[end] = 1
weights = (dx / 3) * weights
return nodes, weights
end | 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)
weights[n + 1 - i] = weights[i]
end
weights = weights ./ sqrt(pi)
nodes = sqrt(2) .* nodes
return nodes, weights
end
##CHUNK 2
length of either `n` and/or `mu` (which ever is a vector).
If all 3 are scalars, then 1d nodes are computed. `mu` and `sig2` are treated as
the mean and variance of a 1d normal distribution
$(qnw_refs)
"""
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.85575 * ((2n + 1).^(-1 / 6))
##CHUNK 3
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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
##CHUNK 4
pp = n * (z .* p1 - p2) ./ (z .* z .- 1)
z1 = z
z = z1 - p1 ./ pp # newton's method
err = maximum(abs, z - z1)
if err < 1e-14
break
end
end
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
##CHUNK 5
elseif lowercase(kind)[1] == 't'
nodes, weights = qnwtrap(n, a, b)
elseif lowercase(kind)[1] == 's'
nodes, weights = qnwsimp(n, a, b)
else
nodes, weights = qnwequi(n, a, b, kind)
end
return do_quad(f, nodes, weights, args...; kwargs...)
end
function qnwmonomial1(vcv::AbstractMatrix)
n = size(vcv, 1)
@assert n == size(vcv, 2) "Variance covariance matrix must be square"
n_nodes = 2n
z1 = zeros(n_nodes, n)
# In each node, random variable i takes value either 1 or -1, and
##CHUNK 6
nodes[i] = -z
weights[i] = 2 ./ (pp .* pp)
weights[n + 1 - i] = weights[i]
end
weights = weights ./ sqrt(pi)
nodes = sqrt(2) .* nodes
return nodes, weights
end
"""
Computes multivariate Simpson quadrature nodes and weights.
##### Arguments
- `n::Union{Int, Vector{Int}}` : Number of desired nodes along each dimension
- `a::Union{Real, Vector{Real}}` : Lower endpoint along each dimension
- `b::Union{Real, Vector{Real}}` : Upper endpoint along each dimension
##CHUNK 7
##### Arguments
- `n::Union{Int, Vector{Int}}` : Number of desired nodes along each dimension
- `a::Union{Real, Vector{Real}}` : Lower endpoint along each dimension
- `b::Union{Real, Vector{Real}}` : Upper endpoint along each dimension
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
"""
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)
##CHUNK 8
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 = zeros(n)
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
##CHUNK 9
##### Arguments
- `n::Union{Int, Vector{Int}}` : Number of desired nodes along each dimension
- `a::Union{Real, Vector{Real}}` : Lower endpoint along each dimension
- `b::Union{Real, Vector{Real}}` : Upper endpoint along each dimension
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
"""
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)
##CHUNK 10
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
# rootfinding iterations
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
|
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
weights[end] = 1
weights = (dx / 3) * weights
return nodes, weights
end
"""
Computes multivariate trapezoid quadrature nodes and weights.
##### Arguments
##CHUNK 2
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
"""
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([2.0, 4.0], Int((n + 1) / 2))
weights = weights[1:n]
##CHUNK 3
- `a::Union{Real, Vector{Real}}` : Lower endpoint along each dimension
- `b::Union{Real, Vector{Real}}` : Upper endpoint along each dimension
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
"""
function qnwcheb(n::Int, a::Real, b::Real)
nodes = (b + a) / 2 .- (b - a) / 2 .* cos.(pi / n .* (0.5:(n - 0.5)))
weights = ((b - a) / n) .* (cos.(pi / n .* ((1:n) .- 0.5) * (2:2:n - 1)') *
(-2.0 ./ ((1:2:n - 2) .* (3:2:n))) .+ 1)
return nodes, weights
end
"""
Computes nodes and weights for multivariate normal distribution.
##### Arguments
##CHUNK 4
($f)(fill(n, n_a), a, b)
end
function ($f)(n::Vector{Int}, a::Vector, b::Vector)
n_n, n_a, n_b = length(n), length(a), length(b)
if !(n_n == n_a == n_b)
error("n, a, and b must have same number of elements")
end
nodes = Vector{Float64}[]
weights = Vector{Float64}[]
for i = 1:n_n
_1d = $f(n[i], a[i], b[i])
push!(nodes, _1d[1])
push!(weights, _1d[2])
end
weights = ckron(weights[end:-1:1]...)
nodes_out = gridmake(nodes...)::Matrix{Float64}
##CHUNK 5
##### Arguments
- `n::Union{Int, Vector{Int}}` : Number of desired nodes along each dimension
- `a::Union{Real, Vector{Real}}` : Lower endpoint along each dimension
- `b::Union{Real, Vector{Real}}` : Upper endpoint along each dimension
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
"""
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)
##CHUNK 6
elseif kind == "H"
j = equidist_pp[1:d]
nodes = (i .* (i .+ 1) ./ 2) * j'
nodes -= fix(nodes)
elseif kind == "R"
nodes = rand(n, d)
else
error("Unknown `kind` specified. Valid choices are N, W, H, R")
end
r = b - a
nodes = a' .+ nodes .* r' # use broadcasting here.
weights = fill((prod(r) / n), n)
return nodes, weights
end
# Other argument types
##CHUNK 7
weights[1] = 1
weights[end] = 1
weights = (dx / 3) * weights
return nodes, weights
end
"""
Computes multivariate trapezoid quadrature nodes and weights.
##### Arguments
- `n::Union{Int, Vector{Int}}` : Number of desired nodes along each dimension
- `a::Union{Real, Vector{Real}}` : Lower endpoint along each dimension
- `b::Union{Real, Vector{Real}}` : Upper endpoint along each dimension
$(qnw_returns)
$(qnw_func_notes)
$(qnw_refs)
##CHUNK 8
if its == maxit
error("Maximum iterations in _qnwlege1")
end
nodes[i] = xm .- xl * z
nodes[n + 1 .- i] = xm .+ xl * z
weights[i] = 2 * xl ./ ((1 .- z .* z) .* pp .* pp)
weights[n + 1 .- i] = weights[i]
return nodes, weights
end
"""
Computes multivariate Guass-Checbychev quadrature nodes and weights.
##### Arguments
- `n::Union{Int, Vector{Int}}` : Number of desired nodes along each dimension
##CHUNK 9
($f)(fill(n, n_b), fill(a, n_b), b)
end
function ($f)(n::Vector{Int}, a::Vector, b::Real)
n_n, n_a = length(n), length(a)
if n_n != n_a
msg = "Cannot construct nodes/weights. n and a have different"
msg *= " lengths"
error(msg)
end
($f)(n, a, fill(b, n_a))
end
function ($f)(n::Vector{Int}, a::Real, b::Vector)
n_n, n_b = length(n), length(b)
if n_n != n_b
msg = "Cannot construct nodes/weights. n and b have different"
msg *= " lengths"
error(msg)
end
##CHUNK 10
($f)(n, a, fill(b, n_a))
end
function ($f)(n::Vector{Int}, a::Real, b::Vector)
n_n, n_b = length(n), length(b)
if n_n != n_b
msg = "Cannot construct nodes/weights. n and b have different"
msg *= " lengths"
error(msg)
end
($f)(n, fill(a, n_b), b)
end
function ($f)(n::Real, a::Vector, b::Vector)
n_a, n_b = length(a), length(b)
if n_a != n_b
msg = "Cannot construct nodes/weights. a and b have different"
msg *= " lengths"
error(msg)
end
|
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.48 * an + 0.96bn + 0.452an * an + 0.83an * bn
z = 1 - r1 / r2
elseif i == 2
r1 = (4.1 + a) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28 + a ) * n * n))
z = z + (z - x[n - 2]) * r1 * r2 * r3
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta")
end
x[i] = z
w[i] = temp / (pp * p2)
end
x = (1 .- x) ./ 2
w = w * exp((logabsgamma(a + n))[1] +
(logabsgamma(b + n))[1] -
(logabsgamma(n + 1))[1] -
(logabsgamma(n + ab + 1))[1] )
w = w / (2 * exp( (logabsgamma(a + 1))[1] +
(logabsgamma(b + 1))[1] -
(logabsgamma(ab + 2))[1] ))
return x, w
end | 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.48 * an + 0.96bn + 0.452an * an + 0.83an * bn
z = 1 - r1 / r2
elseif i == 2
r1 = (4.1 + a) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28 + a ) * n * n))
z = z + (z - x[n - 2]) * r1 * r2 * r3
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta")
end
x[i] = z
w[i] = temp / (pp * p2)
end
x = (1 .- x) ./ 2
w = w * exp((logabsgamma(a + n))[1] +
(logabsgamma(b + n))[1] -
(logabsgamma(n + 1))[1] -
(logabsgamma(n + ab + 1))[1] )
w = w / (2 * exp( (logabsgamma(a + 1))[1] +
(logabsgamma(b + 1))[1] -
(logabsgamma(ab + 2))[1] ))
return x, w
end | [
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.48 * an + 0.96bn + 0.452an * an + 0.83an * bn
z = 1 - r1 / r2
elseif i == 2
r1 = (4.1 + a) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28 + a ) * n * n))
z = z + (z - x[n - 2]) * r1 * r2 * r3
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta")
end
x[i] = z
w[i] = temp / (pp * p2)
end
x = (1 .- x) ./ 2
w = w * exp((logabsgamma(a + n))[1] +
(logabsgamma(b + n))[1] -
(logabsgamma(n + 1))[1] -
(logabsgamma(n + ab + 1))[1] )
w = w / (2 * exp( (logabsgamma(a + 1))[1] +
(logabsgamma(b + 1))[1] -
(logabsgamma(ab + 2))[1] ))
return x, w
end | 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.48 * an + 0.96bn + 0.452an * an + 0.83an * bn
z = 1 - r1 / r2
elseif i == 2
r1 = (4.1 + a) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28 + a ) * n * n))
z = z + (z - x[n - 2]) * r1 * r2 * r3
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta")
end
x[i] = z
w[i] = temp / (pp * p2)
end
x = (1 .- x) ./ 2
w = w * exp((logabsgamma(a + n))[1] +
(logabsgamma(b + n))[1] -
(logabsgamma(n + 1))[1] -
(logabsgamma(n + ab + 1))[1] )
w = w / (2 * exp( (logabsgamma(a + 1))[1] +
(logabsgamma(b + 1))[1] -
(logabsgamma(ab + 2))[1] ))
return x, w
end | 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) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 1
##CHUNK 2
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28+ a ) * n * n))
z = z + (z - x[n-2]) * r1 * r2 * r3
##CHUNK 3
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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28+ a ) * n * n))
z = z + (z - x[n-2]) * r1 * r2 * r3
else
z = 3 * x[i-1] - 3 * x[i-2] + x[i-3]
end
ab = a + b
for its = 1:maxit
temp = 2 + ab
p1 = (a - b + temp * z) / 2
##CHUNK 4
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.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) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
##CHUNK 5
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
##CHUNK 6
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
x[i] = z
w[i] = temp / (pp * p2)
end
x = (1 - x) ./ 2
w = w * exp(gammaln(a + n) +
gammaln(b + n) -
gammaln(n + 1) -
gammaln(n + ab + 1))
#FILE: QuantEcon.jl/test/test_lqnash.jl
##CHUNK 1
w2 = [0 0
0 0
-0.5*e2[2] B[2]/2.]
m1 = [0 0
0 d[1, 2]/2.]
m2 = copy(m1)
# build model and solve it
f1, f2, p1, p2 = nnash(a, b1, b2, r1, r2, q1, q2, s1, s2, w1, w2, m1, m2)
aaa = a - b1*f1 - b2*f2
aa = aaa[1:2, 1:2]
tf = I - aa
tfi = inv(tf)
xbar = tfi*aaa[1:2, 3]
# Define answers from matlab. TODO: this is ghetto
f1_ml = [0.243666582208565 0.027236062661951 -6.827882928738190
0.392370733875639 0.139696450885998 -37.734107291009138]
#CURRENT FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
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 = zeros(n)
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
##CHUNK 2
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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
##CHUNK 3
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
# rootfinding iterations
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
for j in 1:n
# Recurrance relation for Laguerre polynomials
|
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 = zeros(n)
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
# rootfinding iterations
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
for j in 1:n
# Recurrance relation for Laguerre polynomials
p3 = p2
p2 = p1
p1 = ((2j - 1 + a - z) * p2 - (j - 1 + a) * p3) ./ j
end
pp = (n * p1 - (n + a) * p2) ./ z
z1 = z
z = z1 - p1 ./ pp
err = abs(z - z1)
if err < 3e-14
break
end
end
if err > 3e-14
error("failure to converge.")
end
nodes[i] = z
weights[i] = fact / (pp * n * p2)
end
return nodes .* b, weights
end | 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 = zeros(n)
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
# rootfinding iterations
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
for j in 1:n
# Recurrance relation for Laguerre polynomials
p3 = p2
p2 = p1
p1 = ((2j - 1 + a - z) * p2 - (j - 1 + a) * p3) ./ j
end
pp = (n * p1 - (n + a) * p2) ./ z
z1 = z
z = z1 - p1 ./ pp
err = abs(z - z1)
if err < 3e-14
break
end
end
if err > 3e-14
error("failure to converge.")
end
nodes[i] = z
weights[i] = fact / (pp * n * p2)
end
return nodes .* b, weights
end | [
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 = zeros(n)
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
# rootfinding iterations
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
for j in 1:n
# Recurrance relation for Laguerre polynomials
p3 = p2
p2 = p1
p1 = ((2j - 1 + a - z) * p2 - (j - 1 + a) * p3) ./ j
end
pp = (n * p1 - (n + a) * p2) ./ z
z1 = z
z = z1 - p1 ./ pp
err = abs(z - z1)
if err < 3e-14
break
end
end
if err > 3e-14
error("failure to converge.")
end
nodes[i] = z
weights[i] = fact / (pp * n * p2)
end
return nodes .* b, weights
end | 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 = zeros(n)
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
for i = 1:n
# get starting values
if i == 1
z = (1 + a) * (3 + 0.92a) / (1 + 2.4n + 1.8a)
elseif i == 2
z += (15 + 6.25a) ./ (1 + 0.9a + 2.5n)
else
j = i - 2
z += ((1 + 2.55j) ./ (1.9j) + 1.26j * a ./ (1 + 3.5j)) * (z - nodes[j]) ./ (1 + 0.3a)
end
# rootfinding iterations
pp = 0.0
p2 = 0.0
err = 100.0
for it in 1:maxit
p1 = 1.0
p2 = 0.0
for j in 1:n
# Recurrance relation for Laguerre polynomials
p3 = p2
p2 = p1
p1 = ((2j - 1 + a - z) * p2 - (j - 1 + a) * p3) ./ j
end
pp = (n * p1 - (n + a) * p2) ./ z
z1 = z
z = z1 - p1 ./ pp
err = abs(z - z1)
if err < 3e-14
break
end
end
if err > 3e-14
error("failure to converge.")
end
nodes[i] = z
weights[i] = fact / (pp * n * p2)
end
return nodes .* b, weights
end | 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.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) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
##CHUNK 2
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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28+ a ) * n * n))
z = z + (z - x[n-2]) * r1 * r2 * r3
else
z = 3 * x[i-1] - 3 * x[i-2] + x[i-3]
end
ab = a + b
for its = 1:maxit
temp = 2 + ab
p1 = (a - b + temp * z) / 2
##CHUNK 3
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) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 1
##CHUNK 4
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
end
if its >= maxit
error("Failure to converge in qnwbeta1")
end
#CURRENT FILE: QuantEcon.jl/src/quad.jl
##CHUNK 1
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.85575 * ((2n + 1).^(-1 / 6))
elseif i == 2
z = z - 1.14 * (n.^0.426) ./ z
elseif i == 3
z = 1.86z + 0.86nodes[1]
elseif i == 4
z = 1.91z + 0.91nodes[2]
else
z = 2z + nodes[i - 2]
end
##CHUNK 2
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.48 * an + 0.96bn + 0.452an * an + 0.83an * bn
z = 1 - r1 / r2
elseif i == 2
r1 = (4.1 + a) / ((1 + a) * (1 + 0.156a))
r2 = 1 + 0.06 * (n - 8) * (1 + 0.12a) / n
r3 = 1 + 0.012b * (1 + 0.25 * abs(a)) / n
z = z - (1 - z) * r1 * r2 * r3
elseif i == 3
r1 = (1.67 + 0.28a) / (1 + 0.37a)
r2 = 1 + 0.22 * (n - 8) / n
r3 = 1 + 8 * b / ((6.28 + b) * n * n)
##CHUNK 3
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.48 * an + 0.96bn + 0.452an * an + 0.83an * bn
z = 1 - r1 / r2
##CHUNK 4
pp, p2 = 0.0, 0.0
for its = 1:maxit
# recurrance relation for Jacboi polynomials
temp = 2 + ab
p1 = (a - b + temp * z) / 2
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) * (j - 1 + b) * temp
p1 = (bb * p2 - c * p3) / aa
end
pp = (n * (a - b - temp * z) * p1 +
2 * (n + a) * (n + b) * p2) / (temp * (1 - z * z))
z1 = z
z = z1 - p1 ./ pp
if abs(z - z1) < 3e-14 break end
##CHUNK 5
z = z - (x[1] - z) * r1 * r2 * r3
elseif i == n - 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) / (1.67 + 0.28b)
r2 = 1 / (1 + 0.22 * (n - 8) / n)
r3 = 1 / (1 + 8 * a / ((6.28 + a ) * n * n))
z = z + (z - x[n - 2]) * r1 * r2 * r3
else
z = 3 * x[i - 1] - 3 * x[i - 2] + x[i - 3]
end
its = 1
temp = 0.0
##CHUNK 6
length of either `n` and/or `mu` (which ever is a vector).
If all 3 are scalars, then 1d nodes are computed. `mu` and `sig2` are treated as
the mean and variance of a 1d normal distribution
$(qnw_refs)
"""
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.85575 * ((2n + 1).^(-1 / 6))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.