licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
8267
# t.jl # Various forms of t-tests # # Copyright (C) 2012 Simon Kornblith # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export OneSampleTTest, TwoSampleTTest, EqualVarianceTTest, UnequalVarianceTTest abstract type TTest <: HypothesisTest end abstract type TwoSampleTTest <: TTest end StatsAPI.pvalue(x::TTest; tail=:both) = pvalue(TDist(x.df), x.t; tail=tail) default_tail(test::TTest) = :both # confidence interval by inversion function StatsAPI.confint(x::TTest; level::Float64=0.95, tail=:both) check_level(level) if tail == :left (-Inf, confint(x, level=1-(1-level)*2)[2]) elseif tail == :right (confint(x, level=1-(1-level)*2)[1], Inf) elseif tail == :both q = quantile(TDist(x.df), 1-(1-level)/2) (x.xbar-q*x.stderr, x.xbar+q*x.stderr) else throw(ArgumentError("tail=$(tail) is invalid")) end end ## ONE SAMPLE T-TEST struct OneSampleTTest <: TTest n::Int # number of observations xbar::Real # estimated mean df::Int # degrees of freedom stderr::Real # empirical standard error t::Real # t-statistic μ0::Real # mean under h_0 end testname(::OneSampleTTest) = "One sample t-test" population_param_of_interest(x::OneSampleTTest) = ("Mean", x.μ0, x.xbar) # parameter of interest: name, value under h0, point estimate function show_params(io::IO, x::OneSampleTTest, ident="") println(io, ident, "number of observations: $(x.n)") println(io, ident, "t-statistic: $(x.t)") println(io, ident, "degrees of freedom: $(x.df)") println(io, ident, "empirical standard error: $(x.stderr)") end """ OneSampleTTest(xbar::Real, stddev::Real, n::Int, μ0::Real = 0) Perform a one sample t-test of the null hypothesis that `n` values with mean `xbar` and sample standard deviation `stddev` come from a distribution with mean `μ0` against the alternative hypothesis that the distribution does not have mean `μ0`. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function OneSampleTTest(xbar::Real, stddev::Real, n::Int, μ0::Real=0) stderr = stddev/sqrt(n) t = (xbar-μ0)/stderr df = n-1 OneSampleTTest(n, xbar, df, stderr, t, μ0) end """ OneSampleTTest(v::AbstractVector{T<:Real}, μ0::Real = 0) Perform a one sample t-test of the null hypothesis that the data in vector `v` comes from a distribution with mean `μ0` against the alternative hypothesis that the distribution does not have mean `μ0`. Implements: [`pvalue`](@ref), [`confint`](@ref) """ OneSampleTTest(v::AbstractVector{T}, μ0::Real=0) where {T<:Real} = OneSampleTTest(mean(v), std(v), length(v), μ0) """ OneSampleTTest(x::AbstractVector{T<:Real}, y::AbstractVector{T<:Real}, μ0::Real = 0) Perform a paired sample t-test of the null hypothesis that the differences between pairs of values in vectors `x` and `y` come from a distribution with mean `μ0` against the alternative hypothesis that the distribution does not have mean `μ0`. Implements: [`pvalue`](@ref), [`confint`](@ref) !!! note This test is also known as a t-test for paired or dependent samples, see [paired difference test](https://en.wikipedia.org/wiki/Paired_difference_test) on Wikipedia. """ function OneSampleTTest(x::AbstractVector{T}, y::AbstractVector{S}, μ0::Real=0) where {T<:Real, S<:Real} check_same_length(x, y) OneSampleTTest(x - y, μ0) end ## TWO SAMPLE T-TEST (EQUAL VARIANCE) struct EqualVarianceTTest <: TwoSampleTTest n_x::Int # number of observations n_y::Int # number of observations xbar::Real # estimated mean difference df::Int # degrees of freedom stderr::Real # empirical standard error t::Real # t-statistic μ0::Real # mean difference under h_0 end function show_params(io::IO, x::TwoSampleTTest, ident="") println(io, ident, "number of observations: [$(x.n_x),$(x.n_y)]") println(io, ident, "t-statistic: $(x.t)") println(io, ident, "degrees of freedom: $(x.df)") println(io, ident, "empirical standard error: $(x.stderr)") end testname(::EqualVarianceTTest) = "Two sample t-test (equal variance)" population_param_of_interest(x::TwoSampleTTest) = ("Mean difference", x.μ0, x.xbar) # parameter of interest: name, value under h0, point estimate """ EqualVarianceTTest(nx::Int, ny::Int, mx::Real, my::Real, vx::Real, vy::Real, μ0::Real=0) Perform a two-sample t-test of the null hypothesis that samples `x` and `y` described by the number of elements `nx` and `ny`, the mean `mx` and `my`, and variance `vx` and `vy` come from distributions with equals means and variances. The alternative hypothesis is that the distributions have different means but equal variances. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function EqualVarianceTTest(nx::Int, ny::Int, mx::Real, my::Real, vx::Real, vy::Real, μ0::Real=0) xbar = mx - my stddev = sqrt(((nx - 1) * vx + (ny - 1) * vy) / (nx + ny - 2)) stderr = stddev * sqrt(1/nx + 1/ny) t = (xbar - μ0) / stderr df = nx + ny - 2 EqualVarianceTTest(nx, ny, xbar, df, stderr, t, μ0) end """ EqualVarianceTTest(x::AbstractVector{T<:Real}, y::AbstractVector{T<:Real}) Perform a two-sample t-test of the null hypothesis that `x` and `y` come from distributions with equal means and variances against the alternative hypothesis that the distributions have different means but equal variances. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function EqualVarianceTTest(x::AbstractVector{T}, y::AbstractVector{S}, μ0::Real=0) where {T<:Real,S<:Real} nx, ny = length(x), length(y) mx, my = mean(x), mean(y) vx, vy = var(x), var(y) EqualVarianceTTest(nx, ny, mx, my, vx, vy, μ0) end ## TWO SAMPLE T-TEST (UNEQUAL VARIANCE) struct UnequalVarianceTTest <: TwoSampleTTest n_x::Int # number of observations n_y::Int # number of observations xbar::Real # estimated mean df::Real # degrees of freedom stderr::Real # empirical standard error t::Real # t-statistic μ0::Real # mean under h_0 end testname(::UnequalVarianceTTest) = "Two sample t-test (unequal variance)" """ UnequalVarianceTTest(x::AbstractVector{T<:Real}, y::AbstractVector{T<:Real}) Perform an unequal variance two-sample t-test of the null hypothesis that `x` and `y` come from distributions with equal means against the alternative hypothesis that the distributions have different means. This test is sometimes known as Welch's t-test. It differs from the equal variance t-test in that it computes the number of degrees of freedom of the test using the Welch-Satterthwaite equation: ```math ν_{χ'} ≈ \\frac{\\left(\\sum_{i=1}^n k_i s_i^2\\right)^2}{\\sum_{i=1}^n \\frac{(k_i s_i^2)^2}{ν_i}} ``` Implements: [`pvalue`](@ref), [`confint`](@ref) """ function UnequalVarianceTTest(x::AbstractVector{T}, y::AbstractVector{S}, μ0::Real=0) where {T<:Real,S<:Real} nx, ny = length(x), length(y) xbar = mean(x)-mean(y) varx, vary = var(x), var(y) stderr = sqrt(varx/nx + vary/ny) t = (xbar-μ0)/stderr df = (varx / nx + vary / ny)^2 / ((varx / nx)^2 / (nx - 1) + (vary / ny)^2 / (ny - 1)) UnequalVarianceTTest(nx, ny, xbar, df, stderr, t, μ0) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
8141
# Tests for Equality of Variances export OneWayANOVATest, LeveneTest, BrownForsytheTest, FlignerKilleenTest struct VarianceEqualityTest{TD <: ContinuousUnivariateDistribution} <: HypothesisTest Nᵢ::Vector{Int} SStᵢ::Vector{Float64} SSeᵢ::Vector{Float64} DFt::Int DFe::Int # test name, parameter of interest, test statistic name description::Tuple{String, String, String} end population_param_of_interest(t::VarianceEqualityTest) = (t.description[2], "all equal", NaN) testname(t::VarianceEqualityTest) = t.description[1] teststatisticname(t::VarianceEqualityTest{TD}) where {TD <: ContinuousDistribution} = length(t.description[3]) != 0 ? t.description[3] : (TD <: FDist ? "F" : "χ²") StatsAPI.nobs(t::VarianceEqualityTest) = t.Nᵢ StatsAPI.dof(t::VarianceEqualityTest{Chisq}) = t.DFt StatsAPI.dof(t::VarianceEqualityTest{FDist}) = (t.DFt, t.DFe) teststatistic(t::VarianceEqualityTest{FDist}) = (t.DFe/t.DFt)*sum(t.SStᵢ)/sum(t.SSeᵢ) function teststatistic(t::VarianceEqualityTest{Chisq}) y = sum(t.SStᵢ)/sum(t.SSeᵢ) y*(t.DFe+t.DFt)/(1 + y) # sum(t.SStᵢ)/t.s² end StatsAPI.pvalue(t::VarianceEqualityTest{TD}; tail=:right) where {TD <: ContinuousDistribution} = pvalue(TD(dof(t)...), teststatistic(t), tail=tail) function show_params(io::IO, t::VarianceEqualityTest{TD}, indent="") where {TD <: ContinuousDistribution} println(io, indent, "number of observations: ", nobs(t)) println(io, indent, rpad("$(teststatisticname(t)) statistic:", 24), teststatistic(t)) println(io, indent, "degrees of freedom: ", dof(t)) end function Base.show(io::IOContext, t::VarianceEqualityTest) if !get(io, :table, false) # No table show(io.io, t) else println(io, testname(t)) println(io, repeat("-", 55)) SSt = sum(t.SStᵢ) SSe = sum(t.SSeᵢ) MSt = SSt/t.DFt MSe = SSe/t.DFe println(io, "Source SS DF MS F P-value") println(io, repeat("-", 55)) @printf(io, "Treatments %8.3f %4d %8.3f %8.3f %7.5f\n", SSt, t.DFt, MSt, MSt/MSe, pvalue(t)) @printf(io, "Error %8.3f %4d %8.3f\n", SSe, t.DFe, MSe) println(io, repeat("-", 55)) @printf(io, "Total %8.3f %4d\n", SSt+SSe, t.DFt+t.DFe) end end function anova(scores::AbstractVector{<:Real}...) Nᵢ = [length(g) for g in scores] Z̄ᵢ = mean.(scores) Z̄ = mean(Z̄ᵢ) SStᵢ = Nᵢ .* (Z̄ᵢ .- Z̄).^2 SSeᵢ = sum.( (z .- z̄).^2 for (z, z̄) in zip(scores, Z̄ᵢ) ) (Nᵢ, SStᵢ, SSeᵢ) end """ OneWayANOVATest(groups::AbstractVector{<:Real}...) Perform one-way analysis of variance test of the hypothesis that that the `groups` means are equal. The one-way analysis of variance (one-way ANOVA) is a technique that can be used to compare means of two or more samples. The ANOVA tests the null hypothesis, which states that samples in all groups are drawn from populations with the same mean values. To do this, two estimates are made of the population variance. The ANOVA produces an F-statistic, the ratio of the variance calculated among the means to the variance within the samples. Implements: [`pvalue`](@ref) # External links * [One-way analysis of variance on Wikipedia ](https://en.wikipedia.org/wiki/One-way_analysis_of_variance) """ function OneWayANOVATest(groups::AbstractVector{<:Real}...) Nᵢ, SStᵢ, SSeᵢ = anova(groups...) k = length(Nᵢ) VarianceEqualityTest{FDist}(Nᵢ, SStᵢ, SSeᵢ, k-1, sum(Nᵢ)-k, ("One-way analysis of variance (ANOVA) test","Means","F")) end """ LeveneTest(groups::AbstractVector{<:Real}...; scorediff=abs, statistic=mean) Perform Levene's test of the hypothesis that that the `groups` variances are equal. By default the mean `statistic` is used for centering in each of the `groups`, but other statistics are accepted: median or truncated mean, see [`BrownForsytheTest`](@ref). By default the absolute value of the score difference, `scorediff`, is used, but other functions are accepted: x² or √|x|. The test statistic, ``W``, is equivalent to the ``F`` statistic, and is defined as follows: ```math W = \\frac{(N-k)}{(k-1)} \\cdot \\frac{\\sum_{i=1}^k N_i (Z_{i\\cdot}-Z_{\\cdot\\cdot})^2} {\\sum_{i=1}^k \\sum_{j=1}^{N_i} (Z_{ij}-Z_{i\\cdot})^2}, ``` where * ``k`` is the number of different groups to which the sampled cases belong, * ``N_i`` is the number of cases in the ``i``th group, * ``N`` is the total number of cases in all groups, * ``Y_{ij}`` is the value of the measured variable for the ``j``th case from the ``i``th group, * ``Z_{ij} = |Y_{ij} - \\bar{Y}_{i\\cdot}|``, ``\\bar{Y}_{i\\cdot}`` is a mean of the ``i``th group, * ``Z_{i\\cdot} = \\frac{1}{N_i} \\sum_{j=1}^{N_i} Z_{ij}`` is the mean of the ``Z_{ij}`` for group ``i``, * ``Z_{\\cdot\\cdot} = \\frac{1}{N} \\sum_{i=1}^k \\sum_{j=1}^{N_i} Z_{ij}`` is the mean of all ``Z_{ij}``. The test statistic ``W`` is approximately ``F``-distributed with ``k-1`` and ``N-k`` degrees of freedom. Implements: [`pvalue`](@ref) # References * Levene, Howard, "Robust tests for equality of variances". In Ingram Olkin; Harold Hotelling; et al. (eds.). Contributions to Probability and Statistics: Essays in Honor of Harold Hotelling. Stanford University Press. pp. 278–292, 1960 # External links * [Levene's test on Wikipedia ](https://en.wikipedia.org/wiki/Levene%27s_test) """ function LeveneTest(groups::AbstractVector{<:Real}...; scorediff=abs, statistic=mean) # calculate scores Zᵢⱼ = [scorediff.(g .- statistic(g)) for g in groups] # anova Nᵢ, SStᵢ, SSeᵢ = anova(Zᵢⱼ...) k = length(Nᵢ) VarianceEqualityTest{FDist}(Nᵢ, SStᵢ, SSeᵢ, k-1, sum(Nᵢ)-k, ("Levene's test","Variances","W")) end """ BrownForsytheTest(groups::AbstractVector{<:Real}...) The Brown–Forsythe test is a statistical test for the equality of `groups` variances. The Brown–Forsythe test is a modification of the Levene's test with the median instead of the mean statistic for computing the spread within each group. Implements: [`pvalue`](@ref) # References * Brown, Morton B.; Forsythe, Alan B., "Robust tests for the equality of variances". Journal of the American Statistical Association. 69: 364–367, 1974 doi:[10.1080/01621459.1974.10482955](https://doi.org/10.1080%2F01621459.1974.10482955). # External links * [Brown–Forsythe test on Wikipedia ](https://en.wikipedia.org/wiki/Brown%E2%80%93Forsythe_test) """ BrownForsytheTest(groups::AbstractVector{<:Real}...) = LeveneTest(groups...; statistic=median) """ FlignerKilleenTest(groups::AbstractVector{<:Real}...) Perform Fligner-Killeen median test of the null hypothesis that the `groups` have equal variances, a test for homogeneity of variances. This test is most robust against departures from normality, see references. It is a ``k``-sample simple linear rank method that uses the ranks of the absolute values of the centered samples and weights ```math a_{N,i} = \\Phi^{-1}(1/2 + (i/2(N+1))) ``` The version implemented here uses median centering in each of the samples. Implements: [`pvalue`](@ref) # References * Conover, W. J., Johnson, M. E., Johnson, M. M., A comparative study of tests for homogeneity of variances, with applications to the outer continental shelf bidding data. Technometrics, 23, 351–361, 1980 # External links * [Fligner-Killeen test on Statistical Analysis Handbook ](https://www.statsref.com/HTML/index.html?fligner-killeen_test.html) """ function FlignerKilleenTest(groups::AbstractVector{<:Real}...) # calculate scores Zᵢⱼ = [abs.(g .- median(g)) for g in groups] # rank scores (ranks, tieadj) = tiedrank_adj(vcat(Zᵢⱼ...)) qᵢⱼ = quantile.(Normal(),0.5 .+ ranks./2(length(ranks)+1)) Nᵢ = pushfirst!(cumsum([length(g) for g in groups]),0) Qᵢⱼ = [qᵢⱼ[(Nᵢ[i]+1):(Nᵢ[i+1])] for i in 1:length(Nᵢ)-1] # anova Nᵢ, SStᵢ, SSeᵢ = anova(Qᵢⱼ...) k = length(Nᵢ) t3 = VarianceEqualityTest{Chisq}(Nᵢ, SStᵢ, SSeᵢ, k-1, sum(Nᵢ)-k, ("Fligner-Killeen test","Variances","FK")) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1926
export WaldWolfowitzTest struct WaldWolfowitzTest{T <: Real} <: HypothesisTest nabove::Int # Number of points above median (or of value a) nbelow::Int # Number of points below median (or of value b) nruns::Int # Number of runs μ::T # Expected mean σ::T # Expected variance z::T # test z-statistic from Normal distribution end testname(::WaldWolfowitzTest) = "Wald-Wolfowitz Test" population_param_of_interest(x::WaldWolfowitzTest) = ("Number of runs", x.μ, x.nruns) # parameter of interest: name, value under h0, point estimate default_tail(::WaldWolfowitzTest) = :both StatsAPI.pvalue(test::WaldWolfowitzTest; tail=:both) = pvalue(Normal(0.0, 1.0), test.z; tail=tail) function show_params(io::IO, x::WaldWolfowitzTest, ident="") println(io, ident, "number of runs: $(x.nruns)") println(io, ident, "z-statistic: $(x.z)") end """ WaldWolfowitzTest(x::AbstractVector{Bool}) WaldWolfowitzTest(x::AbstractVector{<:Real}) Perform the Wald-Wolfowitz (or Runs) test of the null hypothesis that the given data is random, or independently sampled. The data can come as many-valued or two-valued (Boolean). If many-valued, the sample is transformed by labelling each element as above or below the median. Implements: [`pvalue`](@ref) """ function WaldWolfowitzTest(x::AbstractVector{Bool}) n = length(x) nabove = sum(x) nbelow = n - nabove # Get the expected value and standard deviation μ = 1 + 2 * nabove * (nbelow / n) σ = sqrt((μ - 1) * (μ - 2) / (n - 1)) # Get the number of runs nruns = 1 for k in 1:(n - 1) @inbounds if x[k] != x[k + 1] nruns += 1 end end # calculate simple z-statistic z = (nruns - μ) / σ WaldWolfowitzTest(nabove, nbelow, nruns, μ, σ, z) end WaldWolfowitzTest(x::AbstractVector{<:Real}) = WaldWolfowitzTest(x .>= median(x))
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
5178
# white.jl # White and Breusch-Pagan tests for heteroskedasticity # # Copyright (C) 2020 Paul Söderlind # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export WhiteTest, BreuschPaganTest struct WhiteTest <: HypothesisTest dof::Int #degrees of freedom in test lm::Float64 #Lagrange Multiplier test statistic, distributed as Chisq(dof) type::Symbol end """ WhiteTest(X, e; type = :White) Compute White's (or Breusch-Pagan's) test for heteroskedasticity. `X` is a matrix of regressors and `e` is the vector of residuals from the original model. The keyword argument `type` is either `:linear` for the Breusch-Pagan/Koenker test, `:linear_and_squares` for White's test with linear and squared terms only (no cross-products), or `:White` (the default) for the full White's test (linear, squared and cross-product terms). `X` should include a constant and at least one more regressor, with observations in rows and regressors in columns. In some applications, `X` is a subset of the regressors in the original model, or just the fitted values. This saves degrees of freedom and may give a more powerful test. The `lm` (Lagrange multiplier) test statistic is T*R2 where R2 is from the regression of `e^2` on the terms mentioned above. Under the null hypothesis it is distributed as `Chisq(dof)` where `dof` is the number of independent terms (not counting the constant), so the null is rejected when the test statistic is large enough. Implements: [`pvalue`](@ref) # References * H. White, (1980): A heteroskedasticity-consistent covariance matrix estimator and a direct test for heteroskedasticity, Econometrica, 48, 817-838. * T.S. Breusch & A.R. Pagan (1979), A simple test for heteroscedasticity and random coefficient variation, Econometrica, 47, 1287-1294 * R. Koenker (1981), A note on studentizing a test for heteroscedasticity, Journal of Econometrics, 17, 107-112 # External links * [White's test on Wikipedia](https://en.wikipedia.org/wiki/White_test) """ function WhiteTest(X::AbstractMatrix{<:Real}, e::AbstractVector{<:Real}; type = :White) (n,K) = (size(X,1),size(X,2)) #nobs,nvars n == length(e) || throw(DimensionMismatch("inputs must have the same length")) K >= 2 || throw(ArgumentError("X must have >= 2 columns")) intercept_col = false for i = 1:K col = view(X,:,i) intercept_col = first(col) != 0 && all(==(first(col)), col) intercept_col && break end intercept_col || throw(ArgumentError("one of the colums of X must be a non-zero constant")) if type == :linear #Breush-Pagan/Koenker z = X elseif type == :linear_and_squares #White with linear and squares z = [X X.^2] else #White with linear, squares and cross-products z = fill(NaN,n,round(Int,K*(K+1)/2)) vv = 1 @views for i = 1:K, j = i:K z[:,vv] .= X[:,i] .* X[:,j] #eg. x1*x1, x1*x2, x2*x2 vv += 1 end end dof = rank(z) - 1 #number of independent regressors in z e2 = e.^2 b = z\e2 res = e2 - z*b R2 = 1 - var(res)/var(e2) lm = n*R2 return WhiteTest(dof, lm, type) end """ BreuschPaganTest(X, e) Compute Breusch-Pagan's test for heteroskedasticity. `X` is a matrix of regressors from the original model and `e` the vector of residuals. This is equivalent to `WhiteTest(X, e, type = :linear)`. See [`WhiteTest`](@ref) for further details. """ BreuschPaganTest(X, e) = WhiteTest(X, e, type = :linear) testname(t::WhiteTest) = "White's (or Breusch-Pagan's) test for heteroskedasticity" population_param_of_interest(t::WhiteTest) = ("T*R2", 0, t.lm) default_tail(test::WhiteTest) = :right function show_params(io::IO, t::WhiteTest, ident = "") println(io, ident, "T*R^2 statistic: ", t.lm) println(io, ident, "degrees of freedom: ", t.dof) println(io, ident, "type: ", t.type) end StatsAPI.dof(t::WhiteTest) = t.dof StatsAPI.pvalue(t::WhiteTest) = pvalue(Chisq(t.dof), t.lm, tail=:right)
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
10783
# Wilcoxon.jl # Wilcoxon signed rank tests # # Copyright (C) 2012 Simon Kornblith # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export SignedRankTest, ExactSignedRankTest, ApproximateSignedRankTest ## COMMON SIGNED RANK # Automatic exact/normal selection """ SignedRankTest(x::AbstractVector{<:Real}) SignedRankTest(x::AbstractVector{<:Real}, y::AbstractVector{<:Real}) Perform a Wilcoxon signed rank test of the null hypothesis that the distribution of `x` (or the difference `x - y` if `y` is provided) has zero median against the alternative hypothesis that the median is non-zero. When there are no tied ranks and ≤50 samples, or tied ranks and ≤15 samples, `SignedRankTest` performs an exact signed rank test. In all other cases, `SignedRankTest` performs an approximate signed rank test. Behavior may be further controlled by using [`ExactSignedRankTest`](@ref) or [`ApproximateSignedRankTest`](@ref) directly. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function SignedRankTest(x::AbstractVector{T}) where T<:Real (W, ranks, signs, tie_adjustment, n, median) = signedrankstats(x) n_nonzero = length(ranks) if n_nonzero <= 15 || (n_nonzero <= 50 && tie_adjustment == 0) ExactSignedRankTest(x, W, ranks, signs, tie_adjustment, n, median) else ApproximateSignedRankTest(x, W, ranks, signs, tie_adjustment, n, median) end end SignedRankTest(x::AbstractVector{T}, y::AbstractVector{S}) where {T<:Real,S<:Real} = SignedRankTest(x - y) # Get W and absolute ranks for signed rank test function signedrankstats(x::AbstractVector{S}) where S<:Real nonzero_x = x[x .!= 0] (ranks, tieadj) = tiedrank_adj(abs.(nonzero_x)) W = 0.0 for i = 1:length(nonzero_x) if nonzero_x[i] > 0 W += ranks[i] end end (W, ranks, nonzero_x .> 0, tieadj, length(x), median(x)) end ## EXACT WILCOXON SIGNED RANK TEST struct ExactSignedRankTest{T<:Real} <: HypothesisTest vals::Vector{T} # original values W::Float64 # test statistic: Wilcoxon rank-sum statistic ranks::Vector{Float64} # ranks without ties (zero values) signs::BitArray{1} # signs of input of ranks tie_adjustment::Float64 # adjustment for ties n::Int # number of observations median::Float64 # sample median end """ ExactSignedRankTest(x::AbstractVector{<:Real}[, y::AbstractVector{<:Real}]) Perform a Wilcoxon exact signed rank U test of the null hypothesis that the distribution of `x` (or the difference `x - y` if `y` is provided) has zero median against the alternative hypothesis that the median is non-zero. When there are no tied ranks, the exact p-value is computed using the `psignrank` function from the `Rmath` package. In the presence of tied ranks, a p-value is computed by exhaustive enumeration of permutations, which can be very slow for even moderately sized data sets. Implements: [`pvalue`](@ref), [`confint`](@ref) """ ExactSignedRankTest(x::AbstractVector{T}) where {T<:Real} = ExactSignedRankTest(x, signedrankstats(x)...) ExactSignedRankTest(x::AbstractVector{S}, y::AbstractVector{T}) where {S<:Real,T<:Real} = ExactSignedRankTest(x - y) testname(::ExactSignedRankTest) = "Exact Wilcoxon signed rank test" population_param_of_interest(x::ExactSignedRankTest) = ("Location parameter (pseudomedian)", 0, x.median) # parameter of interest: name, value under h0, point estimate default_tail(test::ExactSignedRankTest) = :both function show_params(io::IO, x::ExactSignedRankTest, ident) println(io, ident, "number of observations: ", x.n) println(io, ident, "Wilcoxon rank-sum statistic: ", x.W) print(io, ident, "rank sums: ") show(io, [sum(x.ranks[x.signs]), sum(x.ranks[map(!, x.signs)])]) println(io) println(io, ident, "adjustment for ties: ", x.tie_adjustment) end # Enumerate all possible Wilcoxon rank-sum results for a given vector, determining left- # and right-tailed p values function signedrankenumerate(x::ExactSignedRankTest) le = 0 gr = 0 n = length(x.ranks) tot = 2^n for i = 0:tot-1 # Interpret bits of i as signs to generate wp for all possible sign combinations Wp = 0 b = i j = 1 while b != 0 Wp += (b & 1)*x.ranks[j] j += 1 b >>= 1 end le += Wp <= x.W gr += Wp >= x.W end (le/tot, gr/tot) end function StatsAPI.pvalue(x::ExactSignedRankTest; tail=:both) check_tail(tail) n = length(x.ranks) if n == 0 1.0 elseif x.tie_adjustment == 0 # Compute exact p-value using method from Rmath, which is fast but cannot account for ties if tail == :both if x.W <= n * (n + 1)/4 2 * psignrank(x.W, n, true) else 2 * psignrank(x.W - 1, n, false) end elseif tail == :left psignrank(x.W, n, true) else psignrank(x.W - 1, n, false) end else # Compute exact p-value by enumerating all possible ranks in the tied data if tail == :both min(1, 2 * minimum(signedrankenumerate(x))) elseif tail == :left first(signedrankenumerate(x)) else last(signedrankenumerate(x)) end end end StatsAPI.confint(x::ExactSignedRankTest; level::Real=0.95, tail=:both) = calculate_ci(x.vals, level, tail=tail) ## APPROXIMATE SIGNED RANK TEST struct ApproximateSignedRankTest{T<:Real} <: HypothesisTest vals::Vector{T} # original values W::Float64 # test statistic: Wilcoxon rank-sum statistic ranks::Vector{Float64} # ranks without ties (zero values) signs::BitArray{1} # signs of input of ranks tie_adjustment::Float64 # adjustment for ties n::Int # number of observations median::Float64 # sample median mu::Float64 # normal approximation: mean sigma::Float64 # normal approximation: std end """ ApproximateSignedRankTest(x::AbstractVector{<:Real}[, y::AbstractVector{<:Real}]) Perform a Wilcoxon approximate signed rank U test of the null hypothesis that the distribution of `x` (or the difference `x - y` if `y` is provided) has zero median against the alternative hypothesis that the median is non-zero. The p-value is computed using a normal approximation to the distribution of the signed rank statistic: ```math \\begin{align*} μ & = \\frac{n(n + 1)}{4}\\\\ σ & = \\frac{n(n + 1)(2 * n + 1)}{24} - \\frac{a}{48}\\\\ a & = \\sum_{t \\in \\mathcal{T}} t^3 - t \\end{align*} ``` where ``\\mathcal{T}`` is the set of the counts of tied values at each tied position. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function ApproximateSignedRankTest(x::Vector, W::Float64, ranks::Vector{T}, signs::BitArray{1}, tie_adjustment::Float64, n::Int, median::Float64) where T<:Real nz = length(ranks) # num non-zeros mu = W - nz * (nz + 1)/4 std = sqrt(nz * (nz + 1) * (2 * nz + 1) / 24 - tie_adjustment / 48) ApproximateSignedRankTest(x, W, ranks, signs, tie_adjustment, n, median, mu, std) end ApproximateSignedRankTest(x::AbstractVector{T}) where {T<:Real} = ApproximateSignedRankTest(x, signedrankstats(x)...) ApproximateSignedRankTest(x::AbstractVector{S}, y::AbstractVector{T}) where {S<:Real,T<:Real} = ApproximateSignedRankTest(x - y) testname(::ApproximateSignedRankTest) = "Approximate Wilcoxon signed rank test" population_param_of_interest(x::ApproximateSignedRankTest) = ("Location parameter (pseudomedian)", 0, x.median) # parameter of interest: name, value under h0, point estimate default_tail(test::ApproximateSignedRankTest) = :both function show_params(io::IO, x::ApproximateSignedRankTest, ident) println(io, ident, "number of observations: ", x.n) println(io, ident, "Wilcoxon rank-sum statistic: ", x.W) print(io, ident, "rank sums: ") show(io, [sum(x.ranks[x.signs]), sum(x.ranks[map(!, x.signs)])]) println(io) println(io, ident, "adjustment for ties: ", x.tie_adjustment) println(io, ident, "normal approximation (μ, σ): ", (x.mu, x.sigma)) end function StatsAPI.pvalue(x::ApproximateSignedRankTest; tail=:both) check_tail(tail) if x.mu == x.sigma == 0 1.0 elseif tail == :both 2 * ccdf(Normal(), abs(x.mu - 0.5 * sign(x.mu))/x.sigma) elseif tail == :left cdf(Normal(), (x.mu + 0.5)/x.sigma) else # tail == :right ccdf(Normal(), (x.mu - 0.5)/x.sigma) end end StatsAPI.confint(x::ApproximateSignedRankTest; level::Real=0.95, tail=:both) = calculate_ci(x.vals, level, tail=tail) # implementation method inspired by these notes: http://www.stat.umn.edu/geyer/old03/5102/notes/rank.pdf function calculate_ci(x::AbstractVector, level::Real=0.95; tail=:both) check_level(level) check_tail(tail) if tail == :both c = level else c = 1 - 2 * (1-level) end n = length(x) m = div(n * (n + 1), 2) k_range = 1:div(m, 2) l = [1 - 2 * psignrank(i, n, true) for i in k_range] k = argmin(abs.(l .- c)) vals = Float64[] enumerated = enumerate(x) for (outer_index, outer_value) in enumerated for (inner_index, inner_value) in enumerated if outer_index > inner_index continue end push!(vals, (inner_value + outer_value) / 2) end end sort!(vals) left = vals[k + 1] right = vals[m - k] if tail == :both return (left, right) elseif tail == :left return (left, Inf) else # tail == :right return (-Inf, right) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
6731
# z.jl # Various forms of z-tests # # Copyright (C) 2016 John Myles White # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. export OneSampleZTest, TwoSampleZTest, EqualVarianceZTest, UnequalVarianceZTest abstract type ZTest <: HypothesisTest end abstract type TwoSampleZTest <: ZTest end StatsAPI.pvalue(x::ZTest; tail=:both) = pvalue(Normal(0.0, 1.0), x.z; tail=tail) default_tail(test::ZTest) = :both # confidence interval by inversion function StatsAPI.confint(x::ZTest; level::Float64=0.95, tail=:both) check_level(level) if tail == :left (-Inf, confint(x, level=1-(1-level)*2)[2]) elseif tail == :right (confint(x, level=1-(1-level)*2)[1], Inf) elseif tail == :both q = cquantile(Normal(0.0, 1.0), (1-level)/2) (x.xbar-q*x.stderr, x.xbar+q*x.stderr) else throw(ArgumentError("tail=$(tail) is invalid")) end end ## ONE SAMPLE Z-TEST struct OneSampleZTest <: ZTest n::Int # number of observations xbar::Real # estimated mean stderr::Real # population standard error z::Real # z-statistic μ0::Real # mean under h_0 end testname(::OneSampleZTest) = "One sample z-test" population_param_of_interest(x::OneSampleZTest) = ("Mean", x.μ0, x.xbar) # parameter of interest: name, value under h0, point estimate function show_params(io::IO, x::OneSampleZTest, ident="") println(io, ident, "number of observations: $(x.n)") println(io, ident, "z-statistic: $(x.z)") println(io, ident, "population standard error: $(x.stderr)") end """ OneSampleZTest(xbar::Real, stddev::Real, n::Int, μ0::Real = 0) Perform a one sample z-test of the null hypothesis that `n` values with mean `xbar` and population standard deviation `stddev` come from a distribution with mean `μ0` against the alternative hypothesis that the distribution does not have mean `μ0`. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function OneSampleZTest(xbar::Real, stddev::Real, n::Int, μ0::Real=0) stderr = stddev/sqrt(n) z = (xbar-μ0)/stderr OneSampleZTest(n, xbar, stderr, z, μ0) end """ OneSampleZTest(v::AbstractVector{T<:Real}, μ0::Real = 0) Perform a one sample z-test of the null hypothesis that the data in vector `v` comes from a distribution with mean `μ0` against the alternative hypothesis that the distribution does not have mean `μ0`. Implements: [`pvalue`](@ref), [`confint`](@ref) """ OneSampleZTest(v::AbstractVector{T}, μ0::Real=0) where {T<:Real} = OneSampleZTest(mean(v), std(v), length(v), μ0) """ OneSampleZTest(x::AbstractVector{T<:Real}, y::AbstractVector{T<:Real}, μ0::Real = 0) Perform a paired sample z-test of the null hypothesis that the differences between pairs of values in vectors `x` and `y` come from a distribution with mean `μ0` against the alternative hypothesis that the distribution does not have mean `μ0`. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function OneSampleZTest(x::AbstractVector{T}, y::AbstractVector{S}, μ0::Real=0) where {T<:Real, S<:Real} check_same_length(x, y) OneSampleZTest(x - y, μ0) end ## TWO SAMPLE Z-TEST (EQUAL VARIANCE) struct EqualVarianceZTest <: TwoSampleZTest n_x::Int # number of observations n_y::Int # number of observations xbar::Real # estimated mean difference stderr::Real # population standard error z::Real # z-statistic μ0::Real # mean difference under h_0 end function show_params(io::IO, x::TwoSampleZTest, ident="") println(io, ident, "number of observations: [$(x.n_x),$(x.n_y)]") println(io, ident, "z-statistic: $(x.z)") println(io, ident, "population standard error: $(x.stderr)") end testname(::EqualVarianceZTest) = "Two sample z-test (equal variance)" population_param_of_interest(x::TwoSampleZTest) = ("Mean difference", x.μ0, x.xbar) # parameter of interest: name, value under h0, point estimate """ EqualVarianceZTest(x::AbstractVector{T<:Real}, y::AbstractVector{T<:Real}) Perform a two-sample z-test of the null hypothesis that `x` and `y` come from distributions with equal means and variances against the alternative hypothesis that the distributions have different means but equal variances. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function EqualVarianceZTest(x::AbstractVector{T}, y::AbstractVector{S}, μ0::Real=0) where {T<:Real,S<:Real} nx, ny = length(x), length(y) xbar = mean(x) - mean(y) stddev = sqrt(((nx - 1) * var(x) + (ny - 1) * var(y)) / (nx + ny - 2)) stderr = stddev * sqrt(1/nx + 1/ny) z = (xbar - μ0) / stderr EqualVarianceZTest(nx, ny, xbar, stderr, z, μ0) end ## TWO SAMPLE Z-TEST (UNEQUAL VARIANCE) struct UnequalVarianceZTest <: TwoSampleZTest n_x::Int # number of observations n_y::Int # number of observations xbar::Real # estimated mean stderr::Real # empirical standard error z::Real # z-statistic μ0::Real # mean under h_0 end testname(::UnequalVarianceZTest) = "Two sample z-test (unequal variance)" """ UnequalVarianceZTest(x::AbstractVector{T<:Real}, y::AbstractVector{T<:Real}) Perform an unequal variance two-sample z-test of the null hypothesis that `x` and `y` come from distributions with equal means against the alternative hypothesis that the distributions have different means. Implements: [`pvalue`](@ref), [`confint`](@ref) """ function UnequalVarianceZTest(x::AbstractVector{T}, y::AbstractVector{S}, μ0::Real=0) where {T<:Real,S<:Real} nx, ny = length(x), length(y) xbar = mean(x)-mean(y) varx, vary = var(x), var(y) stderr = sqrt(varx/nx + vary/ny) z = (xbar-μ0)/stderr UnequalVarianceZTest(nx, ny, xbar, stderr, z, μ0) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
2945
using HypothesisTests, Distributions, Test, Random using HypothesisTests: default_tail using StableRNGs @testset "Anderson-Darling" begin @testset "One sample test" begin n = 1000 rng = StableRNG(1984948) d = Normal(1000, 100) x = rand(rng, d, n) t = OneSampleADTest(x, d) @test t.A² ≈ 1.2960 atol=0.1^4 @test pvalue(t) ≈ 0.2336 atol=0.1^4 @test default_tail(t) == :right d = DoubleExponential() x = rand(rng, d, n) t = OneSampleADTest(x, Normal(mean(d), std(d))) @test t.A² ≈ 11.0704 atol=0.1^4 @test pvalue(t) ≈ 0.0 atol=0.1^4 t = OneSampleADTest(x, d) @test t.A² ≈ 0.8968 atol=0.1^4 @test pvalue(t) ≈ 0.4162 atol=0.1^4 d = Cauchy() x = rand(rng, Cauchy(), n) t = OneSampleADTest(x, Normal()) @test pvalue(t) ≈ 0.0 atol=0.1^4 t = OneSampleADTest(x, d) @test pvalue(t) ≈ 0.9640 atol=0.1^4 d = LogNormal() x = rand(rng, d, n) t = OneSampleADTest(x, Normal(mean(d), std(d))) @test pvalue(t) ≈ 0.0 atol=0.1^4 t = OneSampleADTest(x, d) @test pvalue(t) ≈ 0.9123 atol=0.1^4 d = Uniform(-pi, 2pi) x = rand(rng, d, n) t = OneSampleADTest(x, d) @test pvalue(t) ≈ 0.2337 atol=0.1^4 x = rand(rng, Uniform(0, 1.8), n) t = OneSampleADTest(x, Uniform()) @test pvalue(t) ≈ 0.0 atol=0.1^4 x = rand(rng, Exponential(), n) t = OneSampleADTest(x, Exponential()) @test pvalue(t) ≈ 0.8579 atol=0.1^4 end @testset "k-sample test" begin samples = Any[ [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0], [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8], [34.0, 35.0, 39.0, 40.0, 43.0, 43.0, 44.0, 45.0], [34.0, 34.8, 34.8, 35.4, 37.2, 37.8, 41.2, 42.8] ] t = KSampleADTest(samples...) @test t.A²k ≈ 8.3926 atol=0.1^4 @test t.σ ≈ 1.2038 atol=0.1^4 @test pvalue(t) ≈ 0.0022 atol=0.1^4 @test default_tail(t) == :right ts = KSampleADTest(samples..., nsim = 20000); @test pvalue(ts) ≈ 0.00155 atol=0.1^3 t = KSampleADTest(samples..., modified = false) @test t.A²k ≈ 8.3559 atol=0.1^4 @test t.σ ≈ 1.2038 atol=0.1^4 @test pvalue(t) ≈ 0.0023 atol=0.1^4 ts = KSampleADTest(samples..., modified = false, nsim = 20000); @test pvalue(ts) ≈ 0.00150 atol=0.1^3 end @testset "more tests" begin rng = StableRNG(31412455) samples = Any[rand(rng, Normal(), 50), rand(rng, Normal(0.5), 30)] t = KSampleADTest(samples...) @test pvalue(t) < 0.05 samples = Any[rand(rng, Normal(), 50), rand(rng, Normal(), 30), rand(rng, Normal(), 20)] t = KSampleADTest(samples...) @test pvalue(t) > 0.05 @test pvalue(OneSampleADTest(vcat(rand(rng, Normal(),500), rand(rng, Beta(2,2),500)), Beta(2,2))) ≈ 0.0 atol=0.1^4 n = 1000 x = rand(rng, Exponential(), n) @test pvalue(KSampleADTest(rand(rng, 1000), randn(rng, 1000))) ≈ 0.0 atol=eps() @test pvalue(KSampleADTest(x,x,x,x,x,x)) ≈ 1.0 end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
7562
using HypothesisTests, LinearAlgebra, Test @testset "Augmented Dickey-Fuller" begin sim_data_h0 = [ 0.3823959677906078, -0.2152385089376233, -0.22568375357499895, -1.064710607963763, -0.7535992694654291, 1.5414885543718815, -0.7255977944286491, -0.19563221826190302, 0.23578930816100901, 0.8194975957297876, 1.7827692007679783, 2.2415601558216953, 1.719223398400187, 2.1276192367249394, 2.077168006791274, 1.3835143629873885, -0.39031889042066714, -0.26955292548322785, -1.0271859632037557, -2.7569421445944418, -1.9609935225898258, -1.2909315413337634, -0.7400791638330025, -0.8034537562625632, 0.5334890259883591, 0.46034039265061977, -0.28512392399013586, -1.5051790525247886, -1.558356390052481, -1.7234927478553148, -3.838862996282626, -3.9056309827892153, -2.6831691343211537, -2.1154736745827103, -1.351974746259323, -0.973375866405973, -1.61897292304257, -2.2836191674336015, -4.086645491644496, -5.37569309549424, -5.710963175012358, -5.6404955736512, -5.298701806271377, -3.563536140216995, -2.263620175906803, -2.057256094504186, -3.0661160500417894, -3.9161717203571875, -2.786762284472861, -4.135295740964688, -2.8950048405356283, -2.9506519337429524, -2.1912617197974926, -2.221528606444255, -2.5826112742003486, -4.589914476732911, -5.158773604079549, -6.308401128476547, -4.427778953845362, -5.898403495232742, -6.433614465398474, -7.397158425223975, -8.78226649289989, -8.64796625533862, -9.26408292134744, -10.984072277667181, -10.66330299767977, -12.11067589556128, -12.602947083630847, -13.016034467614029, -12.014105955158076, -10.839424629182965, -12.166394974245012, -13.759609842289079, -14.198319818047874, -12.972522320050007, -11.483432041980393, -9.32399885487954, -10.233477872917042, -9.085657572304541, -9.590729768826915, -9.857796804045044, -8.358714410114315, -7.561410249938924, -7.733050693246021, -8.202130303176117, -7.984506281967517, -7.625359874365167, -7.30533515865711, -7.046118830601424, -6.586422845559796, -6.376436485517654, -4.8532610943403895, -3.5934664907281935, -3.758749591842454, -3.602555096954818, -4.416870391331517, -6.126738597336108, -4.626800721222075, -4.755716359752092, -5.205900331311935 ] @testset "No deterministic term" begin t = ADFTest(sim_data_h0, :none, 0) @test t.n == 100 @test t.deterministic == :none @test t.lag == 0 @test t.stat ≈ -0.6050597112208628 @test t.coef ≈ -0.009972855420884913 @test t.cv ≈ [ -2.5882321870404863, -1.9439589708250309, -1.614431731329 ] @test pvalue(t) ≈ 0.4525095990064268 show(IOBuffer(), t) end @testset "Constant term" begin t = ADFTest(sim_data_h0, :constant, 4) @test t.n == 96 @test t.deterministic == :constant @test t.lag == 4 @test t.stat ≈ -1.3432252172180439 @test t.coef ≈ -0.034891024784937275 @test t.cv ≈ [ -3.49681816639021, -2.8906107514600103, -2.5822770483285953 ] @test pvalue(t) ≈ 0.6091721848538273 show(IOBuffer(), t) end @testset "Linear trend term" begin t = ADFTest(sim_data_h0, :trend, 1) @test t.n == 99 @test t.deterministic == :trend @test t.lag == 1 @test t.stat ≈ -1.643937136091079 @test t.coef ≈ -0.06200340824254233 @test t.cv ≈ [ -4.051321648595895, -3.4548891419983088, -3.1530564880069027 ] @test pvalue(t) ≈ 0.7747580288456625 show(IOBuffer(), t) end @testset "Quadratic trend term" begin t = ADFTest(sim_data_h0, :squared_trend, 10) @test t.n == 90 @test t.deterministic == :squared_trend @test t.lag == 10 @test t.stat ≈ -2.0185041960365777 @test t.coef ≈ -0.11370011315231617 @test t.cv ≈ [ -4.489700198611862, -3.8922014722784897, -3.5900742238045 ] @test pvalue(t) ≈ 0.8095687207005545 show(IOBuffer(), t) end sim_data_h1 = [ 0.3823959677906078, -0.4064364928329272, -0.21366349105383925, -0.9458585999156837, -0.161817961459508, 2.2141788431075566, -1.1599969272467523, -0.05003288745663004, 0.406405082694597, 0.7869108289160771, 1.3567270194962293, 1.1371544648018315, 0.04624047497940731, 0.4315160758144559, 0.16530680797356267, -0.6110002398171043, -2.079333373316608, -0.9189007217208647, -1.21708339858096, -2.338297880681166, -0.3732003183359671, 0.48346182208807886, 0.7925832885448003, 0.33291705184283954, 1.503401308172342, 0.6785520207484317, -0.4061883062665398, -1.4231492816679225, -0.7647519783616538, -0.5475123469836606, -2.3891264219191415, -1.2613311974661598, 0.5917962497349819, 0.8635935846059344, 1.1952957206263544, 0.9762467401665272, -0.15747368655333344, -0.7433830876676981, -2.174717868044743, -2.376406537872116, -1.5234733484541754, -0.6912690728659298, -0.003840769053141846, 1.7332452815278112, 2.1665386050740976, 1.2896333839396656, -0.3640432635677706, -1.032077302099283, 0.6133707848346852, -1.0418480640744843, 0.7193668683918175, 0.3040363409885845, 0.911408384439752, 0.4254373055731135, -0.1483640149695369, -2.081485210017331, -1.6096017323553033, -1.9544283905746491, 0.9034079793438605, -1.0189205517154498, -1.0446712460234568, -1.4858795828372295, -2.1280478590945284, -0.9297236919859942, -1.0809785120018163, -2.26047861232065, -0.8094700261729145, -1.8521079109679686, -1.4183251435535507, -1.1222499557599581, 0.4408035345759739, 1.395083093263098, -0.6294287984304979, -1.907929267259316, -1.3926746093884548, 0.5294601933036396, 1.7538203747214345, 3.0363433744615707, 0.6086926691932826, 1.4521666352091431, 0.22101112108219845, -0.15656147467703047, 1.4208016565922137, 1.5077049884714973, 0.5822120509286517, -0.1779735844657705, 0.12863722897571492, 0.42346502209020714, 0.5317572267531613, 0.5250949414322668, 0.7222434557577614, 0.5711080879210234, 1.8087294351377763, 2.1641593211810846, 0.9167965594762817, 0.6145927746257767, -0.5070189070638104, -1.9633776595364965, 0.5182490463457843, 0.13020888464287564, -0.3850795292384054 ] @testset "No deterministic term" begin t = ADFTest(sim_data_h1, :none, 2) @test t.n == 98 @test t.deterministic == :none @test t.lag == 2 @test t.stat ≈ -4.856134193950414 @test t.coef ≈ -0.5258695197499671 @test t.cv ≈ [ -2.5882321870404863, -1.9439589708250309, -1.614431731329 ] @test pvalue(t) ≈ 2.011399607967822e-6 show(IOBuffer(), t) end @testset "Constant term" begin t = ADFTest(sim_data_h1, :constant, 0) @test t.n == 100 @test t.deterministic == :constant @test t.lag == 0 @test t.stat ≈ -5.371126891727986 @test t.coef ≈ -0.45433645147215723 @test t.cv ≈ [ -3.49681816639021, -2.8906107514600103, -2.5822770483285953 ] @test pvalue(t) ≈ 3.8937264616617045e-6 show(IOBuffer(), t) end @testset "Linear trend term" begin t = ADFTest(sim_data_h1, :trend, 7) @test t.n == 93 @test t.deterministic == :trend @test t.lag == 7 @test t.stat ≈ -2.636305455046 @test t.coef ≈ -0.4407260538688699 @test t.cv ≈ [ -4.051321648595895, -3.4548891419983088, -3.1530564880069027 ] @test pvalue(t) ≈ 0.2634673926249714 show(IOBuffer(), t) end @testset "Quadratic trend term" begin t = ADFTest(sim_data_h1, :squared_trend, 4) @test t.n == 96 @test t.deterministic == :squared_trend @test t.lag == 4 @test t.stat ≈ -4.300112549464304 @test t.coef ≈ -0.6759438045021552 @test t.cv ≈ [ -4.489700198611862, -3.8922014722784897, -3.5900742238045 ] @test pvalue(t) ≈ 0.012662962461719612 show(IOBuffer(), t) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
612
using HypothesisTests using Test using DelimitedFiles @testset "Bartlett's test" begin # Columns are type, length, left, right, bottom, top, diag swiss = readdlm(joinpath(@__DIR__, "data", "swiss3.txt")) genuine = convert(Matrix{Float64}, swiss[view(swiss, :, 1) .== "real", 2:end]) counterfeit = convert(Matrix{Float64}, swiss[view(swiss, :, 1) .== "fake", 2:end]) b = BartlettTest(genuine, counterfeit) @test nobs(b) == (100, 100) @test dof(b) == 21 @test pvalue(b) ≈ 0.0 atol=1e-10 @test b.L′ ≈ 121.8991235 atol=1e-6 @test occursin("reject h_0", sprint(show, b)) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
6979
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Binomial" begin t = BinomialTest(26, 78) @test pvalue(t) ≈ 0.004334880883507431 @test pvalue(t, tail=:left) ≈ 0.002167440441753716 @test pvalue(t, tail=:right) ≈ 0.9989844298129187 @test default_tail(t) == :both @test_ci_approx confint(t) (0.23058523962930383, 0.4491666887959782) @test_ci_approx confint(t, tail=:left) (0.0, 0.4313047758370174) @test_ci_approx confint(t, tail=:right) (0.2451709633730693, 1.0) @test_ci_approx confint(t, method=:wald) (0.22871819521037956, 0.43794847145628707) @test_ci_approx confint(t, tail=:left, method=:wald) (0.0, 0.42112912485444692) @test_ci_approx confint(t, tail=:right, method=:wald) (0.24553754181221971, 1.0) @test_ci_approx confint(t, method=:waldcc) (0.22230793880012298, 0.4443587278665436) @test_ci_approx confint(t, tail=:left, method=:waldcc) (0.0, 0.42753938126470326) @test_ci_approx confint(t, tail=:right, method=:waldcc) (0.23912728540196335, 1.0) @test_ci_approx confint(t, method=:wilson) (0.23872670036358601, 0.44358590287381217) @test_ci_approx confint(t, tail=:left, method=:wilson) (0.0, 0.42541288951088108) @test_ci_approx confint(t, tail=:right, method=:wilson) (0.25242832328277831, 1.0) @test_ci_approx confint(t, method=:jeffrey) (0.23626570247518358, 0.44251318323879296) @test_ci_approx confint(t, tail=:left, method=:jeffrey) (0.0, 0.42466492683653623) @test_ci_approx confint(t, tail=:right, method=:jeffrey) (0.25098836986261724, 1.0) @test_ci_approx confint(t, method=:agresti_coull) (0.2384423809121706, 0.44387022232522744) @test_ci_approx confint(t, tail=:left, method=:agresti_coull) (0.0, 0.42558712894362222) @test_ci_approx confint(t, tail=:right, method=:agresti_coull) (0.25225408385003706, 1.0) @test_ci_approx confint(t, method=:arcsine) (0.23366209634204066,0.44117918327686334) @test_ci_approx confint(t, tail=:left, method=:arcsine) (0.0,0.4235046425920888) @test_ci_approx confint(t, tail=:right, method=:arcsine) (0.2489264087216164,1.0) show(IOBuffer(), t) t = BinomialTest([trues(6); falses(3)]) @test pvalue(t) ≈ 0.5078125000000002 @test pvalue(t, tail=:left) ≈ 0.91015625 @test pvalue(t, tail=:right) ≈ 0.2539062500000001 @test_ci_approx confint(t) (0.2992950562085405, 0.9251453685803082) @test_ci_approx confint(t, tail=:left) (0.0, 0.9022531865607242) @test_ci_approx confint(t, tail=:right) (0.3449413659437032, 1.0) @test_ci_approx confint(t, method=:wald) (0.35868803903340479, 0.97464529429992841) @test_ci_approx confint(t, tail=:left, method=:wald) (0.0,0.92513047859481645) @test_ci_approx confint(t, tail=:right, method=:wald) (0.40820285473851681,1.0) @test_ci_approx confint(t, method=:waldcc) (0.3031324834778487, 1.0) @test_ci_approx confint(t, tail=:left, method=:waldcc) (0.0, 0.9806860341503718) @test_ci_approx confint(t, tail=:right, method=:waldcc) (0.35264729918296145, 1.0) @test_ci_approx confint(t, method=:wilson) (0.35420213558039609,0.87941618161308899) @test_ci_approx confint(t, tail=:left, method=:wilson) (0.0,0.85802909820500495) @test_ci_approx confint(t, tail=:right, method=:wilson) (0.39825972868840931,1.0) @test_ci_approx confint(t, method=:jeffrey) (0.34779179347226591,0.89578677833922582) @test_ci_approx confint(t, tail=:left, method=:jeffrey) (0.0,0.86830830610561005) @test_ci_approx confint(t, tail=:right, method=:jeffrey) (0.39604343455469687,1.0) @test_ci_approx confint(t, method=:agresti_coull) (0.350905767251112,0.88271254994237336) @test_ci_approx confint(t, tail=:left, method=:agresti_coull) (0.0,0.86049746046629294) @test_ci_approx confint(t, tail=:right, method=:agresti_coull) (0.39579136642712159,1.0) @test_ci_approx confint(t, method=:arcsine) (0.345812446615087,0.9188773496172281) @test_ci_approx confint(t, tail=:left, method=:arcsine) (0.0,0.8879439981269358) @test_ci_approx confint(t, tail=:right, method=:arcsine) (0.3965293068864491,1.0) show(IOBuffer(), t) t = BinomialTest(0, 100, 0.01) @test pvalue(t) ≈ 0.7320646825464591 show(IOBuffer(), t) t = BinomialTest(100, 100, 0.99) @test pvalue(t) ≈ 0.7320646825464584 show(IOBuffer(), t) # from issue #295 # without clamping: (-0.05457239484968546, 0.4890548596328611) @test_ci_approx confint(BinomialTest(0, 5), method=:agresti_coull) (0.0, 0.4890548596328611) # without clamping: (0.5109451403671388, 1.0545723948496855) @test_ci_approx confint(BinomialTest(5, 5), method=:agresti_coull) (0.5109451403671388, 1.0) # without clamping: (-0.15060901623063327, 0.5506090162306333) @test_ci_approx confint(BinomialTest(1, 5), method=:wald) (0.0, 0.5506090162306333) # without clamping: (0.44939098376936687, 1.1506090162306333) @test_ci_approx confint(BinomialTest(4, 5), method=:wald) (0.44939098376936687, 1.0) # without clamping: (-2.7755575615628914e-17, 0.2775327998628899) @test_ci_approx confint(BinomialTest(0, 10), method=:wilson) (0.0, 0.2775327998628899) # without clamping: (0.7575059933447587, 1.0000000000000002) @test_ci_approx confint(BinomialTest(12, 12), method=:wilson) (0.7575059933447587, 1.0) end @testset "SignTest" begin x = [55, 58, 61, 61, 62, 62, 62, 63, 63, 64, 66, 68, 68, 69, 69, 69, 70, 71, 72, 72] @test pvalue(SignTest(x)) ≈ 1.907348632812499e-6 @test pvalue(SignTest(x), tail=:left) ≈ 1.0 @test pvalue(SignTest(x), tail=:right) ≈ 9.536743164062495e-7 @test pvalue(SignTest(x, 70)) ≈ 0.004425048828125003 @test pvalue(SignTest(x, 70), tail=:left) ≈ 0.0022125244140625013 @test pvalue(SignTest(x, 70), tail=:right) ≈ 0.9996356964111328 @test default_tail(SignTest(x)) == :both @test_ci_approx confint(SignTest(x, 70)) (62, 69) @test_ci_approx confint(SignTest(x, 70), level=0.9998) (61, 71) show(IOBuffer(), SignTest(x, 70)) x = [9, 2, 7, 5] y = [7, 2, 6, 4] @test pvalue(SignTest(x, y)) ≈ 0.25 @test_ci_approx confint(SignTest(x, y)) (0, 2) show(IOBuffer(), SignTest(x, y)) # www.stat.umn.edu/geyer/old03/5102/notes/rank.pdf x = [-4.7, 3.7, 22.4, 13.6, 8.7, 9.1, -7.8, 10.8, 15.6, 23.5, 14.4, 20.2, 6.5, 10.1, -6.9] @test pvalue(SignTest(x)) ≈ 0.03515625 @test pvalue(SignTest(x), tail=:left) ≈ 0.996307373046875 @test pvalue(SignTest(x), tail=:right) ≈ 0.017578125000000007 @test_ci_approx confint(SignTest(x), level=0.99995) (-7.8, 23.5) @test_ci_approx confint(SignTest(x), level=0.9999) (-6.9, 22.4) @test_ci_approx confint(SignTest(x), level=0.993) (-4.7, 20.2) @test_ci_approx confint(SignTest(x), level=0.965) (3.7, 15.6) @test_ci_approx confint(SignTest(x), level=0.882) (6.5, 14.4) @test_ci_approx confint(SignTest(x), level=0.7) (8.7, 13.6) @test_ci_approx confint(SignTest(x), level=0.6) (9.1, 10.8) show(IOBuffer(), SignTest(x)) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
5014
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Box-Pierce and Ljung-Box" begin sim_data_h0=[ 0.297287984535462;0.382395967790608;-0.597634476728231;-0.0104452446373756; -0.839026854388764;0.311111338498334;2.29508782383731;-2.26708634880053; 0.529965576166746;0.431421526422912;0.583708287568779;0.963271605038191; 0.458790955053717;-0.522336757421508;0.408395838324752;-0.0504512299336653; -0.693653643803886;-1.77383325340806;0.120765964937439;-0.757633037720528; -1.72975618139069;0.795948622004616;0.670061981256062;0.550852377500761; -0.0633745924295606;1.33694278225092;-0.0731486333377393;-0.745464316640756; -1.22005512853465;-0.0531773375276925;-0.165136357802834;-2.11537024842731; -0.0667679865065892;1.22246184846806;0.567695459738444;0.763498928323387; 0.378598879853350;-0.645597056636597;-0.664646244391031;-1.80302632421089; -1.28904760384974;-0.335270079518118;0.0704676013611580;0.341793767379823; 1.73516566605438;1.29991596431019;0.206364081402617;-1.00885995553760; -0.850055670315398;1.12940943588433;-1.34853345649183;1.24029090042906; -0.0556470932073243;0.759390213945460;-0.0302668866467625;-0.361082667756094; -2.00730320253256;-0.568859127346638;-1.14962752439700;1.88062217463119; -1.47062454138738;-0.535210970165732;-0.963543959825501;-1.38510806767591; 0.134300237561270;-0.616116666008819;-1.71998935631974;0.320769279987411; -1.44737289788151;-0.492271188069566;-0.413087383983183;1.00192851245595; 1.17468132597511;-1.32697034506205;-1.59321486804407;-0.438709975758797; 1.22579749799787;1.48909027806961;2.15943318710085;-0.909479018037503; 1.14782030061250;-0.505072196522373;-0.267067035218130;1.49908239393073; 0.797304160175390;-0.171640443307097;-0.469079609930096;0.217624021208600; 0.359146407602350;0.320024715708058;0.259216328055686;0.459695985041628; 0.209986360042143;1.52317539117726;1.25979460361220;-0.165283101114261; 0.156194494887636;-0.814315294376699 ] @testset "Box-Pierce" begin t = HypothesisTests.BoxPierceTest(sim_data_h0,2,1) @test t.n == 98 @test t.lag == 2 @test t.dof == 1 @test t.Q ≈ 1.233942980734545 @test pvalue(t) ≈ 0.2666415904008932 @test default_tail(t) == :right show(IOBuffer(), t) end @testset "Ljung-Box" begin t = HypothesisTests.LjungBoxTest(sim_data_h0,5,2) @test t.n == 98 @test t.lag == 5 @test t.dof == 2 @test t.Q ≈ 3.2090126519163626 @test pvalue(t) ≈ 0.36050846449240337 @test default_tail(t) == :right show(IOBuffer(), t) end sim_data_h1 = [ 0.297287984535462;0.739141549233162;0.200148986990924;0.00799107498178517; -0.889482260507899;-0.758664696605681;1.65153486606286;-0.0576451005433905; -0.0346690043041814;0.407112251420912;1.08264369056513;2.14031035829007; 2.70237027783226;2.07841446849019;2.09178211716330;1.83616297011523; 0.882207285185406;-1.26603340222014;-1.66313630328235;-2.37358658099330; -4.07911918759795;-3.38691842881493;-2.17050437704247;-1.03767734630572; -0.657436094883687;0.859322672282215;1.15526940186602;0.383062163913809; -1.10696135239789;-1.49644960957930;-1.62878748357863;-3.62098034584788; -3.92330815645045;-2.39921383551812;-1.13436869594816;0.122020643841029; 0.865334261247033;0.356197863707534;-0.496809086316101;-2.50605658690248; -4.14727278223788;-4.56018044213284;-4.15756709452688;-3.27923261341258; -0.952643341682653;1.14051373831478;1.86077356988515;0.881914206830145; -0.349990693084770;0.444846342133559;-0.709720638006125;0.255172232181642; 0.463475776812484;1.23900947646595;1.31750175206863;0.848216591786478; -1.38469381800938;-2.48495668649384;-3.71616740278679;-1.83329170276481; -2.55572436386911;-3.05209269597923;-3.85933788583984;-5.10068572188995; -4.82872126295472;-4.88037646498750;-6.12782473541832;-5.56850746301833; -6.29123443287801;-6.37120026861768;-6.17115737646099;-4.49210025871193; -2.36449177154091;-2.81673039329756;-4.26394380853887;-4.71042342801617; -3.14752747305988;-0.874815661197385;2.05391263558195;1.81766084302006; 2.71283952156198;2.20503697644599;1.56512548004846;2.71572187705509; 3.58663276862696;3.31760231592873;2.43605333859629;2.14560733274553; 2.20305920531810;2.32001356226611;2.38231484117959;2.62246972577731; 2.64225557862103;3.90714116778931;5.15568733137306;4.84939934619662; 4.42876751091166;3.04538591485831 ] @testset "Box-Pierce" begin t = HypothesisTests.BoxPierceTest(sim_data_h1,3) @test t.n == 98 @test t.lag == 3 @test t.dof == 0 @test t.Q ≈ 176.16899390632153 @test pvalue(t) ≈ 5.925682677971866e-38 show(IOBuffer(), t) end @testset "Ljung-Box" begin t = HypothesisTests.LjungBoxTest(sim_data_h1,12) @test t.n == 98 @test t.lag == 12 @test t.dof == 0 @test t.Q ≈ 271.8894095341075 @test pvalue(t) ≈ 3.6622231247462687e-51 show(IOBuffer(), t) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
18337
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Breusch-Godfrey" begin # data simulated under H_1 data_h1 = [ -2.1844072302156263 1 -0.02187576598418861 1.4250842322231618 -2.0224314101114222 -3.8237365225754556 1 -2.1844072302156263 -0.3986195023723653 -0.725318617093708 -4.692622964314854 1 -3.8237365225754556 0.865359034508392 -0.9716762048860438 -9.465165251695765 1 -4.692622964314854 -1.5248868209889381 -1.8178664695259354 -3.784086411104036 1 -9.465165251695765 -0.018434833227298542 0.8719091772543835 -7.682951955540945 1 -3.784086411104036 -0.6298048032223702 -1.6804917747830277 -8.068822143998775 1 -7.682951955540945 0.3994394061296323 -0.5382489016869288 -8.558608055778492 1 -8.068822143998775 -0.34662848289604303 -1.0915556882219897 -10.905266364277344 1 -8.558608055778492 0.13174261149628444 -2.373156801968529 -3.7593874757578343 1 -10.905266364277344 1.2873446803519781 1.3193356146665325 -0.4071004208759922 1 -3.7593874757578343 0.6312912597626849 0.2928588585051935 -0.21264428099357685 1 -0.4071004208759922 -1.2337261440146907 0.6677002797481758 -0.2566792446386543 1 -0.21264428099357685 -0.8585845030636355 0.21112095190111557 1.4652422469376796 1 -0.2566792446386543 0.2582660780400912 0.3254542082853489 -0.03370549493934421 1 1.4652422469376796 -1.4599892950591262 0.3142665708225735 -3.6655187094551787 1 -0.03370549493934421 0.5095274347206296 -1.2436129408018743 -3.67007844594898 1 -3.6655187094551787 -1.2459007156231243 0.8724432818783148 -4.269483828240617 1 -3.67007844594898 -1.3316534960103243 0.402333915295087 -9.072321453339633 1 -4.269483828240617 -1.360732996599522 -0.918403552104298 -6.298475056265913 1 -9.072321453339633 0.5429237557639659 0.564993224895932 -8.851275959789886 1 -6.298475056265913 -2.63399370777994 -0.8745409882369648 -7.240409805869097 1 -8.851275959789886 0.1499014406502077 -0.487019467609227 -8.742193488440103 1 -7.240409805869097 -1.6587759684101517 -0.5287577864433531 -8.085128207595446 1 -8.742193488440103 -2.748600587280482 0.6442930345934977 -4.595734505262792 1 -8.085128207595446 -0.4180662233306449 0.909924517665989 -8.876081007098774 1 -4.595734505262792 -1.4313262030289144 -1.3628300743751958 -6.097510119608872 1 -8.876081007098774 1.1540597669111703 0.8739856083349014 -8.187395934761742 1 -6.097510119608872 -0.4855284875097715 -0.8548933573000406 -4.630296021087888 1 -8.187395934761742 0.7754380459705584 0.7550975795526141 -6.678197570842665 1 -4.630296021087888 0.7560596380052317 -0.8436185092902743 -8.454654098952108 1 -6.678197570842665 -1.626729284162485 0.27766300810348893 -8.87315711823648 1 -8.454654098952108 -0.944684415100926 -0.9030356944859604 -8.299137304666294 1 -8.87315711823648 0.658322671059814 -1.513350928595663 -7.66583122908761 1 -8.299137304666294 -0.4489512342884181 -0.6593759619410697 -5.544754187110598 1 -7.66583122908761 1.1851174294240252 -0.7403475629601508 -0.2346062802414116 1 -5.544754187110598 1.9716204287413468 1.1351529072038815 -2.7080211703552033 1 -0.2346062802414116 -0.0740194597978335 -0.8957439911719416 -4.405304542289478 1 -2.7080211703552033 -0.20212227601885754 0.02136996876872505 -10.874421844205603 1 -4.405304542289478 -1.458002434697322 -1.5544394018554584 -7.980300798148038 1 -10.874421844205603 1.797342002330958 0.193735930526397 -6.092985977023801 1 -7.980300798148038 -0.9064866353733989 0.9206450790295183 -5.429540806278794 1 -6.092985977023801 -0.9702203522809195 0.16364495372354845 -2.8135611982312048 1 -5.429540806278794 -0.7689287953327062 0.2606593892993496 -5.233993628762067 1 -2.8135611982312048 -0.3959933139142994 -2.620564252102542 -4.636500469478656 1 -5.233993628762067 0.4751826349484905 -1.0562153109753674 -3.951599322839157 1 -4.636500469478656 0.6386323305899096 -0.0903512992302431 -4.5338888862750215 1 -3.951599322839157 -0.3987477530370317 0.27865272355818926 -3.27448245549044 1 -4.5338888862750215 -0.0803466446475703 -0.06596847546469198 -2.116669048507199 1 -3.27448245549044 1.0018399414103412 -0.1569479584427068 -5.632636058340474 1 -2.116669048507199 -0.7048446599977012 -1.8390689017857673 -6.612580447433536 1 -5.632636058340474 -1.4340505462257125 -0.5674519382746356 -6.047621290327909 1 -6.612580447433536 0.4347509475695458 -0.9192186367107573 -12.316195547709809 1 -6.047621290327909 -0.09220577556331351 -3.8819978594268876 -9.790653346165218 1 -12.316195547709809 -0.46408289171823325 0.8665458026221579 -7.081636830140645 1 -9.790653346165218 2.187832361106393 0.432306709021104 -7.798466676804453 1 -7.081636830140645 0.5791414166174949 -0.3229959302497174 -8.48368570601047 1 -7.798466676804453 -0.9147242711971281 0.3402161710448687 -6.844741808358232 1 -8.48368570601047 -0.1550598509968508 -0.29961787965293785 -1.9143881179353244 1 -6.844741808358232 0.060717820312243403 1.9136035721789713 -6.350825197915615 1 -1.9143881179353244 -0.27085887966353506 -1.6190985435203415 -5.386740290175477 1 -6.350825197915615 0.11104289827811374 0.5169712744781768 -8.201462522665064 1 -5.386740290175477 0.6427956685597893 -1.2825811121125588 -6.86037895816535 1 -8.201462522665064 -1.0932960849422242 1.0840840119878734 -7.681177025769711 1 -6.86037895816535 0.0867583435648074 -0.7944197379913668 -8.700601165824938 1 -7.681177025769711 -0.07077890859801883 -0.025668064894330093 -6.737037436370262 1 -8.700601165824938 1.2497099131508578 -0.011462506736218826 -3.6689503491552253 1 -6.737037436370262 0.1512033860208509 1.4678868411216563 -1.249607364746875 1 -3.6689503491552253 0.35515785025036173 1.315845372889509 -1.9479972265280567 1 -1.249607364746875 -0.9253434974479612 0.27236940715678176 0.06459657520168782 1 -1.9479972265280567 -0.233103327838231 0.44237536440754566 1.6736047640968876 1 0.06459657520168782 1.3606109850208474 -1.1966483101519632 3.3481475962652025 1 1.6736047640968876 0.7311973736313007 0.48457993854995624 4.395242135786573 1 3.3481475962652025 0.4787377009574211 1.4147590837932418 5.718254592907931 1 4.395242135786573 0.6051343777576946 1.0451679003902126 7.701764680294246 1 5.718254592907931 1.276972611856289 -0.1978660512585745 8.761139787455583 1 7.701764680294246 -1.3961992590989196 0.32892107972067225 8.130728492876539 1 8.761139787455583 0.11709983671299977 -1.7983067508193347 12.0528015874146 1 8.130728492876539 0.6266845348314155 1.44050014454746 11.188183563801353 1 12.0528015874146 0.3133823643278484 -0.5232908450257276 12.92107497611711 1 11.188183563801353 0.9862522782876494 0.43490251042216804 12.271768495692909 1 12.92107497611711 0.5066085599761962 0.07774415899993356 14.189399733550822 1 12.271768495692909 0.8718155606585614 0.14324697267944667 15.088143644678663 1 14.189399733550822 0.6995645399732705 -0.43422769970595093 17.365142073656695 1 15.088143644678663 2.0096551932105817 0.24387704638876334 15.474852839205559 1 17.365142073656695 0.15269868152330113 -0.12389276233418343 14.228935730675236 1 15.474852839205559 -0.7879019375423509 0.42889110309176043 17.394434630323023 1 14.228935730675236 0.9986772266084378 1.189248289168407 16.54384322429009 1 17.394434630323023 -0.4953901743665539 0.2059465326047665 18.353069936157006 1 16.54384322429009 0.3638388194911837 1.0218854109275881 16.07119383937772 1 18.353069936157006 0.6753443406355725 -1.1990648633034413 20.977942062323052 1 16.07119383937772 0.6008899714463747 2.3805130457880845 23.626966845968067 1 20.977942062323052 -1.5021368491168559 2.1896086828053907 27.902989083231745 1 23.626966845968067 -0.3727356407152467 2.1299921566412503 24.021974044852822 1 27.902989083231745 -1.2766407160812419 -0.3876601960862665 22.470178938207653 1 24.021974044852822 0.6451054034379425 -0.23211025519653547 22.71778230013325 1 22.470178938207653 1.9058844942684128 0.20626950528981075 18.975581322758284 1 22.71778230013325 -1.5881288112102452 1.107610369079468 19.971416875068105 1 18.975581322758284 0.29738396177383514 0.8667513992731141 23.11402529567158 1 19.971416875068105 0.3028824231221631 1.6776251628069427 17.780386660161668 1 23.11402529567158 -0.10176910274960058 -1.4298441320561919 ] coeff_vec = data_h1[:,2:end]\data_h1[:,1] res_vec = data_h1[:,1] - data_h1[:,2:end]*coeff_vec t = BreuschGodfreyTest(data_h1[:,2:end],res_vec,4) @test t.n == 100 @test t.lag == 4 @test t.BG ≈ 31.39810637185552 @test pvalue(t) ≈ 2.5390992557054064e-6 @test default_tail(t) == :right show(IOBuffer(), t) t = BreuschGodfreyTest(data_h1[:,2:end],res_vec,2,false) @test t.n == 98 @test t.lag == 2 @test t.BG ≈ 27.71445552148237 @test pvalue(t) ≈ 9.591409846298036e-7 show(IOBuffer(), t) coeff_vec = data_h1[:,3:end]\data_h1[:,1] # no constant res_vec = data_h1[:,1] - data_h1[:,3:end]*coeff_vec t = BreuschGodfreyTest(data_h1[:,3:end],res_vec,10) @test t.n == 100 @test t.lag == 10 @test t.BG ≈ 34.562955523063515 @test pvalue(t) ≈ 0.0001482189344859451 show(IOBuffer(), t) # data simulated under H_0 data_h0 = [ -2.6393758379263925 1 -0.22997735515901174 1.4250842322231618 -2.0224314101114222 -3.8148641358053834 1 -2.6393758379263925 -0.3986195023723653 -0.725318617093708 -4.677326144975626 1 -3.8148641358053834 0.865359034508392 -0.9716762048860438 -8.864079316218326 1 -4.677326144975626 -1.5248868209889381 -1.8178664695259354 -3.460887006123175 1 -8.864079316218326 -0.018434833227298542 0.8719091772543835 -8.998633967744288 1 -3.460887006123175 -0.6298048032223702 -1.6804917747830277 -7.665975510821412 1 -8.998633967744288 0.3994394061296323 -0.5382489016869288 -8.56702198923559 1 -7.665975510821412 -0.34662848289604303 -1.0915556882219897 -11.214833972884769 1 -8.56702198923559 0.13174261149628444 -2.373156801968529 -4.446594124802662 1 -11.214833972884769 1.2873446803519781 1.3193356146665325 -1.6998765285430706 1 -4.446594124802662 0.6312912597626849 0.2928588585051935 -1.6972964464315492 1 -1.6998765285430706 -1.2337261440146907 0.6677002797481758 -1.2272304633377735 1 -1.6972964464315492 -0.8585845030636355 0.21112095190111557 0.30586906328114577 1 -1.2272304633377735 0.2582660780400912 0.3254542082853489 -1.041825499276659 1 0.30586906328114577 -1.4599892950591262 0.3142665708225735 -4.0872691626960425 1 -1.041825499276659 0.5095274347206296 -1.2436129408018743 -2.8079705764801184 1 -4.0872691626960425 -1.2459007156231243 0.8724432818783148 -3.5781229211748493 1 -2.8079705764801184 -1.3316534960103243 0.402333915295087 -7.919753510576073 1 -3.5781229211748493 -1.360732996599522 -0.918403552104298 -4.050334580805227 1 -7.919753510576073 0.5429237557639659 0.564993224895932 -7.385113567278499 1 -4.050334580805227 -2.63399370777994 -0.8745409882369648 -6.389907039488093 1 -7.385113567278499 0.1499014406502077 -0.487019467609227 -8.362337662947732 1 -6.389907039488093 -1.6587759684101517 -0.5287577864433531 -7.698895749951619 1 -8.362337662947732 -2.748600587280482 0.6442930345934977 -5.183985240958993 1 -7.698895749951619 -0.4180662233306449 0.909924517665989 -9.354302625888938 1 -5.183985240958993 -1.4313262030289144 -1.3628300743751958 -6.0060845548714905 1 -9.354302625888938 1.1540597669111703 0.8739856083349014 -7.251074336523842 1 -6.0060845548714905 -0.4855284875097715 -0.8548933573000406 -3.750382446404393 1 -7.251074336523842 0.7754380459705584 0.7550975795526141 -5.770679903165536 1 -3.750382446404393 0.7560596380052317 -0.8436185092902743 -6.1571290241435745 1 -5.770679903165536 -1.626729284162485 0.27766300810348893 -6.758646960354187 1 -6.1571290241435745 -0.944684415100926 -0.9030356944859604 -7.251801456499875 1 -6.758646960354187 0.658322671059814 -1.513350928595663 -7.120615787554741 1 -7.251801456499875 -0.4489512342884181 -0.6593759619410697 -5.588509539557388 1 -7.120615787554741 1.1851174294240252 -0.7403475629601508 -0.5390053133408673 1 -5.588509539557388 1.9716204287413468 1.1351529072038815 -2.5300623604990955 1 -0.5390053133408673 -0.0740194597978335 -0.8957439911719416 -3.7798892423452592 1 -2.5300623604990955 -0.20212227601885754 0.02136996876872505 -9.04942964730818 1 -3.7798892423452592 -1.458002434697322 -1.5544394018554584 -5.4354744982455365 1 -9.04942964730818 1.797342002330958 0.193735930526397 -3.5679532514488668 1 -5.4354744982455365 -0.9064866353733989 0.9206450790295183 -3.2063386742141633 1 -3.5679532514488668 -0.9702203522809195 0.16364495372354845 -1.051934916538913 1 -3.2063386742141633 -0.7689287953327062 0.2606593892993496 -4.863145941477073 1 -1.051934916538913 -0.3959933139142994 -2.620564252102542 -5.212678725939295 1 -4.863145941477073 0.4751826349484905 -1.0562153109753674 -4.614614610635563 1 -5.212678725939295 0.6386323305899096 -0.0903512992302431 -4.424400676415464 1 -4.614614610635563 -0.3987477530370317 0.27865272355818926 -2.5809040973960595 1 -4.424400676415464 -0.0803466446475703 -0.06596847546469198 -2.283035131341285 1 -2.5809040973960595 1.0018399414103412 -0.1569479584427068 -4.838392113346874 1 -2.283035131341285 -0.7048446599977012 -1.8390689017857673 -6.765964527239637 1 -4.838392113346874 -1.4340505462257125 -0.5674519382746356 -6.146713996908273 1 -6.765964527239637 0.4347509475695458 -0.9192186367107573 -12.93695213339396 1 -6.146713996908273 -0.09220577556331351 -3.8819978594268876 -10.328147452628222 1 -12.93695213339396 -0.46408289171823325 0.8665458026221579 -7.312623658528083 1 -10.328147452628222 2.187832361106393 0.432306709021104 -6.601242580580354 1 -7.312623658528083 0.5791414166174949 -0.3229959302497174 -7.007982630266133 1 -6.601242580580354 -0.9147242711971281 0.3402161710448687 -4.711869773110432 1 -7.007982630266133 -0.1550598509968508 -0.29961787965293785 -1.3112388084541342 1 -4.711869773110432 0.060717820312243403 1.9136035721789713 -4.778553640411378 1 -1.3112388084541342 -0.27085887966353506 -1.6190985435203415 -3.597048209305651 1 -4.778553640411378 0.11104289827811374 0.5169712744781768 -5.91625887800437 1 -3.597048209305651 0.6427956685597893 -1.2825811121125588 -3.8341200305975844 1 -5.91625887800437 -1.0932960849422242 1.0840840119878734 -5.05155415725161 1 -3.8341200305975844 0.0867583435648074 -0.7944197379913668 -5.902658917952474 1 -5.05155415725161 -0.07077890859801883 -0.025668064894330093 -3.0148968638612246 1 -5.902658917952474 1.2497099131508578 -0.011462506736218826 -0.5435623298882797 1 -3.0148968638612246 0.1512033860208509 1.4678868411216563 2.576402881110434 1 -0.5435623298882797 0.35515785025036173 1.315845372889509 1.840001826392218 1 2.576402881110434 -0.9253434974479612 0.27236940715678176 3.7629568916181633 1 1.840001826392218 -0.233103327838231 0.44237536440754566 4.300779090152549 1 3.7629568916181633 1.3606109850208474 -1.1966483101519632 4.890327561532721 1 4.300779090152549 0.7311973736313007 0.48457993854995624 6.712083346070772 1 4.890327561532721 0.4787377009574211 1.4147590837932418 8.918662089794555 1 6.712083346070772 0.6051343777576946 1.0451679003902126 10.889228410523366 1 8.918662089794555 1.276972611856289 -0.1978660512585745 10.771798896063286 1 10.889228410523366 -1.3961992590989196 0.32892107972067225 8.897958495974741 1 10.771798896063286 0.11709983671299977 -1.7983067508193347 11.231705359232382 1 8.897958495974741 0.6266845348314155 1.44050014454746 11.085832271063609 1 11.231705359232382 0.3133823643278484 -0.5232908450257276 12.02548460222439 1 11.085832271063609 0.9862522782876494 0.43490251042216804 11.819287696755126 1 12.02548460222439 0.5066085599761962 0.07774415899993356 13.96911393915951 1 11.819287696755126 0.8718155606585614 0.14324697267944667 13.840528753974972 1 13.96911393915951 0.6995645399732705 -0.43422769970595093 15.684175759900603 1 13.840528753974972 2.0096551932105817 0.24387704638876334 14.08213146714004 1 15.684175759900603 0.15269868152330113 -0.12389276233418343 13.303842222767337 1 14.08213146714004 -0.7879019375423509 0.42889110309176043 16.40951365835989 1 13.303842222767337 0.9986772266084378 1.189248289168407 15.406011864201629 1 16.40951365835989 -0.4953901743665539 0.2059465326047665 17.105004411081747 1 15.406011864201629 0.3638388194911837 1.0218854109275881 14.766483437171006 1 17.105004411081747 0.6753443406355725 -1.1990648633034413 19.48191551080787 1 14.766483437171006 0.6008899714463747 2.3805130457880845 22.133552497574904 1 19.48191551080787 -1.5021368491168559 2.1896086828053907 25.492693395853813 1 22.133552497574904 -0.3727356407152467 2.1299921566412503 20.970851703684147 1 25.492693395853813 -1.2766407160812419 -0.3876601960862665 19.83986700193583 1 20.970851703684147 0.6451054034379425 -0.23211025519653547 20.241165411067264 1 19.83986700193583 1.9058844942684128 0.20626950528981075 17.31664682866259 1 20.241165411067264 -1.5881288112102452 1.107610369079468 19.675283574585194 1 17.31664682866259 0.29738396177383514 0.8667513992731141 21.79754881195714 1 19.675283574585194 0.3028824231221631 1.6776251628069427 16.68579877178968 1 21.79754881195714 -0.10176910274960058 -1.4298441320561919 ] coeff_vec = data_h0[:,2:end]\data_h0[:,1] res_vec = data_h0[:,1] - data_h0[:,2:end]*coeff_vec t = BreuschGodfreyTest(data_h0[:,2:end],res_vec,4) @test t.n == 100 @test t.lag == 4 @test t.BG ≈ 1.9781996740849623 @test pvalue(t) ≈ 0.7397687483602012 show(IOBuffer(), t) t = BreuschGodfreyTest(data_h0[:,2:end],res_vec,2,false) @test t.n == 98 @test t.lag == 2 @test t.BG ≈ 0.03720525092311448 @test pvalue(t) ≈ 0.9815693354165801 show(IOBuffer(), t) coeff_vec = data_h0[:,3:end]\data_h0[:,1] # no constant res_vec = data_h0[:,1] - data_h0[:,3:end]*coeff_vec t = BreuschGodfreyTest(data_h0[:,3:end],res_vec,10) @test t.n == 100 @test t.lag == 10 @test t.BG ≈ 11.156984521656943 @test pvalue(t) ≈ 0.3454190353708124 show(IOBuffer(), t) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1478
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Circular" begin @testset "Fisher, 1995 example 4.11" begin @test abs(pvalue(RayleighTest(0.2370, 60)) - 0.034) <= 0.001 end @testset "Fisher, 1995 example 4.12" begin t = RayleighTest( [2, 9, 18, 24, 30, 35, 35, 39, 39, 44, 44, 49, 56, 70, 76, 76, 81, 86, 91, 112, 121, 127, 133, 134, 138, 147, 152, 157, 166, 171, 177, 187, 206, 210, 211, 215, 238, 246, 269, 270, 285, 292, 305, 315, 325, 328, 329, 343, 354, 359] *pi/180) @test abs(pvalue(t) - 0.20) <= 0.01 @test default_tail(t) == :both show(IOBuffer(), t) end wind_direction_6am = [356, 97, 211, 232, 343, 292, 157, 302, 335, 302, 324, 85, 324, 340, 157, 238, 254, 146, 232, 122, 329]*pi/180 wind_direction_12pm = [119, 162, 221, 259, 270, 29, 97, 292, 40, 313, 94, 45, 47, 108, 221, 270, 119, 248, 270, 45, 23]*pi/180 @testset "Fisher, 1995 example 6.8" begin t = FisherTLinearAssociation(wind_direction_6am, wind_direction_12pm) @test abs(t.rho_t- 0.191) < 0.001 @test abs(pvalue(t) - 0.01) < 0.01 @test default_tail(t) == :both show(IOBuffer(), t) end @testset "Jammaladak, 2001 example 8.1" begin t = JammalamadakaCircularCorrelation(wind_direction_6am, wind_direction_12pm) @test abs(t.r - 0.2704648) < 1e-7 @test abs(pvalue(t) - 0.2247383) < 1e-7 @test default_tail(t) == :both show(IOBuffer(), t) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
985
using HypothesisTests, Test @testset "Clark-West tests" begin e1 = [ 9.78432, 12.73500, 8.67224, 2.62740, 5.60947, 7.57809, 4.53774, 2.51084, 0.49290, 3.48394, 9.46152, 9.41220, 2.36289, 0.34495, 3.33599, 5.31357, 4.28219, -3.74471, -5.73575, -3.71781 ] e2 = [ 2.82053, 4.39754, -1.78647, -4.30662, 3.69526, 3.37259, -1.09002, -0.50984, -0.78973, 3.89077, 7.52849, 2.82373, -3.95838, -0.13606, 4.54444, 4.18216, 1.67993, -5.38077, -0.85686, 2.70479 ] atol = 1e-4 cw_test = ClarkWestTest(e1, e2) @test pvalue(cw_test) ≈ 0.0002 atol=atol @test pvalue(cw_test, tail=:right) ≈ 0.0001 atol=atol cw_test = ClarkWestTest(e1, e2, 3) @test pvalue(cw_test) ≈ 0.0157 atol=atol @test pvalue(cw_test, tail=:right) ≈ 0.0079 atol=atol show(IOBuffer(), cw_test) @test_throws DimensionMismatch ClarkWestTest(rand(3), rand(4)) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
385
using HypothesisTests, Test mutable struct TestTest <: HypothesisTests.HypothesisTest end @testset "Common" begin @test_throws DimensionMismatch HypothesisTests.check_same_length([1], []) @test_throws ArgumentError HypothesisTests.check_level(1.0) result = HypothesisTests.population_param_of_interest(TestTest()) @test result[1] == "not implemented yet" @test isnan(result[2]) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1727
using HypothesisTests using Test using DelimitedFiles @testset "Correlation" begin # Columns are line number, calcium, iron nutrient = readdlm(joinpath(@__DIR__, "data", "nutrient.txt"))[:, 1:3] w = CorrelationTest(nutrient[:,2], nutrient[:,3]) let out = sprint(show, w) @test occursin("reject h_0", out) && !occursin("fail to", out) end let ci = confint(w) @test first(ci) ≈ 0.3327138 atol=1e-6 @test last(ci) ≈ 0.4546639 atol=1e-6 end @test nobs(w) == 737 @test dof(w) == 735 @test pvalue(w) < 1e-25 x = CorrelationTest(nutrient[:,1], nutrient[:,2]) @test occursin("fail to reject", sprint(show, x)) let ci = confint(x) @test first(ci) ≈ -0.1105478 atol=1e-6 @test last(ci) ≈ 0.0336730 atol=1e-6 end @test pvalue(x) ≈ 0.2948405 atol=1e-6 end @testset "Partial correlation" begin # Columns are information, similarities, arithmetic, picture completion wechsler = readdlm(joinpath(@__DIR__, "data", "wechsler.txt"))[:,2:end] w = CorrelationTest(wechsler[:,1], wechsler[:,2], wechsler[:,3:4]) let out = sprint(show, w) @test occursin("reject h_0", out) && !occursin("fail to", out) end let ci = confint(w) @test first(ci) ≈ 0.4963917 atol=1e-6 @test last(ci) ≈ 0.8447292 atol=1e-6 end @test nobs(w) == 37 @test dof(w) == 33 @test pvalue(w) < 0.00001 X = [ 2 1 0 4 2 0 15 3 1 20 4 1] x = CorrelationTest(view(X,:,1), view(X,:,2), view(X,:,3)) @test occursin("fail to reject", sprint(show, x)) @test confint(x) == (-1.0, 1.0) @test nobs(x) == 4 @test dof(x) == 1 @test pvalue(x) ≈ 0.25776212 atol=1e-6 end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1495
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Diebold-Mariano tests" begin e_ets = [0.002241270, -0.000661906, -1.200002613, -4.000218178, 3.799373533, 3.401005111, -1.199692125, -0.800490048, -1.200048999, 3.399847229, 7.000708948, 2.200989241, -4.800165569, -1.201043375, 3.400167556, 3.000709085, 0.400267950, -6.800169207, -2.401259050, 1.200112198] e_arima = [0.1209998, 8.0622269, -0.9189429, -1.7952436, 5.3431277, 2.0459823, -0.6073261, 0.5516816, -0.7633238, 4.1229472, 5.8785333, 1.2828331, -3.4854233, 1.1971370, 3.1709314, 2.3408457, 0.4962286, -5.9841362, 0.1537114, 0.4207951] atol = 1e-3 dm_test = DieboldMarianoTest(e_ets, e_arima) @test pvalue(dm_test) ≈ 0.8871 atol=atol @test pvalue(dm_test, tail=:right) ≈ 0.5565 atol=atol @test pvalue(dm_test, tail=:left) ≈ 0.4435 atol=atol dm_test = DieboldMarianoTest(e_ets, e_arima; lookahead=10) @test pvalue(dm_test) ≈ 0.9362 atol=atol @test pvalue(dm_test, tail=:right) ≈ 0.5319 atol=atol @test pvalue(dm_test, tail=:left) ≈ 0.4681 atol=atol dm_test = DieboldMarianoTest(e_ets, e_arima; loss=abs) @test pvalue(dm_test) ≈ 0.7818 atol=atol @test pvalue(dm_test, tail=:right) ≈ 0.3909 atol=atol @test pvalue(dm_test, tail=:left) ≈ 0.6091 atol=atol show(IOBuffer(), dm_test) @test_throws DimensionMismatch DieboldMarianoTest(rand(3), rand(4)) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
11557
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Durbin-Watson" begin x_sim = [ 0.2972879845354616, 0.3823959677906078, -0.5976344767282311, -0.01044524463737564, -0.839026854388764, 0.31111133849833383, 2.2950878238373105, -2.2670863488005306, 0.5299655761667461, 0.43142152642291204, 0.5837082875687786, 0.9632716050381906, 0.45879095505371686, -0.5223367574215084, 0.40839583832475224, -0.050451229933665284, -0.6936536438038856, -1.7738332534080556, 0.12076596493743928, -0.7576330377205277, -1.7297561813906863, 0.7959486220046159, 0.6700619812560624, 0.5508523775007609, -0.06337459242956062, 1.3369427822509223, -0.07314863333773934, -0.7454643166407556, -1.2200551285346526, -0.05317733752769253, -0.1651363578028337, -2.115370248427311, -0.0667679865065892, 1.2224618484680618, 0.5676954597384435, 0.7634989283233873, 0.37859887985335006, -0.645597056636597, -0.6646462443910314, -1.8030263242108941, -1.2890476038497443, -0.3352700795181175, 0.07046760136115796, 0.34179376737982303, 1.7351656660543822, 1.299915964310192, 0.20636408140261675, -1.0088599555376034, -0.8500556703153979, 1.1294094358843267, -1.348533456491827, 1.2402909004290597, -0.055647093207324264, 0.7593902139454598, -0.030266886646762546, -0.36108266775609366, -2.0073032025325626, -0.5688591273466379, -1.1496275243969976, 1.880622174631185, -1.4706245413873802, -0.5352109701657319, -0.9635439598255011, -1.3851080676759138, 0.13430023756127, -0.6161166660088192, -1.719989356319742, 0.32076927998741056, -1.4473728978815112, -0.4922711880695664, -0.4130873839831828, 1.001928512455953, 1.174681325975111, -1.326970345062047, -1.593214868044067, -0.43870997575879667, 1.225797497997867, 1.4890902780696147, 2.1594331871008534, -0.9094790180375028, 1.1478203006125018, -0.5050721965223731, -0.2670670352181297, 1.499082393930729, 0.7973041601753904, -0.17164044330709693, -0.46907960993009634, 0.21762402120860017, 0.35914640760234967, 0.3200247157080577, 0.2592163280556861, 0.459695985041628, 0.20998636004214272, 1.5231753911772645, 1.2597946036121963, -0.16528310111426064, 0.15619449488763584, -0.8143152943766987, -1.7098682060045913, 1.4999378761140325, -0.1289156385300165 ] y_p1_sim = [ # simulated with 0.9 error correlation -2.201341073669063, -4.307803337512109, -0.09857411277132777, -1.541105730821739, -0.027145670802778188, -2.686792369309708, 1.0325029592455204, -4.546430983473314, -0.05574145987936152, -1.0484672373273398, -0.0727407422074402, 2.928588488596894, 2.431548457465139, -1.6824694270670264, -1.1425390408702634, -0.05703441237172502, -3.7519965683524736, -2.093296650507312, -3.017127214946707, -5.023733247576096, -6.99222421705045, -1.5297654016216695, -7.079699435755043, -3.653535679506873, -7.199787077141922, -8.99013125698203, -7.629907186756253, -9.932939819777665, -5.792469964809508, -6.07806145541466, -3.499680333201193, -4.202234791648873, -5.778858317935674, -4.24373192427373, -2.085017620018707, -3.014335715988717, -0.1471613303199173, 1.8578539252085335, -0.23403766619329314, -1.6531056420525947, -3.788213810884947, 2.4223665300397057, -0.7782405228814611, -1.446646277164314, -0.439089647647926, -0.6568645300510487, -0.1479791111026496, -0.37816853906616543, -1.5546979990960859, 0.7934110284198954, 0.5250598397936805, 0.715179599821307, -2.6619881622077957, 0.6738306385872681, -0.5829579084083533, -1.6036851727710095, 1.7676938677132092, 2.1178719441137925, -0.9822453774326113, 2.644398248982846, -0.4222365679492326, -0.08802559167948826, 0.004781669065527239, 0.772037726995288, -0.589376818822907, -0.009942853176962085, -1.2940732511754347, 3.3672146186572194, 0.5720957571272467, 1.9994832545202734, -0.2408374457735749, 1.6235559488713027, 4.765160983845028, 2.2423062077647176, 2.018531795146693, 3.6912668457665974, 7.052100921101374, 2.891089489994272, 5.012011484448072, 2.9058206661961257, 4.74433866373019, 4.522254758963782, 4.483117294212917, 7.161931707757217, 6.608363617973065, 8.54801536915603, 5.975318310443797, 4.404349461089431, 6.93366550050009, 4.447502046635322, 5.24747472180249, 6.072362283142831, 5.9553560646539605, 3.2489334527924516, 3.5194287418405414, -0.24943173222751147, 2.619648178234713, 4.7339671460783475, -1.5079676768571109, 3.805732205983656, 2.384418539000519 ] # regression n = length(y_p1_sim) X = [ones(n, 1) x_sim] b = X \ y_p1_sim resid = y_p1_sim - X * b t = DurbinWatsonTest(X, resid) # asymptotic p-values @test t.n == 101 @test t.DW ≈ 0.40499929824035813 @test t.p_compute == :ndep @test pvalue(t) ≈ 5.158964292454297e-16 @test pvalue(t, tail = :left) ≈ 0.9999999999999998 @test pvalue(t, tail = :right) ≈ 2.5794821462271485e-16 @test default_tail(t) == :both show(IOBuffer(), t) t = DurbinWatsonTest(X, resid; p_compute = :exact) # exact p-values @test t.n == 101 @test t.DW ≈ 0.40499929824035813 @test t.p_compute == :exact @test pvalue(t) ≈ 3.6994415420651786e-24 @test pvalue(t, tail = :left) ≈ 1.00 @test pvalue(t, tail = :right) ≈ 1.8497207710325893e-24 @test default_tail(t) == :both show(IOBuffer(), t) y_m1_sim = [ # simulated with -0.9 error correlation -1.3910099248613454, -1.5236862020915085, 4.097936666328973, -1.8511224691327444, 4.089543164538723, -4.495552189456728, 7.111817193652225, -5.978343737983263, 6.002151715790337, -2.927307499513737, 5.458083999297893, 1.169591175532601, 4.594296073450898, -4.243581518221936, 2.8299935873046445, -0.5860831006926581, -0.9991240800029624, 0.10615464305915895, -1.7044498818807359, -0.9995564116656306, -3.5319792844484295, 4.179137229344947, -5.254163800722545, 5.711864125579977, -5.990925805935972, 1.5816393282765917, -1.7032484999745658, -0.617286443723021, 1.5845107369357039, -0.6096898012505031, 3.3496253127300184, -1.1686422345229122, -1.5918280931408098, 1.1415907584907719, 3.006908809246799, 0.16279484914286346, 4.785411299104295, 2.2981183100018683, 0.212429391905895, -1.163256462733893, -3.062755396990661, 5.4435487477430335, -3.425834811822814, 2.6321872628475, -0.837244387584767, 4.031062468957392, 0.24230351459424804, 2.563723587223389, -2.388107267343436, 3.894089606181092, -0.005377707121046793, 1.4234173532692622, -1.8229221872128627, 3.8287942020863945, -0.6858661742876399, 1.1178057096772471, 2.5196873774438067, 0.38418130890537316, -1.4155851844623182, 2.8866125226188566, -0.4941340798489638, -0.0011241065963577546, 0.43409066782110806, 0.6425507130120189, -1.3986687332385075, 1.8531056183925938, -2.1057647202687244, 5.003685916104994, -2.3348521765098624, 3.0528589106154387, -3.234749402470284, 4.142408525714717, 2.75967828902951, 1.8334770219703578, -0.9220644601902186, 2.498387343549808, 3.580976074314626, -0.37369360814264785, 4.713559024928862, 0.05056665062182075, 3.374560008823081, 1.6454107505584676, 1.5983424828203905, 3.9197926529917604, 2.7024280115597086, 4.662666562844124, -0.805868878530069, 0.9823593012348448, 2.8591273650074895, -0.12192899074208174, 2.8388011459132807, 1.716213267783003, 2.7887106550396696, -1.3611491982524841, 3.6582922884633065, -3.3126745262864654, 5.030080939945388, 1.0915507567022984, -2.9861092295546072, 3.7140067907674967, 0.6518327501226435 ] # regression n = length(y_m1_sim) X = [ones(n, 1) x_sim] b = X \ y_m1_sim resid = y_m1_sim - X * b t = DurbinWatsonTest(X, resid) # asymptotic p-values @test t.n == 101 @test t.DW ≈ 3.1196941838878423 @test t.p_compute == :ndep @test pvalue(t) ≈ 1.3691928363065143e-8 @test pvalue(t, tail = :left) ≈ 6.8459641815325715e-9 @test pvalue(t, tail = :right) ≈ 0.9999999931540359 @test default_tail(t) == :both show(IOBuffer(), t) t = DurbinWatsonTest(X, resid; p_compute = :exact) # exact p-values @test t.n == 101 @test t.DW ≈ 3.1196941838878423 @test t.p_compute == :exact @test pvalue(t) ≈ 6.608698033261362e-10 @test pvalue(t, tail = :left) ≈ 3.304349016630681e-10 @test pvalue(t, tail = :right) ≈ 0.9999999996695651 @test default_tail(t) == :both show(IOBuffer(), t) y_0_sim = [ # simulated with 0 error correlation -1.7961754992652044, -2.5510957528383353, 3.2525339877180928, 0.19231575061789374, 1.89169121462802, -1.7386623034795425, 3.258218157382714, -2.526695955245271, 2.3288443884260106, 0.7381645606308258, 1.8471935105613477, 4.537960965742147, 2.7213734745790865, -1.9897890454508897, -0.30877316780251873, 1.466080926146517, -2.613632233922138, 0.24522161603320347, -1.3710354663088093, -2.4209400297411765, -3.4512221745897302, 2.881796133532548, -3.597925434303817, 1.8506552588011762, -2.380926529249864, -3.160258392310042, 0.09071892000097082, -2.6081167226985844, 2.088064405287688, -0.024234312547235515, 2.385739734138283, 0.3967490275831522, -2.3202265548315593, 0.33309301826620985, 2.8843408018580714, 0.8655964597465511, 3.7488337387014004, 4.297643800846097, 0.1873148360133016, -1.207270876248609, -3.205052473244388, 4.259413925143798, -0.7425056693856398, -0.598646937182016, 1.1973080753889698, 1.507929336481593, 2.1567293512995978, 1.2684047056422159, -0.6475511763894612, 1.968716146589186, 1.6551464263288553, 0.8306015804336573, -1.9237481856587493, 2.628892109084551, 0.7853215622266103, -0.28924845119256015, 3.3683615196802235, 1.5894237058883518, -1.9790760667912535, 2.570502472637483, -0.34918890076289344, -0.07692872949280205, 0.2585418367307264, 0.9004832694436649, -1.0522919323231783, 0.5574000211207956, -0.8615471735157796, 3.820189106289126, -0.14496612583980942, 1.218044512431157, -1.2637743788791052, 1.5357218567794906, 4.895903296016806, 1.1354244022005544, 0.36426053387077517, 1.7715587797565924, 4.779742721710445, -0.30330824012822477, 3.393632860526853, 1.3438900516253283, 2.7745850292681986, 2.4674323600529258, 1.7461500847342628, 4.242713515247852, 3.1964332401219315, 4.847669943114067, 0.8363177531165059, -0.35817985387610163, 3.3565008608192253, 0.32924436697495, 1.9868939670380534, 2.810384666312773, 2.4117663029348924, -0.4810983070564472, 1.5143233221817027, -1.7185645332767443, 2.4464053017635212, 3.997453694160127, -3.8861258284250813, 3.094705799661703, 1.4768492077143098 ] # regression n = length(y_0_sim) X = [ones(n, 1) x_sim] b = X \ y_0_sim resid = y_0_sim - X * b t = DurbinWatsonTest(X, resid) @test t.n == 101 @test t.DW ≈ 2.0315450779948154 @test t.p_compute == :ndep @test pvalue(t) ≈ 0.8794168553233327 @test pvalue(t, tail = :left) ≈ 0.43970842766166635 @test pvalue(t, tail = :right) ≈ 0.5602915723383337 @test default_tail(t) == :both show(IOBuffer(), t) t = DurbinWatsonTest(X, resid; p_compute = :exact) # exact p-values @test t.n == 101 @test t.DW ≈ 2.0315450779948154 @test t.p_compute == :exact @test pvalue(t) ≈ 0.8794168553233327 # exact p-values outsid [0,1], use approx. @test pvalue(t, tail = :left) ≈ 0.43970842766166635 @test pvalue(t, tail = :right) ≈ 0.5602915723383337 @test default_tail(t) == :both show(IOBuffer(), t) # test corner cases t1 = DurbinWatsonTest(X, size(X,1), 0.00, :exact) @test pvalue(t1) == 0.00 @test pvalue(t1, tail = :left) == 1.00 @test pvalue(t1, tail = :right) == 0.00 show(IOBuffer(), t1) t1 = DurbinWatsonTest(X, size(X,1), 4.00, :exact) @test pvalue(t1) == 0.00 @test pvalue(t1, tail = :left) == 0.00 @test pvalue(t1, tail = :right) == 1.00 show(IOBuffer(), t1) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1544
using HypothesisTests, Test using HypothesisTests: default_tail using StableRNGs @testset "F-tests" begin @testset "Basic variance F-test" begin rng = StableRNG(12) y1_h0 = 4 .+ randn(rng, 500) y2_h0 = 4 .+ randn(rng, 400) t = VarianceFTest(y1_h0, y2_h0) @test t.n_x == 500 @test t.n_y == 400 @test t.df_x == 499 @test t.df_y == 399 @test t.F ≈ 0.859582 rtol=1e-5 @test pvalue(t) ≈ 0.109714 rtol=1e-5 @test pvalue(t, tail=:left) ≈ 0.0548572 rtol=1e-5 @test pvalue(t, tail=:right) ≈ 0.945143 rtol=1e-5 @test default_tail(t) == :both t = VarianceFTest(y2_h0, y1_h0) @test t.n_x == 400 @test t.n_y == 500 @test t.df_x == 399 @test t.df_y == 499 @test t.F ≈ 1.163355 rtol=1e-5 @test pvalue(t) ≈ 0.109714 rtol=1e-5 @test pvalue(t, tail=:right) ≈ 0.0548572 rtol=1e-5 @test pvalue(t, tail=:left) ≈ 0.945143 rtol=1e-5 @test default_tail(t) == :both y1_h1 = 0.7*randn(rng, 200) y2_h1 = 1.3*randn(rng, 120) t = VarianceFTest(y1_h1, y2_h1) @test t.n_x == 200 @test t.n_y == 120 @test t.df_x == 199 @test t.df_y == 119 @test t.F ≈ 0.264161 rtol=1e-5 @test pvalue(t) < 1e-8 @test default_tail(t) == :both @test pvalue(t, tail=:left) < 1e-8 @test pvalue(t, tail=:right) > 1.0 - 1e-8 end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
5838
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Fisher" begin t = @inferred(HypothesisTests.FisherExactTest(1, 1, 1, 1)) @test t.ω ≈ 1.0 @test pvalue(t; tail=:left) ≈ 0.8333333333333337 @test pvalue(t; tail=:right) ≈ 0.8333333333333337 @test pvalue(t; method=:central) ≈ 1.0 @test pvalue(t; method=:minlike) ≈ 1.0 @test default_tail(t) == :both @test_ci_approx confint(t; tail=:left) (0.0, 76.24918299781056) @test_ci_approx confint(t; tail=:right) (0.013114894621608135, Inf) @test_ci_approx confint(t; method=:central) (0.006400016357911029, 156.2496006379585) #@test_approx_eq [confint(t; method=:minlike)...] [0.0131, 76.2492] show(IOBuffer(), t) # http://en.wikipedia.org/wiki/Fisher%27s_exact_test t = HypothesisTests.FisherExactTest(1, 9, 11, 3) @test t.ω ≈ 0.03720908483238119 @test pvalue(t; tail=:left) ≈ 0.0013797280926100427 @test pvalue(t; tail=:right) ≈ 0.9999663480953023 @test pvalue(t; method=:central) ≈ 0.0027594561852200853 @test pvalue(t; method=:minlike) ≈ 0.002759456185220088 @test_ci_approx confint(t; tail=:left) (0.0, 0.32600296913224913) @test_ci_approx confint(t; tail=:right) (0.0012948958389639856, Inf) @test_ci_approx confint(t; method=:central) (0.0006360029488751071, 0.42586647569637387) #@test_approx_eq [confint(t; method=:minlike)...] [0.0013, 0.3567] show(IOBuffer(), t) # http://www.physics.csbsju.edu/stats/exact.html t = HypothesisTests.FisherExactTest(7, 12, 0, 5) @test t.ω ≈ Inf @test pvalue(t; tail=:left) ≈ 1.0 @test pvalue(t; tail=:right) ≈ 0.1455862977602108 @test pvalue(t; method=:central, tail=:both) ≈ 0.2911725955204216 @test pvalue(t; method=:minlike, tail=:both) ≈ 0.2720685111989459 @test_ci_approx confint(t; tail=:left) (0.0, Inf) @test_ci_approx confint(t; tail=:right) (0.539859556284207, Inf) @test_ci_approx confint(t; method=:central) (0.39239937500428096, Inf) #@test_approx_eq [confint(t; method=:minlike)...] [0.5171, Inf] show(IOBuffer(), t) t = HypothesisTests.FisherExactTest(12, 7, 5, 0) @test t.ω ≈ 0.0 @test pvalue(t; tail=:left) ≈ 0.1455862977602108 @test pvalue(t; tail=:right) ≈ 1.0 @test pvalue(t; method=:central, tail=:both) ≈ 0.29117259552042146 @test pvalue(t; method=:minlike, tail=:both) ≈ 0.2720685111989459 @test_ci_approx confint(t; tail=:left) (0.0, 1.852333608546057) @test_ci_approx confint(t; tail=:right) (0.0, Inf) @test_ci_approx confint(t; method=:central) (0.0, 2.5484240386190433) #@test_approx_eq [confint(t; method=:minlike)...] [0.0, 1.9338] show(IOBuffer(), t) t = HypothesisTests.FisherExactTest(0, 5, 7, 12) @test t.ω ≈ 0.0 @test pvalue(t; tail=:left) ≈ 0.1455862977602108 @test pvalue(t; tail=:right) ≈ 1.0 @test pvalue(t; method=:central, tail=:both) ≈ 0.29117259552042146 @test pvalue(t; method=:minlike, tail=:both) ≈ 0.2720685111989459 @test_ci_approx confint(t; tail=:left) (0.0, 1.8523336085460567) @test_ci_approx confint(t; tail=:right) (0.0, Inf) @test_ci_approx confint(t; method=:central) (0.0, 2.5484240386190433) #@test_approx_eq [confint(t; method=:minlike)...] [0.0, 1.9338] show(IOBuffer(), t) t = HypothesisTests.FisherExactTest(5, 0, 12, 7) @test t.ω ≈ Inf @test pvalue(t; tail=:left) ≈ 1.0 @test pvalue(t; tail=:right) ≈ 0.1455862977602108 @test pvalue(t; method=:central, tail=:both) ≈ 0.29117259552042146 @test pvalue(t; method=:minlike, tail=:both) ≈ 0.2720685111989459 @test_ci_approx confint(t; tail=:left) (0.0, Inf) @test_ci_approx confint(t; tail=:right) (0.5398595562842079, Inf) @test_ci_approx confint(t; method=:central) (0.39239937500428096, Inf) #@test_approx_eq [confint(t; method=:minlike)...] [0.5171, Inf] show(IOBuffer(), t) # http://www.stata.com/support/faqs/statistics/fishers-exact-test/ t = HypothesisTests.FisherExactTest(2, 31, 136, 15532) @test t.ω ≈ 7.3653226779913386 @test pvalue(t; tail=:left) ≈ 0.9970112864705307 @test pvalue(t; tail=:right) ≈ 0.03390271476034175 @test pvalue(t; method=:central, tail=:both) ≈ 0.06780542952068347 @test pvalue(t; method=:minlike, tail=:both) ≈ 0.03390271476034175 @test_ci_approx confint(t; tail=:left) (0.0,25.20252454804777) @test_ci_approx confint(t; tail=:right) (1.2436262312601785, Inf) @test_ci_approx confint(t; method=:central) (0.8458141614657836, 29.44434308524672) #@test_approx_eq [confint(t; method=:minlike)...] [1.2436, 28.3557] show(IOBuffer(), t) # http://www.utstat.toronto.edu/~brunner/oldclass/312f12/lectures/312f12FisherWithR.pdf # http://vassarstats.net/odds2x2.html t = HypothesisTests.FisherExactTest(4, 1, 20, 1) @test t.ω ≈ 0.21821789023599236 @test pvalue(t; tail=:left) ≈ 0.353846153846154 @test pvalue(t; tail=:right) ≈ 0.9692307692307692 @test pvalue(t; method=:central) ≈ 0.7076923076923074 @test pvalue(t; method=:minlike) ≈ 0.353846153846154 @test_ci_approx confint(t; tail=:left) (0.0, 9.594302003876502) @test_ci_approx confint(t; tail=:right) (0.004963263361921223, Inf) @test_ci_approx confint(t; method=:central) (0.002430190787475382, 19.59477744071154) #@test_approx_eq [confint(t; method=:minlike)...] [0.005, 9.5943] show(IOBuffer(), t) # Corner cases gh #276 t = HypothesisTests.FisherExactTest(5, 0, 5, 0) @test pvalue(t; tail=:left) ≈ 1 @test pvalue(t; tail=:right) ≈ 1 @test pvalue(t; method=:central) ≈ 1 @test pvalue(t; method=:minlike) ≈ 1 @test_ci_approx confint(t; tail=:left) (0.0, Inf) @test_ci_approx confint(t; tail=:right) (0.0, Inf) @test_ci_approx confint(t; method=:central) (0.0, Inf) t = HypothesisTests.FisherExactTest(0, 5, 0, 5) @test pvalue(t; tail=:left) ≈ 1 @test pvalue(t; tail=:right) ≈ 1 @test pvalue(t; method=:central) ≈ 1 @test pvalue(t; method=:minlike) ≈ 1 @test_ci_approx confint(t; tail=:left) (0.0, Inf) @test_ci_approx confint(t; tail=:right) (0.0, Inf) @test_ci_approx confint(t; method=:central) (0.0, Inf) t = HypothesisTests.FisherExactTest(1, 1, 1, 1) @test HypothesisTests.pvalue(t, tail=:both) <= 1 show(IOBuffer(), t) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
3176
using HypothesisTests using Test using DelimitedFiles @testset "Hotelling utility functions" begin HT = HypothesisTests @test HT.checkdims(rand(3, 2), rand(4, 2)) == (2, 3, 4) # Mismatched number of variables @test_throws DimensionMismatch HT.checkdims(rand(4, 3), rand(4, 6)) # Empty observations @test_throws ArgumentError HT.checkdims(rand(0, 4), rand(2, 4)) Sx = [ 3.0 -1.5 0.0 -1.5 1.0 0.5 0.0 0.5 1.0] Sy = fill(4.5, (3, 3)) out = [3.5 0.5 1.5 0.5 2.166667 1.833333 1.5 1.833333 2.166667] @test HT.poolcov!(Sx, 2, Sy, 1) ≈ out atol=1e-6 # Input is modified @test Sx ≈ out atol=1e-6 # Positive semi-definite but not positive definite P = [ 1.0000 0.7426 0.1601 -0.7000 0.5500 0.7426 1.0000 -0.2133 -0.5818 0.5000 0.1601 -0.2133 1.0000 -0.1121 0.1000 -0.7000 -0.5818 -0.1121 1.0000 0.4500 0.5500 0.5000 0.1000 0.4500 1.0000] # Positive definite Q = [ 1.0 -0.5 0.0 -0.5 1.0 -0.5 0.0 -0.5 1.0] @test @inferred(HT.At_Binv_A(ones(5), P)) ≈ -0.8008792 atol=1e-6 @test @inferred(HT.At_Binv_A(ones(3), Q)) ≈ 10.0 end @testset "One sample Hotelling's T²" begin # Columns are calcium, iron, protein, vitamin A, vitamin C nutrient = readdlm(joinpath(@__DIR__, "data", "nutrient.txt"))[:,2:end] t = OneSampleHotellingT2Test(nutrient, [1000, 15, 60, 800, 75]) @test nobs(t) == 737 @test dof(t) == (5, 732) @test pvalue(t) ≈ 0.0 atol=eps() @test t.T² ≈ 1758.5413137 atol=1e-6 @test t.F ≈ 349.7968048 atol=1e-6 let out = sprint(show, t) @test occursin("reject h_0", out) && !occursin("fail to", out) end # Columns are survey answers: husbands' to questions 1-4, wives' to questions 1-4 spouse = readdlm(joinpath(@__DIR__, "data", "spouse.txt")) # Paired p = OneSampleHotellingT2Test(spouse[:,1:4], spouse[:,5:end]) @test nobs(p) == 30 @test dof(p) == (4, 26) @test pvalue(p) ≈ 0.039369144 atol=1e-6 @test p.T² ≈ 13.127840261 atol=1e-6 @test p.F ≈ 2.942446955 atol=1e-6 let out = sprint(show, p) @test occursin("reject h_0", out) && !occursin("fail to", out) end end @testset "Two sample Hotelling's T²" begin # Columns are type, length, left, right, bottom, top, diag swiss = readdlm(joinpath(@__DIR__, "data", "swiss3.txt")) genuine = convert(Matrix{Float64}, swiss[view(swiss, :, 1) .== "real", 2:end]) counterfeit = convert(Matrix{Float64}, swiss[view(swiss, :, 1) .== "fake", 2:end]) eq = EqualCovHotellingT2Test(genuine, counterfeit) @test nobs(eq) == (100, 100) @test dof(eq) == (6, 193) @test pvalue(eq) ≈ 0.0 atol=eps() @test eq.T² ≈ 2412.4506855 atol=1e-6 @test eq.F ≈ 391.9217023 atol=1e-6 @test occursin("reject h_0", sprint(show, eq)) un = UnequalCovHotellingT2Test(genuine, counterfeit) @test nobs(un) == (100, 100) @test dof(un) == (6, 193) @test pvalue(un) ≈ 0.0 atol=eps() @test un.T² ≈ 2412.4506855 atol=1e-6 @test un.F ≈ 391.9217023 atol=1e-6 @test occursin("reject h_0", sprint(show, un)) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
3439
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Jarque-Bera" begin sim_data_h0 = 1.0 .+ [ 0.2972879845354616, 0.3823959677906078, -0.5976344767282311, -0.01044524463737564, -0.839026854388764, 0.31111133849833383, 2.2950878238373105, -2.2670863488005306, 0.5299655761667461, 0.43142152642291204, 0.5837082875687786, 0.9632716050381906, 0.45879095505371686, -0.5223367574215084, 0.40839583832475224, -0.050451229933665284, -0.6936536438038856, -1.7738332534080556, 0.12076596493743928, -0.7576330377205277, -1.7297561813906863, 0.7959486220046159, 0.6700619812560624, 0.5508523775007609, -0.06337459242956062, 1.3369427822509223, -0.07314863333773934, -0.7454643166407556, -1.2200551285346526, -0.05317733752769253, -0.1651363578028337, -2.115370248427311, -0.0667679865065892, 1.2224618484680618, 0.5676954597384435, 0.7634989283233873, 0.37859887985335006, -0.645597056636597, -0.6646462443910314, -1.8030263242108941, -1.2890476038497443, -0.3352700795181175, 0.07046760136115796, 0.34179376737982303, 1.7351656660543822, 1.299915964310192, 0.20636408140261675, -1.0088599555376034, -0.8500556703153979, 1.1294094358843267, -1.348533456491827, 1.2402909004290597, -0.055647093207324264, 0.7593902139454598, -0.030266886646762546, -0.36108266775609366, -2.0073032025325626, -0.5688591273466379, -1.1496275243969976, 1.880622174631185, -1.4706245413873802, -0.5352109701657319, -0.9635439598255011, -1.3851080676759138, 0.13430023756127, -0.6161166660088192, -1.719989356319742, 0.32076927998741056, -1.4473728978815112, -0.4922711880695664, -0.4130873839831828, 1.001928512455953, 1.174681325975111, -1.326970345062047, -1.593214868044067, -0.43870997575879667, 1.225797497997867, 1.4890902780696147, 2.1594331871008534, -0.9094790180375028, 1.1478203006125018, -0.5050721965223731, -0.2670670352181297, 1.499082393930729, 0.7973041601753904, -0.17164044330709693, -0.46907960993009634, 0.21762402120860017, 0.35914640760234967, 0.3200247157080577, 0.2592163280556861, 0.459695985041628, 0.20998636004214272, 1.5231753911772645, 1.2597946036121963, -0.16528310111426064, 0.15619449488763584, -0.8143152943766987, -1.7098682060045913, 1.4999378761140325, -0.1289156385300165, -0.4501839715598432 ] t = JarqueBeraTest(sim_data_h0) @test t.n == 102 @test t.JB ≈ 1.0204197333021678 @test t.skew ≈ -0.020527653857777352 @test t.kurt ≈ 2.5117242352057993 @test pvalue(t) ≈ 0.6003695680393418 @test default_tail(t) == :right show(IOBuffer(), t) t = JarqueBeraTest(sim_data_h0; adjusted=true) @test t.JB ≈ 0.9170583190120135 @test pvalue(t) ≈ 0.6322128462414497 show(IOBuffer(), t) sim_data_h1 = [ 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1 ] t = JarqueBeraTest(sim_data_h1) @test t.n == 102 @test t.JB ≈ 17.00081983024691 @test t.skew ≈ 0.11785113019775637 @test t.kurt ≈ 1.0138888888888888 @test pvalue(t) ≈ 0.00020338498134114293 @test default_tail(t) == :right show(IOBuffer(), t) t = JarqueBeraTest(sim_data_h1; adjusted=true) @test t.JB ≈ 18.529299970269175 @test pvalue(t) ≈ 9.471388144608105e-5 show(IOBuffer(), t) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
2889
using HypothesisTests, Distributions, Test @testset "Kolmogorov-Smirnov" begin # sample drawn from uniform distribution x = [0.3500, 0.1966, 0.2511, 0.6160, 0.4733, 0.3517, 0.8308, 0.5853, 0.5497, 0.9172, 0.2858, 0.7572, 0.7537, 0.3804, 0.5678, 0.0759, 0.0540, 0.5308, 0.7792, 0.9340, 0.1299, 0.5688, 0.4694, 0.0119, 0.3371 ] t = ApproximateOneSampleKSTest(x, Uniform()) @test t.δ ≈ 0.1440 @test t.δn ≈ 0.0571 @test t.δp ≈ 0.1440 @test pvalue(t) ≈ 0.6777349664784745 @test pvalue(t; tail=:left) ≈ 0.849573771973747 @test pvalue(t; tail=:right) ≈ 0.3545875485608989 @test default_tail(t) == :both show(IOBuffer(), t) t = ApproximateTwoSampleKSTest(x, [(0:24)/25...]) @test t.δ ≈ 0.12 @test t.δn ≈ 0.08 @test t.δp ≈ 0.12 @test pvalue(t) ≈ 0.993764859699076 @test pvalue(t; tail=:left) ≈ 0.8521437889662113 @test pvalue(t; tail=:right) ≈ 0.697676326071031 @test default_tail(t) == :both show(IOBuffer(), t) t = ExactOneSampleKSTest(x, Uniform()) @test t.δ ≈ 0.1440 @test t.δn ≈ 0.0571 @test t.δp ≈ 0.1440 @test pvalue(t) ≈ 0.6263437768244742 @test pvalue(t; tail=:left) ≈ 0.8195705417998183 @test pvalue(t; tail=:right) ≈ 0.32350648882777194 @test default_tail(t) == :both show(IOBuffer(), t) ## check fit to normal distribution t = ApproximateOneSampleKSTest(x, Normal()) @test t.δ ≈ 0.5047473010922947 @test t.δn ≈ 0.5047473010922947 @test t.δp ≈ 0.17515194649718513 @test pvalue(t) ≈ 5.871827067532435e-6 @test pvalue(t; tail=:left) ≈ 2.9359135337662175e-6 @test pvalue(t; tail=:right) ≈ 0.21569061887162347 ## check unequal sample size t = ApproximateTwoSampleKSTest(x, [(0:5)/6...]) @test t.δ ≈ 0.22 @test t.δn ≈ 0.22 @test t.δp ≈ 0.09333333333333346 @test pvalue(t) ≈ 0.973300892518972 @test pvalue(t; tail=:left) ≈ 0.6260111498528065 @test pvalue(t; tail=:right) ≈ 0.9191544797498837 # http://ocw.mit.edu/courses/mathematics/18-443-statistics-for-applications-fall-2006/lecture-notes/lecture14.pdf x = [0.58, 0.42, 0.52, 0.33, 0.43, 0.23, 0.58, 0.76, 0.53, 0.64] t = ApproximateOneSampleKSTest(x, Uniform()) @test t.δ ≈ 0.26 @test t.δn ≈ 0.23 @test t.δp ≈ 0.26 @test pvalue(t) ≈ 0.5084937988981307 @test pvalue(t; tail=:left) ≈ 0.3471494153245104 @test pvalue(t; tail=:right) ≈ 0.25872229825964005 t = ApproximateTwoSampleKSTest(x, [(0:9)/10...]) @test t.δ ≈ 0.3 @test t.δn ≈ 0.3 @test t.δp ≈ 0.2 @test pvalue(t) ≈ 0.7590978384203948 @test pvalue(t; tail=:left) ≈ 0.406569659740599 @test pvalue(t; tail=:right) ≈ 0.6703200460356393 t = ExactOneSampleKSTest(x, Uniform()) @test t.δ ≈ 0.26 @test t.δn ≈ 0.23 @test t.δp ≈ 0.26 @test pvalue(t) ≈ 0.4351284228580825 @test pvalue(t; tail=:left) ≈ 0.3013310572470338 @test pvalue(t; tail=:right) ≈ 0.2193143479950862 # Check two samples with ties t = ApproximateTwoSampleKSTest(ones(10), ones(10)) @test isapprox(t.δ, 0., atol=1e-16) @test isapprox(t.δp, 0., atol=1e-16) @test isapprox(t.δn, 0., atol=1e-16) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1650
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Kruskal-Wallis" begin # www.uni-siegen.de/phil/sozialwissenschaften/soziologie/mitarbeiter/ludwig-mayerhofer/statistik/statistik_downloads/statistik_ii_7.pdf u5 = [620, 5350, 7220] u250 = [3580, 4180, 5690] u2500 = [3600, 3820, 3840, 3850, 4160, 5300, 6900, 7120, 9370] more = [3920, 4520, 4760, 8560, 10350] t = HypothesisTests.KruskalWallisTest(u5, u250, u2500, more) @test t.n_i == [length(u5), length(u250), length(u2500), length(more)] @test t.df == 3 @test t.R_i == [31, 25, 88, 66] @test t.H ≈ 1.5803174603174597 @test t.tie_adjustment == 1 @test pvalue(t) ≈ 0.6638608922384397 @test default_tail(t) == :right show(IOBuffer(), t) # http://www.brightstat.com/index.php?option=com_content&task=view&id=41&Itemid=1&limit=1&limitstart=2 city1 = [68, 93, 123, 83, 108, 122] city2 = [119, 116, 101, 103, 113, 84] city3 = [70, 68, 54, 73, 81, 68] city4 = [61, 54, 59, 67, 59, 70] t = HypothesisTests.KruskalWallisTest(city1, city2, city3, city4) @test t.n_i == [length(city1), length(city2), length(city3), length(city4)] @test t.df == 3 @test t.R_i == [104, 113, 53, 30] @test t.H ≈ 16.028783253379856 @test t.tie_adjustment ≈ 0.9969565217391304 @test pvalue(t) ≈ 0.0011186794961869423 show(IOBuffer(), t) # example with non-integer rank sum t1 = [1.2,1.9,2.1] t2 = [3.4,1.9,5.6] t3 = [1.3,4.4,9.9] t = KruskalWallisTest(t1, t2, t3) @test t.n_i == [length(t1), length(t2), length(t3)] @test t.df == 2 @test t.R_i == [9.5, 17.5, 18.0] @test t.H ≈ 2.039215686274513 @test t.tie_adjustment ≈ 0.9916666666666667 @test pvalue(t) ≈ 0.3607363776845705 show(IOBuffer(), t) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
3751
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Mann-Whitney" begin @testset "Basic exact test" begin @test abs(@inferred(pvalue(ExactMannWhitneyUTest([1:10;], [2.1:2:21;]))) - 0.0232) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([2.1:2:21;], [1:10;]))) - 0.0232) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([1.5:10:100;], [2.1:2:21;]))) - 0.0068) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([2.1:2:21;], [1.5:10:100;]))) - 0.0068) <= 1e-4 @test default_tail(ExactMannWhitneyUTest([1:10;], [2.1:2:21;])) == :both show(IOBuffer(), ExactMannWhitneyUTest([1:10;], [2.1:2:21;])) end @testset "Exact with ties" begin @test abs(@inferred(pvalue(ExactMannWhitneyUTest([1:10;], [1:10;]))) - 1) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([1:10;], [2:11;]))) - 0.5096) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([2:11;], [1:10;]))) - 0.5096) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([1:10;], [1:5; ones(5)]))) - 0.0057) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([1:5; ones(5)], [1:10;]))) - 0.0057) <= 1e-4 show(IOBuffer(), ExactMannWhitneyUTest([1:10;], [1:10;])) end @testset "Exact with ties and unequal lengths" begin @test abs(@inferred(pvalue(ExactMannWhitneyUTest([1:10;], [2:2:24;]))) - 0.0118) <= 1e-4 @test abs(@inferred(pvalue(ExactMannWhitneyUTest([2:2:24;], [1:10;]))) - 0.0118) <= 1e-4 show(IOBuffer(), ExactMannWhitneyUTest([1:10;], [2:2:24;])) end @testset "Approximate test" begin @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([1:10;], [2.1:2:21;]))) - 0.0257) <= 1e-4 @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([2.1:2:21;], [1:10;]))) - 0.0257) <= 1e-4 @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([1.5:10:100;], [2.1:2:21;]))) - 0.0091) <= 1e-4 @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([2.1:2:21;], [1.5:10:100;]))) - 0.0091) <= 1e-4 @test default_tail(ApproximateMannWhitneyUTest([1:10;], [2.1:2:21;])) == :both show(IOBuffer(), ApproximateMannWhitneyUTest([1:10;], [2.1:2:21;])) end @testset "Approximate with ties" begin @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([1:10;], [1:10;]))) - 1) <= 1e-4 @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([1:10;], [2:11;]))) - 0.4948) <= 1e-4 @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([2:11;], [1:10;]))) - 0.4948) <= 1e-4 @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([1:10;], [1:5; ones(5)]))) - 0.0076) <= 1e-4 @test abs(@inferred(pvalue(ApproximateMannWhitneyUTest([1:5; ones(5)], [1:10;]))) - 0.0076) <= 1e-4 show(IOBuffer(), ApproximateMannWhitneyUTest([1:10;], [1:10;])) end @testset "Tests for automatic selection" begin @test abs(@inferred(pvalue(MannWhitneyUTest([1:10;], [2.1:2:21;]))) - 0.0232) <= 1e-4 @test abs(@inferred(pvalue(MannWhitneyUTest([1:10;], [2:11;]))) - 0.4948) <= 1e-4 show(IOBuffer(), MannWhitneyUTest([1:10;], [2.1:2:21;])) end @testset "Issue #39" begin @test abs(@inferred(pvalue(ExactMannWhitneyUTest(Float32[1:10;], Float32[2:11;]))) - 0.5096) <= 1e-4 end @testset "Issue #113" begin @test abs(pvalue(ApproximateMannWhitneyUTest(Float32[1:10;], Float32[2:11;])) - 0.4948) <= 1e-4 end @testset "Issue #126 pvalues above 1" begin A = [1.34937, 1.75722,0.276514, 1.04546, 1.69085, 0.738085, 2.36313] B = [2.62325, 1.16533, 1.1327, 0.728714] m = ExactMannWhitneyUTest(A,B) p = @inferred(pvalue(m; tail = :both)) @test p == 1 A = [12,10,7,6,3,1] B = [11,9,8,5,4,2] m = MannWhitneyUTest(A,B) p = @inferred(pvalue(m; tail = :both)) @test p == 1 m = ApproximateMannWhitneyUTest(A, B) p = @inferred(pvalue(m; tail = :both)) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1136
using HypothesisTests, Test, Statistics, StableRNGs @testset "Permutation" begin @testset "ExactPermutationTest" begin @test pvalue(ExactPermutationTest([1,2,3], [4,5,6], mean), tail=:both) ≈ 0.1 @test pvalue(ExactPermutationTest([4,5,6], [1,2,3], mean), tail=:both) ≈ 0.1 @test pvalue(ExactPermutationTest([1,2,3], [4,5,6], mean), tail=:left) ≈ 0.05 @test pvalue(ExactPermutationTest([4,5,6], [1,2,3], mean), tail=:right) ≈ 0.05 end @testset "ApproximatePermutationTest" begin rng = StableRNG(12345) @test pvalue(ApproximatePermutationTest(rng, [1,2,3], [4,5,6], mean, 100), tail=:both) ≈ 0.14 @test pvalue(ApproximatePermutationTest(rng, [4,5,6], [1,2,3], mean, 100), tail=:both) ≈ 0.08 @test pvalue(ApproximatePermutationTest(rng, [1,2,3], [4,5,6], mean, 100), tail=:left) ≈ 0.05 @test pvalue(ApproximatePermutationTest(rng, [4,5,6], [1,2,3], mean, 100), tail=:right) ≈ 0.05 # Test that the non-rng method works @test ApproximatePermutationTest([4,5,6], [1,2,3], mean, 100) isa HypothesisTests.PermutationTest{Float64} end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
5697
using HypothesisTests, Test using StatsBase using HypothesisTests: default_tail @testset "Power Divergence" begin #Example 1 in R #Agresti (2007) p. 39 d = [[762,484] [327,239] [468,477]] m = PowerDivergenceTest(d) @test m.theta0 ≈ [0.25523082406125785,0.19670969099133556,0.11593952361049113,0.08935608756107216,0.1935739395970214,0.1491899341788219] @test m.thetahat ≈ [0.2763873775843308,0.1755531374682626,0.11860718171926006,0.08668842945230323,0.16974972796517954,0.17301414581066377] c = confint(m, method=:sison_glaz) c0 = [(.25788900979, .29554669435), (.15705476968, .19471245423), (.10010881393, .13776649848), (.06819006166, .10584774622), (.15125136017, .18890904473), (.15451577802, .19217346257)] for i = 1:length(c) @test c[i][1] ≈ c0[i][1] @test c[i][2] ≈ c0[i][2] end @test pvalue(m) ≈ 2.9535891832117357e-7 @test default_tail(m) == :right @test m.stat ≈ 30.070149095754687 @test m.df ≈ 2 @test m.n ≈ 2757 @test m.residuals ≈ reshape([2.198855766015898,-2.504669492560728,0.4113701700566286,-0.46858294710127296,-2.8432397155451494,3.2386734435365825], size(d)) @test m.stdresiduals ≈ reshape([4.502053521086705,-4.502053521086705,0.6994517329844298,-0.6994517329844298,-5.315945542704929,5.315945542704929], size(d)) m = PowerDivergenceTest(d,lambda=0.0) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=-1.0) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=-2.0) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=-0.5) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=2/3) testname(m) pvalue(m) show(IOBuffer(), m) m = ChisqTest(d) m = MultinomialLRTest(d) confint(m) confint(m, tail=:left) confint(m, tail=:right) confint(m, method = :auto) confint(m, method = :auto, tail=:left) confint(m, method = :auto, tail=:right) confint(m, method = :bootstrap) confint(m, method = :bootstrap, tail=:left) confint(m, method = :bootstrap, tail=:right) confint(m, method = :gold) confint(m, method = :gold, tail=:left) confint(m, method = :gold, tail=:right) confint(m, method = :quesenberry_hurst) confint(m, method = :quesenberry_hurst, tail=:left) confint(m, method = :quesenberry_hurst, tail=:right) confint(m, method = :sison_glaz) confint(m, method = :sison_glaz, correct=false) confint(m, method = :sison_glaz, tail=:left) confint(m, method = :sison_glaz, tail=:right) @test_throws ArgumentError confint(m, method=:FOO) @test_throws ArgumentError confint(m, tail=:fox) @test confint(m, method = :quesenberry_hurst) == confint(m, method = :auto) == confint(m) #Example 3 in R d = [ 20, 15, 25 ] m = PowerDivergenceTest(d) @test m.theta0 ≈ [0.3333333333333333,0.3333333333333333,0.3333333333333333] @test m.thetahat ≈ [0.3333333333333333,0.25,0.4166666666666667] c = confint(m) c0 = [(.21666666667, .48098082062), (.13333333333, .39764748728), (.30000000000, .56431415395)] for i in 1:length(c) @test c[i][1] ≈ c0[i][1] @test c[i][2] ≈ c0[i][2] end @test pvalue(m) ≈ 0.2865047968601901 @test m.stat ≈ 2.5 @test m.df ≈ 2 @test m.n ≈ 60 @test m.residuals ≈ [0.0,-1.118033988749895,1.118033988749895] @test m.stdresiduals ≈ [0.0,-1.3693063937629153,1.3693063937629153] m = PowerDivergenceTest(d,lambda=0.0) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=-1.0) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=-2.0) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=-0.5) testname(m) pvalue(m) show(IOBuffer(), m) m = PowerDivergenceTest(d,lambda=2/3) testname(m) pvalue(m) show(IOBuffer(), m) m = ChisqTest(d) m = MultinomialLRTest(d) confint(m) confint(m, tail=:left) confint(m, tail=:right) confint(m, method = :auto) confint(m, method = :auto, tail=:left) confint(m, method = :auto, tail=:right) confint(m, method = :bootstrap) confint(m, method = :bootstrap, tail=:left) confint(m, method = :bootstrap, tail=:right) confint(m, method = :gold) confint(m, method = :gold, tail=:left) confint(m, method = :gold, tail=:right) confint(m, method = :quesenberry_hurst) confint(m, method = :quesenberry_hurst, tail=:left) confint(m, method = :quesenberry_hurst, tail=:right) confint(m, method = :sison_glaz) confint(m, method = :sison_glaz, correct=false) confint(m, method = :sison_glaz, tail=:left) confint(m, method = :sison_glaz, tail=:right) @test_throws ArgumentError confint(m, method=:FOO) @test_throws ArgumentError confint(m, tail=:fox) @test confint(m, method = :sison_glaz) == confint(m, method = :auto) == confint(m) # x=[1,2,3,1,2,3] y=[1,1,1,2,2,3] d = counts(x,y,3) ChisqTest(d) MultinomialLRTest(d) PowerDivergenceTest(x,y,3) PowerDivergenceTest(x,y,(1:3,1:3)) ChisqTest(x,y,3) ChisqTest(x,y,(1:3,1:3)) MultinomialLRTest(x,y,3) MultinomialLRTest(x,y,(1:3,1:3)) # Test that large counts don't cause overflow (issue #43) d = [113997 1031298 334453 37471] PowerDivergenceTest(d) # Pearson's Chi-Squared Test # As in https://en.wikipedia.org/wiki/Pearson's_chi-squared_test#Fairness_of_dice O = [5,8,9,8,10,20] E = fill(10,6) m = ChisqTest(O,E) @test pvalue(m) ≈ 0.01990522033477436 @test m.stat ≈ 13.4 @test m.df == 5 @test m.n == 60 @test m.residuals ≈ reshape([-1.5811388300841895,-0.6324555320336759,-0.31622776601683794,-0.6324555320336759, 0.0, 3.162277660168379],size(O)) # As in https://en.wikipedia.org/wiki/Pearson's_chi-squared_test#Goodness_of_fit O = [44,56] E = fill(50,2) m = ChisqTest(O,E) @test pvalue(m) ≈ 0.23013934044341544 @test m.stat ≈ 1.44 @test m.df == 1 @test m.n == 100 @test m.residuals ≈ reshape([-0.848528137423857,0.848528137423857],size(O)) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
1209
using Test, Random, Statistics # Confidence intervals should be tested component-wise against # expected results; splatting them into arrays and checking for # approximate array equality is incorrect when either limit is # infinite. macro test_ci_approx(x::Expr, y::Expr) return quote Test.@test typeof($(esc(x))) <: Tuple{Real,Real} Test.@test typeof($(esc(x))) == typeof($(esc(y))) Test.@test all(map(isapprox, $(esc(x)), $(esc(y)))) end end include("anderson_darling.jl") include("augmented_dickey_fuller.jl") include("bartlett.jl") include("binomial.jl") include("box_test.jl") include("breusch_godfrey.jl") include("circular.jl") include("common.jl") include("durbin_watson.jl") include("fisher.jl") include("jarque_bera.jl") include("hotelling.jl") include("kolmogorov_smirnov.jl") include("kruskal_wallis.jl") include("mann_whitney.jl") include("correlation.jl") include("permutation.jl") include("power_divergence.jl") include("shapiro_wilk.jl") include("show.jl") include("t.jl") include("wald_wolfowitz.jl") include("wilcoxon.jl") include("z.jl") include("f.jl") include("diebold_mariano.jl") include("clark_west.jl") include("white.jl") include("var_equality.jl")
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
5318
using HypothesisTests, LinearAlgebra, Test, Random using StableRNGs @testset "Shapiro-Wilk" begin @testset "shapiro_wilk_coefs" begin @test HypothesisTests.shapiro_wilk_coefs(3) == [sqrt(2.0) / 2.0, 0.0, -sqrt(2.0) / 2.0] swc = HypothesisTests.shapiro_wilk_coefs(10) @test swc[4] == -swc[7] @test swc[2] == -swc[9] swc = HypothesisTests.shapiro_wilk_coefs(11) @test swc[6] == 0.0 @test swc[5] == -swc[7] @test swc[3] == -swc[9] @test swc[1] == -swc[11] #anti-symmetry swc = HypothesisTests.shapiro_wilk_coefs(20) @test all([swc[i] == -swc[end - i + 1] for i in eachindex(swc)]) # Values obtained by calling `_swilkfort` fortran subroutine directly. swc10 = HypothesisTests.shapiro_wilk_coefs(10) res = swc10[1:5] .- [0.573715, 0.32897, 0.214349, 0.122791, 0.0400887] @test norm(res, 1) ≈ 0.0 atol = length(swc10) * eps(Float32) swc20 = HypothesisTests.shapiro_wilk_coefs(20) res = swc20[1:10] .- [0.473371, 0.32174, 0.255663, 0.208297, 0.16864, 0.133584, 0.101474, 0.0712893, 0.0423232, 0.0140351] @test norm(res, 1) ≈ 0.0 atol = length(swc20) * eps(Float32) rng = StableRNG(0x5bca7c69b794f8ce) X = sort(rand(rng, Float64, 10)) # W, pval, _ = swilkfort(X) W = 0.9088434774710951 # pval = 0.2731410626084226 @test HypothesisTests.unsafe_swstat(X, swc10) ≈ W atol = eps(Float32) end @testset "Shapiro-Wilk" begin # syntactic tests @test_throws ArgumentError ShapiroWilkTest([1, 2]) @test_throws ArgumentError("at least 3 samples are required, got 2") ShapiroWilkTest([1, 2], HypothesisTests.shapiro_wilk_coefs(3)) @test_throws ArgumentError ShapiroWilkTest([1, 2, 3], censored=4) @test_throws DimensionMismatch ShapiroWilkTest([1, 2, 3], HypothesisTests.shapiro_wilk_coefs(4)) @test_throws ArgumentError("sample doesn't seem to be sorted or is constant (up to numerical accuracy)") ShapiroWilkTest([1,1,1]) @test_throws ArgumentError("sample is constant (up to numerical accuracy)") ShapiroWilkTest([1,1,1], sorted=false) t = ShapiroWilkTest([1, 2, 3]) @test t.W == 1.0 @test pvalue(t) == 1.0 @test_throws ArgumentError("censored samples not implemented yet") pvalue(ShapiroWilkTest(1:4, censored=1)) str = sprint(show, t) @test str == """Shapiro-Wilk normality test --------------------------- Population details: parameter of interest: Squared correlation of data and expected order statistics of N(0,1) (W) value under h_0: 1.0 point estimate: 1.0 Test summary: outcome with 95% confidence: fail to reject h_0 one-sided p-value: 1.0000 Details: number of observations: 3 censored ratio: 0.0 W-statistic: 1.0 """ # testing different cases of N for N in (3, 5, 11, 12) rng = StableRNG(0x5bca7c69b794f8ce) X = sort(randn(rng, N)) t = ShapiroWilkTest(X; sorted=true) # analytic properties from Shapiro-Wilk 1965: # Lemma 1: Scale and origin invariance: scale, shift = rand(rng, 2) @test t.W ≈ ShapiroWilkTest(X .+ shift).W @test t.W ≈ ShapiroWilkTest(scale .* X).W @test t.W ≈ ShapiroWilkTest(scale .* X .+ shift).W # Lemma 2, 3: upper and lower bounds @test N * t.coefs[1]^2 / (N - 1) ≤ t.W ≤ 1.0 # test the computation of pvalue in those cases @test pvalue(t) ≥ 0.05 end @testset "Worked Example" begin # **Worked Example** (Section 4) from # PATRICK ROYSTON Approximating the Shapiro-Wilk W-test for non-normality # *Statistics and Computing* (1992) **2**, 117-119 X = [48.4, 49.0, 59.5, 59.6, 60.7, 88.8, 98.2, 109.4, 169.1, 227.1] swc = HypothesisTests.shapiro_wilk_coefs(length(X)) @test norm(swc[1:5] .- [0.5737, 0.3290, 0.2143, 0.1228, 0.0401], Inf) < 5.0e-5 W = HypothesisTests.unsafe_swstat(X, swc) @test W ≈ 0.8078 atol = 2.9e-5 t = ShapiroWilkTest(X) @test t.W == W @test pvalue(t) ≈ 0.018 atol = 4.7e-5 @test pvalue(t) ≈ pvalue(ShapiroWilkTest(X, sorted=true)) @test iszero(HypothesisTests.censored_ratio(t)) @test length(t.coefs) == length(X) # test for un-sorted sample X2 = X[[9,8,2,3,4,5,7,10,1,6]] t2 = ShapiroWilkTest(X2) @test_throws ArgumentError ShapiroWilkTest(X2, sorted=true) @test t2.W ≈ t.W @test pvalue(t2) ≈ pvalue(t) X3 = X[[2,8,9,3,4,5,7,10,1,6]] t3 = ShapiroWilkTest(X3) @test t3.W ≈ t.W @test pvalue(t3) ≈ pvalue(t) @test pvalue(t3) ≠ pvalue(ShapiroWilkTest(X3, sorted=true)) end end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
7655
using HypothesisTests, Test @testset "Show" begin # based on power_divergence.jl tests d = [[762,484] [327,239] [468,477]] m = PowerDivergenceTest(d) if VERSION < v"1.4" @test sprint(show, m, context=:compact => true) == """ Pearson's Chi-square Test ------------------------- Population details: parameter of interest: Multinomial Probabilities value under h_0: [0.255231, 0.19671, 0.11594, 0.0893561, 0.193574, 0.14919] point estimate: [0.276387, 0.175553, 0.118607, 0.0866884, 0.16975, 0.173014] 95% confidence interval: Tuple{Float64,Float64}[(0.2545, 0.2994), (0.1573, 0.1955), (0.1033, 0.1358), (0.07357, 0.1019), (0.1517, 0.1894), (0.1548, 0.1928)] Test summary: outcome with 95% confidence: reject h_0 one-sided p-value: <1e-6 Details: Sample size: 2757 statistic: 30.070149095754687 degrees of freedom: 2 residuals: [2.19886, -2.50467, 0.41137, -0.468583, -2.84324, 3.23867] std. residuals: [4.50205, -4.50205, 0.699452, -0.699452, -5.31595, 5.31595] """ d = [ 20, 15, 25 ] m = PowerDivergenceTest(d) @test sprint(show, m, context=:compact => true) == """ Pearson's Chi-square Test ------------------------- Population details: parameter of interest: Multinomial Probabilities value under h_0: [0.333333, 0.333333, 0.333333] point estimate: [0.333333, 0.25, 0.416667] 95% confidence interval: Tuple{Float64,Float64}[(0.2167, 0.481), (0.1333, 0.3976), (0.3, 0.5643)] Test summary: outcome with 95% confidence: fail to reject h_0 one-sided p-value: 0.2865 Details: Sample size: 60 statistic: 2.5 degrees of freedom: 2 residuals: [0.0, -1.11803, 1.11803] std. residuals: [0.0, -1.36931, 1.36931] """ elseif VERSION < v"1.6" @test sprint(show, m, context=:compact => true) == """ Pearson's Chi-square Test ------------------------- Population details: parameter of interest: Multinomial Probabilities value under h_0: [0.255231, 0.19671, 0.11594, 0.0893561, 0.193574, 0.14919] point estimate: [0.276387, 0.175553, 0.118607, 0.0866884, 0.16975, 0.173014] 95% confidence interval: [(0.2545, 0.2994), (0.1573, 0.1955), (0.1033, 0.1358), (0.07357, 0.1019), (0.1517, 0.1894), (0.1548, 0.1928)] Test summary: outcome with 95% confidence: reject h_0 one-sided p-value: <1e-6 Details: Sample size: 2757 statistic: 30.070149095754687 degrees of freedom: 2 residuals: [2.19886, -2.50467, 0.41137, -0.468583, -2.84324, 3.23867] std. residuals: [4.50205, -4.50205, 0.699452, -0.699452, -5.31595, 5.31595] """ d = [ 20, 15, 25 ] m = PowerDivergenceTest(d) @test sprint(show, m, context=:compact => true) == """ Pearson's Chi-square Test ------------------------- Population details: parameter of interest: Multinomial Probabilities value under h_0: [0.333333, 0.333333, 0.333333] point estimate: [0.333333, 0.25, 0.416667] 95% confidence interval: [(0.2167, 0.481), (0.1333, 0.3976), (0.3, 0.5643)] Test summary: outcome with 95% confidence: fail to reject h_0 one-sided p-value: 0.2865 Details: Sample size: 60 statistic: 2.5 degrees of freedom: 2 residuals: [0.0, -1.11803, 1.11803] std. residuals: [0.0, -1.36931, 1.36931] """ else @test sprint(show, m, context=:compact => true) == """ Pearson's Chi-square Test ------------------------- Population details: parameter of interest: Multinomial Probabilities value under h_0: [0.255231, 0.19671, 0.11594, 0.0893561, 0.193574, 0.14919] point estimate: [0.276387, 0.175553, 0.118607, 0.0866884, 0.16975, 0.173014] 95% confidence interval: [(0.2545, 0.2994), (0.1573, 0.1955), (0.1033, 0.1358), (0.07357, 0.1019), (0.1517, 0.1894), (0.1548, 0.1928)] Test summary: outcome with 95% confidence: reject h_0 one-sided p-value: <1e-06 Details: Sample size: 2757 statistic: 30.070149095754687 degrees of freedom: 2 residuals: [2.19886, -2.50467, 0.41137, -0.468583, -2.84324, 3.23867] std. residuals: [4.50205, -4.50205, 0.699452, -0.699452, -5.31595, 5.31595] """ d = [ 20, 15, 25 ] m = PowerDivergenceTest(d) @test sprint(show, m, context=:compact => true) == """ Pearson's Chi-square Test ------------------------- Population details: parameter of interest: Multinomial Probabilities value under h_0: [0.333333, 0.333333, 0.333333] point estimate: [0.333333, 0.25, 0.416667] 95% confidence interval: [(0.2167, 0.481), (0.1333, 0.3976), (0.3, 0.5643)] Test summary: outcome with 95% confidence: fail to reject h_0 one-sided p-value: 0.2865 Details: Sample size: 60 statistic: 2.5 degrees of freedom: 2 residuals: [0.0, -1.11803, 1.11803] std. residuals: [0.0, -1.36931, 1.36931] """ end # based on t.jl tests tst = OneSampleTTest(-5:10) @test sprint(show, tst) == """ One sample t-test ----------------- Population details: parameter of interest: Mean value under h_0: 0 point estimate: 2.5 95% confidence interval: (-0.03693, 5.037) Test summary: outcome with 95% confidence: fail to reject h_0 two-sided p-value: 0.0530 Details: number of observations: 16 t-statistic: 2.100420126042015 degrees of freedom: 15 empirical standard error: 1.1902380714238083 """ # issue #248 x = [ 6.598170000000001e-7, 6.9452e-7, 2.41933e-7, 2.4264999999999997e-7, 4.830650000000001e-7, 2.67262e-7, 2.5027699999999996e-7, 2.51241e-7, 2.67511e-7, 2.27148e-7, 2.41169e-7, 2.56646e-7, 4.31067e-7, 2.2686500000000001e-7, 2.35553e-7, 2.32062e-7, 7.36284e-7, ] y = [ 3.59147e-7, 2.75594e-7, 1.63942e-7, 1.7980399999999999e-7, 2.82113e-7, 1.6574299999999998e-7, 1.60492e-7, 1.61266e-7, 2.12196e-7, 1.51524e-7, 1.86578e-7, 2.1346e-7, 1.59902e-7, 1.50073e-7, 1.64e-7, 1.42769e-7, 1.70032e-7, ] tst = UnequalVarianceTTest(x, y) @test sprint(show, tst) == """ Two sample t-test (unequal variance) ------------------------------------ Population details: parameter of interest: Mean difference value under h_0: 0 point estimate: 1.55673e-7 95% confidence interval: (5.93e-8, 2.52e-7) Test summary: outcome with 95% confidence: reject h_0 two-sided p-value: 0.0031 Details: number of observations: [17,17] t-statistic: 3.3767280623082523 degrees of freedom: 19.363987783845342 empirical standard error: 4.610162387563106e-8 """ end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
2301
using HypothesisTests, Test using HypothesisTests: default_tail @testset "T-test" begin @testset "One sample" begin @test pvalue(OneSampleTTest(-5:5)) == 1 tst = OneSampleTTest(-5:10) @test abs(pvalue(tst) - 0.0530) <= 1e-4 @test abs(pvalue(tst; tail=:left) - 0.9735) <= 1e-4 @test abs(pvalue(tst; tail=:right) - 0.0265) <= 1e-4 @test default_tail(tst) == :both show(IOBuffer(), tst) tst = OneSampleTTest(mean(-5:10), std(-5:10), 16) @test abs(pvalue(tst) - 0.0530) <= 1e-4 @test all(abs.([confint(tst)...;] - [-0.0369, 5.0369]) .<= 1e-4) @test all(abs.([confint(tst, level=0.9)...;] - [0.4135, 4.5865]) .<= 1e-4) c = confint(tst; tail=:left) @test c[1] == -Inf @test abs(c[2] - 4.5865) .<= 1e-4 c = confint(tst; tail=:right) @test abs(c[1] - 0.4135) .<= 1e-4 @test c[2] == Inf show(IOBuffer(), tst) tst = OneSampleTTest(-10:5) @test abs(pvalue(tst) - 0.0530) <= 1e-4 @test abs(pvalue(tst; tail=:left) - 0.0265) <= 1e-4 @test abs(pvalue(tst; tail=:right) - 0.9735) <= 1e-4 @test all(abs.([confint(tst)...] - [-5.0369, 0.0369]) .<= 1e-4) @test abs.(confint(tst; tail=:left)[2] - (-0.4135)) .<= 1e-4 @test abs.(confint(tst; tail=:right)[1] - (-4.5865)) .<= 1e-4 show(IOBuffer(), tst) end @testset "Paired" begin @test abs(pvalue(OneSampleTTest([1, 1, 2, 1, 0], [0, 1, 1, 1, 0])) - 0.1778) <= 1e-4 end @testset "Two sample" begin # From http://en.wikipedia.org/w/index.php?title=Student%27s_t-test&oldid=526762741 a1 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99] a2 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98] tst = EqualVarianceTTest(a1, a2) @test tst.df == 10 @test abs(tst.t - 1.959) <= 1e-3 @test abs(pvalue(tst) - 0.078) <= 1e-3 @test all(abs.([confint(tst)...] - [-0.0131, 0.2031]) .<= 1e-4) @test default_tail(tst) == :both show(IOBuffer(), tst) n1 = length(a1) n2 = length(a2) m1 = mean(a1) m2 = mean(a2) v1 = var(a1) v2 = var(a2) tst2 = EqualVarianceTTest(n1, n2, m1, m2, v1, v2) @test tst.df == tst2.df @test tst.t == tst2.t @test pvalue(tst) == pvalue(tst2) tst = UnequalVarianceTTest(a1, a2) @test abs(tst.df - 7.03) <= 0.01 @test abs(tst.t - 1.959) <= 1e-3 @test abs(pvalue(tst) - 0.091) <= 1e-3 @test all(abs.([confint(tst)...] - [-0.0196, 0.2096]) .<= 1e-4) @test default_tail(tst) == :both show(IOBuffer(), tst) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
2556
using HypothesisTests using Test using Statistics using DelimitedFiles @testset "Equality of Variances" begin # https://en.wikipedia.org/wiki/One-way_analysis_of_variance#Example groups = [ [6, 8, 4, 5, 3, 4], [8, 12, 9, 11, 6, 8], [13, 9, 11, 8, 7, 12] ] t = OneWayANOVATest(groups...) @test nobs(t) == fill(6, 3) @test dof(t) == (2,15) @test pvalue(t) ≈ 0.002 atol=1e-3 @test occursin("reject h_0", sprint(show, t)) show(IOContext(IOBuffer(), :table => true), t) show(IOBuffer(), t) # http://www.real-statistics.com/one-way-analysis-of-variance-anova/confidence-interval-anova/ groups = [ [51, 87, 50, 48, 79, 61, 53], [82, 91, 92, 80, 52, 79, 73, 74], [79, 84, 74, 98, 63, 83, 85, 58], [85, 80, 65, 71, 67, 51], ] t = OneWayANOVATest(groups...) @test nobs(t) == [7, 8, 8, 6] @test dof(t) == (3,25) @test pvalue(t) ≈ 0.072 atol=1e-3 @test occursin("reject h_0", sprint(show, t)) # http://www.real-statistics.com/one-way-analysis-of-variance-anova/homogeneity-variances/levenes-test/ groups = [ [51, 87, 50, 48, 79, 61, 53, 54], [82, 91, 92, 80, 52, 79, 73, 74], [79, 84, 74, 98, 63, 83, 85, 58], [85, 80, 65, 71, 67, 51, 63, 93], ] # with means l = LeveneTest(groups...; statistic=mean) @test nobs(l) == fill(8, 4) @test dof(l) == (3,28) @test pvalue(l) ≈ 0.90357 atol=1e-4 # with medians l = LeveneTest(groups...; statistic=median) @test pvalue(l) ≈ 0.97971 atol=1e-4 # with 10% trimmed means l = LeveneTest(groups...; statistic=v->mean(trim(v, prop=0.1))) @test pvalue(l) ≈ 0.90357 atol=1e-4 # Fligner-Killeen Test t = FlignerKilleenTest(groups...) @test nobs(t) == fill(8, 4) @test dof(t) == 3 @test pvalue(t) ≈ 0.9878 atol=1e-4 @test HypothesisTests.teststatistic(t) ≈ 0.1311 atol=1e-5 @test occursin("reject h_0", sprint(show, t)) # https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm # Columns are gear diameter and batch number gear = readdlm(joinpath(@__DIR__, "data", "gear.txt")) samples = reshape(gear[:,1],:,10) groups2 = tuple((samples[:,i] for i in 1:size(samples,1))...) # Brown-Forsythe Test l = BrownForsytheTest(groups2...) @test nobs(l) == fill(10, 10) @test dof(l) == (9,90) @test HypothesisTests.teststatistic(l) ≈ 1.705910 atol=1e-5 @test pvalue(l) ≈ 0.0991 atol=1e-4 @test occursin("reject h_0", sprint(show, l)) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
2126
using HypothesisTests, Test using Distributions @testset "Wald-Wolfowitz test" begin @testset "Many-Valued Observations" begin # Get set of dependent observations x = 1:1000 tst = WaldWolfowitzTest(x) @test tst.z ≈ -31.575 atol=1e-3 @test pvalue(tst) ≈ 8.052e-219 atol=1e-222 # Test consistency of z-statistics @test pvalue(tst) == pvalue(Normal(tst.μ, tst.σ), tst.nruns) @test pvalue(tst, tail=:left) == pvalue(Normal(tst.μ, tst.σ), tst.nruns, tail=:left) @test pvalue(tst, tail=:right) == pvalue(Normal(tst.μ, tst.σ), tst.nruns, tail=:right) expected_output = """ Wald-Wolfowitz Test ------------------- Population details: parameter of interest: Number of runs value under h_0: 501.0 point estimate: 2 Test summary: outcome with 95% confidence: reject h_0 two-sided p-value: <1e-99 Details: number of runs: 2 z-statistic: -31.575338477995764 """ output = sprint(show, tst) @test output == expected_output end @testset "Two-Valued Observations" begin # equivalent data as above (half under median half over) x = [falses(500); trues(500)] tst = WaldWolfowitzTest(x) @test tst.z ≈ -31.575 atol=1e-3 @test pvalue(tst) ≈ 8.052e-219 atol=1e-222 # Test consistency of z-statistics @test pvalue(tst) == pvalue(Normal(tst.μ, tst.σ), tst.nruns) @test pvalue(tst, tail=:left) == pvalue(Normal(tst.μ, tst.σ), tst.nruns, tail=:left) @test pvalue(tst, tail=:right) == pvalue(Normal(tst.μ, tst.σ), tst.nruns, tail=:right) expected_output = """ Wald-Wolfowitz Test ------------------- Population details: parameter of interest: Number of runs value under h_0: 501.0 point estimate: 2 Test summary: outcome with 95% confidence: reject h_0 two-sided p-value: <1e-99 Details: number of runs: 2 z-statistic: -31.575338477995764 """ output = sprint(show, tst) @test output == expected_output end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
6260
using HypothesisTests, Test @testset "White tests" begin X = [ 4.18 0.77 1.00; -3.41 0.73 1.00; 5.75 0.81 1.00; 0.05 0.80 1.00; -2.18 0.82 1.00; 3.88 0.81 1.00; 0.73 0.77 1.00; 5.70 0.77 1.00; -0.69 0.83 1.00; -8.14 0.87 1.00; 5.37 0.99 1.00; 1.87 0.95 1.00; 5.76 0.80 1.00; -0.79 0.89 1.00; -13.23 1.21 1.00; 3.97 1.26 1.00; 5.20 0.81 1.00; 3.16 0.61 1.00; 6.41 0.53 1.00; 1.72 0.64 1.00; 2.20 0.75 1.00; 1.06 0.95 1.00; 9.54 0.96 1.00; -4.75 1.31 1.00; -5.05 1.04 1.00; 0.48 1.07 1.00; 3.41 1.21 1.00; -2.21 1.08 1.00; 0.21 1.15 1.00; -2.37 1.35 1.00; -1.55 1.24 1.00; -6.91 1.28 1.00; -7.62 1.24 1.00; 4.81 1.21 1.00; 3.51 1.07 1.00; -3.68 0.87 1.00; -3.42 0.80 1.00; -6.03 0.92 1.00; -1.99 0.98 1.00; 3.20 1.13 1.00; -3.88 1.06 1.00; -3.35 0.96 1.00; -3.10 1.05 1.00; 11.14 0.76 1.00; 1.17 0.51 1.00; 11.27 0.59 1.00; 4.56 0.63 1.00; 0.78 0.67 1.00; 3.50 0.69 1.00; 2.40 0.62 1.00; 2.84 0.63 1.00; 6.71 0.71 1.00; 0.63 0.69 1.00; 3.11 0.67 1.00; -3.90 0.74 1.00; -0.41 0.76 1.00; 0.85 0.76 1.00; -3.56 0.76 1.00; 2.26 0.70 1.00; -1.78 0.73 1.00; -2.06 0.76 1.00; -4.62 0.71 1.00; 0.61 0.73 1.00; -0.56 0.81 1.00; -6.01 0.78 1.00; 1.59 0.75 1.00; -2.88 0.82 1.00; 10.44 0.83 1.00; -0.82 0.86 1.00; -1.01 1.00 1.00; -1.80 0.73 1.00; 1.73 0.64 1.00; 7.92 0.65 1.00; 1.11 0.58 1.00; -0.79 0.62 1.00; -0.94 0.72 1.00; 4.92 0.66 1.00; 1.16 0.55 1.00; -0.65 0.62 1.00; -1.03 0.55 1.00; -4.58 0.60 1.00; 3.79 0.65 1.00; 6.31 0.61 1.00; 3.66 0.65 1.00; 0.42 0.56 1.00; 6.72 0.53 1.00; 4.79 0.60 1.00; -1.31 0.52 1.00; 4.59 0.49 1.00; 0.90 0.52 1.00; -6.49 0.52 1.00; 6.16 0.46 1.00; -8.35 0.45 1.00; 4.47 0.46 1.00; 1.12 0.39 1.00; -3.13 0.49 1.00; 12.43 0.42 1.00; 4.36 0.43 1.00; 1.90 0.47 1.00; -2.14 0.44 1.00 ] e = [ 5.19346; 2.22296; 3.82622; 2.93541; 0.70453; 1.98955; 0.56655; 1.54306; 0.57363; -0.13346; 1.68565; 9.24558; 7.39317; 2.45484; -4.83724; -0.74742; -0.22633; 0.51537; 2.82822; 9.35943; 5.38263; 6.59691; 1.79080; 0.54506; 4.06661; -4.18808; 1.69414; 5.40963; 2.92762; -2.67351; -2.74613; -3.52752; -4.27775; 2.88245; -8.12566; 0.08760; 2.20495; -0.45509; -0.06959; 1.51330; 1.37878; -2.33046; 0.35730; -11.41189; -0.48083; 1.08917; 2.52333; 1.73218; 15.60426; -0.15961; -0.22174; -1.19174; 13.92022; 1.16044; 0.08087; -5.81547; -5.14199; -5.69918; -0.36585; -3.70294; 2.83687; -1.37631; -2.55403; -4.10796; 1.32092; -1.64056; -4.09963; -4.85728; -1.45496; -3.12612; -4.36648; -3.23379; 5.22893; 5.06730; -0.63041; -1.70377; -5.71335; -2.76831; 2.20443; -0.10174; -2.36727; -5.49859; -4.78093; -3.36665; 5.12027; -3.03180; -2.52035; 3.10913; -3.51388; -0.70389; -1.01963; -8.78989; 2.95170; -3.95464; -4.01258; -1.92315; -4.94209; 5.29138; 1.28435; 0.28832 ] atol = 1e-4 w_test = WhiteTest(X, e, type = :linear) @test pvalue(w_test) ≈ 0.1287 atol=atol w_test = WhiteTest(X, e, type = :linear_and_squares) @test pvalue(w_test) ≈ 0.2774 atol=atol w_test = WhiteTest(X, e) w_pval = pvalue(w_test) @test w_pval ≈ 0.3458 atol=atol refstr = """ White's (or Breusch-Pagan's) test for heteroskedasticity -------------------------------------------------------- Population details: parameter of interest: T*R2 value under h_0: 0 point estimate: $(sprint(show, w_test.lm; context=:compact => true)) Test summary: outcome with 95% confidence: fail to reject h_0 one-sided p-value: $(round(w_pval,digits=4)) Details: T*R^2 statistic: $(sprint(show, w_test.lm ; context=:compact => true)) degrees of freedom: $(sprint(show, w_test.dof ; context=:compact => true)) type: $(w_test.type) """ buffer = IOBuffer() show(buffer, w_test) str = String(take!(buffer)) @test str == refstr @test_throws DimensionMismatch WhiteTest([rand(3) ones(3)], rand(4)) @test_throws ArgumentError WhiteTest(ones(4,1), rand(4)) @test_throws ArgumentError WhiteTest([zeros(4) rand(4)], rand(4)) @test_throws ArgumentError WhiteTest(rand(4,2), rand(4)) bp_test = BreuschPaganTest(X, e) @test pvalue(bp_test) ≈ 0.1287 atol=atol show(IOBuffer(), bp_test) end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
4330
using HypothesisTests, Test using HypothesisTests: default_tail @testset "Wilcoxon" begin @testset "Basic exact test" begin @test abs(@inferred(pvalue(ExactSignedRankTest([1:10;], [2:2:20;]))) - 0.0020) <= 1e-4 @test abs(@inferred(pvalue(ExactSignedRankTest([2:2:20;], [1:10;]))) - 0.0020) <= 1e-4 @test abs(@inferred(pvalue(ExactSignedRankTest([1:10;], [2:2:16; -1; 1]))) - 0.4316) <= 1e-4 @test abs(@inferred(pvalue(ExactSignedRankTest([2:2:16; -1; 1], [1:10;]))) - 0.4316) <= 1e-4 @test default_tail(ExactSignedRankTest([1:10;], [2:2:20;])) == :both show(IOBuffer(), ExactSignedRankTest([1:10;], [2:2:20;])) end @testset "Exact with ties" begin @test abs(@inferred(pvalue(ExactSignedRankTest([1:10;], [1:10;]))) - 1) <= 1e-4 @test abs(@inferred(pvalue(ExactSignedRankTest([1:10;], [2:11;]))) - 0.0020) <= 1e-4 @test abs(@inferred(pvalue(ExactSignedRankTest([2:11;], [1:10;]))) - 0.0020) <= 1e-4 @test abs(@inferred(pvalue(ExactSignedRankTest(1:10, [1:5; ones(5)]))) - 0.0625) <= 1e-4 @test abs(@inferred(pvalue(ExactSignedRankTest([1:5; ones(5)], [1:10;]))) - 0.0625) <= 1e-4 show(IOBuffer(), ExactSignedRankTest([1:10;], [1:10;])) end @testset "Approximate test" begin @test abs(@inferred(pvalue(ApproximateSignedRankTest([1:10;], [2:2:20;]))) - 0.005922) <= 1e-6 @test abs(@inferred(pvalue(ApproximateSignedRankTest([2:2:20;], [1:10;]))) - 0.005922) <= 1e-6 @test abs(@inferred(pvalue(ApproximateSignedRankTest([1:10;], [2:2:16; -1; 1]))) - 0.4148) <= 1e-4 @test abs(@inferred(pvalue(ApproximateSignedRankTest([2:2:16; -1; 1], [1:10;]))) - 0.4148) <= 1e-4 @test default_tail(ApproximateSignedRankTest([1:10;], [2:2:20;])) == :both show(IOBuffer(), ApproximateSignedRankTest([1:10;], [2:2:20;])) end @testset "Approximate with ties" begin @test abs(@inferred(pvalue(ApproximateSignedRankTest([1:10;], [1:10;]))) - 1) <= 1e-4 @test abs(@inferred(pvalue(ApproximateSignedRankTest([1:10;], [2:11;]))) - 0.001904) <= 1e-6 @test abs(@inferred(pvalue(ApproximateSignedRankTest([2:11;], [1:10;]))) - 0.001904) <= 1e-6 @test abs(@inferred(pvalue(ApproximateSignedRankTest([1:10;], [1:5; ones(5)]))) - 0.05906) <= 1e-5 @test abs(@inferred(pvalue(ApproximateSignedRankTest([1:5; ones(5)], 1:10))) - 0.05906) <= 1e-5 show(IOBuffer(), ApproximateSignedRankTest([1:10;], [1:10;])) end @testset "Tests for automatic selection" begin @test abs(@inferred(pvalue(SignedRankTest([1:10;], [2:2:20;]))) - 0.0020) <= 1e-4 @test abs(@inferred(pvalue(SignedRankTest([1:10;], [2:11;]))) - 0.0020) <= 1e-4 @test default_tail(SignedRankTest([1:10;], [2:2:20;])) == :both show(IOBuffer(), SignedRankTest([1:10;], [2:2:20;])) end @testset "One Sample tests" begin # P-value computed using R wilcox.test @test abs(@inferred(pvalue(SignedRankTest([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] .- 10.1))) - 0.09460449) <= 1e-4 # P-value computed using R wilcox.test @test abs(@inferred(pvalue(SignedRankTest([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] .- 10.1))) - 0.1928101) <= 1e-4 end @testset "One Sample tests with ties" begin # P-value computed using R package exactRankTests wilcox.exact @test abs(@inferred(pvalue(SignedRankTest([1,2,3,4,5,6,7,10,10,10,10,10,13,14,15] .- 10.1))) - 0.04052734) <= 1e-4 # P-value computed using R wilcox.test @test abs(@inferred(pvalue(SignedRankTest([1,2,3,4,5,6,7,10,10,10,10,10,13,14,15,16] .- 10.1))) - 0.1021964) <= 1e-4 end @testset "Issue 128" begin @test @inferred(pvalue(SignedRankTest([54.5, 54.5, 95.0, 51.5]), tail=:left)) == 1 @test @inferred(pvalue(SignedRankTest([54.5, 54.5, 95.0, 51.5]), tail=:right)) == 0.0625 end @testset "Test confidence interval" begin x = [-7.8, -6.9, -4.7, 3.7, 6.5, 8.7, 9.1, 10.1, 10.8, 13.6, 14.4, 16.6, 20.2, 22.4, 23.5] @test isapprox(@inferred(confint(ExactSignedRankTest(x)))[1], 3.3, atol=1e-4) @test isapprox(@inferred(confint(ExactSignedRankTest(x)))[2], 15.5, atol=1e-4) @test isapprox(@inferred(confint(ApproximateSignedRankTest(x)))[1], 3.3, atol=1e-4) @test isapprox(@inferred(confint(ApproximateSignedRankTest(x)))[2], 15.5, atol=1e-4) @test isapprox(@inferred(confint(SignedRankTest(x); tail=:left))[1], 4.45, atol=1e-4) @test isapprox(@inferred(confint(SignedRankTest(x); tail=:right))[2], 14.45, atol=1e-4) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
code
3515
using HypothesisTests, Test using Distributions using HypothesisTests: default_tail @testset "Z test" begin # This is always the null in our tests. null = Normal(0.0, 1.0) @testset "One sample" begin x = -5:5 @test pvalue(OneSampleZTest(x)) == 1 x = -5:10 m, s, n = mean(x), std(x), length(x) se = s / sqrt(n) z = (m - 0) / se tst = OneSampleZTest(x) @test pvalue(tst) ≈ 2 * min(cdf(null, z), ccdf(null, z)) @test pvalue(tst; tail=:left) ≈ cdf(null, z) @test pvalue(tst; tail=:right) ≈ ccdf(null, z) @test default_tail(tst) == :both show(IOBuffer(), tst) tst = OneSampleZTest(m, s, n) @test pvalue(tst) ≈ 2 * min(cdf(null, z), ccdf(null, z)) @test confint(tst)[1] ≈ m + quantile(null, 0.05 / 2) * se @test confint(tst)[2] ≈ m + cquantile(null, 0.05 / 2) * se @test confint(tst; level=0.9)[1] ≈ m + quantile(null, 0.10 / 2) * se @test confint(tst; level=0.9)[2] ≈ m + cquantile(null, 0.10 / 2) * se @test confint(tst; tail=:left)[1] ≈ -Inf @test confint(tst; tail=:left)[2] ≈ m + cquantile(null, 0.05) * se @test confint(tst; tail=:right)[1] ≈ m + quantile(null, 0.05) * se @test confint(tst; tail=:right)[2] ≈ Inf @test_throws ArgumentError confint(tst; tail=2) show(IOBuffer(), tst) x = -10:5 m, s, n = mean(x), std(x), length(x) se = s / sqrt(n) z = (m - 0) / se tst = OneSampleZTest(x) @test pvalue(tst) ≈ 2 * min(cdf(null, z), ccdf(null, z)) @test pvalue(tst; tail=:left) ≈ cdf(null, z) @test pvalue(tst; tail=:right) ≈ ccdf(null, z) show(IOBuffer(), tst) tst = OneSampleZTest(m, s, n) @test pvalue(tst) ≈ 2 * min(cdf(null, z), ccdf(null, z)) @test confint(tst)[1] ≈ m + quantile(null, 0.05 / 2) * se @test confint(tst)[2] ≈ m + cquantile(null, 0.05 / 2) * se @test confint(tst; level=0.9)[1] ≈ m + quantile(null, 0.10 / 2) * se @test confint(tst; level=0.9)[2] ≈ m + cquantile(null, 0.10 / 2) * se @test confint(tst; tail=:left)[1] ≈ -Inf @test confint(tst; tail=:left)[2] ≈ m + cquantile(null, 0.05) * se @test confint(tst; tail=:right)[1] ≈ m + quantile(null, 0.05) * se @test confint(tst; tail=:right)[2] ≈ Inf show(IOBuffer(), tst) end @testset "Paired samples" begin x, y = [1, 1, 2, 1, 0], [0, 1, 1, 1, 0] m, s, n = mean(x - y), std(x - y), length(x - y) se = s / sqrt(n) z = (m - 0) / se tst = OneSampleZTest(x, y) @test pvalue(tst) ≈ 2 * min(cdf(null, z), ccdf(null, z)) end @testset "Two sample" begin a1 = [30.02, 29.99, 30.11, 29.97, 30.01, 29.99] a2 = [29.89, 29.93, 29.72, 29.98, 30.02, 29.98] tst = EqualVarianceZTest(a1, a2) m1, s1sq, n1 = mean(a1), var(a1), length(a1) m2, s2sq, n2 = mean(a2), var(a2), length(a2) xbar = (m1 - m2) avg_var = (n1 - 1) / (n1 + n2 - 2) * s1sq + (n2 - 1) / (n1 + n2 - 2) * s2sq se = sqrt(avg_var / n1 + avg_var / n2) z = xbar / se @test tst.z ≈ z @test pvalue(tst) ≈ 2 * min(cdf(null, z), ccdf(null, z)) @test pvalue(tst; tail=:left) ≈ cdf(null, z) @test pvalue(tst; tail=:right) ≈ ccdf(null, z) @test default_tail(tst) == :both @test confint(tst)[1] ≈ xbar + quantile(null, 0.05 / 2) * se @test confint(tst)[2] ≈ xbar + cquantile(null, 0.05 / 2) * se show(IOBuffer(), tst) tst = UnequalVarianceZTest(a1, a2) se = sqrt(s1sq / n1 + s2sq / n2) z = xbar / se @test tst.z ≈ z @test pvalue(tst) ≈ 2 * min(cdf(null, z), ccdf(null, z)) @test pvalue(tst; tail=:left) ≈ cdf(null, z) @test pvalue(tst; tail=:right) ≈ ccdf(null, z) @test confint(tst)[1] ≈ xbar + quantile(null, 0.05 / 2) * se @test confint(tst)[2] ≈ xbar + cquantile(null, 0.05 / 2) * se show(IOBuffer(), tst) end end
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
docs
1420
## HypothesisTests.jl *HypothesisTests.jl* is a Julia package that implements a wide range of hypothesis tests. - **Build & Testing Status:** [![Build Status](https://github.com/JuliaStats/HypothesisTests.jl/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/JuliaStats/HypothesisTests.jl/actions/workflows/ci.yml?query=branch%3Amaster) [![Coverage Status](https://codecov.io/gh/JuliaStats/HypothesisTests.jl/branch/master/graph/badge.svg?token=ztSoTXYVhb)](https://codecov.io/gh/JuliaStats/HypothesisTests.jl) - **Documentation**: [![][docs-stable-img]][docs-stable-url] [![][docs-latest-img]][docs-latest-url] [docs-latest-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-latest-url]: http://JuliaStats.github.io/HypothesisTests.jl/dev/ [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: http://JuliaStats.github.io/HypothesisTests.jl/stable/ ## Quick start Some examples: ```julia using HypothesisTests pvalue(OneSampleTTest(x)) pvalue(OneSampleTTest(x), tail=:left) pvalue(OneSampleTTest(x), tail=:right) confint(OneSampleTTest(x)) confint(OneSampleTTest(x, tail=:left)) confint(OneSampleTTest(x, tail=:right)) OneSampleTTest(x).t OneSampleTTest(x).df pvalue(OneSampleTTest(x, y)) pvalue(EqualVarianceTTest(x, y)) pvalue(UnequalVarianceTTest(x, y)) pvalue(MannWhitneyUTest(x, y)) pvalue(SignedRankTest(x, y)) pvalue(SignedRankTest(x)) ```
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
docs
211
# HypothesisTests package This package implements several hypothesis tests in Julia. ```@contents Pages = ["methods.md", "parametric.md", "nonparametric.md", "time_series.md", "multivariate.md"] Depth = 2 ```
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
docs
376
# Methods This page documents the generic `confint`, `pvalue` and `testname` methods which are supported by most tests. Some particular tests support additional arguments: see the documentation for the relevant methods provided in sections covering these tests. ## Confidence interval ```@docs confint ``` ## p-value ```@docs pvalue ``` ## Test name ```@docs testname ```
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
docs
402
# Multivariate tests ## Hotelling's ``T^2`` test ```@docs OneSampleHotellingT2Test EqualCovHotellingT2Test UnequalCovHotellingT2Test ``` ## Equality of covariance matrices Bartlett's test for equality of two covariance matrices is provided. This is equivalent to Box's ``M``-test for two groups. ```@docs BartlettTest ``` ## Correlation and partial correlation test ```@docs CorrelationTest ```
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
docs
1112
# Nonparametric tests ## Anderson-Darling test Available are both one-sample and ``k``-sample tests. ```@docs OneSampleADTest KSampleADTest ``` ## Binomial test ```@docs BinomialTest confint(::BinomialTest) ``` ## Fisher exact test ```@docs FisherExactTest confint(::FisherExactTest) pvalue(::FisherExactTest) ``` ## Kolmogorov-Smirnov test Available are an exact one-sample test and approximate (i.e. asymptotic) one- and two-sample tests. ```@docs ExactOneSampleKSTest ApproximateOneSampleKSTest ApproximateTwoSampleKSTest ``` ## Kruskal-Wallis rank sum test ```@docs KruskalWallisTest ``` ## Mann-Whitney U test ```@docs MannWhitneyUTest ExactMannWhitneyUTest ApproximateMannWhitneyUTest ``` ## Sign test ```@docs SignTest ``` ## Wald-Wolfowitz independence test ```@docs WaldWolfowitzTest ``` ## Wilcoxon signed rank test ```@docs SignedRankTest ExactSignedRankTest ApproximateSignedRankTest ``` ## Permutation test ```@docs ExactPermutationTest ApproximatePermutationTest ``` ## Fligner-Killeen test ```@docs FlignerKilleenTest ``` ## Shapiro-Wilk test ```@docs ShapiroWilkTest ```
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
docs
618
# Parametric tests ```@setup ht using HypothesisTests ``` ## Power divergence test ```@docs PowerDivergenceTest confint(::PowerDivergenceTest) ``` ## Pearson chi-squared test ```@docs ChisqTest ``` ## Multinomial likelihood ratio test ```@docs MultinomialLRTest ``` ## t-test ```@docs OneSampleTTest EqualVarianceTTest UnequalVarianceTTest ``` ## z-test ```@docs OneSampleZTest EqualVarianceZTest UnequalVarianceZTest ``` ## F-test ```@docs VarianceFTest ``` ## One-way ANOVA Test ```@docs OneWayANOVATest ``` ## Levene's Test ```@docs LeveneTest ``` ## Brown-Forsythe Test ```@docs BrownForsytheTest ```
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.11.3
6c3ce99fdbaf680aa6716f4b919c19e902d67c9c
docs
465
# Time series tests ## Durbin-Watson test ```@docs DurbinWatsonTest ``` ## Box-Pierce and Ljung-Box tests ```@docs BoxPierceTest LjungBoxTest ``` ## Breusch-Godfrey test ```@docs BreuschGodfreyTest ``` ## Jarque-Bera test ```@docs JarqueBeraTest ``` ## Augmented Dickey-Fuller test ```@docs ADFTest ``` ## Clark-West test ```@docs ClarkWestTest ``` ## Diebold-Mariano test ```@docs DieboldMarianoTest ``` ## White test ```@docs WhiteTest BreuschPaganTest ```
HypothesisTests
https://github.com/JuliaStats/HypothesisTests.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
874
using Documenter # Print `@debug` statements (https://github.com/JuliaDocs/Documenter.jl/issues/955) if haskey(ENV, "GITHUB_ACTIONS") ENV["JULIA_DEBUG"] = "Documenter" end using MCMCDiagnosticTools DocMeta.setdocmeta!( MCMCDiagnosticTools, :DocTestSetup, :(using MCMCDiagnosticTools); recursive=true ) makedocs(; modules=[MCMCDiagnosticTools], authors="David Widmann", repo=Remotes.GitHub("TuringLang", "MCMCDiagnosticTools.jl"), sitename="MCMCDiagnosticTools.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://turinglang.github.io/MCMCDiagnosticTools.jl", assets=String[], ), pages=["Home" => "index.md"], warnonly=:footnote, checkdocs=:exports, ) deploydocs(; repo="github.com/TuringLang/MCMCDiagnosticTools.jl", push_preview=true, devbranch="main" )
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
883
module MCMCDiagnosticTools using AbstractFFTs: AbstractFFTs using DataAPI: DataAPI using DataStructures: DataStructures using Distributions: Distributions using MLJModelInterface: MLJModelInterface as MMI using SpecialFunctions: SpecialFunctions using StatsBase: StatsBase using StatsFuns: StatsFuns, sqrt2 using Tables: Tables using LinearAlgebra: LinearAlgebra using Random: Random using Statistics: Statistics export bfmi export discretediag export ess, ess_rhat, rhat, AutocovMethod, FFTAutocovMethod, BDAAutocovMethod export gelmandiag, gelmandiag_multivariate export gewekediag export heideldiag export mcse export rafterydiag export rstar include("utils.jl") include("bfmi.jl") include("discretediag.jl") include("ess_rhat.jl") include("gelmandiag.jl") include("gewekediag.jl") include("heideldiag.jl") include("mcse.jl") include("rafterydiag.jl") include("rstar.jl") end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
1984
""" bfmi(energy::AbstractVector{<:Real}) -> Real bfmi(energy::AbstractMatrix{<:Real}; dims::Int=1) -> AbstractVector{<:Real} Calculate the estimated Bayesian fraction of missing information (BFMI). When sampling with Hamiltonian Monte Carlo (HMC), BFMI quantifies how well momentum resampling matches the marginal energy distribution. The current advice is that values smaller than 0.3 indicate poor sampling. However, this threshold is provisional and may change. A BFMI value below the threshold often indicates poor adaptation of sampling parameters or that the target distribution has heavy tails that were not well explored by the Markov chain. For more information, see Section 6.1 of [^Betancourt2018] or [^Betancourt2016] for a complete account. `energy` is either a vector of Hamiltonian energies of draws or a matrix of energies of draws for multiple chains. `dims` indicates the dimension in `energy` that contains the draws. The default `dims=1` assumes `energy` has the shape `draws` or `(draws, chains)`. If a different shape is provided, `dims` must be set accordingly. If `energy` is a vector, a single BFMI value is returned. Otherwise, a vector of BFMI values for each chain is returned. [^Betancourt2018]: Betancourt M. (2018). A Conceptual Introduction to Hamiltonian Monte Carlo. [arXiv:1701.02434v2](https://arxiv.org/pdf/1701.02434v2.pdf) [stat.ME] [^Betancourt2016]: Betancourt M. (2016). Diagnosing Suboptimal Cotangent Disintegrations in Hamiltonian Monte Carlo. [arXiv:1604.00695v1](https://arxiv.org/pdf/1604.00695v1.pdf) [stat.ME] """ function bfmi end function bfmi(energy::AbstractVector{<:Real}) return Statistics.mean(abs2, diff(energy)) / Statistics.var(energy) end function bfmi(energy::AbstractMatrix{<:Real}; dims::Int=1) energy_diff = diff(energy; dims=dims) energy_var = Statistics.var(energy; dims=dims) return dropdims(Statistics.mean(abs2.(energy_diff); dims=dims) ./ energy_var; dims=dims) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
13404
function update_hangartner_temp_vars!(u::Matrix{Int}, X::Matrix{Int}, t::Int) d = size(X, 2) for j in 1:d u[X[t, j], j] += 1 end end function hangartner_inner(Y::AbstractMatrix, m::Int) ## setup temp vars n, d = size(Y) # Count for each category in each chain u = zeros(Int, m, d) v = zeros(Int, m, d) for t in 1:n # fill out temp vars update_hangartner_temp_vars!(u, Y, t) end phia, chi_stat, m_tot = weiss_sub(u, v, n) return (n * sum(chi_stat), m_tot) end """ weiss(X::AbstractMatrix) Assess the convergence of the MCMC chains with the Weiss procedure. It computes ``\\frac{X^2}{c}`` and evaluates a p-value from the ``\\chi^2`` distribution with ``(|R| − 1)(s − 1)`` degrees of freedom. """ function weiss(X::AbstractMatrix) ## number of iterations, number of chains n, d = size(X) ## mapping of values to integers v_dict = Dict{eltype(X),Int}() ## max unique categories mc = map(c -> length(unique(X[:, c])), 1:d) m = length(unique(X)) ## counter of number of unique values in each chain r0 = 0 ## Count for each category in each chain u = zeros(Int, m, d) ## Number of times a category did not transition in each chain v = zeros(Int, m, d) for t in 1:n for c in 1:d if !(X[t, c] in keys(v_dict)) r0 += 1 v_dict[X[t, c]] = r0 end idx1 = v_dict[X[t, c]] u[idx1, c] += 1 if t > 1 if X[t - 1, c] == X[t, c] v[idx1, c] += 1 end end end end phia, chi_stat, m_tot = weiss_sub(u, v, n) ca = (1 + phia) / (1 - phia) stat = (n / ca) * sum(chi_stat) pval = NaN if ((m_tot - 1) * (d - 1)) >= 1 pval = Distributions.ccdf(Distributions.Chisq((m_tot - 1) * (d - 1)), stat) end return (stat, m_tot, pval, ca) end function weiss_sub(u::Matrix{Int}, v::Matrix{Int}, t::Int) m, d = size(u) nt = 0.0 dt = 0.0 m_tot = 0 mp = zeros(Float64, m, d) ma = zeros(Float64, m) phia = 0.0 ca = 0.0 df = 0.0 chi_stat = zeros(Float64, d) for j in 1:m p1 = 0.0 p2 = 0.0 for l in 1:d #aggregate p1 += v[j, l] / (d * (t - 1)) p2 += u[j, l] / (d * t) #per chain mp[j, l] = u[j, l] / t ma[j] += u[j, l] / (d * t) end nt += p1 dt += p2^2 if ma[j] > 0 m_tot += 1 for l in 1:d chi_stat[l] += (mp[j, l] - ma[j])^2 / ma[j] end end end phia = 1.0 + (1.0 / t) - ((1 - nt) / (1 - dt)) phia = min(max(phia, 0.0), 1.0 - eps()) return (phia, chi_stat, m_tot) end function update_billingsley_temp_vars!(f::Array{Int,3}, X::Matrix{Int}, t::Int) d = size(X, 2) for j in 1:d if t > 1 f[X[t - 1, j], X[t, j], j] += 1 end end end function billingsley_sub(f::Array{Int,3}) df = 0.0 stat = 0.0 m, d = size(f)[2:3] # marginal transitions, i.e. # number of transitions from each category mf = mapslices(sum, f; dims=[2]) # For each category, number of chains for which # that category was present A = vec(mapslices((x) -> sum(x .> 0), mf; dims=[3])) # For each category, number of categories it # transitioned to B = vec(mapslices((x) -> sum(x .> 0), mapslices(sum, f; dims=[3]); dims=[2])) # transition probabilities in each chain P = f ./ mf # transition probabilities mP = (mapslices(sum, f; dims=[3]) ./ mapslices(sum, mf; dims=[3])) replace!(mP, NaN => 0) mP = reshape(mP, size(mP)[1:2]) idx = findall((A .* B) .> 0) for j in idx #df for billingsley df += (A[j] - 1) * (B[j] - 1) #billingsley for k in idx if (mP[j, k] > 0.0) for l in 1:d if mf[j, 1, l] > 0 && isfinite(P[j, k, l]) stat += mf[j, 1, l] * (P[j, k, l] - mP[j, k])^2 / mP[j, k] end end end end end return (stat, df, mP) end function bd_inner(Y::AbstractMatrix, m::Int) num_iters, num_chains = size(Y) # Transition matrix for each chain f = zeros(Int, m, m, num_chains) for t in 1:num_iters # fill out temp vars update_billingsley_temp_vars!(f, Y, t) end return billingsley_sub(f) end @doc raw""" simulate_DAR1!(X::Matrix{Int}, phi::Float64, sampler) Simulate a DAR(1) model independently in each column of `X`. The DAR(1) model ``(X_t)_{t \geq 0}`` is defined by ```math X_t = \alpha_t X_{t-1} + (1 - \alpha_t) \epsilon_{t-1}, ``` where ```math \begin{aligned} X_1 \sim \text{sampler}, \\ \alpha_t \sim \operatorname{Bernoulli}(\phi), \\ \epsilon_{t-1} \sim \text{sampler}, \end{aligned} ``` are independent random variables. """ function simulate_DAR1!(X::Matrix{Int}, phi::Float64, sampler) n = size(X, 1) n > 0 || error("output matrix must be non-empty") # for all simulations @inbounds for j in axes(X, 2) # sample first value from categorical distribution with probabilities `prob` X[1, j] = rand(sampler) for t in 2:n # compute next value X[t, j] = if rand() <= phi # copy previous value with probability `phi` X[t - 1, j] else # sample value with probability `1-phi` rand(sampler) end end end return X end function simulate_MC(N::Int, P::Matrix{Float64}) X = zeros(Int, N) n, m = size(P) X[1] = StatsBase.sample(1:n) for i in 2:N X[i] = StatsBase.wsample(1:n, vec(P[X[i - 1], :])) end return X end function diag_all( X::AbstractMatrix, method::Symbol, nsim::Int, start_iter::Int, step_size::Int ) ## number of iterations, number of chains n, d = size(X) ## mapping of values to integers v_dict = Dict{eltype(X),Int}() ## max unique categories mc = map(c -> length(unique(X[:, c])), 1:d) m = length(unique(X)) ## counter of number of unique values in each chain r0 = 0 ## Count for each category in each chain u = zeros(Int, m, d) ## Number of times a category did not transition in each chain v = zeros(Int, m, d) ## transition matrix for each chain f = zeros(Int, m, m, d) length_result = length(start_iter:step_size:n) result = ( stat=Vector{Float64}(undef, length_result), df=Vector{Float64}(undef, length_result), pvalue=Vector{Float64}(undef, length_result), ) result_iter = 1 for t in 1:n for c in 1:d if !(X[t, c] in keys(v_dict)) r0 += 1 v_dict[X[t, c]] = r0 end idx1 = v_dict[X[t, c]] u[idx1, c] += 1 if t > 1 idx2 = v_dict[X[t - 1, c]] f[idx1, idx2, c] += 1 if X[t - 1, c] == X[t, c] v[idx1, c] += 1 end end end if ((t >= start_iter) && (((t - start_iter) % step_size) == 0)) phia, chi_stat, m_tot = weiss_sub(u, v, t) hot_stat, df, mP = billingsley_sub(f) phat = mapslices(sum, u; dims=[2])[:, 1] / sum(mapslices(sum, u; dims=[2])) ca = (1 + phia) / (1 - phia) stat = NaN pval = NaN df0 = NaN if method == :hangartner stat = t * sum(chi_stat) df0 = (m - 1) * (d - 1) if m > 1 && !isnan(stat) pval = Distributions.ccdf(Distributions.Chisq(df0), stat) end elseif method == :weiss stat = (t / ca) * sum(chi_stat) df0 = (m - 1) * (d - 1) pval = NaN if m > 1 && !isnan(stat) pval = Distributions.ccdf(Distributions.Chisq(df0), stat) end elseif method == :DARBOOT stat = t * sum(chi_stat) sampler_phat = Distributions.sampler(Distributions.Categorical(phat)) bstats = zeros(nsim) Y = Matrix{Int}(undef, t, d) for b in 1:nsim simulate_DAR1!(Y, phia, sampler_phat) s = hangartner_inner(Y, m)[1] @inbounds bstats[b] = s end non_nan_bstats = filter(!isnan, bstats) df0 = Statistics.mean(non_nan_bstats) pval = Statistics.mean(stat <= x for x in non_nan_bstats) elseif method == :MCBOOT bstats = zeros(Float64, nsim) for b in 1:nsim Y = reduce(hcat, [simulate_MC(t, mP) for j in 1:d]) s = hangartner_inner(Y, m)[1] bstats[b] = s end non_nan_bstats = filter(!isnan, bstats) df0 = Statistics.mean(non_nan_bstats) pval = Statistics.mean(stat <= x for x in non_nan_bstats) elseif method == :billingsley stat = hot_stat df0 = df if df > 0 && !isnan(hot_stat) pval = Distributions.ccdf(Distributions.Chisq(df), hot_stat) end elseif method == :billingsleyBOOT stat = hot_stat bstats = zeros(Float64, nsim) for b in 1:nsim Y = reduce(hcat, [simulate_MC(t, mP) for j in 1:d]) (s, sd) = bd_inner(Y, m)[1:2] bstats[b] = s / sd end non_nan_bstats = filter(!isnan, bstats) df0 = Statistics.mean(non_nan_bstats) statodf = stat / df pval = Statistics.mean(statodf <= x for x in non_nan_bstats) else error("Unexpected") end result.stat[result_iter] = stat result.df[result_iter] = df0 result.pvalue[result_iter] = pval result_iter += 1 end end return result end function discretediag_sub( c::AbstractArray{<:Real,3}, frac::Real, method::Symbol, nsim::Int, start_iter::Int, step_size::Int, ) num_iters, num_chains, num_vars = size(c) ## Between-chain diagnostic length_results = length(start_iter:step_size:num_iters) plot_vals_stat = Matrix{Float64}(undef, length_results, num_vars) plot_vals_pval = Matrix{Float64}(undef, length_results, num_vars) between_chain_vals = ( stat=Vector{Float64}(undef, num_vars), df=Vector{Float64}(undef, num_vars), pvalue=Vector{Float64}(undef, num_vars), ) for j in 1:num_vars X = convert(AbstractMatrix{Int}, c[:, :, j]) result = diag_all(X, method, nsim, start_iter, step_size) plot_vals_stat[:, j] .= result.stat ./ result.df plot_vals_pval[:, j] .= result.pvalue between_chain_vals.stat[j] = result.stat[end] between_chain_vals.df[j] = result.df[end] between_chain_vals.pvalue[j] = result.pvalue[end] end ## Within-chain diagnostic within_chain_vals = ( stat=Matrix{Float64}(undef, num_vars, num_chains), df=Matrix{Float64}(undef, num_vars, num_chains), pvalue=Matrix{Float64}(undef, num_vars, num_chains), ) for k in 1:num_chains for j in 1:num_vars x = convert(AbstractVector{Int}, c[:, k, j]) idx1 = 1:round(Int, frac * num_iters) idx2 = round(Int, num_iters - frac * num_iters + 1):num_iters x1 = x[idx1] x2 = x[idx2] n_min = min(length(x1), length(x2)) Y = [x1[1:n_min] x2[(end - n_min + 1):end]] result = diag_all(Y, method, nsim, n_min, step_size) within_chain_vals.stat[j, k] = result.stat[end] within_chain_vals.df[j, k] = result.df[end] within_chain_vals.pvalue[j, k] = result.pvalue[end] end end return between_chain_vals, within_chain_vals, plot_vals_stat, plot_vals_pval end """ discretediag(samples::AbstractArray{<:Real,3}; frac=0.3, method=:weiss, nsim=1_000) Compute discrete diagnostic on `samples` with shape `(draws, chains, parameters)`. `method` can be one of `:weiss`, `:hangartner`, `:DARBOOT`, `:MCBOOT`, `:billinsgley`, and `:billingsleyBOOT`. # References Benjamin E. Deonovic, & Brian J. Smith. (2017). Convergence diagnostics for MCMC draws of a categorical variable. """ function discretediag( chains::AbstractArray{<:Real,3}; frac::Real=0.3, method::Symbol=:weiss, nsim::Int=1000 ) valid_methods = (:weiss, :hangartner, :DARBOOT, :MCBOOT, :billingsley, :billingsleyBOOT) method in valid_methods || throw( ArgumentError("`method` must be one of :" * join(valid_methods, ", :", " and :")), ) 0 < frac < 1 || throw(ArgumentError("`frac` must be in (0,1)")) num_iters = size(chains, 1) between_chain_vals, within_chain_vals, _, _ = discretediag_sub( chains, frac, method, nsim, num_iters, num_iters ) return between_chain_vals, within_chain_vals end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
24242
# methods abstract type AbstractAutocovMethod end const _DOC_SPLIT_CHAINS = """`split_chains` indicates the number of chains each chain is split into. When `split_chains > 1`, then the diagnostics check for within-chain convergence. When `d = mod(draws, split_chains) > 0`, i.e. the chains cannot be evenly split, then 1 draw is discarded after each of the first `d` splits within each chain.""" """ AutocovMethod <: AbstractAutocovMethod The `AutocovMethod` uses a standard algorithm for estimating the mean autocovariance of MCMC chains. It is is based on the discussion by [^VehtariGelman2021] and uses the biased estimator of the autocovariance, as discussed by [^Geyer1992]. [^VehtariGelman2021]: Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Bürkner, P. C. (2021). Rank-normalization, folding, and localization: An improved ``\\widehat {R}`` for assessing convergence of MCMC. Bayesian Analysis. doi: [10.1214/20-BA1221](https://doi.org/10.1214/20-BA1221) arXiv: [1903.08008](https://arxiv.org/abs/1903.08008) [^Geyer1992]: Geyer, C. J. (1992). Practical Markov Chain Monte Carlo. Statistical Science, 473-483. """ struct AutocovMethod <: AbstractAutocovMethod end """ FFTAutocovMethod <: AbstractAutocovMethod The `FFTAutocovMethod` uses a standard algorithm for estimating the mean autocovariance of MCMC chains. The algorithm is the same as the one of [`AutocovMethod`](@ref) but this method uses fast Fourier transforms (FFTs) for estimating the autocorrelation. !!! info To be able to use this method, you have to load a package that implements the [AbstractFFTs.jl](https://github.com/JuliaMath/AbstractFFTs.jl) interface such as [FFTW.jl](https://github.com/JuliaMath/FFTW.jl) or [FastTransforms.jl](https://github.com/JuliaApproximation/FastTransforms.jl). """ struct FFTAutocovMethod <: AbstractAutocovMethod end """ BDAAutocovMethod <: AbstractAutocovMethod The `BDAAutocovMethod` uses a standard algorithm for estimating the mean autocovariance of MCMC chains. It is is based on the discussion by [^VehtariGelman2021]. and uses the variogram estimator of the autocorrelation function discussed by [^BDA3]. [^VehtariGelman2021]: Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Bürkner, P. C. (2021). Rank-normalization, folding, and localization: An improved ``\\widehat {R}`` for assessing convergence of MCMC. Bayesian Analysis. doi: [10.1214/20-BA1221](https://doi.org/10.1214/20-BA1221) arXiv: [1903.08008](https://arxiv.org/abs/1903.08008) [^BDA3]: Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian data analysis. CRC press. """ struct BDAAutocovMethod <: AbstractAutocovMethod end # caches struct AutocovCache{T,S} samples::Matrix{T} chain_var::Vector{S} end struct FFTAutocovCache{T,S,C,P,I} samples::Matrix{T} chain_var::Vector{S} samples_cache::C plan::P invplan::I end mutable struct BDAAutocovCache{T,S,M} samples::Matrix{T} chain_var::Vector{S} mean_chain_var::M end function build_cache(::AutocovMethod, samples::Matrix, var::Vector) # check arguments niter, nchains = size(samples) length(var) == nchains || throw(DimensionMismatch()) return AutocovCache(samples, var) end function build_cache(::FFTAutocovMethod, samples::Matrix, var::Vector) # check arguments niter, nchains = size(samples) length(var) == nchains || throw(DimensionMismatch()) # create cache for FFT T = complex(eltype(samples)) n = nextprod([2, 3], 2 * niter - 1) samples_cache = Matrix{T}(undef, n, nchains) # create plans of FFTs fft_plan = AbstractFFTs.plan_fft!(samples_cache, 1) ifft_plan = AbstractFFTs.plan_ifft!(samples_cache, 1) return FFTAutocovCache(samples, var, samples_cache, fft_plan, ifft_plan) end function build_cache(::BDAAutocovMethod, samples::Matrix, var::Vector) # check arguments nchains = size(samples, 2) length(var) == nchains || throw(DimensionMismatch()) return BDAAutocovCache(samples, var, Statistics.mean(var)) end update!(cache::AutocovCache) = nothing function update!(cache::FFTAutocovCache) # copy samples and add zero padding samples = cache.samples samples_cache = cache.samples_cache niter, nchains = size(samples) n = size(samples_cache, 1) T = eltype(samples_cache) @inbounds for j in 1:nchains for i in 1:niter samples_cache[i, j] = samples[i, j] end for i in (niter + 1):n samples_cache[i, j] = zero(T) end end # compute unnormalized autocovariance cache.plan * samples_cache @. samples_cache = abs2(samples_cache) cache.invplan * samples_cache return nothing end function update!(cache::BDAAutocovCache) # recompute mean of within-chain variances cache.mean_chain_var = Statistics.mean(cache.chain_var) return nothing end function mean_autocov(k::Int, cache::AutocovCache) # check arguments samples = cache.samples niter, nchains = size(samples) 0 ≤ k < niter || throw(ArgumentError("only lags ≥ 0 and < $niter are supported")) # compute mean of unnormalized autocovariance estimates firstrange = 1:(niter - k) lastrange = (k + 1):niter s = Statistics.mean(1:nchains) do i return @inbounds LinearAlgebra.dot( view(samples, firstrange, i), view(samples, lastrange, i) ) end # normalize autocovariance estimators by `niter` instead of `niter - k` to obtain biased # but more stable estimators for all lags as discussed by Geyer (1992) return s / niter end function mean_autocov(k::Int, cache::FFTAutocovCache) # check arguments niter, nchains = size(cache.samples) 0 ≤ k < niter || throw(ArgumentError("only lags ≥ 0 and < $niter are supported")) # compute mean autocovariance # we use biased but more stable estimators as discussed by Geyer (1992) samples_cache = cache.samples_cache chain_var = cache.chain_var uncorrection_factor = (niter - 1)//niter # undo corrected=true for chain_var result = Statistics.mean(1:nchains) do i @inbounds(real(samples_cache[k + 1, i]) / real(samples_cache[1, i])) * chain_var[i] end return result * uncorrection_factor end function mean_autocov(k::Int, cache::BDAAutocovCache) # check arguments samples = cache.samples niter, nchains = size(samples) 0 ≤ k < niter || throw(ArgumentError("only lags ≥ 0 and < $niter are supported")) # compute mean autocovariance n = niter - k idxs = 1:n s = Statistics.mean(1:nchains) do j return sum(idxs) do i @inbounds abs2(samples[i, j] - samples[k + i, j]) end end return cache.mean_chain_var - s / (2 * n) end """ ess( samples::AbstractArray{<:Union{Missing,Real}}; kind=:bulk, relative::Bool=false, autocov_method=AutocovMethod(), split_chains::Int=2, maxlag::Int=250, kwargs... ) Estimate the effective sample size (ESS) of the `samples` of shape `(draws, [chains[, parameters...]])` with the `autocov_method`. Optionally, the `kind` of ESS estimate to be computed can be specified (see below). Some `kind`s accept additional `kwargs`. If `relative` is `true`, the relative ESS is returned, i.e. `ess / (draws * chains)`. $_DOC_SPLIT_CHAINS There must be at least 3 draws in each chain after splitting. `maxlag` indicates the maximum lag for which autocovariance is computed and must be greater than 0. For a given estimand, it is recommended that the ESS is at least `100 * chains` and that ``\\widehat{R} < 1.01``.[^VehtariGelman2021] See also: [`AutocovMethod`](@ref), [`FFTAutocovMethod`](@ref), [`BDAAutocovMethod`](@ref), [`rhat`](@ref), [`ess_rhat`](@ref), [`mcse`](@ref) ## Kinds of ESS estimates If `kind` isa a `Symbol`, it may take one of the following values: - `:bulk`: basic ESS computed on rank-normalized draws. This kind diagnoses poor convergence in the bulk of the distribution due to trends or different locations of the chains. - `:tail`: minimum of the quantile-ESS for the symmetric quantiles where `tail_prob=0.1` is the probability in the tails. This kind diagnoses poor convergence in the tails of the distribution. If this kind is chosen, `kwargs` may contain a `tail_prob` keyword. - `:basic`: basic ESS, equivalent to specifying `kind=Statistics.mean`. !!! note While Bulk-ESS is conceptually related to basic ESS, it is well-defined even if the chains do not have finite variance.[^VehtariGelman2021] For each parameter, rank-normalization proceeds by first ranking the inputs using "tied ranking" and then transforming the ranks to normal quantiles so that the result is standard normally distributed. This transform is monotonic. Otherwise, `kind` specifies one of the following estimators, whose ESS is to be estimated: - `Statistics.mean` - `Statistics.median` - `Statistics.std` - `StatsBase.mad` - `Base.Fix2(Statistics.quantile, p::Real)` [^VehtariGelman2021]: Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Bürkner, P. C. (2021). Rank-normalization, folding, and localization: An improved ``\\widehat {R}`` for assessing convergence of MCMC. Bayesian Analysis. doi: [10.1214/20-BA1221](https://doi.org/10.1214/20-BA1221) arXiv: [1903.08008](https://arxiv.org/abs/1903.08008) """ function ess(samples::AbstractArray{<:Union{Missing,Real}}; kind=:bulk, kwargs...) # if we just call _ess(Val(kind), ...) Julia cannot infer the return type with default # const-propagation. We keep this type-inferrable by manually dispatching to the cases. if kind === :bulk return _ess(Val(:bulk), samples; kwargs...) elseif kind === :tail return _ess(Val(:tail), samples; kwargs...) elseif kind === :basic return _ess(Val(:basic), samples; kwargs...) elseif kind isa Symbol throw(ArgumentError("the `kind` `$kind` is not supported by `ess`")) else return _ess(kind, samples; kwargs...) end end function _ess(estimator, samples::AbstractArray{<:Union{Missing,Real}}; kwargs...) x = _expectand_proxy(estimator, samples) if x === nothing throw(ArgumentError("the estimator $estimator is not yet supported by `ess`")) end return _ess(Val(:basic), x; kwargs...) end function _ess(kind::Val, samples::AbstractArray{<:Union{Missing,Real}}; kwargs...) return _ess_rhat(kind, samples; kwargs...).ess end function _ess( ::Val{:tail}, x::AbstractArray{<:Union{Missing,Real}}; tail_prob::Real=1//10, kwargs... ) # workaround for https://github.com/JuliaStats/Statistics.jl/issues/136 T = Base.promote_eltype(x, tail_prob) pl = convert(T, tail_prob / 2) pu = convert(T, 1 - tail_prob / 2) S_lower = _ess(Base.Fix2(Statistics.quantile, pl), x; kwargs...) S_upper = _ess(Base.Fix2(Statistics.quantile, pu), x; kwargs...) return map(min, S_lower, S_upper) end """ rhat(samples::AbstractArray{Union{Real,Missing}}; kind::Symbol=:rank, split_chains=2) Compute the ``\\widehat{R}`` diagnostics for each parameter in `samples` of shape `(draws, [chains[, parameters...]])`.[^VehtariGelman2021] `kind` indicates the kind of ``\\widehat{R}`` to compute (see below). $_DOC_SPLIT_CHAINS See also [`ess`](@ref), [`ess_rhat`](@ref), [`rstar`](@ref) ## Kinds of ``\\widehat{R}`` The following `kind`s are supported: - `:rank`: maximum of ``\\widehat{R}`` with `kind=:bulk` and `kind=:tail`. - `:bulk`: basic ``\\widehat{R}`` computed on rank-normalized draws. This kind diagnoses poor convergence in the bulk of the distribution due to trends or different locations of the chains. - `:tail`: ``\\widehat{R}`` computed on draws folded around the median and then rank-normalized. This kind diagnoses poor convergence in the tails of the distribution due to different scales of the chains. - `:basic`: Classic ``\\widehat{R}``. [^VehtariGelman2021]: Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Bürkner, P. C. (2021). Rank-normalization, folding, and localization: An improved ``\\widehat {R}`` for assessing convergence of MCMC. Bayesian Analysis. doi: [10.1214/20-BA1221](https://doi.org/10.1214/20-BA1221) arXiv: [1903.08008](https://arxiv.org/abs/1903.08008) """ function rhat(samples::AbstractArray{<:Union{Missing,Real}}; kind::Symbol=:rank, kwargs...) # if we just call _rhat(Val(kind), ...) Julia cannot infer the return type with default # const-propagation. We keep this type-inferrable by manually dispatching to the cases. if kind === :rank return _rhat(Val(:rank), samples; kwargs...) elseif kind === :bulk return _rhat(Val(:bulk), samples; kwargs...) elseif kind === :tail return _rhat(Val(:tail), samples; kwargs...) elseif kind === :basic return _rhat(Val(:basic), samples; kwargs...) else return throw(ArgumentError("the `kind` `$kind` is not supported by `rhat`")) end end function _rhat(::Val{:basic}, chains::AbstractArray{<:Union{Missing,Real}}; kwargs...) # define output array axes_out = _param_axes(chains) T = promote_type(eltype(chains), typeof(zero(eltype(chains)) / 1)) rhat = similar(chains, T, axes_out) if T !== Missing _rhat_basic!(rhat, chains; kwargs...) end return _maybescalar(rhat) end function _rhat_basic!( rhat::AbstractArray{T}, chains::AbstractArray{<:Union{Missing,Real}}; split_chains::Int=2, ) where {T<:Union{Missing,Real}} # compute size of matrices (each chain may be split!) niter = size(chains, 1) ÷ split_chains nchains = split_chains * size(chains, 2) # define caches for mean and variance chain_mean = Array{T}(undef, 1, nchains) chain_var = Array{T}(undef, nchains) samples = Array{T}(undef, niter, nchains) # compute correction factor correctionfactor = (niter - 1)//niter # for each parameter for (i, chains_slice) in zip(eachindex(rhat), _eachparam(chains)) # check that no values are missing if any(x -> x === missing, chains_slice) rhat[i] = missing continue end # split chains copyto_split!(samples, chains_slice) # calculate mean of chains Statistics.mean!(chain_mean, samples) # calculate within-chain variance @inbounds for j in 1:nchains chain_var[j] = Statistics.var( view(samples, :, j); mean=chain_mean[j], corrected=true ) end W = Statistics.mean(chain_var) # compute variance estimator var₊, which accounts for between-chain variance as well # avoid NaN when nchains=1 and set the variance estimator var₊ to the the within-chain variance in that case var₊ = correctionfactor * W + Statistics.var(chain_mean; corrected=(nchains > 1)) # estimate rhat rhat[i] = sqrt(var₊ / W) end return rhat end function _rhat(::Val{:bulk}, x::AbstractArray{<:Union{Missing,Real}}; kwargs...) return _rhat(Val(:basic), _rank_normalize(x); kwargs...) end function _rhat(::Val{:tail}, x::AbstractArray{<:Union{Missing,Real}}; kwargs...) return _rhat(Val(:bulk), _fold_around_median(x); kwargs...) end function _rhat(::Val{:rank}, x::AbstractArray{<:Union{Missing,Real}}; kwargs...) Rbulk = _rhat(Val(:bulk), x; kwargs...) Rtail = _rhat(Val(:tail), x; kwargs...) return map(max, Rtail, Rbulk) end """ ess_rhat( samples::AbstractArray{<:Union{Missing,Real}}; kind::Symbol=:rank, kwargs..., ) -> NamedTuple{(:ess, :rhat)} Estimate the effective sample size and ``\\widehat{R}`` of the `samples` of shape `(draws, [chains[, parameters...]])`. When both ESS and ``\\widehat{R}`` are needed, this method is often more efficient than calling `ess` and `rhat` separately. See [`rhat`](@ref) for a description of supported `kind`s and [`ess`](@ref) for a description of `kwargs`. """ function ess_rhat( samples::AbstractArray{<:Union{Missing,Real}}; kind::Symbol=:rank, kwargs... ) # if we just call _ess_rhat(Val(kind), ...) Julia cannot infer the return type with # default const-propagation. We keep this type-inferrable by manually dispatching to the # cases. if kind === :rank return _ess_rhat(Val(:rank), samples; kwargs...) elseif kind === :bulk return _ess_rhat(Val(:bulk), samples; kwargs...) elseif kind === :tail return _ess_rhat(Val(:tail), samples; kwargs...) elseif kind === :basic return _ess_rhat(Val(:basic), samples; kwargs...) else return throw(ArgumentError("the `kind` `$kind` is not supported by `ess_rhat`")) end end function _ess_rhat( ::Val{:basic}, chains::AbstractArray{<:Union{Missing,Real}}; split_chains::Int=2, maxlag::Int=250, kwargs..., ) # define output arrays axes_out = _param_axes(chains) T = promote_type(eltype(chains), typeof(zero(eltype(chains)) / 1)) ess = similar(chains, T, axes_out) rhat = similar(chains, T, axes_out) # compute number of iterations (each chain may be split!) niter = size(chains, 1) ÷ split_chains if !(niter > 4) # discard the last pair of autocorrelations, which are poorly estimated and only matter # when chains have mixed poorly anyways. # leave the last even autocorrelation as a bias term that reduces variance for # case of antithetical chains, see below @warn "number of draws after splitting must be >4 but is $niter. ESS cannot be computed." fill!(ess, NaN) _rhat_basic!(rhat, chains; split_chains) elseif T !== Missing maxlag > 0 || throw(DomainError(maxlag, "maxlag must be >0.")) maxlag = min(maxlag, niter - 4) _ess_rhat_basic!(ess, rhat, chains; split_chains, maxlag, kwargs...) end return (; ess=_maybescalar(ess), rhat=_maybescalar(rhat)) end function _ess_rhat_basic!( ess::TA, rhat::TA, chains::AbstractArray{<:Union{Missing,Real}}; relative::Bool=false, autocov_method::AbstractAutocovMethod=AutocovMethod(), split_chains::Int=2, maxlag::Int=250, ) where {T<:Union{Missing,Real},TA<:AbstractArray{T}} # compute size of matrices (each chain may be split!) niter = size(chains, 1) ÷ split_chains nchains = split_chains * size(chains, 2) ntotal = niter * nchains # define caches for mean and variance chain_mean = Array{T}(undef, 1, nchains) chain_var = Array{T}(undef, nchains) samples = Array{T}(undef, niter, nchains) # compute correction factor correctionfactor = (niter - 1)//niter # define cache for the computation of the autocorrelation esscache = build_cache(autocov_method, samples, chain_var) # set maximum relative ess for antithetic chains, see below rel_ess_max = log10(oftype(one(T), ntotal)) # for each parameter for (i, chains_slice) in zip(eachindex(ess), _eachparam(chains)) # check that no values are missing if any(x -> x === missing, chains_slice) ess[i] = missing rhat[i] = missing continue end # split chains copyto_split!(samples, chains_slice) # calculate mean of chains Statistics.mean!(chain_mean, samples) # calculate within-chain variance @inbounds for j in 1:nchains chain_var[j] = Statistics.var( view(samples, :, j); mean=chain_mean[j], corrected=true ) end W = Statistics.mean(chain_var) # compute variance estimator var₊, which accounts for between-chain variance as well # avoid NaN when nchains=1 and set the variance estimator var₊ to the the within-chain variance in that case var₊ = correctionfactor * W + Statistics.var(chain_mean; corrected=(nchains > 1)) inv_var₊ = inv(var₊) # estimate rhat rhat[i] = sqrt(var₊ / W) # center the data around 0 samples .-= chain_mean # update cache update!(esscache) # compute the first two autocorrelation estimates # by combining autocorrelation (or rather autocovariance) estimates of each chain ρ_odd = 1 - inv_var₊ * (W - mean_autocov(1, esscache)) ρ_even = one(ρ_odd) # estimate at lag 0 is known # sum correlation estimates pₜ = ρ_even + ρ_odd sum_pₜ = pₜ k = 2 while k < (maxlag - 1) # compute subsequent autocorrelation of all chains # by combining estimates of each chain ρ_even = 1 - inv_var₊ * (W - mean_autocov(k, esscache)) ρ_odd = 1 - inv_var₊ * (W - mean_autocov(k + 1, esscache)) # stop summation if p becomes non-positive Δ = ρ_even + ρ_odd Δ > zero(Δ) || break # generate a monotone sequence pₜ = min(Δ, pₜ) # update sum sum_pₜ += pₜ # update indices k += 2 end # for antithetic chains # - reduce variance by averaging truncation to odd lag and truncation to next even lag # - prevent negative ESS for short chains by ensuring τ is nonnegative # See discussions in: # - § 3.2 of Vehtari et al. https://arxiv.org/pdf/1903.08008v5.pdf # - https://github.com/TuringLang/MCMCDiagnosticTools.jl/issues/40 # - https://github.com/stan-dev/rstan/pull/618 # - https://github.com/stan-dev/stan/pull/2774 ρ_even = maxlag > 1 ? 1 - inv_var₊ * (W - mean_autocov(k, esscache)) : zero(ρ_even) τ = max(0, 2 * sum_pₜ + max(0, ρ_even) - 1) # estimate the relative effective sample size ess[i] = min(inv(τ), rel_ess_max) end if !relative # absolute effective sample size ess .*= ntotal end return (; ess, rhat) end function _ess_rhat(::Val{:bulk}, x::AbstractArray{<:Union{Missing,Real}}; kwargs...) return _ess_rhat(Val(:basic), _rank_normalize(x); kwargs...) end function _ess_rhat( kind::Val{:tail}, x::AbstractArray{<:Union{Missing,Real}}; split_chains::Int=2, kwargs..., ) S = _ess(kind, x; split_chains=split_chains, kwargs...) R = _rhat(kind, x; split_chains=split_chains) return (ess=S, rhat=R) end function _ess_rhat( ::Val{:rank}, x::AbstractArray{<:Union{Missing,Real}}; split_chains::Int=2, kwargs... ) Sbulk, Rbulk = _ess_rhat(Val(:bulk), x; split_chains=split_chains, kwargs...) Rtail = _rhat(Val(:tail), x; split_chains=split_chains) Rrank = map(max, Rtail, Rbulk) return (ess=Sbulk, rhat=Rrank) end # Compute an expectand `z` such that ``\\textrm{mean-ESS}(z) ≈ \\textrm{f-ESS}(x)``. # If no proxy expectand for `f` is known, `nothing` is returned. _expectand_proxy(f, x) = nothing _expectand_proxy(::typeof(Statistics.mean), x) = x function _expectand_proxy(::typeof(Statistics.median), x) y = similar(x) # avoid using the `dims` keyword for median because it # - can error for Union{Missing,Real} (https://github.com/JuliaStats/Statistics.jl/issues/8) # - is type-unstable (https://github.com/JuliaStats/Statistics.jl/issues/39) for (xi, yi) in zip(_eachparam(x), _eachparam(y)) yi .= xi .≤ Statistics.median(vec(xi)) end return y end function _expectand_proxy(::typeof(Statistics.std), x) return (x .- Statistics.mean(x; dims=_sample_dims(x))) .^ 2 end function _expectand_proxy(::typeof(StatsBase.mad), x) x_folded = _fold_around_median(x) return _expectand_proxy(Statistics.median, x_folded) end function _expectand_proxy(f::Base.Fix2{typeof(Statistics.quantile),<:Real}, x) y = similar(x) # currently quantile does not support a dims keyword argument for (xi, yi) in zip(_eachparam(x), _eachparam(y)) if any(ismissing, xi) # quantile function raises an error if there are missing values fill!(yi, missing) else yi .= xi .≤ f(vec(xi)) end end return y end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
4076
function _gelmandiag(psi::AbstractArray{<:Real,3}; alpha::Real=0.05) niters, nchains, nparams = size(psi) nchains > 1 || error("Gelman diagnostic requires at least 2 chains") rfixed = (niters - 1) / niters rrandomscale = (nchains + 1) / (nchains * niters) # `eachslice(psi; dims=2)` breaks type inference S2 = map(x -> Statistics.cov(x; dims=1), (view(psi, :, i, :) for i in axes(psi, 2))) W = Statistics.mean(S2) psibar = dropdims(Statistics.mean(psi; dims=1); dims=1) B = niters .* Statistics.cov(psibar) w = LinearAlgebra.diag(W) b = LinearAlgebra.diag(B) s2 = mapreduce(LinearAlgebra.diag, hcat, S2)' psibar2 = vec(Statistics.mean(psibar; dims=1)) var_w = vec(Statistics.var(s2; dims=1)) ./ nchains var_b = (2 / (nchains - 1)) .* b .^ 2 var_wb = (niters / nchains) .* ( LinearAlgebra.diag(Statistics.cov(s2, psibar .^ 2)) .- 2 .* psibar2 .* LinearAlgebra.diag(Statistics.cov(s2, psibar)) ) V = @. rfixed * w + rrandomscale * b var_V = rfixed^2 * var_w + rrandomscale^2 * var_b + 2 * rfixed * rrandomscale * var_wb df = @. 2 * V^2 / var_V B_df = nchains - 1 W_df = @. 2 * w^2 / var_w estimates = Array{Float64}(undef, nparams) upperlimits = Array{Float64}(undef, nparams) q = 1 - alpha / 2 for i in 1:nparams correction = (df[i] + 3) / (df[i] + 1) rrandom = rrandomscale * b[i] / w[i] estimates[i] = sqrt(correction * (rfixed + rrandom)) if !isnan(rrandom) rrandom *= Distributions.quantile(Distributions.FDist(B_df, W_df[i]), q) end upperlimits[i] = sqrt(correction * (rfixed + rrandom)) end return estimates, upperlimits, W, B end """ gelmandiag(samples::AbstractArray{<:Real,3}; alpha::Real=0.95) Compute the Gelman, Rubin and Brooks diagnostics [^Gelman1992] [^Brooks1998] on `samples` with shape `(draws, chains, parameters)`. Values of the diagnostic’s potential scale reduction factor (PSRF) that are close to one suggest convergence. As a rule-of-thumb, convergence is rejected if the 97.5 percentile of a PSRF is greater than 1.2. [^Gelman1992]: Gelman, A., & Rubin, D. B. (1992). Inference from iterative simulation using multiple sequences. Statistical science, 7(4), 457-472. [^Brooks1998]: Brooks, S. P., & Gelman, A. (1998). General methods for monitoring convergence of iterative simulations. Journal of computational and graphical statistics, 7(4), 434-455. """ function gelmandiag(chains::AbstractArray{<:Real,3}; kwargs...) estimates, upperlimits = _gelmandiag(chains; kwargs...) return (psrf=estimates, psrfci=upperlimits) end """ gelmandiag_multivariate(samples::AbstractArray{<:Real,3}; alpha::Real=0.05) Compute the multivariate Gelman, Rubin and Brooks diagnostics on `samples` with shape `(draws, chains, parameters)`. """ function gelmandiag_multivariate(chains::AbstractArray{<:Real,3}; kwargs...) niters, nchains, nparams = size(chains) if nparams < 2 error( "computation of the multivariate potential scale reduction factor requires ", "at least two variables", ) end estimates, upperlimits, W, B = _gelmandiag(chains; kwargs...) # compute multivariate potential scale reduction factor (PSRF) # the eigenvalues of `X := W⁻¹ B` and `Y := L⁻¹ B L⁻ᵀ = L⁻¹ Bᵀ L⁻ᵀ = L⁻¹ (L⁻¹ B)ᵀ`, # where `W = L Lᵀ`, are identical but `Y` is symmetric whereas `X` is not in general # (remember, `W` and `B` are symmetric positive semi-definite matrices) # for symmetric matrices specialized implementations for computing eigenvalues are used rfixed = (niters - 1) / niters rrandomscale = (nchains + 1) / (nchains * niters) C = LinearAlgebra.cholesky(LinearAlgebra.Symmetric(W)) L = C.L Y = L \ (L \ LinearAlgebra.Symmetric(B))' λmax = LinearAlgebra.eigmax(LinearAlgebra.Symmetric(Y)) multivariate = rfixed + rrandomscale * λmax return (psrf=estimates, psrfci=upperlimits, psrfmultivariate=multivariate) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
1725
""" gewekediag(x::AbstractVector{<:Real}; first::Real=0.1, last::Real=0.5, kwargs...) Compute the Geweke diagnostic [^Geweke1991] from the `first` and `last` proportion of samples `x`. The diagnostic is designed to asses convergence of posterior means estimated with autocorrelated samples. It computes a normal-based test statistic comparing the sample means in two windows containing proportions of the first and last iterations. Users should ensure that there is sufficient separation between the two windows to assume that their samples are independent. A non-significant test p-value indicates convergence. Significant p-values indicate non-convergence and the possible need to discard initial samples as a burn-in sequence or to simulate additional samples. `kwargs` are forwarded to [`mcse`](@ref). [^Geweke1991]: Geweke, J. F. (1991). Evaluating the accuracy of sampling-based approaches to the calculation of posterior moments (No. 148). Federal Reserve Bank of Minneapolis. """ function gewekediag(x::AbstractVector{<:Real}; first::Real=0.1, last::Real=0.5, kwargs...) 0 < first < 1 || throw(ArgumentError("`first` is not in (0, 1)")) 0 < last < 1 || throw(ArgumentError("`last` is not in (0, 1)")) first + last <= 1 || throw(ArgumentError("`first` and `last` proportions overlap")) n = length(x) x1 = x[1:round(Int, first * n)] x2 = x[round(Int, n - last * n + 1):n] s = hypot( Base.first(mcse(reshape(x1, :, 1, 1); split_chains=1, kwargs...)), Base.first(mcse(reshape(x2, :, 1, 1); split_chains=1, kwargs...)), ) z = (Statistics.mean(x1) - Statistics.mean(x2)) / s p = SpecialFunctions.erfc(abs(z) / sqrt2) return (zscore=z, pvalue=p) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
2324
""" heideldiag( x::AbstractVector{<:Real}; alpha::Real=0.05, eps::Real=0.1, start::Int=1, kwargs... ) Compute the Heidelberger and Welch diagnostic [^Heidelberger1983]. This diagnostic tests for non-convergence (non-stationarity) and whether ratios of estimation interval halfwidths to means are within a target ratio. Stationarity is rejected (0) for significant test p-values. Halfwidth tests are rejected (0) if observed ratios are greater than the target, as is the case for `s2` and `beta[1]`. `kwargs` are forwarded to [`mcse`](@ref). [^Heidelberger1983]: Heidelberger, P., & Welch, P. D. (1983). Simulation run length control in the presence of an initial transient. Operations Research, 31(6), 1109-1144. """ function heideldiag( x::AbstractVector{<:Real}; alpha::Real=1//20, eps::Real=0.1, start::Int=1, kwargs... ) n = length(x) delta = trunc(Int, 0.10 * n) y = x[trunc(Int, n / 2):end] T = typeof(zero(eltype(x)) / 1) s = first(mcse(reshape(y, :, 1, 1); split_chains=1, kwargs...)) S0 = length(y) * s^2 i, pvalue, converged, ybar = 1, one(T), false, T(NaN) while i < n / 2 y = x[i:end] m = length(y) ybar = Statistics.mean(y) B = cumsum(y) - ybar * collect(1:m) Bsq = (B .* B) ./ (m * S0) I = sum(Bsq) / m pvalue = 1 - T(pcramer(I)) converged = pvalue > alpha if converged break end i += delta end s = first(mcse(reshape(y, :, 1, 1); split_chains=1, kwargs...)) halfwidth = sqrt2 * SpecialFunctions.erfcinv(T(alpha)) * s passed = halfwidth / abs(ybar) <= eps return ( burnin=i + start - 2, stationarity=converged, pvalue=pvalue, mean=ybar, halfwidth=halfwidth, test=passed, ) end ## Csorgo S and Faraway JJ. The exact and asymptotic distributions of the ## Cramer-von Mises statistic. Journal of the Royal Statistical Society, ## Series B, 58: 221-234, 1996. function pcramer(q::Real) p = 0.0 for k in 0:3 c1 = 4.0 * k + 1.0 c2 = c1^2 / (16.0 * q) p += SpecialFunctions.gamma(k + 0.5) / factorial(k) * sqrt(c1) * exp(-c2) * SpecialFunctions.besselk(0.25, c2) end return p / (pi^1.5 * sqrt(q)) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
5908
const normcdf1 = 0.8413447460685429 # StatsFuns.normcdf(1) const normcdfn1 = 0.15865525393145705 # StatsFuns.normcdf(-1) """ mcse(samples::AbstractArray{<:Union{Missing,Real}}; kind=Statistics.mean, kwargs...) Estimate the Monte Carlo standard errors (MCSE) of the estimator `kind` applied to `samples` of shape `(draws, [chains[, parameters...]])`. See also: [`ess`](@ref) ## Kinds of MCSE estimates The estimator whose MCSE should be estimated is specified with `kind`. `kind` must accept a vector of the same `eltype` as `samples` and return a real estimate. For the following estimators, the effective sample size [`ess`](@ref) and an estimate of the asymptotic variance are used to compute the MCSE, and `kwargs` are forwarded to `ess`: - `Statistics.mean` - `Statistics.median` - `Statistics.std` - `Base.Fix2(Statistics.quantile, p::Real)` For other estimators, the subsampling bootstrap method (SBM)[^FlegalJones2011][^Flegal2012] is used as a fallback, and the only accepted `kwargs` are `batch_size`, which indicates the size of the overlapping batches used to estimate the MCSE, defaulting to `floor(Int, sqrt(draws * chains))`. Note that SBM tends to underestimate the MCSE, especially for highly autocorrelated chains. One should verify that autocorrelation is low by checking the bulk- and tail-ESS values. [^FlegalJones2011]: Flegal JM, Jones GL. (2011) Implementing MCMC: estimating with confidence. Handbook of Markov Chain Monte Carlo. pp. 175-97. [pdf](http://faculty.ucr.edu/~jflegal/EstimatingWithConfidence.pdf) [^Flegal2012]: Flegal JM. (2012) Applicability of subsampling bootstrap methods in Markov chain Monte Carlo. Monte Carlo and Quasi-Monte Carlo Methods 2010. pp. 363-72. doi: [10.1007/978-3-642-27440-4_18](https://doi.org/10.1007/978-3-642-27440-4_18) """ function mcse(x::AbstractArray{<:Union{Missing,Real}}; kind=Statistics.mean, kwargs...) return _mcse(kind, x; kwargs...) end _mcse(f, x; kwargs...) = _mcse_sbm(f, x; kwargs...) function _mcse( ::typeof(Statistics.mean), samples::AbstractArray{<:Union{Missing,Real}}; kwargs... ) S = _ess(Statistics.mean, samples; kwargs...) dims = _sample_dims(samples) return dropdims(Statistics.std(samples; dims=dims); dims=dims) ./ sqrt.(S) end function _mcse( ::typeof(Statistics.std), samples::AbstractArray{<:Union{Missing,Real}}; kwargs... ) dims = _sample_dims(samples) x = (samples .- Statistics.mean(samples; dims=dims)) .^ 2 # expectand proxy S = _ess(Statistics.mean, x; kwargs...) # asymptotic variance of sample variance estimate is Var[var] = E[μ₄] - E[var]², # where μ₄ is the 4th central moment # by the delta method, Var[std] = Var[var] / 4E[var] = (E[μ₄]/E[var] - E[var])/4, # See e.g. Chapter 3 of Van der Vaart, AW. (200) Asymptotic statistics. Vol. 3. mean_var = dropdims(Statistics.mean(x; dims=dims); dims=dims) mean_moment4 = dropdims(Statistics.mean(abs2, x; dims=dims); dims=dims) return @. sqrt((mean_moment4 / mean_var - mean_var) / S) / 2 end function _mcse( f::Base.Fix2{typeof(Statistics.quantile),<:Real}, samples::AbstractArray{<:Union{Missing,Real}}; kwargs..., ) p = f.x S = _ess(f, samples; kwargs...) ndims(samples) < 3 && return _mcse_quantile(vec(samples), p, S) T = eltype(S) R = promote_type(eltype(samples), typeof(oneunit(eltype(samples)) / sqrt(oneunit(T)))) values = similar(S, R) for (i, xi) in zip(eachindex(values, S), _eachparam(samples)) values[i] = _mcse_quantile(vec(xi), p, S[i]) end return values end function _mcse( ::typeof(Statistics.median), samples::AbstractArray{<:Union{Missing,Real}}; kwargs... ) S = _ess(Statistics.median, samples; kwargs...) ndims(samples) < 3 && return _mcse_quantile(vec(samples), 1//2, S) T = eltype(S) R = promote_type(eltype(samples), typeof(oneunit(eltype(samples)) / sqrt(oneunit(T)))) values = similar(S, R) for (i, xi) in zip(eachindex(values, S), _eachparam(samples)) values[i] = _mcse_quantile(vec(xi), 1//2, S[i]) end return values end function _mcse_quantile(x, p, Seff) Seff === missing && return missing S = length(x) # quantile error distribution is asymptotically normal; estimate σ (mcse) with 2 # quadrature points: xl and xu, chosen as quantiles so that xu - xl = 2σ # compute quantiles of error distribution in probability space (i.e. quantiles passed through CDF) # Beta(α,β) is the approximate error distribution of quantile estimates α = Seff * p + 1 β = Seff * (1 - p) + 1 prob_x_upper = StatsFuns.betainvcdf(α, β, normcdf1) prob_x_lower = StatsFuns.betainvcdf(α, β, normcdfn1) # use inverse ECDF to get quantiles in quantile (x) space l = max(floor(Int, prob_x_lower * S), 1) u = min(ceil(Int, prob_x_upper * S), S) iperm = partialsortperm(x, l:u) # sort as little of x as possible xl = x[first(iperm)] xu = x[last(iperm)] # estimate mcse from quantiles return (xu - xl) / 2 end function _mcse_sbm( f, x::AbstractArray{<:Union{Missing,Real}}; batch_size::Int=floor(Int, sqrt(size(x, 1) * size(x, 2))), ) ndims(x) < 3 && return _mcse_sbm(f, vec(x), batch_size) T = promote_type(eltype(x), typeof(zero(eltype(x)) / 1)) param_dims = _param_dims(x) axes_out = map(Base.Fix1(axes, x), param_dims) values = similar(x, T, axes_out) for (i, xi) in zip(eachindex(values), _eachparam(x)) values[i] = _mcse_sbm(f, vec(xi), batch_size) end return values end function _mcse_sbm(f, x, batch_size) any(x -> x === missing, x) && return missing n = length(x) i1 = firstindex(x) v = Statistics.var( f(view(x, i:(i + batch_size - 1))) for i in i1:(i1 + n - batch_size); corrected=false, ) return sqrt(v * (batch_size//n)) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
3591
@doc raw""" rafterydiag( x::AbstractVector{<:Real}; q=0.025, r=0.005, s=0.95, eps=0.001, range=1:length(x) ) Compute the Raftery and Lewis diagnostic [^Raftery1992]. This diagnostic is used to determine the number of iterations required to estimate a specified quantile `q` within a desired degree of accuracy. The diagnostic is designed to determine the number of autocorrelated samples required to estimate a specified quantile $\theta_q$, such that $\Pr(\theta \le \theta_q) = q$, within a desired degree of accuracy. In particular, if $\hat{\theta}_q$ is the estimand and $\Pr(\theta \le \hat{\theta}_q) = \hat{P}_q$ the estimated cumulative probability, then accuracy is specified in terms of `r` and `s`, where $\Pr(q - r < \hat{P}_q < q + r) = s$. Thinning may be employed in the calculation of the diagnostic to satisfy its underlying assumptions. However, users may not want to apply the same (or any) thinning when estimating posterior summary statistics because doing so results in a loss of information. Accordingly, sample sizes estimated by the diagnostic tend to be conservative (too large). Furthermore, the argument `r` specifies the margin of error for estimated cumulative probabilities and `s` the probability for the margin of error. `eps` specifies the tolerance within which the probabilities of transitioning from initial to retained iterations are within the equilibrium probabilities for the chain. This argument determines the number of samples to discard as a burn-in sequence and is typically left at its default value. [^Raftery1992]: A L Raftery and S Lewis. Bayesian Statistics, chapter How Many Iterations in the Gibbs Sampler? Volume 4. Oxford University Press, New York, 1992. """ function rafterydiag( x::AbstractVector{<:Real}; q=0.025, r=0.005, s=0.95, eps=0.001, range=1:length(x) ) nx = length(x) phi = sqrt(2.0) * SpecialFunctions.erfinv(s) nmin = ceil(Int, q * (1.0 - q) * (phi / r)^2) if nmin > nx @warn "At least $nmin samples are needed for specified q, r, and s" kthin = -1 burnin = total = NaN else dichot = Int[(x .<= StatsBase.quantile(x, q))...] kthin = 0 bic = 1.0 local test, ntest while bic >= 0.0 kthin += 1 test = dichot[1:kthin:nx] ntest = length(test) temp = test[1:(ntest - 2)] + 2 * test[2:(ntest - 1)] + 4 * test[3:ntest] trantest = reshape(StatsBase.counts(temp, 0:7), 2, 2, 2) g2 = 0.0 for i1 in 1:2, i2 in 1:2, i3 in 1:2 tt = trantest[i1, i2, i3] if tt > 0 fitted = sum(trantest[:, i2, i3]) * sum(trantest[i1, i2, :]) / sum(trantest[:, i2, :]) g2 += 2.0 * tt * log(tt / fitted) end end bic = g2 - 2.0 * log(ntest - 2.0) end tranfinal = StatsBase.counts(test[1:(ntest - 1)] + 2 * test[2:ntest], 0:3) alpha = tranfinal[3] / (tranfinal[1] + tranfinal[3]) beta = tranfinal[2] / (tranfinal[2] + tranfinal[4]) kthin *= step(range) m = log(eps * (alpha + beta) / max(alpha, beta)) / log(abs(1.0 - alpha - beta)) burnin = kthin * ceil(m) + first(range) - 1 n = ((2.0 - alpha - beta) * alpha * beta * phi^2) / (r^2 * (alpha + beta)^3) keep = kthin * ceil(n) total = burnin + keep end return ( thinning=kthin, burnin=burnin, total=total, nmin=nmin, dependencefactor=total / nmin ) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
9803
""" rstar( rng::Random.AbstractRNG=Random.default_rng(), classifier, samples, chain_indices::AbstractVector{Int}; subset::Real=0.7, split_chains::Int=2, verbosity::Int=0, ) Compute the ``R^*`` convergence statistic of the table `samples` with the `classifier`. `samples` must be either an `AbstractMatrix`, an `AbstractVector`, or a table (i.e. implements the Tables.jl interface) whose rows are draws and whose columns are parameters. `chain_indices` indicates the chain ids of each row of `samples`. This method supports ragged chains, i.e. chains of nonequal lengths. """ function rstar( rng::Random.AbstractRNG, classifier, x, y::AbstractVector{Int}; subset::Real=0.7, split_chains::Int=2, verbosity::Int=0, ) # check the arguments _check_model_supports_continuous_inputs(classifier) _check_model_supports_multiclass_targets(classifier) _check_model_supports_multiclass_predictions(classifier) MMI.nrows(x) != length(y) && throw(DimensionMismatch()) 0 < subset < 1 || throw(ArgumentError("`subset` must be a number in (0, 1)")) # randomly sub-select training and testing set ysplit = split_chain_indices(y, split_chains) train_ids, test_ids = shuffle_split_stratified(rng, ysplit, subset) 0 < length(train_ids) < length(y) || throw(ArgumentError("training and test data subsets must not be empty")) xtable = _astable(x) ycategorical = MMI.categorical(ysplit) # train classifier on training data data = MMI.reformat(classifier, xtable, ycategorical) train_data = MMI.selectrows(classifier, train_ids, data...) fitresult, _ = MMI.fit(classifier, verbosity, train_data...) # compute predictions on test data # we exploit that MLJ demands that # reformat(model, args...)[1] = reformat(model, args[1]) # (https://alan-turing-institute.github.io/MLJ.jl/dev/adding_models_for_general_use/#Implementing-a-data-front-end) test_data = MMI.selectrows(classifier, test_ids, data[1]) predictions = _predict(classifier, fitresult, test_data...) # compute statistic ytest = ycategorical[test_ids] result = _rstar(MMI.scitype(predictions), predictions, ytest) return result end # check that the model supports the inputs and targets, and has predictions of the desired form function _check_model_supports_continuous_inputs(classifier) # ideally we would not allow MMI.Unknown but some models do not implement the traits input_scitype_classifier = MMI.input_scitype(classifier) if input_scitype_classifier !== MMI.Unknown && !(MMI.Table(MMI.Continuous) <: input_scitype_classifier) throw( ArgumentError( "classifier does not support tables of continuous values as inputs" ), ) end return nothing end function _check_model_supports_multiclass_targets(classifier) target_scitype_classifier = MMI.target_scitype(classifier) if target_scitype_classifier !== MMI.Unknown && !(AbstractVector{<:MMI.Finite} <: target_scitype_classifier) throw( ArgumentError( "classifier does not support vectors of multi-class labels as targets" ), ) end return nothing end function _check_model_supports_multiclass_predictions(classifier) if !( MMI.predict_scitype(classifier) <: Union{ MMI.Unknown, AbstractVector{<:MMI.Finite}, AbstractVector{<:MMI.Density{<:MMI.Finite}}, } ) throw( ArgumentError( "classifier does not support vectors of multi-class labels or their densities as predictions", ), ) end return nothing end _astable(x::AbstractVecOrMat) = Tables.table(x) _astable(x) = Tables.istable(x) ? x : throw(ArgumentError("Argument is not a valid table")) # Workaround for https://github.com/JuliaAI/MLJBase.jl/issues/863 # `MLJModelInterface.predict` sometimes returns predictions and sometimes predictions + additional information # TODO: Remove once the upstream issue is fixed function _predict(model::MMI.Model, fitresult, x) y = MMI.predict(model, fitresult, x) return if :predict in MMI.reporting_operations(model) first(y) else y end end """ rstar( rng::Random.AbstractRNG=Random.default_rng(), classifier, samples::AbstractArray{<:Real}; subset::Real=0.7, split_chains::Int=2, verbosity::Int=0, ) Compute the ``R^*`` convergence statistic of the `samples` with the `classifier`. `samples` is an array of draws with the shape `(draws, [chains[, parameters...]])`.` This implementation is an adaption of algorithms 1 and 2 described by Lambert and Vehtari. The `classifier` has to be a supervised classifier of the MLJ framework (see the [MLJ documentation](https://alan-turing-institute.github.io/MLJ.jl/dev/list_of_supported_models/#model_list) for a list of supported models). It is trained with a `subset` of the samples from each chain. Each chain is split into `split_chains` separate chains to additionally check for within-chain convergence. The training of the classifier can be inspected by adjusting the `verbosity` level. If the classifier is deterministic, i.e., if it predicts a class, the value of the ``R^*`` statistic is returned (algorithm 1). If the classifier is probabilistic, i.e., if it outputs probabilities of classes, the scaled Poisson-binomial distribution of the ``R^*`` statistic is returned (algorithm 2). !!! note The correctness of the statistic depends on the convergence of the `classifier` used internally in the statistic. # Examples ```jldoctest rstar; setup = :(using Random; Random.seed!(101)) julia> using MLJBase, MLJIteration, EvoTrees, Statistics, StatisticalMeasures julia> samples = fill(4.0, 100, 3, 2); ``` One can compute the distribution of the ``R^*`` statistic (algorithm 2) with a probabilistic classifier. For instance, we can use a gradient-boosted trees model with `nrounds = 100` sequentially stacked trees and learning rate `eta = 0.05`: ```jldoctest rstar julia> model = EvoTreeClassifier(; nrounds=100, eta=0.05); julia> distribution = rstar(model, samples); julia> round(mean(distribution); digits=2) 1.0f0 ``` Note, however, that it is recommended to determine `nrounds` based on early-stopping. With the MLJ framework, this can be achieved in the following way (see the [MLJ documentation](https://alan-turing-institute.github.io/MLJ.jl/dev/controlling_iterative_models/) for additional explanations): ```jldoctest rstar julia> model = IteratedModel(; model=EvoTreeClassifier(; eta=0.05), iteration_parameter=:nrounds, resampling=Holdout(), measures=log_loss, controls=[Step(5), Patience(2), NumberLimit(100)], retrain=true, ); julia> distribution = rstar(model, samples); julia> round(mean(distribution); digits=2) 1.0f0 ``` For deterministic classifiers, a single ``R^*`` statistic (algorithm 1) is returned. Deterministic classifiers can also be derived from probabilistic classifiers by e.g. predicting the mode. In MLJ this corresponds to a pipeline of models. ```jldoctest rstar julia> evotree_deterministic = Pipeline(model; operation=predict_mode); julia> value = rstar(evotree_deterministic, samples); julia> round(value; digits=2) 1.0 ``` # References Lambert, B., & Vehtari, A. (2020). ``R^*``: A robust MCMC convergence diagnostic with uncertainty using decision tree classifiers. """ function rstar(rng::Random.AbstractRNG, classifier, x::AbstractArray; kwargs...) samples = reshape(x, size(x, 1) * size(x, 2), :) chain_inds = repeat(axes(x, 2); inner=size(x, 1)) return rstar(rng, classifier, samples, chain_inds; kwargs...) end function rstar(classifier, x, y::AbstractVector{Int}; kwargs...) return rstar(Random.default_rng(), classifier, x, y; kwargs...) end # Fix method ambiguity issue function rstar(rng::Random.AbstractRNG, classifier, x::AbstractVector{Int}; kwargs...) samples = reshape(x, length(x), :) chain_inds = ones(Int, length(x)) return rstar(rng, classifier, samples, chain_inds; kwargs...) end function rstar(classifier, x::AbstractArray; kwargs...) return rstar(Random.default_rng(), classifier, x; kwargs...) end # R⋆ for deterministic predictions (algorithm 1) function _rstar( ::Type{<:AbstractVector{<:MMI.Finite}}, predictions::AbstractVector, ytest::AbstractVector, ) length(predictions) == length(ytest) || error("numbers of predictions and targets must be equal") mean_accuracy = Statistics.mean(p == y for (p, y) in zip(predictions, ytest)) nclasses = length(MMI.classes(ytest)) return nclasses * mean_accuracy end # R⋆ for probabilistic predictions (algorithm 2) function _rstar( ::Type{<:AbstractVector{<:MMI.Density{<:MMI.Finite}}}, predictions::AbstractVector, ytest::AbstractVector, ) length(predictions) == length(ytest) || error("numbers of predictions and targets must be equal") # create Poisson binomial distribution with support `0:length(predictions)` distribution = Distributions.PoissonBinomial(map(Distributions.pdf, predictions, ytest)) # scale distribution to support in `[0, nclasses]` nclasses = length(MMI.classes(ytest)) scaled_distribution = (nclasses//length(predictions)) * distribution return scaled_distribution end # unsupported types of predictions and targets function _rstar(::Any, predictions, targets) throw( ArgumentError( "unsupported types of predictions ($(typeof(predictions))) and targets ($(typeof(targets)))", ), ) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
7204
""" copyto_split!(out::AbstractMatrix, x::AbstractMatrix) Copy the elements of matrix `x` to matrix `out`, in which each column of `x` is split across multiple columns of `out`. To split each column of `x` into `split` columns, where the size of `x` is `(m, n)`, the size of `out` must be `(m ÷ split, n * split)`. If `d = rem(m, split) > 0`, so that `m` is not evenly divisible by `split`, then a single row of `x` is discarded after each of the first `d` splits for each column. """ function copyto_split!(out::AbstractMatrix, x::AbstractMatrix) # check dimensions nrows_out, ncols_out = size(out) nrows_x, ncols_x = size(x) nsplits, ncols_extra = divrem(ncols_out, ncols_x) ncols_extra == 0 || throw( DimensionMismatch( "the output matrix must have an integer multiple of the number of columns evenly divisible by the those of the input matrix", ), ) nrows_out2, nrows_discard = divrem(nrows_x, nsplits) nrows_out == nrows_out2 || throw( DimensionMismatch( "the output matrix must have $nsplits times as many rows as as the input matrix", ), ) if nrows_discard > 0 offset = firstindex(x) offset_out = firstindex(out) for _ in 1:ncols_x, k in 1:nsplits copyto!(out, offset_out, x, offset, nrows_out) offset += nrows_out + (k ≤ nrows_discard) offset_out += nrows_out end else copyto!(out, reshape(x, nrows_out, ncols_out)) end return out end """ unique_indices(x) -> (unique, indices) Return the results of `unique(collect(x))` along with the a vector of the same length whose elements are the indices in `x` at which the corresponding unique element in `unique` is found. """ function unique_indices(x) inds = eachindex(x) T = eltype(inds) ind_map = DataStructures.SortedDict{eltype(x),Vector{T}}() for i in inds xi = x[i] inds_xi = get!(ind_map, xi) do return T[] end push!(inds_xi, i) end unique = collect(keys(ind_map)) indices = collect(values(ind_map)) return unique, indices end """ split_chain_indices( chain_inds::AbstractVector{Int}, split::Int=2, ) -> AbstractVector{Int} Split each chain in `chain_inds` into `split` chains. For each chain in `chain_inds`, all entries are assumed to correspond to draws that have been ordered by iteration number. The result is a vector of the same length as `chain_inds` where each entry is the new index of the chain that the corresponding draw belongs to. """ function split_chain_indices(c::AbstractVector{Int}, split::Int=2) cnew = similar(c) if split == 1 copyto!(cnew, c) return cnew end _, indices = unique_indices(c) chain_ind = 1 for inds in indices ndraws_per_split, rem = divrem(length(inds), split) # here we can't use Iterators.partition because it's greedy. e.g. we can't partition # 4 items across 3 partitions because Iterators.partition(1:4, 1) == [[1], [2], [3]] # and Iterators.partition(1:4, 2) == [[1, 2], [3, 4]]. But we would want # [[1, 2], [3], [4]]. i = j = 0 ndraws_this_split = ndraws_per_split + (j < rem) for ind in inds cnew[ind] = chain_ind if (i += 1) == ndraws_this_split i = 0 j += 1 ndraws_this_split = ndraws_per_split + (j < rem) chain_ind += 1 end end end return cnew end """ shuffle_split_stratified( rng::Random.AbstractRNG, group_ids::AbstractVector, frac::Real, ) -> (inds1, inds2) Randomly split the indices of `group_ids` into two groups, where `frac` indices from each group are in `inds1` and the remainder are in `inds2`. This is used, for example, to split data into training and test data while preserving the class balances. """ function shuffle_split_stratified( rng::Random.AbstractRNG, group_ids::AbstractVector, frac::Real ) _, indices = unique_indices(group_ids) T = eltype(eltype(indices)) N1_tot = sum(x -> round(Int, length(x) * frac), indices) N2_tot = length(group_ids) - N1_tot inds1 = Vector{T}(undef, N1_tot) inds2 = Vector{T}(undef, N2_tot) items_in_1 = items_in_2 = 0 for inds in indices N = length(inds) N1 = round(Int, N * frac) N2 = N - N1 Random.shuffle!(rng, inds) copyto!(inds1, items_in_1 + 1, inds, 1, N1) copyto!(inds2, items_in_2 + 1, inds, N1 + 1, N2) items_in_1 += N1 items_in_2 += N2 end return inds1, inds2 end """ _fold_around_median(x::AbstractArray) Compute the absolute deviation of `x` from `Statistics.median(x)`. """ function _fold_around_median(x::AbstractArray) T = promote_type(eltype(x), typeof(zero(eltype(x)) / 1)) y = similar(x, T) # avoid using the `dims` keyword for median because it # - can error for Union{Missing,Real} (https://github.com/JuliaStats/Statistics.jl/issues/8) # - is type-unstable (https://github.com/JuliaStats/Statistics.jl/issues/39) for (xi, yi) in zip(_eachparam(x), _eachparam(y)) yi .= abs.(xi .- Statistics.median(vec(xi))) end return y end """ _rank_normalize(x::AbstractArray) Rank-normalize the inputs `x` along the sample dimensions. Rank-normalization proceeds by first ranking the inputs using "tied ranking" and then transforming the ranks to normal quantiles so that the result is standard normally distributed. """ function _rank_normalize(x::AbstractArray) T = promote_type(eltype(x), typeof(zero(eltype(x)) / 1)) y = similar(x, T) map(_rank_normalize!, _eachparam(y), _eachparam(x)) return y end function _rank_normalize!(values, x) if any(ismissing, x) fill!(values, missing) return values end rank = StatsBase.tiedrank(x) _normal_quantiles_from_ranks!(values, rank) map!(StatsFuns.norminvcdf, values, values) return values end # transform the ranks to quantiles of a standard normal distribution applying the # "α-β correction" recommended in Eq 6.10.3 of # Blom. Statistical Estimates and Transformed Beta-Variables. Wiley; New York, 1958 function _normal_quantiles_from_ranks!(q, r; α=3//8) n = length(r) q .= (r .- α) ./ (n - 2α + 1) return q end # utilities for supporting input arrays with an arbitrary number of dimensions _sample_dims(x::AbstractArray) = ntuple(identity, min(2, ndims(x))) _param_dims(x::AbstractArray) = ntuple(i -> i + 2, max(0, ndims(x) - 2)) _param_axes(x::AbstractArray) = map(Base.Fix1(axes, x), _param_dims(x)) function _params_array(x::AbstractArray, param_dim::Int=3) param_dim > 0 || throw(ArgumentError("param_dim must be positive")) sample_sizes = ntuple(Base.Fix1(size, x), param_dim - 1) return reshape(x, sample_sizes..., :) end function _eachparam(x::AbstractArray, param_dim::Int=3) return eachslice(_params_array(x, param_dim); dims=param_dim) end # convert 0-dimensional arrays to scalars _maybescalar(x::AbstractArray{<:Any,0}) = x[] _maybescalar(x::AbstractArray) = x
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
297
using MCMCDiagnosticTools using Aqua using Test @testset "Aqua" begin # Test ambiguities separately without Base and Core # Ref: https://github.com/JuliaTesting/Aqua.jl/issues/77 Aqua.test_all(MCMCDiagnosticTools; ambiguities=false) Aqua.test_ambiguities(MCMCDiagnosticTools) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
923
@testset "bfmi.jl" begin energy = [1, 2, 3, 4] @test @inferred(bfmi(energy)) isa Real # compare with energy value computed by hand @test bfmi(energy) ≈ 0.6 # energy values derived from sampling a 10-dimensional Cauchy energy = [ 42, 44, 45, 46, 42, 43, 36, 36, 31, 36, 36, 32, 36, 31, 31, 29, 29, 30, 25, 26, 29, 29, 27, 30, 31, 29, ] # compare with energy value computed by Python's arviz.bfmi(energy) @test bfmi(energy) ≈ 0.2406937229 energy_multichain = repeat(energy, 1, 4) @test @inferred(bfmi(energy_multichain)) isa Vector{<:Real} @test bfmi(energy_multichain) ≈ fill(0.2406937229, 4) @test bfmi(energy_multichain) ≈ bfmi(energy_multichain'; dims=2) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
1169
@testset "discretediag.jl" begin nparams = 4 ndraws = 100 nchains = 2 samples = rand(-100:100, ndraws, nchains, nparams) @testset "results" begin for method in (:weiss, :hangartner, :DARBOOT, :MCBOOT, :billingsley, :billingsleyBOOT) between_chain, within_chain = @inferred(discretediag(samples; method=method)) @test between_chain isa NamedTuple{(:stat, :df, :pvalue)} for name in (:stat, :df, :pvalue) x = getfield(between_chain, name) @test x isa Vector{Float64} @test length(x) == nparams end @test within_chain isa NamedTuple{(:stat, :df, :pvalue)} for name in (:stat, :df, :pvalue) x = getfield(within_chain, name) @test x isa Matrix{Float64} @test size(x) == (nparams, nchains) end end end @testset "exceptions" begin @test_throws ArgumentError discretediag(samples; method=:somemethod) for x in (-0.3, 0, 1, 1.2) @test_throws ArgumentError discretediag(samples; frac=x) end end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
17319
using Distributions using DynamicHMC using FFTW: FFTW using LogDensityProblems using LogExpFunctions using OffsetArrays using MCMCDiagnosticTools using MCMCDiagnosticTools: _rank_normalize using Random using Statistics using StatsBase using Test struct ExplicitAutocovMethod <: MCMCDiagnosticTools.AbstractAutocovMethod end struct ExplicitESSCache{S} samples::S end function MCMCDiagnosticTools.build_cache( ::ExplicitAutocovMethod, samples::Matrix, var::Vector ) return ExplicitESSCache(samples) end MCMCDiagnosticTools.update!(::ExplicitESSCache) = nothing function MCMCDiagnosticTools.mean_autocov(k::Int, cache::ExplicitESSCache) return mean(autocov(cache.samples, k:k; demean=true)) end struct CauchyProblem end LogDensityProblems.logdensity(p::CauchyProblem, θ) = -sum(log1psq, θ) function LogDensityProblems.logdensity_and_gradient(p::CauchyProblem, θ) return -sum(log1psq, θ), -2 .* θ ./ (1 .+ θ .^ 2) end LogDensityProblems.dimension(p::CauchyProblem) = 50 function LogDensityProblems.capabilities(p::CauchyProblem) return LogDensityProblems.LogDensityOrder{1}() end mymean(x) = mean(x) @testset "ess_rhat.jl" begin @testset "ess/ess_rhat/rhat basics" begin @testset "only promote eltype when necessary" begin sizes = ((100,), (100, 4), (100, 4, 2), (100, 4, 2, 3)) @testset for kind in (:rank, :bulk, :tail, :basic), sz in sizes @testset for T in (Float32, Float64, Int) x = T <: Int ? rand(1:10, sz...) : rand(T, sz...) TV = length(sz) < 3 ? float(T) : Array{float(T),length(sz) - 2} kind === :rank || @test @inferred(ess(x; kind=kind)) isa TV @test @inferred(rhat(x; kind=kind)) isa TV @test @inferred(ess_rhat(x; kind=kind)) isa NamedTuple{(:ess, :rhat),Tuple{TV,TV}} end end @testset for kind in (mean, median, mad, std, Base.Fix2(quantile, 0.25)), sz in sizes @testset for T in (Float32, Float64, Int) x = T <: Int ? rand(1:10, sz...) : rand(T, sz...) TV = length(sz) < 3 ? float(T) : Array{float(T),length(sz) - 2} @test @inferred(ess(x; kind=kind)) isa TV end end end @testset "errors" begin # check that issue #137 is fixed x = rand(4, 3, 5) x2 = rand(5, 3, 5) x3 = rand(100, 3, 5) x4 = rand(1, 3, 5) @testset for f in (ess, ess_rhat) @testset for kind in (:rank, :bulk, :tail, :basic) f === ess && kind === :rank && continue if f === ess @test all(isnan, f(x; split_chains=1, kind=kind)) @test all(isnan, f(x4; split_chains=2, kind=kind)) else @test all(isnan, f(x; split_chains=1, kind=kind).ess) @test f(x; split_chains=1, kind=kind).rhat == rhat(x; split_chains=1, kind=kind) @test all(isnan, f(x4; split_chains=2, kind=kind).ess) end f(x2; split_chains=1, kind=kind) if f === ess @test all(isnan, f(x2; split_chains=2, kind=kind)) else @test all(isnan, f(x2; split_chains=2, kind=kind).ess) @test f(x2; split_chains=2, kind=kind).rhat == rhat(x2; split_chains=2, kind=kind) end f(x3; maxlag=1, kind=kind) @test_throws DomainError f(x3; maxlag=0, kind=kind) end @test_throws ArgumentError f(x2; kind=:foo) end @test_throws ArgumentError rhat(x2; kind=:foo) @test_throws ArgumentError ess(x2; kind=mymean) end @testset "relative=true" begin @testset for kind in (:rank, :bulk, :tail, :basic), niter in (50, 100), nchains in (2, 4) ss = niter * nchains x = rand(niter, nchains, 2) kind === :rank || @test ess(x; kind, relative=true) ≈ ess(x; kind) / ss S, R = ess_rhat(x; kind) S2, R2 = ess_rhat(x; kind, relative=true) @test S2 ≈ S / ss @test R2 == R end end @testset "Union{Missing,Float64} eltype" begin @testset for kind in (:rank, :bulk, :tail, :basic) x = Array{Union{Missing,Float64}}(undef, 1000, 4, 3) x .= randn.() x[1, 1, 1] = missing S1 = ess(x; kind=kind === :rank ? :bulk : kind) R1 = rhat(x; kind=kind) S2, R2 = ess_rhat(x; kind=kind) @test ismissing(S1[1]) @test ismissing(R1[1]) @test ismissing(S2[1]) @test ismissing(R2[1]) @test !any(ismissing, S1[2:3]) @test !any(ismissing, R1[2:3]) @test !any(ismissing, S2[2:3]) @test !any(ismissing, R2[2:3]) end end @testset "produces similar arrays to inputs" begin @testset for kind in (:rank, :bulk, :tail, :basic), _axes in ((-5:94, 2:5, 11:15), (-5:94, 2:5, 11:15, 0:2)) # simultaneously checks that we index correctly and that output types are correct x = randn(map(length, _axes)...) N = ndims(x) y = OffsetArray(x, _axes...) S11 = ess(y; kind=kind === :rank ? :bulk : kind) R11 = rhat(y; kind=kind) S12, R12 = ess_rhat(y; kind=kind) @test S11 isa OffsetArray{Float64,N - 2} @test S12 isa OffsetArray{Float64,N - 2} @test R11 isa OffsetArray{Float64,N - 2} @test R12 isa OffsetArray{Float64,N - 2} @test axes(S11) == axes(S12) == axes(R11) == axes(R12) == _axes[3:end] S21 = ess(x; kind=kind === :rank ? :bulk : kind) R21 = rhat(x; kind=kind) S22, R22 = ess_rhat(x; kind=kind) @test S22 == S21 == collect(S21) @test R21 == R22 == collect(R11) y = OffsetArray(similar(x, Missing), _axes...) S31 = ess(y; kind=kind === :rank ? :bulk : kind) R31 = rhat(y; kind=kind) S32, R32 = ess_rhat(y; kind=kind) @test S31 isa OffsetArray{Missing,N - 2} @test S32 isa OffsetArray{Missing,N - 2} @test R31 isa OffsetArray{Missing,N - 2} @test R32 isa OffsetArray{Missing,N - 2} @test axes(S31) == axes(S32) == axes(R31) == axes(R32) == _axes[3:end] end end @testset "ess, ess_rhat, and rhat consistency" begin x = randn(1000, 4, 10, 3) @testset for kind in (:rank, :bulk, :tail, :basic), split_chains in (1, 2) R1 = rhat(x; kind, split_chains) for i in axes(x, 4) @test rhat(x[:, :, :, i]; kind, split_chains) == R1[:, i] for j in axes(x, 3) @test rhat(x[:, :, j, i]; kind, split_chains) == R1[j, i] end end @testset for autocov_method in (AutocovMethod(), BDAAutocovMethod()), maxlag in (100, 10) kind_ess = kind === :rank ? :bulk : kind S1 = ess(x; kind=kind_ess, split_chains, autocov_method, maxlag) S2, R2 = ess_rhat(x; kind, split_chains, autocov_method, maxlag) @test S1 == S2 @test R1 == R2 for i in axes(x, 4) xi = x[:, :, :, i] @test ess( xi; kind=kind_ess, split_chains, autocov_method, maxlag ) == S1[:, i] @test ess_rhat(xi; kind, split_chains, autocov_method, maxlag) == (ess=S1[:, i], rhat=R1[:, i]) for j in axes(x, 3) xji = x[:, :, j, i] @test ess( xji; kind=kind_ess, split_chains, autocov_method, maxlag ) == S1[j, i] @test ess_rhat( xji; kind, split_chains, autocov_method, maxlag ) == (ess=S1[j, i], rhat=R1[j, i]) end end end end end end # now that we have checked mutual consistency of each method, we perform all following # checks for whichever method is most convenient @testset "ESS and R̂ (IID samples)" begin # Repeat tests with different scales @testset for scale in (1, 50, 100), nchains in (1, 10), split_chains in (1, 2) x = scale * randn(10_000, nchains, 40) ntotal = size(x, 1) * size(x, 2) ess_standard, rhat_standard = ess_rhat(x; split_chains=split_chains) ess_standard2, rhat_standard2 = ess_rhat( x; split_chains=split_chains, autocov_method=AutocovMethod() ) ess_fft, rhat_fft = ess_rhat( x; split_chains=split_chains, autocov_method=FFTAutocovMethod() ) ess_bda, rhat_bda = ess_rhat( x; split_chains=split_chains, autocov_method=BDAAutocovMethod() ) # check that we get (roughly) the same results @test ess_standard == ess_standard2 @test ess_standard ≈ ess_fft @test rhat_standard == rhat_standard2 == rhat_fft == rhat_bda # check that the estimates are reasonable @test all(x -> isapprox(x, ntotal; rtol=0.1), ess_standard) @test all(x -> isapprox(x, ntotal; rtol=0.1), ess_bda) @test all(x -> isapprox(x, 1; rtol=0.1), rhat_standard) # BDA method fluctuates more @test var(ess_standard) < var(ess_bda) end end @testset "ESS and R̂ (identical samples)" begin x = ones(10_000, 10, 40) ess_standard, rhat_standard = ess_rhat(x) ess_standard2, rhat_standard2 = ess_rhat(x; autocov_method=AutocovMethod()) ess_fft, rhat_fft = ess_rhat(x; autocov_method=FFTAutocovMethod()) ess_bda, rhat_bda = ess_rhat(x; autocov_method=BDAAutocovMethod()) # check that the estimates are all NaN for ess in (ess_standard, ess_standard2, ess_fft, ess_bda) @test all(isnan, ess) end for rhat in (rhat_standard, rhat_standard2, rhat_fft, rhat_bda) @test all(isnan, rhat) end end @testset "Autocov of AutocovMethod and FFTAutocovMethod equivalent to StatsBase" begin x = randn(1_000, 10, 40) ess_exp = ess(x; autocov_method=ExplicitAutocovMethod()) @testset "$autocov_method" for autocov_method in [FFTAutocovMethod(), AutocovMethod()] @test ess(x; autocov_method=autocov_method) ≈ ess_exp end end @testset "ESS and R̂ for chains with 2 epochs that have not mixed" begin # checks that splitting yields lower ESS estimates and higher Rhat estimates x = randn(1000, 4, 10) .+ repeat([0, 10]; inner=(500, 1, 1)) ess_array, rhat_array = ess_rhat(x; kind=:basic, split_chains=1) @test all(x -> isapprox(x, 1; rtol=0.1), rhat_array) ess_array2, rhat_array2 = ess_rhat(x; kind=:basic, split_chains=2) @test all(ess_array2 .< ess_array) @test all(>(2), rhat_array2) end @testset "ess(x; kind=f)" begin # we check the ESS estimates by simulating uncorrelated, correlated, and # anticorrelated chains, mapping the draws to a target distribution, computing the # estimand, and estimating the ESS for the chosen estimator, computing the # corresponding MCSE, and checking that the mean estimand is close to the asymptotic # value of the estimand, with a tolerance chosen using the MCSE. ndraws = 1000 nchains = 4 nparams = 100 x = randn(ndraws, nchains, nparams) mymean(x; kwargs...) = mean(x; kwargs...) @test_throws ArgumentError ess(x; kind=mymean) estimators = [mean, median, std, mad, Base.Fix2(quantile, 0.25)] dists = [Normal(10, 100), Exponential(10), TDist(7) * 10 - 20] # AR(1) coefficients. 0 is IID, -0.3 is slightly anticorrelated, 0.9 is highly autocorrelated φs = [-0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9] # account for all but the 2 skipped checks nchecks = nparams * length(φs) * ((length(estimators) - 1) * length(dists) + 1) α = (0.01 / nchecks) / 2 # multiple correction @testset for f in estimators, dist in dists, φ in φs f === mad && !(dist isa Normal) && continue σ = sqrt(1 - φ^2) # ensures stationary distribution is N(0, 1) x = ar1(φ, σ, ndraws, nchains, nparams) x .= quantile.(dist, cdf.(Normal(), x)) # stationary distribution is dist μ_mean = dropdims(mapslices(f ∘ vec, x; dims=(1, 2)); dims=(1, 2)) dist = asymptotic_dist(f, dist) n = @inferred(ess(x; kind=f)) μ = mean(dist) mcse = sqrt.(var(dist) ./ n) for i in eachindex(μ_mean, mcse) atol = quantile(Normal(0, mcse[i]), 1 - α) @test μ_mean[i] ≈ μ atol = atol end end end @testset "ESS thresholded for antithetic chains" begin # for φ = -0.3 (slightly antithetic), ESS without thresholding for low ndraws is # often >ndraws*log10(ndraws) # for φ = -0.9 (highly antithetic), ESS without thresholding for low ndraws is # usually negative nchains = 4 @testset for ndraws in (10, 100), φ in (-0.3, -0.9) x = ar1(φ, sqrt(1 - φ^2), ndraws, nchains, 1000) Smin, Smax = extrema(ess(x; kind=mean)) ntotal = ndraws * nchains @test Smax == ntotal * log10(ntotal) @test Smin > 0 end end @testset "ess(x; kind=:bulk)" begin xnorm = randn(1_000, 4, 10) @test ess(xnorm; kind=:bulk) == ess(_rank_normalize(xnorm); kind=:basic) xcauchy = quantile.(Cauchy(), cdf.(Normal(), xnorm)) # transformation by any monotonic function should not change the bulk ESS/R-hat @test ess(xnorm; kind=:bulk) == ess(xcauchy; kind=:bulk) end @testset "tail- ESS and R-hat detect mismatched scales" begin # simulate chains with same stationary mean but different stationary scales φ = 0.1 # low autocorrelation σs = sqrt(1 - φ^2) .* [0.1, 1, 10, 100] ndraws = 1_000 nparams = 100 x = 10 .+ mapreduce(hcat, σs) do σ return ar1(φ, σ, ndraws, 1, nparams) end # recommended convergence thresholds ess_cutoff = 100 * size(x, 2) # recommended cutoff is 100 * nchains rhat_cutoff = 1.01 # sanity check that standard and bulk ESS and R-hat both fail to detect # mismatched scales S, R = ess_rhat(x; kind=:basic) @test all(≥(ess_cutoff), S) @test all(≤(rhat_cutoff), R) Sbulk, Rbulk = ess_rhat(x; kind=:bulk) @test all(≥(ess_cutoff), Sbulk) @test all(≤(rhat_cutoff), Rbulk) # check that tail- ESS detects mismatched scales and signal poor convergence S_tail, R_tail = ess_rhat(x; kind=:tail) @test all(<(ess_cutoff), S_tail) @test all(>(rhat_cutoff), R_tail) end @testset "bulk and tail ESS and R-hat for heavy tailed" begin # sampling Cauchy distribution with large max depth to allow for better tail # exploration. From https://avehtari.github.io/rhat_ess/rhat_ess.html chains have # okay bulk ESS and R-hat values, while some tail ESS and R-hat values are poor. prob = CauchyProblem() reporter = NoProgressReport() algorithm = DynamicHMC.NUTS(; max_depth=20) rng = Random.default_rng() posterior_matrices = map(1:4) do _ # ~2.5 mins to sample result = mcmc_with_warmup(rng, prob, 1_000; algorithm=algorithm, reporter=reporter) hasproperty(result, :posterior_matrix) && return result.posterior_matrix return reduce(hcat, result.chain) end x = permutedims(cat(posterior_matrices...; dims=3), (2, 3, 1)) Sbulk, Rbulk = ess_rhat(x; kind=:bulk) Stail, Rtail = ess_rhat(x; kind=:tail) ess_cutoff = 100 * size(x, 2) # recommended cutoff is 100 * nchains @test mean(≥(ess_cutoff), Sbulk) > 0.9 @test mean(≥(ess_cutoff), Stail) < mean(≥(ess_cutoff), Sbulk) @test mean(≤(1.01), Rbulk) > 0.9 @test mean(≤(1.01), Rtail) < 0.8 end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
977
@testset "gelmandiag.jl" begin nparams = 4 ndraws = 100 nchains = 2 samples = randn(ndraws, nchains, nparams) @testset "results" begin result = @inferred(gelmandiag(samples)) @test result isa NamedTuple{(:psrf, :psrfci)} for name in (:psrf, :psrfci) x = getfield(result, name) @test x isa Vector{Float64} @test length(x) == nparams end result = @inferred(gelmandiag_multivariate(samples)) @test result isa NamedTuple{(:psrf, :psrfci, :psrfmultivariate)} for name in (:psrf, :psrfci) x = getfield(result, name) @test x isa Vector{Float64} @test length(x) == nparams end @test result.psrfmultivariate isa Float64 end @testset "exceptions" begin @test_throws ErrorException gelmandiag(samples[:, 1:1, :]) @test_throws ErrorException gelmandiag_multivariate(samples[:, :, 1:1]) end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
577
@testset "gewekediag.jl" begin @testset "results" begin @testset for T in (Float32, Float64) samples = randn(T, 100) @inferred NamedTuple{(:zscore, :pvalue),Tuple{T,T}} gewekediag(samples) end end @testset "exceptions" begin samples = randn(100) for x in (-0.3, 0, 1, 1.2) @test_throws ArgumentError gewekediag(samples; first=x) @test_throws ArgumentError gewekediag(samples; last=x) end @test_throws ArgumentError gewekediag(samples; first=0.6, last=0.5) end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
229
@testset "heideldiag.jl" begin @testset "results" begin @testset for T in (Float32, Float64) samples = randn(T, 100) @test @inferred(heideldiag(samples)) isa NamedTuple end end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
1183
using Distributions, Statistics, StatsBase # AR(1) process function ar1(φ::Real, σ::Real, n::Int...) T = float(Base.promote_eltype(φ, σ)) x = randn(T, n...) x .*= σ accumulate!(x, x; dims=1) do xi, ϵ return muladd(φ, xi, ϵ) end return x end asymptotic_dist(::typeof(mean), dist) = Normal(mean(dist), std(dist)) function asymptotic_dist(::typeof(var), dist) μ = var(dist) σ = μ * sqrt(kurtosis(dist) + 2) return Normal(μ, σ) end function asymptotic_dist(::typeof(std), dist) μ = std(dist) σ = μ * sqrt(kurtosis(dist) + 2) / 2 return Normal(μ, σ) end asymptotic_dist(::typeof(median), dist) = asymptotic_dist(Base.Fix2(quantile, 1//2), dist) function asymptotic_dist(f::Base.Fix2{typeof(quantile),<:Real}, dist) p = f.x μ = quantile(dist, p) σ = sqrt(p * (1 - p)) / pdf(dist, μ) return Normal(μ, σ) end function asymptotic_dist(::typeof(mad), dist::Normal) # Example 21.10 of Asymptotic Statistics. Van der Vaart d = Normal(zero(dist.μ), dist.σ) dtrunc = truncated(d; lower=0) μ = median(dtrunc) σ = 1 / (4 * pdf(d, quantile(d, 3//4))) return Normal(μ, σ) / quantile(Normal(), 3//4) end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
4976
using Test using Distributions using MCMCDiagnosticTools using OffsetArrays using Statistics using StatsBase @testset "mcse.jl" begin @testset "estimator defaults to mean" begin x = randn(100, 4, 10) @test mcse(x) == mcse(x; kind=mean) end @testset "ESS-based methods forward kwargs to ess" begin x = randn(100, 4, 10) @testset for f in [mean, median, std, Base.Fix2(quantile, 0.1)] @test @inferred(mcse(x; kind=f, split_chains=1)) ≠ mcse(x; kind=f) end end @testset "mcse falls back to _mcse_sbm" begin x = randn(100, 4, 10) estimator = mad @test @inferred(mcse(x; kind=estimator)) == MCMCDiagnosticTools._mcse_sbm(estimator, x) ≠ MCMCDiagnosticTools._mcse_sbm(estimator, x; batch_size=16) == mcse(x; kind=estimator, batch_size=16) end @testset "handles all sizes correctly" begin @testset for f in [mean, median, std, Base.Fix2(quantile, 0.1), mad] x = randn(100, 4, 3, 2) se = @inferred mcse(x; kind=f) for i in axes(x, 4) xi = x[:, :, :, i] @test @inferred(mcse(xi; kind=f)) ≈ se[:, i] for j in axes(x, 3) xij = xi[:, :, j] @test @inferred(mcse(xij; kind=f)) ≈ se[j, i] end end xv = x[:, 1, 1, 1] @test @inferred(mcse(xv; kind=f)) ≈ mcse(reshape(xv, :, 1); kind=f) end end @testset "mcse produces similar vectors to inputs" begin # simultaneously checks that we index correctly and that output types are correct _axes = (-5:94, 2:5, 11:15, 0:1) @testset for T in (Float32, Float64), estimator in [mean, median, std, Base.Fix2(quantile, T(0.1)), mad], _axes in ((-5:94, 2:5, 11:15), (-5:94, 2:5, 11:15, 0:1)) N = length(_axes) - 2 x = randn(T, map(length, _axes)...) y = OffsetArray(x, _axes...) se = mcse(y; kind=estimator) @test se isa OffsetArray{T,N} @test axes(se) == _axes[3:end] se2 = mcse(x; kind=estimator) @test se2 ≈ collect(se) # quantile errors if data contains missings estimator isa Base.Fix2{typeof(quantile)} && continue y = OffsetArray(similar(x, Missing), _axes...) @test mcse(y; kind=estimator) isa OffsetArray{Missing,N} end end @testset "mcse with Union{Missing,Float64} eltype" begin @testset for sz in ((1000, 4), (1000, 4, 3)) x = Array{Union{Missing,Float64}}(undef, sz...) x .= randn.() x[1] = missing @testset for f in [mean, median, std, mad] se = mcse(x; kind=f) if ndims(x) > 2 @test ismissing(se[1]) @test !any(ismissing, se[2:end]) else @test ismissing(se) end end end end @testset "estimand is within interval defined by MCSE estimate" begin # we check the MCSE estimates by simulating uncorrelated, correlated, and # anticorrelated chains, mapping the draws to a target distribution, computing the # estimand, estimating the MCSE for the chosen estimator, and checking that the mean # estimand is close to the asymptotic value of the estimand, with a tolerance chosen # using the MCSE. ndraws = 1000 nchains = 4 nparams = 100 estimators = [mean, median, std, Base.Fix2(quantile, 0.25)] dists = [Normal(10, 100), Exponential(10), TDist(7) * 10 - 20] mcse_methods = [mcse, MCMCDiagnosticTools._mcse_sbm] # AR(1) coefficients. 0 is IID, -0.3 is slightly anticorrelated, 0.9 is highly autocorrelated φs = [-0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9] # account for all but the 2 skipped checks nchecks = nparams * (length(φs) + count(≤(5), φs)) * length(dists) α = (0.01 / nchecks) / 2 # multiple correction @testset for mcse in mcse_methods, f in estimators, dist in dists, φ in φs # _mcse_sbm underestimates the MCSE for highly correlated chains mcse === MCMCDiagnosticTools._mcse_sbm && φ > 0.5 && continue σ = sqrt(1 - φ^2) # ensures stationary distribution is N(0, 1) x = ar1(φ, σ, ndraws, nchains, nparams) x .= quantile.(dist, cdf.(Normal(), x)) # stationary distribution is dist μ_mean = dropdims(mapslices(f ∘ vec, x; dims=(1, 2)); dims=(1, 2)) μ = mean(asymptotic_dist(f, dist)) se = mcse === MCMCDiagnosticTools._mcse_sbm ? mcse(f, x) : mcse(x; kind=f) for i in eachindex(μ_mean, se) atol = quantile(Normal(0, se[i]), 1 - α) @test μ_mean[i] ≈ μ atol = atol end end end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
256
@testset "rafterydiag.jl" begin samples = randn(5_000) @testset "results" begin @test @inferred(rafterydiag(samples)) isa NamedTuple end @testset "warning" begin @test_logs (:warn,) rafterydiag(samples[1:100]) end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
7897
using MCMCDiagnosticTools using Distributions using EvoTrees using MLJBase: MLJBase, Pipeline, predict_mode using MLJDecisionTreeInterface using MLJLIBSVMInterface using MLJModels using MLJXGBoostInterface using Tables using Random using Test # XGBoost errors on 32bit systems: https://github.com/dmlc/XGBoost.jl/issues/92 const XGBoostClassifiers = if Sys.WORD_SIZE == 64 (XGBoostClassifier(), Pipeline(XGBoostClassifier(); operation=predict_mode)) else () end @testset "rstar.jl" begin N = 1_000 @testset "samples input type: $wrapper" for wrapper in [Vector, Array, Tables.table] # In practice, probably you want to use EvoTreeClassifier with early stopping classifiers = ( EvoTreeClassifier(; nrounds=1_000, eta=0.1), Pipeline(EvoTreeClassifier(; nrounds=1_000, eta=0.1); operation=predict_mode), DecisionTreeClassifier(), SVC(), XGBoostClassifiers..., ) @testset "examples (classifier = $classifier)" for classifier in classifiers sz = wrapper === Vector ? N : (N, 2) # Compute R⋆ statistic for a mixed chain. samples = wrapper(randn(sz...)) dist = rstar(classifier, samples, rand(1:3, N)) # Mean of the statistic should be focused around 1, i.e., the classifier does not # perform better than random guessing. if classifier isa MLJBase.Deterministic @test dist isa Float64 else @test dist isa LocationScale @test dist.ρ isa PoissonBinomial @test minimum(dist) == 0 @test maximum(dist) == 6 end @test mean(dist) ≈ 1 rtol = 0.25 wrapper === Vector && break # Compute R⋆ statistic for a mixed chain. samples = wrapper(randn(4 * N, 8)) chain_indices = repeat(1:4, N) dist = rstar(classifier, samples, chain_indices) # Mean of the statistic should be closte to 1, i.e., the classifier does not perform # better than random guessing. if classifier isa MLJBase.Deterministic @test dist isa Float64 else @test dist isa LocationScale @test dist.ρ isa PoissonBinomial @test minimum(dist) == 0 @test maximum(dist) == 8 end @test mean(dist) ≈ 1 rtol = 0.15 # Compute the R⋆ statistic for a non-mixed chain. samples = wrapper([ sin.(1:N) cos.(1:N) 100 .* cos.(1:N) 100 .* sin.(1:N) ]) chain_indices = repeat(1:2; inner=N) dist = rstar(classifier, samples, chain_indices; split_chains=1) # Mean of the statistic should be close to 2, i.e., the classifier should be able to # learn an almost perfect decision boundary between chains. if classifier isa MLJBase.Deterministic @test dist isa Float64 else @test dist isa LocationScale @test dist.ρ isa PoissonBinomial @test minimum(dist) == 0 @test maximum(dist) == 2 end @test mean(dist) ≈ 2 rtol = 0.15 # Compute the R⋆ statistic for identical chains that individually have not mixed. samples = ones(sz) samples[div(N, 2):end, :] .= 2 chain_indices = repeat(1:4; outer=div(N, 4)) dist = rstar(classifier, samples, chain_indices; split_chains=1) # without split chains cannot distinguish between chains @test mean(dist) ≈ 1 rtol = 0.15 dist = rstar(classifier, samples, chain_indices) # with split chains can learn almost perfect decision boundary @test mean(dist) ≈ 2 rtol = 0.15 end wrapper === Vector && continue @testset "exceptions (classifier = $classifier)" for classifier in classifiers samples = wrapper(randn(N - 1, 2)) @test_throws DimensionMismatch rstar(classifier, samples, rand(1:3, N)) for subset in (-0.3, 0, 1 / (3 * N), 1 - 1 / (3 * N), 1, 1.9) samples = wrapper(randn(N, 2)) @test_throws ArgumentError rstar( classifier, samples, rand(1:3, N); subset=subset ) end end end @testset "table with chain_ids produces same result as 3d array" begin nchains = 3 samples = randn(N, nchains, 2, 4) # manually construct samples_mat and chain_inds for comparison samples_mat = reshape(samples, N * nchains, size(samples, 3) * size(samples, 4)) chain_inds = Vector{Int}(undef, N * nchains) i = 1 for chain in 1:nchains, draw in 1:N chain_inds[i] = chain i += 1 end # In practice, probably you want to use EvoTreeClassifier with early stopping rng = MersenneTwister(42) classifiers = ( EvoTreeClassifier(; rng=rng, nrounds=1_000, eta=0.1), Pipeline( EvoTreeClassifier(; rng=rng, nrounds=1_000, eta=0.1); operation=predict_mode ), DecisionTreeClassifier(; rng=rng), SVC(), XGBoostClassifiers..., ) @testset "classifier = $classifier" for classifier in classifiers Random.seed!(rng, 42) dist1 = rstar(rng, classifier, samples_mat, chain_inds) Random.seed!(rng, 42) dist2 = rstar(rng, classifier, samples) Random.seed!(rng, 42) dist3 = rstar(rng, classifier, reshape(samples, N, nchains, :)) @test dist1 == dist2 == dist3 @test typeof(rstar(classifier, samples)) === typeof(dist2) === typeof(dist3) end end @testset "model traits requirements" begin samples = randn(2, 3, 4) inputs_error = ArgumentError( "classifier does not support tables of continuous values as inputs" ) model = UnivariateDiscretizer() @test_throws inputs_error rstar(model, samples) @test_throws inputs_error MCMCDiagnosticTools._check_model_supports_continuous_inputs( model ) targets_error = ArgumentError( "classifier does not support vectors of multi-class labels as targets" ) predictions_error = ArgumentError( "classifier does not support vectors of multi-class labels or their densities as predictions", ) models = if Sys.WORD_SIZE == 64 (EvoTreeRegressor(), EvoTreeCount(), XGBoostRegressor(), XGBoostCount()) else (EvoTreeRegressor(), EvoTreeCount()) end for model in models @test_throws targets_error rstar(model, samples) @test_throws targets_error MCMCDiagnosticTools._check_model_supports_multiclass_targets( model ) @test_throws predictions_error MCMCDiagnosticTools._check_model_supports_multiclass_predictions( model ) end end @testset "incorrect type of predictions" begin @test_throws ArgumentError MCMCDiagnosticTools._rstar( AbstractVector{<:MLJBase.Continuous}, rand(2), rand(3) ) @test_throws ArgumentError MCMCDiagnosticTools._rstar(1.0, rand(2), rand(2)) end @testset "single chain: method ambiguity issue" begin samples = rand(1:5, N) rng = MersenneTwister(42) dist = rstar(rng, DecisionTreeClassifier(), samples) @test mean(dist) ≈ 1 atol = 0.15 Random.seed!(rng, 42) dist2 = rstar(rng, DecisionTreeClassifier(), samples, ones(Int, N)) @test dist2 == dist end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
1067
using MCMCDiagnosticTools using FFTW using Random using Statistics using Test Random.seed!(1) @testset "MCMCDiagnosticTools.jl" begin include("helpers.jl") @testset "Aqua" begin include("aqua.jl") end @testset "utils" begin include("utils.jl") end @testset "Bayesian fraction of missing information" begin include("bfmi.jl") end @testset "discrete diagnostic" begin include("discretediag.jl") end @testset "ESS and R̂" begin include("ess_rhat.jl") end @testset "Monte Carlo standard error" begin include("mcse.jl") end @testset "Gelman, Rubin and Brooks diagnostic" begin include("gelmandiag.jl") end @testset "Geweke diagnostic" begin include("gewekediag.jl") end @testset "Heidelberger and Welch diagnostic" begin include("heideldiag.jl") end @testset "Raftery and Lewis diagnostic" begin include("rafterydiag.jl") end @testset "R⋆ diagnostic" begin include("rstar.jl") end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
code
7978
using MCMCDiagnosticTools using Test using OffsetArrays using Random using Statistics @testset "unique_indices" begin @testset "indices=$(eachindex(inds))" for inds in [ rand(11:14, 100), transpose(rand(11:14, 10, 10)) ] unique, indices = @inferred MCMCDiagnosticTools.unique_indices(inds) @test unique isa Vector{Int} if eachindex(inds) isa CartesianIndices{2} @test indices isa Vector{Vector{CartesianIndex{2}}} else @test indices isa Vector{Vector{Int}} end @test issorted(unique) @test issetequal(union(indices...), eachindex(inds)) for i in eachindex(unique, indices) @test all(inds[indices[i]] .== unique[i]) end end end @testset "copy_split!" begin # check a matrix with even number of rows x = rand(50, 20) # check incompatible sizes @test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(similar(x, 25, 20), x) @test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(similar(x, 50, 40), x) y = similar(x, 25, 40) MCMCDiagnosticTools.copyto_split!(y, x) @test reshape(y, size(x)) == x # check a matrix with odd number of rows x = rand(51, 20) # check incompatible sizes @test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(similar(x, 25, 20), x) @test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(similar(x, 51, 40), x) MCMCDiagnosticTools.copyto_split!(y, x) @test reshape(y, 50, 20) == x[vcat(1:25, 27:51), :] # check with 3 splits y = similar(x, 16, 60) x = rand(50, 20) MCMCDiagnosticTools.copyto_split!(y, x) @test reshape(y, 48, :) == x[vcat(1:16, 18:33, 35:50), :] x = rand(49, 20) MCMCDiagnosticTools.copyto_split!(y, x) @test reshape(y, 48, :) == x[vcat(1:16, 18:33, 34:49), :] end @testset "split_chain_indices" begin c = [2, 2, 1, 3, 4, 3, 4, 1, 2, 1, 4, 3, 3, 2, 4, 3, 4, 1, 4, 1] @test @inferred(MCMCDiagnosticTools.split_chain_indices(c, 1)) == c cnew = @inferred MCMCDiagnosticTools.split_chain_indices(c, 2) @test issetequal(Base.unique(cnew), 1:maximum(cnew)) # check no indices skipped unique, indices = MCMCDiagnosticTools.unique_indices(c) uniquenew, indicesnew = MCMCDiagnosticTools.unique_indices(cnew) for (i, inew) in enumerate(1:2:7) @test length(indicesnew[inew]) ≥ length(indicesnew[inew + 1]) @test indices[i] == vcat(indicesnew[inew], indicesnew[inew + 1]) end cnew = MCMCDiagnosticTools.split_chain_indices(c, 3) @test issetequal(Base.unique(cnew), 1:maximum(cnew)) # check no indices skipped unique, indices = MCMCDiagnosticTools.unique_indices(c) uniquenew, indicesnew = MCMCDiagnosticTools.unique_indices(cnew) for (i, inew) in enumerate(1:3:11) @test length(indicesnew[inew]) ≥ length(indicesnew[inew + 1]) ≥ length(indicesnew[inew + 2]) @test indices[i] == vcat(indicesnew[inew], indicesnew[inew + 1], indicesnew[inew + 2]) end end @testset "shuffle_split_stratified" begin rng = Random.default_rng() c = rand(1:4, 100) unique, indices = MCMCDiagnosticTools.unique_indices(c) @testset "frac=$frac" for frac in [0.3, 0.5, 0.7] inds1, inds2 = @inferred(MCMCDiagnosticTools.shuffle_split_stratified(rng, c, frac)) @test issetequal(vcat(inds1, inds2), eachindex(c)) for inds in indices common_inds = intersect(inds1, inds) @test length(common_inds) == round(frac * length(inds)) end end end @testset "_rank_normalize" begin @testset for sz in ((1000,), (1000, 4), (1000, 4, 8), (1000, 4, 8, 2)) x = randexp(sz...) dims = MCMCDiagnosticTools._sample_dims(x) z = @inferred MCMCDiagnosticTools._rank_normalize(x) @test size(z) == size(x) @test all(xi -> isapprox(xi, 0; atol=1e-13), mean(z; dims)) @test all(xi -> isapprox(xi, 1; rtol=1e-2), std(z; dims)) end end @testset "_fold_around_median" begin @testset for sz in ((1000,), (1000, 4), (1000, 4, 8), (1000, 4, 8, 2)) x = rand(sz...) dims = MCMCDiagnosticTools._sample_dims(x) @inferred MCMCDiagnosticTools._fold_around_median(x) @test MCMCDiagnosticTools._fold_around_median(x) ≈ abs.(x .- median(x; dims)) x = Array{Union{Missing,Float64}}(undef, sz...) x .= randn.() x[1] = missing foldx = @inferred(MCMCDiagnosticTools._fold_around_median(x)) @test all(ismissing, foldx[:, :, 1, 1]) length(sz) > 2 && @test foldx[:, :, 2:end, :] ≈ abs.(x[:, :, 2:end, :] .- median(x[:, :, 2:end, :]; dims)) end end @testset "_sample_dims" begin x = randn(10) @test @inferred(MCMCDiagnosticTools._sample_dims(x)) === (1,) x = randn(10, 2) @test @inferred(MCMCDiagnosticTools._sample_dims(x)) === (1, 2) x = randn(10, 2, 3) @test @inferred(MCMCDiagnosticTools._sample_dims(x)) === (1, 2) x = randn(10, 2, 3, 4) @test @inferred(MCMCDiagnosticTools._sample_dims(x)) === (1, 2) end @testset "_param_dims" begin x = randn(10) @test @inferred(MCMCDiagnosticTools._param_dims(x)) === () x = randn(10, 2) @test @inferred(MCMCDiagnosticTools._param_dims(x)) === () x = randn(10, 2, 3) @test @inferred(MCMCDiagnosticTools._param_dims(x)) === (3,) x = randn(10, 2, 3, 4) @test @inferred(MCMCDiagnosticTools._param_dims(x)) === (3, 4) end @testset "_param_axes" begin x = OffsetArray(randn(10), -4:5) @test @inferred(MCMCDiagnosticTools._param_axes(x)) === () x = OffsetArray(randn(10, 2), -4:5, 0:1) @test @inferred(MCMCDiagnosticTools._param_axes(x)) === () x = OffsetArray(randn(10, 2, 3), -4:5, 0:1, -3:-1) @test @inferred(MCMCDiagnosticTools._param_axes(x)) === (axes(x, 3),) x = OffsetArray(randn(10, 2, 3, 4), -4:5, 0:1, -3:-1, 0:3) @test @inferred(MCMCDiagnosticTools._param_axes(x)) === (axes(x, 3), axes(x, 4)) end @testset "_params_array" begin x = randn(10) @test MCMCDiagnosticTools._params_array(x) == reshape(x, :, 1, 1) @test MCMCDiagnosticTools._params_array(x, 1) == x @test MCMCDiagnosticTools._params_array(x, 2) == reshape(x, :, 1) @test MCMCDiagnosticTools._params_array(x, 3) == reshape(x, :, 1, 1) @test MCMCDiagnosticTools._params_array(x, 4) == reshape(x, :, 1, 1, 1) x = randn(10, 2) @test MCMCDiagnosticTools._params_array(x) == reshape(x, size(x)..., 1) @test MCMCDiagnosticTools._params_array(x, 1) == vec(x) @test MCMCDiagnosticTools._params_array(x, 2) == x @test MCMCDiagnosticTools._params_array(x, 3) == reshape(x, size(x)..., 1) @test MCMCDiagnosticTools._params_array(x, 4) == reshape(x, size(x)..., 1, 1) x = randn(10, 2, 3) @test MCMCDiagnosticTools._params_array(x) == x @test MCMCDiagnosticTools._params_array(x, 1) == vec(x) @test MCMCDiagnosticTools._params_array(x, 2) == reshape(x, size(x, 1), :) @test MCMCDiagnosticTools._params_array(x, 3) == x @test MCMCDiagnosticTools._params_array(x, 4) == reshape(x, size(x)..., 1) x = randn(10, 2, 3, 4) @test MCMCDiagnosticTools._params_array(x) == reshape(x, size(x, 1), size(x, 2), :) @test MCMCDiagnosticTools._params_array(x, 1) == vec(x) @test MCMCDiagnosticTools._params_array(x, 2) == reshape(x, size(x, 1), :) @test MCMCDiagnosticTools._params_array(x, 3) == reshape(x, size(x, 1), size(x, 2), :) @test MCMCDiagnosticTools._params_array(x, 4) == x @test_throws ArgumentError MCMCDiagnosticTools._params_array(x, -1) @test_throws ArgumentError MCMCDiagnosticTools._params_array(x, 0) end @testset "_maybescalar" begin sz = (1, 2, 3) @testset for d in 0:length(sz) x = randn(sz[1:d]) if d == 0 @test MCMCDiagnosticTools._maybescalar(x) === x[] else @test MCMCDiagnosticTools._maybescalar(x) === x end end end
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
docs
1597
# MCMCDiagnosticTools.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://turinglang.github.io/MCMCDiagnosticTools.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://turinglang.github.io/MCMCDiagnosticTools.jl/dev) [![Build Status](https://github.com/TuringLang/MCMCDiagnosticTools.jl/workflows/CI/badge.svg?branch=main)](https://github.com/TuringLang/MCMCDiagnosticTools.jl/actions?query=workflow%3ACI+branch%3Amain) [![Coverage](https://codecov.io/gh/TuringLang/MCMCDiagnosticTools.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/TuringLang/MCMCDiagnosticTools.jl) [![Coverage](https://coveralls.io/repos/github/TuringLang/MCMCDiagnosticTools.jl/badge.svg?branch=main)](https://coveralls.io/github/TuringLang/MCMCDiagnosticTools.jl?branch=main) [![Aqua QA](https://raw.githubusercontent.com/JuliaTesting/Aqua.jl/master/badge.svg)](https://github.com/JuliaTesting/Aqua.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) [![ColPrac: Contributor's Guide on Collaborative Practices for Community Packages](https://img.shields.io/badge/ColPrac-Contributor's%20Guide-blueviolet)](https://github.com/SciML/ColPrac) [![Powered by NumFOCUS](https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A)](https://numfocus.org) Functionality for diagnosing samples generated using Markov Chain Monte Carlo. This package is a joint collaboration between the [Turing](https://turinglang.org/) and [ArviZ](https://www.arviz.org/) projects.
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "MIT" ]
0.3.10
8ba8b1840d3ab5b38e7c71c23c3193bb5cbc02b5
docs
1008
```@meta CurrentModule = MCMCDiagnosticTools ``` # MCMCDiagnosticTools MCMCDiagnosticTools provides functionality for diagnosing samples generated using Markov Chain Monte Carlo. ## Background Some methods were originally part of [Mamba.jl](https://github.com/brian-j-smith/Mamba.jl) and then [MCMCChains.jl](https://github.com/TuringLang/MCMCChains.jl). This package is a joint collaboration between the [Turing](https://turinglang.org/) and [ArviZ](https://www.arviz.org/) projects. ## Effective sample size and $\widehat{R}$ ```@docs ess rhat ess_rhat ``` The following `autocov_method`s are supported: ```@docs AutocovMethod FFTAutocovMethod BDAAutocovMethod ``` ## Monte Carlo standard error ```@docs mcse ``` ## R⋆ diagnostic ```@docs rstar ``` ## Bayesian fraction of missing information ```@docs bfmi ``` ## Other diagnostics !!! note These diagnostics are older and less widely used. ```@docs discretediag gelmandiag gelmandiag_multivariate gewekediag heideldiag rafterydiag ```
MCMCDiagnosticTools
https://github.com/TuringLang/MCMCDiagnosticTools.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
1173
using Documenter, GigaSOM makedocs(modules = [GigaSOM], clean = false, format = Documenter.HTML(prettyurls = !("local" in ARGS), canonical = "https://lcsb-biocore.github.io/GigaSOM.jl/stable/", assets = ["assets/gigasomlogotransp.ico"]), sitename = "GigaSOM.jl", authors = "The developers of GigaSOM.jl", linkcheck = !("skiplinks" in ARGS), pages = [ "Home" => "index.md", "Background" => "background.md", "Tutorial" => [ "Introduction" => "tutorials/basicUsage.md", "Cytometry data" => "tutorials/processingFCSData.md", "Advanced distributed processing" => "tutorials/distributedProcessing.md", "Conclusion" => "tutorials/whereToGoNext.md", ], "Functions" => "functions.md", "How to contribute" => "howToContribute.md", ], ) deploydocs( repo = "github.com/LCSB-BioCore/GigaSOM.jl.git", target = "build", branch = "gh-pages", devbranch = "develop", push_preview = true )
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
1304
""" Main module for `GigaSOM.jl` - Huge-scale, high-performance flow cytometry clustering The documentation is here: http://LCSB-BioCore.github.io/GigaSOM.jl """ module GigaSOM using CSV using DataFrames using Distances using Distributed using DistributedData using Distributions using FCSFiles using FileIO using DistributedArrays using NearestNeighbors using Serialization using StableRNGs include("base/structs.jl") include("base/dataops.jl") include("base/trainutils.jl") include("analysis/core.jl") include("analysis/embedding.jl") include("io/input.jl") include("io/process.jl") include("io/splitting.jl") #core export initGigaSOM, trainGigaSOM, mapToGigaSOM #trainutils export linearRadius, expRadius, gaussianKernel, bubbleKernel, thresholdKernel, distMatrix #embedding export embedGigaSOM # structs export Som #io/input export readFlowset, readFlowFrame, loadFCS, loadFCSHeader, getFCSSize, loadFCSSizes, loadFCSSet, selectFCSColumns, distributeFCSFileVector, distributeFileVector, getCSVSize, loadCSV, loadCSVSizes, loadCSVSet #io/splitting export slicesof, vcollectSlice, collectSlice #io/process export cleanNames!, getMetaData, getMarkerNames #dataops (higher-level operations on data) export dtransform_asinh end # module
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
9295
""" initGigaSOM(data, args...) Initializes a SOM by random selection from the training data. A generic overload that works for matrices and DataFrames that can be coerced to `Matrix{Float64}`. Other arguments are passed to the data-independent `initGigaSOM`. Arguments: - `data`: matrix of data for running the initialization """ function initGigaSOM(data::Union{Matrix,DataFrame}, args...; kwargs...) d = Matrix{Float64}(data) (n, ncol) = size(d) means = [sum(d[:, i]) / n for i = 1:ncol] sdevs = [sqrt(sum((d[:, i] .- means[i]) .^ 2.0) / n) for i = 1:ncol] return initGigaSOM(ncol, means, sdevs, args...; kwargs...) end """ function initGigaSOM(data::Dinfo, xdim::Int64, ydim::Int64 = xdim; seed=rand(Int), rng=StableRNG(seed)) `initGigaSOM` overload for working with distributed-style `Dinfo` data. The rest of the arguments is passed to the data-independent `initGigaSOM`. Arguments: - `data`: a `Dinfo` object with the distributed dataset matrix """ function initGigaSOM(data::Dinfo, args...; kwargs...) ncol = get_val_from(data.workers[1], :(size($(data.val))[2])) (means, sdevs) = dstat(data, Vector(1:ncol)) initGigaSOM(ncol, means, sdevs, args...; kwargs...) end """ function initGigaSOM(ncol::Int64, means::Vector{Float64}, sdevs::Vector{Float64}, xdim::Int64, ydim::Int64 = xdim; seed = rand(Int), rng = StableRNG(seed)) Generate a stable random initial SOM with the random distribution that matches the parameters. Arguments: - `ncol`: number of desired data columns - `means`, `sdevs`: vectors that describe the data distribution, both of size `ncol` - `xdim`, `ydim`: Size of the SOM - `seed`: a seed (defaults to random seed from the current default random generator - `rng`: a random number generator to be used (defaults to a `StableRNG` initialized with the `seed`) Returns: a new `Som` structure """ function initGigaSOM( ncol::Int64, means::Vector{Float64}, sdevs::Vector{Float64}, xdim::Int64, ydim::Int64 = xdim; seed = rand(UInt), rng = StableRNG(seed), ) numCodes = xdim * ydim grid = gridRectangular(xdim, ydim) # Initialize with an unbiased random gaussian with same mean/sd as the data # in each dimension codes = randn(rng, (numCodes, ncol)) for col = 1:ncol codes[:, col] .*= sdevs[col] codes[:, col] .+= means[col] end return Som(codes = codes, xdim = xdim, ydim = ydim, grid = grid) end """ trainGigaSOM( som::Som, dInfo::Dinfo; kernelFun::Function = gaussianKernel, metric = Euclidean(), somDistFun = distMatrix(Chebyshev()), knnTreeFun = BruteTree, rStart = 0.0, rFinal = 0.1, radiusFun = expRadius(-5.0), epochs = 20, eachEpoch = (e, r, som) -> nothing, ) # Arguments: - `som`: object of type Som with an initialised som - `dInfo`: `Dinfo` object that describes a loaded dataset - `kernelFun::function`: optional distance kernel; one of (`bubbleKernel, gaussianKernel`) default is `gaussianKernel` - `metric`: Passed as metric argument to the KNN-tree constructor - `somDistFun`: Function for computing the distances in the SOM map - `knnTreeFun`: Constructor of the KNN-tree (e.g. from NearestNeighbors package) - `rStart`: optional training radius. If zero (default), it is computed from the SOM grid size. - `rFinal`: target radius at the last epoch, defaults to 0.1 - `radiusFun`: Function that generates radius decay, e.g. `linearRadius` or `expRadius(10.0)` - `epochs`: number of SOM training iterations (default 10) - `eachEpoch`: a function to call back after each epoch, accepting arguments `(epochNumber, radius, som)`. For simplicity, this gets additionally called once before the first epoch, with `epochNumber` set to zero. """ function trainGigaSOM( som::Som, dInfo::Dinfo; kernelFun::Function = gaussianKernel, metric = Euclidean(), somDistFun = distMatrix(Chebyshev()), knnTreeFun = BruteTree, rStart = 0.0, rFinal = 0.1, radiusFun = expRadius(-5.0), epochs = 20, eachEpoch = (e, r, som) -> nothing, ) # set the default radius if rStart == 0.0 rStart = (som.xdim + som.ydim) / 2 @debug "The radius has been determined automatically." rStart rFinal end # get the SOM neighborhood distances dm = somDistFun(som.grid) result_som = copy(som) result_som.codes = copy(som.codes) # prevent rewriting by reference eachEpoch(0, rStart, result_som) for epoch = 1:epochs @debug "Epoch $epoch..." numerator, denominator = distributedEpoch( dInfo, result_som.codes, knnTreeFun(Array{Float64,2}(transpose(result_som.codes)), metric), ) r = radiusFun(rStart, rFinal, epoch, epochs) @debug "radius: $r" if r <= 0 @error "Sanity check failed: radius must be positive" error("Radius check") end wEpoch = kernelFun(dm, r) result_som.codes = (wEpoch * numerator) ./ (wEpoch * denominator) eachEpoch(epoch, r, result_som) end return result_som end """ trainGigaSOM(som::Som, train; kwargs...) Overload of `trainGigaSOM` for simple DataFrames and matrices. This slices the data, distributes them to the workers, and runs normal `trainGigaSOM`. Data is `unscatter`d after the computation. """ function trainGigaSOM(som::Som, train; kwargs...) train = Matrix{Float64}(train) #this slices the data into parts and and sends them to workers dInfo = scatter_array(:GigaSOMtrainDataVar, train, workers()) som_res = trainGigaSOM(som, dInfo; kwargs...) unscatter(dInfo) return som_res end """ doEpoch(x::Array{Float64, 2}, codes::Array{Float64, 2}, tree) vectors and the adjustment in radius after each epoch. # Arguments: - `x`: training Data - `codes`: Codebook - `tree`: knn-compatible tree built upon the codes """ function doEpoch(x::Array{Float64,2}, codes::Array{Float64,2}, tree) # initialise numerator and denominator with 0's sumNumerator = zeros(Float64, size(codes)) sumDenominator = zeros(Float64, size(codes)[1]) # for each sample in dataset / trainingsset for s = 1:size(x, 1) (bmuIdx, bmuDist) = knn(tree, x[s, :], 1) target = bmuIdx[1] sumNumerator[target, :] .+= x[s, :] sumDenominator[target] += 1 end return sumNumerator, sumDenominator end """ distributedEpoch(dInfo::Dinfo, codes::Matrix{Float64}, tree) Execute the `doEpoch` in parallel on workers described by `dInfo` and collect the results. Returns pair of numerator and denominator matrices. """ function distributedEpoch(dInfo::Dinfo, codes::Matrix{Float64}, tree) return dmapreduce( dInfo, (data) -> doEpoch(data, codes, tree), ((n1, d1), (n2, d2)) -> (n1 + n2, d1 + d2), ) end """ mapToGigaSOM(som::Som, dInfo::Dinfo; knnTreeFun = BruteTree, metric = Euclidean(), output::Symbol=tmp_symbol(dInfo)::Dinfo Compute the index of the BMU for each row of the input data. # Arguments - `som`: a trained SOM - `dInfo`: `Dinfo` that describes the loaded and distributed data - `knnTreeFun`: Constructor of the KNN-tree (e.g. from NearestNeighbors package) - `metric`: Passed as metric argument to the KNN-tree constructor - `output`: Symbol to save the result, defaults to `tmp_symbol(dInfo)` Data must have the same number of dimensions as the training dataset and will be normalised with the same parameters. """ function mapToGigaSOM( som::Som, dInfo::Dinfo; knnTreeFun = BruteTree, metric = Euclidean(), output::Symbol = tmp_symbol(dInfo), )::Dinfo tree = knnTreeFun(Array{Float64,2}(transpose(som.codes)), metric) return dtransform(dInfo, (d) -> (vcat(knn(tree, transpose(d), 1)[1]...)), output) end """ mapToGigaSOM(som::Som, data; knnTreeFun = BruteTree, metric = Euclidean()) Overload of `mapToGigaSOM` for simple DataFrames and matrices. This slices the data using `DistributedArrays`, sends them the workers, and runs normal `mapToGigaSOM`. Data is `unscatter`d after the computation. """ function mapToGigaSOM(som::Som, data; knnTreeFun = BruteTree, metric = Euclidean()) data = Matrix{Float64}(data) if size(data, 2) != size(som.codes, 2) @error "Data dimension ($(size(data,2))) does not match codebook dimension ($(size(som.codes,2)))." error("Data dimensions do not match") end dInfo = scatter_array(:GigaSOMmappingDataVar, data, workers()) rInfo = mapToGigaSOM(som, dInfo, knnTreeFun = knnTreeFun, metric = metric) res = gather_array(rInfo) unscatter(dInfo) unscatter(rInfo) return DataFrame(index = res) end """ scaleEpochTime(iteration::Int64, epochs::Int64) Convert iteration ID and epoch number to relative time in training. """ function scaleEpochTime(iteration::Int64, epochs::Int64) # prevent division by zero on 1-epoch training if epochs > 1 epochs -= 1 end return Float64(iteration - 1) / Float64(epochs) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
9309
""" embedGigaSOM(som::GigaSOM.Som, dInfo::Dinfo; knnTreeFun = BruteTree, metric = Euclidean(), k::Int64=0, adjust::Float64=1.0, smooth::Float64=0.0, m::Float64=10.0, output::Symbol=tmp_symbol(dInfo))::Dinfo Return a data frame with X,Y coordinates of EmbedSOM projection of the data. # Arguments: - `som`: a trained SOM - `dInfo`: `Dinfo` that describes the loaded dataset - `knnTreeFun`: Constructor of the KNN-tree (e.g. from NearestNeighbors package) - `metric`: Passed as metric argument to the KNN-tree constructor - `k`: number of nearest neighbors to consider (high values get quadratically slower) - `adjust`: position adjustment parameter (higher values avoid non-local approximations) - `smooth`: approximation smoothness (the higher the value, the larger the neighborhood of approximate local linearity of the projection) - `m`: exponential decay rate for the score when approaching the `k+1`-th neighbor distance - `output`: variable name for storing the distributed result Data must have the same number of dimensions as the training dataset, and must be normalized using the same parameters. """ function embedGigaSOM( som::GigaSOM.Som, dInfo::Dinfo; knnTreeFun = BruteTree, metric = Euclidean(), k::Int64 = 0, adjust::Float64 = 1.0, smooth::Float64 = 0.0, m::Float64 = 10.0, output::Symbol = tmp_symbol(dInfo), )::Dinfo # convert `smooth` to `boost` boost = exp(-smooth - 1) # default `k` if k == 0 k = Integer(1 + sqrt(som.xdim * som.ydim)) @debug "embedding defaults" k end # check if `k` isn't too high if k > som.xdim * som.ydim k = Integer(som.xdim * som.ydim) end # prepare the kNN-tree for lookups tree = knnTreeFun(Array{Float64,2}(transpose(som.codes)), metric) # run the distributed computation return dtransform( dInfo, (d) -> (embedGigaSOM_internal(som, d, tree, k, adjust, boost, m)), output, ) end """ embedGigaSOM(som::GigaSOM.Som, data; knnTreeFun = BruteTree, metric = Euclidean(), k::Int64=0, adjust::Float64=1.0, smooth::Float64=0.0, m::Float64=10.0) Overload of `embedGigaSOM` for simple DataFrames and matrices. This slices the data using `DistributedArrays`, sends them the workers, and runs normal `embedGigaSOM`. All data is properly `unscatter`d after the computation. # Examples: Produce a 2-column matrix with 2D cell coordinates: ``` e = embedGigaSOM(som, data) ``` Plot the result using 2D histogram from Gadfly: ``` using Gadfly draw(PNG("output.png",20cm,20cm), plot(x=e[:,1], y=e[:,2], Geom.histogram2d(xbincount=200, ybincount=200))) ``` """ function embedGigaSOM( som::GigaSOM.Som, data; knnTreeFun = BruteTree, metric = Euclidean(), k::Int64 = 0, adjust::Float64 = 1.0, smooth::Float64 = 0.0, m::Float64 = 10.0, ) data = Matrix{Float64}(data) dInfo = scatter_array(:GigaSOMembeddingDataVar, data, workers()) rInfo = embedGigaSOM( som, dInfo, knnTreeFun = knnTreeFun, metric = metric, k = k, adjust = adjust, smooth = smooth, m = m, ) res = gather_array(rInfo) unscatter(dInfo) unscatter(rInfo) return res end """ embedGigaSOM_internal(som::GigaSOM.Som, data::Matrix{Float64}, tree, k::Int64, adjust::Float64, boost::Float64, m::Float64) Internal function to compute parts of the embedding on a prepared kNN-tree structure (`tree`) and `smooth` converted to `boost`. """ function embedGigaSOM_internal( som::GigaSOM.Som, data::Matrix{Float64}, tree, k::Int64, adjust::Float64, boost::Float64, m::Float64, ) ndata = size(data, 1) ncodes = size(som.codes, 1) dim = size(data, 2) # output buffer e = zeros(Float64, ndata, 2) # in case k<ncodes, we use 1 more neighbor to estimate the decay from 'm' nk = k if nk < ncodes nk += 1 end # buffer for indexes of the nk nearest SOM points sp = zeros(Int, nk) # process all data points in this batch for di = 1:size(data, 1) # find the nearest neighbors of the point and sort them by distance (knidx, kndist) = knn(tree, Array{Float64,1}(data[di, :]), nk) sortperm!(sp, kndist) knidx = knidx[sp] # nearest point indexes kndist = kndist[sp] # their corresponding distances # Compute the distribution of the weighted distances mean = 0.0 sd = 0.0 wsum = 0.0 for i = 1:nk tmp = kndist[i] w = 1.0 / i #the weight mean += tmp * w sd += tmp * tmp * w wsum += w end mean /= wsum sd = boost / sqrt(sd / wsum - mean * mean) nmax = m / kndist[nk] # if there is the cutoff if k < nk for i = 1:k kndist[i] = exp((mean - kndist[i]) * sd) * (1 - exp(kndist[i] * nmax - m)) end else #no neighborhood cutoff for i = 1:k kndist[i] = exp((mean - kndist[i]) * sd) end end # `mtx` is used as a matrix of a linear equation (like A|b) with 2 # unknowns. Derivations of square-error function are added to the # matrix in a way that solving the matrix (i.e. finding the zero) # effectively minimizes the error. mtx = zeros(Float64, 2, 3) # The embedding works with pairs of points on the SOM, say I and J. # Thus there are 2 cycles for all pairs of `i` and `j`. for i = 1:k idx = knidx[i] # index of I in SOM ix = Float64(som.grid[idx, 1]) # position of I in 2D space iy = Float64(som.grid[idx, 2]) is = kndist[i] # precomputed score of I # a bit of single-point gravity helps with avoiding singularities gs = 1e-9 * is mtx[1, 1] += gs mtx[2, 2] += gs mtx[1, 3] += gs * ix mtx[2, 3] += gs * iy for j = (i+1):k jdx = knidx[j] # same values for J as for I jx = Float64(som.grid[jdx, 1]) jy = Float64(som.grid[jdx, 2]) js = kndist[j] # compute values for approximation scalar::Float64 = 0 # this will be dot(Point-I, J-I) sqdist::Float64 = 0 # ... norm(J-I) for kk = 1:dim tmp = som.codes[idx, kk] * som.codes[jdx, kk] sqdist += tmp * tmp scalar += tmp * (data[di, kk] - som.codes[idx, kk]) end if scalar != 0 if sqdist == 0 # sounds like I==J ... continue else # If everything went right, `scalar` now becomes the # position of the point being embedded on the line # defined by I,J, relatively to both points (I has # position 0 and J has position 1). scalar /= sqdist end end # Process this information into matrix coefficients that give # derivation of the error that the resulting point will have # from the `scalar` position between 2D images of I and J. # # Note: I originally did the math by hand, but, seriously, do # not waste time with that and use e.g. Sage for getting the # derivatives right if anything should get modified here. hx = jx - ix hy = jy - iy hp = hx * hx + hy * hy # Higher `adjust` parameter lowers approximation influence of # SOM points that are too far in 2D. s = is * js * ((1 + hp)^(-adjust)) * exp(-((scalar - 0.5)^2)) sihp = s / hp rhsc = s * (scalar + (hx * ix + hy * iy) / hp) mtx[1, 1] += hx * hx * sihp mtx[1, 2] += hx * hy * sihp mtx[2, 1] += hy * hx * sihp mtx[2, 2] += hy * hy * sihp mtx[1, 3] += hx * rhsc mtx[2, 3] += hy * rhsc end end # Now the matrix contains a derivative of the error sum function; # solving the matrix using the Cramer rule means finding zero of the # derivative, which gives the minimum-error position, which is in turn # the desired embedded point position that gets saved to output `e`. det = mtx[1, 1] * mtx[2, 2] - mtx[1, 2] * mtx[2, 1] e[di, 1] = (mtx[1, 3] * mtx[2, 2] - mtx[1, 2] * mtx[2, 3]) / det e[di, 2] = (mtx[1, 1] * mtx[2, 3] - mtx[2, 1] * mtx[1, 3]) / det end return e end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
297
""" dtransform_asinh(dInfo::Dinfo, columns::Vector{Int}, cofactor=5) Transform columns of the dataset by asinh transformation with `cofactor`. """ function dtransform_asinh(dInfo::Dinfo, columns::Vector{Int}, cofactor = 5) dapply_cols(dInfo, (v, _) -> asinh.(v ./ cofactor), columns) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
939
""" Som Structure to hold all data of a trained SOM. # Fields: - `codes::Array{Float64,2}`: 2D-array of codebook vectors. One vector per row - `xdim::Int`: number of neurons in x-direction - `ydim::Int`: number of neurons in y-direction - `numCodes::Int`: total number of neurons - `grid::Array{Float64,2}`: 2D-array of coordinates of neurons on the map (2 columns (x,y)] for rectangular and hexagonal maps 3 columns (x,y,z) for spherical maps) """ mutable struct Som codes::Matrix{Float64} xdim::Int ydim::Int numCodes::Int grid::Matrix{Float64} Som(; codes::Matrix{Float64}, xdim::Int, ydim::Int, numCodes::Int = xdim * ydim, grid::Matrix{Float64}, ) = new(codes, xdim, ydim, numCodes, grid) end Base.copy(som::Som) = Som( codes = som.codes, xdim = som.xdim, ydim = som.ydim, numCodes = som.numCodes, grid = som.grid, )
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
4012
""" linearRadius(initRadius::Float64, iteration::Int64, decay::String, epochs::Int64) Return a neighbourhood radius. Use as the `radiusFun` parameter for `trainGigaSOM`. # Arguments - `initRadius`: Initial Radius - `finalRadius`: Final Radius - `iteration`: Training iteration - `epochs`: Total number of epochs """ function linearRadius( initRadius::Float64, finalRadius::Float64, iteration::Int64, epochs::Int64, ) scaledTime = scaleEpochTime(iteration, epochs) return initRadius * (1 - scaledTime) + finalRadius * scaledTime end """ expRadius(steepness::Float64) Return a function to be used as a `radiusFun` of `trainGigaSOM`, which causes exponencial decay with the selected steepness. Use: `trainGigaSOM(..., radiusFun = expRadius(0.5))` # Arguments - `steepness`: Steepness of exponential descent. Good values range from -100.0 (almost linear) to 100.0 (really quick decay). """ function expRadius(steepness::Float64 = 0.0) return (initRadius::Float64, finalRadius::Float64, iteration::Int64, epochs::Int64) -> begin scaledTime = scaleEpochTime(iteration, epochs) if steepness < -100.0 # prevent floating point underflows error("Sanity check: steepness too low, use linearRadius instead.") end # steepness is simulated by moving both points closer to zero adjust = finalRadius * (1 - 1.1^(-steepness)) if initRadius <= 0 || (initRadius - adjust) <= 0 || finalRadius <= 0 error( "Radii must be positive. (Possible alternative cause: steepness is too high.)", ) end initRadius -= adjust finalRadius -= adjust return adjust + initRadius * ((finalRadius / initRadius)^scaledTime) end end """ gridRectangular(xdim, ydim) Create coordinates of all neurons on a rectangular SOM. The return-value is an array of size (Number-of-neurons, 2) with x- and y- coordinates of the neurons in the first and second column respectively. The distance between neighbours is 1.0. The point of origin is bottom-left. The first neuron sits at (0,0). # Arguments - `xdim`: number of neurons in x-direction - `ydim`: number of neurons in y-direction """ function gridRectangular(xdim, ydim) grid = zeros(Float64, (xdim * ydim, 2)) for ix = 1:xdim for iy = 1:ydim grid[ix+(iy-1)*xdim, 1] = ix - 1 grid[ix+(iy-1)*xdim, 2] = iy - 1 end end return grid end """ gaussianKernel(x, r::Float64) Return the value of normal distribution PDF (σ=`r`, μ=0) at `x` """ function gaussianKernel(x, r::Float64) return Distributions.pdf.(Distributions.Normal(0.0, r), x) end function bubbleKernelSqScalar(x::Float64, r::Float64) if x >= r return 0 else return sqrt(1 - x / r) end end """ bubbleKernel(x, r::Float64) Return a "bubble" (spherical) distribution kernel. """ function bubbleKernel(x, r::Float64) return bubbleKernelSqScalar.(x .^ 2, r^2) end """ thresholdKernel(x, r::Float64) Simple FlowSOM-like hard-threshold kernel """ function thresholdKernel(x, r::Float64, maxRatio = 4 / 5, zero = 1e-6) if r >= maxRatio * maximum(x) #prevent smoothing everything to a single point r = maxRatio * maximum(x) end return zero .+ (x .<= r) end """ distMatrix(metric=Chebyshev()) Return a function that uses the `metric` (compatible with metrics from package `Distances`) calculates distance matrixes from normal row-wise data matrices, using the `metric`. Use as a parameter of `trainGigaSOM`. """ function distMatrix(metric = Chebyshev()) return (grid::Matrix{Float64}) -> begin n = size(grid, 1) dm = zeros(Float64, n, n) for i = 1:n for j = 1:n dm[i, j] = metric(grid[i, :], grid[j, :]) end end return dm::Matrix{Float64} end end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
8385
""" loadFCSHeader(fn::String)::Tuple{Vector{Int}, Dict{String,String}} Efficiently extract data offsets and keyword dictionary from an FCS file. """ function loadFCSHeader(fn::String)::Tuple{Vector{Int},Dict{String,String}} open(fn) do io offsets = FCSFiles.parse_header(io) params = FCSFiles.parse_text(io, offsets[1], offsets[2]) FCSFiles.verify_text(params) (offsets, params) end end """ getFCSSize(offsets, params)::Tuple{Int,Int} Convert the offsets and keywords from an FCS file to cell and parameter count, respectively. """ function getFCSSize(offsets, params)::Tuple{Int,Int} nData = parse(Int, params["\$TOT"]) nParams = parse(Int, params["\$PAR"]) if params["\$DATATYPE"] != "F" @error "Only float32 FCS files are currently supported" error("Unsupported FCS format") end beginData = parse(Int, params["\$BEGINDATA"]) endData = parse(Int, params["\$ENDDATA"]) #check that the $TOT and $PAR look okay if !(offsets[3] == 0 && offsets[4] == 0) && ( ( 1 + offsets[4] - offsets[3] != nData * nParams * 4 && offsets[4] - offsets[3] != nData * nParams * 4 ) || offsets[3] != beginData || offsets[4] != endData ) @warn "Data size mismatch, FCS is likely broken." end return (nData, nParams) end """ loadFCSSizes(fns::Vector{String}) Load cell counts in many FCS files at once. Useful as input for `slicesof`. """ function loadFCSSizes(fns::Vector{String})::Vector{Int} [( begin o, s = loadFCSHeader(fn) getFCSSize(o, s)[1] end ) for fn in fns] end """ loadFCS(fn::String; applyCompensation::Bool=true)::Tuple{Dict{String,String}, Matrix{Float64}} Read a FCS file. Return a tuple that contains in order: - dictionary of the keywords contained in the file - raw column names - prettified and annotated column names - raw data matrix If `applyCompensation` is set, the function parses and retrieves a spillover matrix (if any valid keyword in the FCS is found that would contain it) and applies it to compensate the data. """ function loadFCS( fn::String; applyCompensation::Bool = true, )::Tuple{Dict{String,String},Matrix{Float64}} fcs = FileIO.load(fn) meta = getMetaData(fcs.params) data = hcat(map(x -> Vector{Float64}(fcs.data[x]), meta[:, :N])...) if applyCompensation spill = getSpillover(fcs.params) if spill != nothing names, mtx = spill cols = indexin(names, meta[:, :N]) if any(cols .== nothing) @error "Unknown columns in compensation matrix" names cols error("Invalid compensation matrix") end compensate!(data, mtx, Vector{Int}(cols)) end end return (fcs.params, data) end """ loadFCSSet(name::Symbol, fns::Vector{String}, pids=workers(); applyCompensation=true, postLoad=(d,i)->d)::Dinfo This runs the FCS loading machinery in a distributed way, so that the files `fns` (with full path) are sliced into equal parts and saved as a distributed variable `name` on workers specified by `pids`. `applyCompensation` is passed to loadFCS function. See `slicesof` for description of the slicing. `postLoad` is applied to the loaded FCS file data (and the index) -- use this function to e.g. filter out certain columns right on loading, using `selectFCSColumns`. The loaded dataset can be manipulated by the distributed functions, e.g. - `dselect` for removing columns - `dscale` for normalization - `dtransform_asinh` (and others) for transformation - etc. """ function loadFCSSet( name::Symbol, fns::Vector{String}, pids = workers(); applyCompensation = true, postLoad = (d, i) -> d, )::Dinfo slices = slicesof(loadFCSSizes(fns), length(pids)) dmap( slices, (slice) -> Base.eval( Main, :( begin $name = vcollectSlice( (i) -> last( $postLoad( loadFCS($fns[i]; applyCompensation = $applyCompensation), i, ), ), $slice, ) nothing end ), ), pids, ) return Dinfo(name, pids) end """ selectFCSColumns(selectColnames::Vector{String}) Return a function useful with `loadFCSSet`, which loads only the specified (prettified) column names from the FCS files. Use `getMetaData`, `getMarkerNames` and `cleanNames!` to retrieve the usable column names for a FCS. """ function selectFCSColumns(selectColnames::Vector{String}) ((metadata, data), idx) -> begin _, names = getMarkerNames(getMetaData(metadata)) cleanNames!(names) colIdxs = indexin(selectColnames, names) if any(colIdxs .== nothing) @error "Some columns were not found" error("unknown column") end (metadata, data[:, colIdxs]) end end """ distributeFCSFileVector(name::Symbol, fns::Vector{String}, pids=workers())::Dinfo Distribute a vector of integers among the workers that describes which file from `fns` the cell comes from. Useful for producing per-file statistics. The vector is saved on workers specified by `pids` as a distributed variable `name`. """ function distributeFCSFileVector(name::Symbol, fns::Vector{String}, pids = workers())::Dinfo sizes = loadFCSSizes(fns) slices = slicesof(sizes, length(pids)) return distributeFileVector(name, sizes, slices, pids) end """ distributeFileVector(name::Symbol, sizes::Vector{Int}, slices::Vector{Tuple{Int,Int,Int,Int}}, pids=workers())::Dinfo Generalized version of `distributeFCSFileVector` that produces the integer vector from any `sizes` and `slices`. """ function distributeFileVector( name::Symbol, sizes::Vector{Int}, slices::Vector{Tuple{Int,Int,Int,Int}}, pids = workers(), )::Dinfo dmap( slices, (slice) -> Base.eval(Main, :($name = collectSlice((i) -> fill(i, $sizes[i]), $slice))), pids, ) return Dinfo(name, pids) end """ function getCSVSize(fn::String; args...)::Tuple{Int,Int} Read the dimensions (number of rows and columns, respectively) from a CSV file `fn`. `args` are passed to function `CSV.file`. # Example getCSVSize("test.csv", header=false) """ function getCSVSize(fn::String; args...)::Tuple{Int,Int} n = 0 k = 0 # ideally, this will not try to load the whole CSV in the memory for row in CSV.File(fn, type = Float64; args...) n += 1 if length(row) > k k = length(row) end end return (n, k) end """ function loadCSVSizes(fns::Vector{String}; args...)::Vector{Int} Determine number of rows in a list of CSV files (passed as `fns`). Equivalent to `loadFCSSizes`. """ function loadCSVSizes(fns::Vector{String}; args...)::Vector{Int} [getCSVSize(fn, type = Float64; args...)[1] for fn in fns] end """ function loadCSV(fn::String; args...)::Matrix{Float64} CSV equivalent of `loadFCS`. The metadata (header, column names) are not extracted. `args` are passed to `CSV.read`. """ function loadCSV(fn::String; args...)::Matrix{Float64} CSV.read(fn, DataFrame, type = Float64; args...) |> Matrix{Float64} end """ function loadCSVSet( name::Symbol, fns::Vector{String}, pids = workers(); postLoad = (d, i) -> d, csvargs..., )::Dinfo CSV equivalent of `loadFCSSet`. `csvargs` are passed as keyword arguments to CSV-loading functions. """ function loadCSVSet( name::Symbol, fns::Vector{String}, pids = workers(); postLoad = (d, i) -> d, csvargs..., )::Dinfo slices = slicesof(loadCSVSizes(fns; csvargs...), length(pids)) dmap( slices, (slice) -> Base.eval( Main, :( begin $name = vcollectSlice( (i) -> $postLoad(loadCSV($fns[i]; $csvargs...), i), $slice, ) nothing end ), ), pids, ) return Dinfo(name, pids) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
4402
""" cleanNames!(mydata::Vector{String}) Replaces problematic characters in column names, avoids duplicate names, and prefixes an '_' if the name starts with a number. # Arguments: - `mydata`: vector of names (gets modified) """ function cleanNames!(mydata::Vector{String}) # replace problematic characters, # put "_" in front of colname in case it starts with a number # avoid duplicate names (add suffixes _2, _3, ...) usedNames = Set{String}() for j in eachindex(mydata) mydata[j] = replace(mydata[j], "-" => "_") if isnumeric(first(mydata[j])) mydata[j] = "_" * mydata[j] end # avoid duplicate names if mydata[j] in usedNames idx = 2 while "$(mydata[j])_$idx" in usedNames idx += 1 end mydata[j] *= "_$idx" end push!(usedNames, mydata[j]) end end """ getMetaData(f) Collect the meta data information in a more user friendly format. # Arguments: - `f`: input structure with `.params` and `.data` fields """ function getMetaData(meta::Dict{String,String})::DataFrame # declarations and initializations metaKeys = keys(meta) channel_properties = [] defaultValue = "" # determine the number of channels pars = parse(Int, strip(join(meta["\$PAR"]))) # determine the available channel properties for (key,) in meta if length(key) >= 2 && key[1:2] == "\$P" i = 3 while i <= length(key) && isdigit(key[i]) i += 1 end if i <= length(key) && !in(key[i:end], channel_properties) push!(channel_properties, key[i:end]) end end end # create a data frame for the results df = Matrix{String}(undef, pars, length(channel_properties)) df .= defaultValue df = DataFrame(df, :auto) rename!(df, Symbol.(channel_properties)) # collect the data from params for ch = 1:pars for p in channel_properties if "\$P$ch$p" in metaKeys df[ch, Symbol(p)] = meta["\$P$ch$p"] end end end return df end """ getMarkerNames(meta::DataFrame)::Tuple{Vector{String}, Vector{String}} Extract suitable raw names (useful for selecting columns) and pretty readable names (useful for humans) from FCS file metadata. """ function getMarkerNames(meta::DataFrame)::Tuple{Vector{String},Vector{String}} orig = Array{String}(meta[:, :N]) nice = copy(orig) if hasproperty(meta, :S) for i = 1:size(meta, 1) if strip(meta[i, :S]) != "" nice[i] = meta[i, :S] end end end return (orig, nice) end """ compensate!(data::Matrix{Float64}, spillover::Matrix{Float64}, cols::Vector{Int}) Apply a compensation matrix in `spillover` (the individual columns of which describe, in order, the spillover of `cols` in `data`) to the matrix `data` in-place. """ function compensate!(data::Matrix{Float64}, spillover::Matrix{Float64}, cols::Vector{Int}) data[:, cols] = data[:, cols] * inv(spillover) end """ parseSpillover(str::String)::Union{Tuple{Vector{String},Matrix{Float64}}, Nothing} Parses the spillover matrix from the string from FCS parameter value. """ function parseSpillover(str::String)::Tuple{Vector{String},Matrix{Float64}} fields = split(str, ',') n = parse(Int, fields[1]) if length(fields) != 1 + n + n * n @error "Spillover matrix of size $n expects $(1+n+n*n) fields, got $(length(fields)) instead." error("Invalid spillover matrix") end names = fields[2:(1+n)] spill = collect(transpose(reshape(parse.(Float64, fields[(2+n):length(fields)]), n, n))) names, spill end """ getSpillover(params::Dict{String, String})::Union{Tuple{Vector{String},Matrix{Float64}}, Nothing} Get a spillover matrix from FCS `params`. Returns a pair with description of columns to be applied, and with the actual spillover matrix. Returns `nothing` in case spillover is not present. """ function getSpillover( params::Dict{String,String}, )::Union{Tuple{Vector{String},Matrix{Float64}},Nothing} spillNames = ["\$SPILL", "\$SPILLOVER", "SPILL", "SPILLOVER"] for i in spillNames if in(i, keys(params)) return parseSpillover(params[i]) end end return nothing end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
3721
""" slicesof(lengths::Vector{Int}, slices::Int)::Vector{Tuple{Int,Int,Int,Int}} Given a list of `lengths` of input arrays, compute a slicing into a specified amount of equally-sized `slices`. The output is a vector of 4-tuples where each specifies how to create one slice. The i-th tuple field contains, in order: - the index of input array at which the i-th slice begins - first element of the i-th slice in that input array - the index of input array with the last element of the i-th slice - the index of the last element of the i-th slice in that array """ function slicesof(lengths::Vector{Int}, slices::Int)::Vector{Tuple{Int,Int,Int,Int}} nfiles = length(lengths) total = sum(lengths) sliceLen = repeat([div(total, slices)], slices) for i = 1:mod(total, slices) sliceLen[i] += 1 end result = repeat([(0, 0, 0, 0)], slices) ifile = 1 # file in the window off = 0 # cells already taken from that window for i = 1:slices startFile = ifile startOff = off + 1 avail = lengths[ifile] - off while avail < sliceLen[i] ifile += 1 off = 0 avail += lengths[ifile] end rest = avail - sliceLen[i] off = lengths[ifile] - rest if startOff > lengths[startFile] && startFile < ifile startOff = 1 startFile += 1 end result[i] = (startFile, startOff, ifile, off) end result end """ vcollectSlice(loadMtx, (startFile, startOff, finalFile, finalOff)::Tuple{Int,Int,Int,Int})::Matrix Given a method to obtain matrix content (`loadMtx`), reconstruct a slice from the information generated by `slicesof`. This function is specialized for reconstructing matrices and arrays, where the "element counts" split by `slicesof` are in fact matrix rows. The function is therefore named _v_collect (the slicing and concatenation is _v_ertical). The actual data content and loading method is abstracted out -- function `loadMtx` gets the index of the input part that it is required to fetch (e.g. index of one FCS file), and is expected to return that input part as a whole matrix. `vcollectSlice` correctly calls this function as required and extracts relevant portions of the matrices, so that at the end the whole slice can be pasted together. Example: # get a list of files filenames=["a.fcs", "b.fcs"] # get descriptions of 5 equally sized parts of the data slices = slicesof(loadFCSSizes(filenames), 5) # reconstruct first 3 columns of the first slice mySlice = vcollectSlice( i -> last(loadFCS(slices[i]))[:,1:3], slices[1]) # (note: function loadFCS returns 4 items, the matrix is the last one) """ function vcollectSlice( loadMtx, (startFile, startOff, finalFile, finalOff)::Tuple{Int,Int,Int,Int}, )::Matrix vcat( [ begin m = loadMtx(i) beginIdx = i == startFile ? startOff : 1 endIdx = i == finalFile ? finalOff : size(m, 1) m[beginIdx:endIdx, :] end for i = startFile:finalFile ]..., ) end """ collectSlice(loadVec, (startFile, startOff, finalFile, finalOff)::Tuple{Int,Int,Int,Int})::Vector Alternative of `vcollectSlice` for 1D vectors. """ function collectSlice( loadVec, (startFile, startOff, finalFile, finalOff)::Tuple{Int,Int,Int,Int}, )::Vector vcat( [ begin v = loadVec(i) beginIdx = i == startFile ? startOff : 1 endIdx = i == finalFile ? finalOff : length(v) v[beginIdx:endIdx] end for i = startFile:finalFile ]..., ) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
857
using GigaSOM, DataFrames, XLSX, CSV, Test, Random, Distributed, DistributedData using FileIO, DataFrames, Distances using JSON, SHA import LinearAlgebra owd = pwd() """ Check if the `pwd()` is the `/test` directory, and if not it changes to it. """ function checkDir() files = readdir() if !in("runtests.jl", files) cd(dirname(dirname(pathof(GigaSOM)))) end end checkDir() @testset "GigaSOM test suite" begin include("testDataOps.jl") include("testTrainutils.jl") include("testSplitting.jl") include("testInput.jl") #this loads the PBMC dataset required for the batch/parallel tests include("testLoadPBMC8.jl") include("testBatch.jl") include("testParallel.jl") #misc tests that require some of the above data too include("testInputCSV.jl") include("testFileSplitting.jl") end cd(owd)
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
2167
@testset "Single-CPU batch processing" begin som = initGigaSOM(pbmc8_data, 10, 10, seed = 1234) #check whether the distributed version works the same save_at(1, :test, pbmc8_data) som2 = initGigaSOM(Dinfo(:test, [1]), 10, 10, seed = 1234) @test som.codes == som2.codes remove_from(1, :test) @testset "Check SOM dimensions" begin @test size(som.codes) == (100, 10) @test som.xdim == 10 @test som.ydim == 10 @test som.numCodes == 100 end som = trainGigaSOM(som, pbmc8_data, epochs = 1) winners = mapToGigaSOM(som, pbmc8_data) embed = embedGigaSOM(som, pbmc8_data, k = 10, smooth = 0.1, adjust = 2.3, m = 4.5) @testset "Check results" begin codes = som.codes @test size(codes) == (100, 10) dfCodes = DataFrame(codes, :auto) rename!(dfCodes, Symbol.(antigens)) dfEmbed = DataFrame(embed, :auto) CSV.write(genDataPath * "/batchDfCodes.csv", dfCodes) CSV.write(genDataPath * "/batchWinners.csv", winners) CSV.write(genDataPath * "/batchEmbedded.csv", dfEmbed) #load the ref data refBatchDfCodes = CSV.File(refDataPath * "/refBatchDfCodes.csv") |> DataFrame refBatchWinners = CSV.File(refDataPath * "/refBatchWinners.csv") |> DataFrame refBatchEmbedded = CSV.File(refDataPath * "/refBatchEmbedded.csv") |> DataFrame #load the generated data batchDfCodes = CSV.File(genDataPath * "/batchDfCodes.csv") |> DataFrame batchDfCodesTest = first(batchDfCodes, 10) batchWinners = CSV.File(genDataPath * "/batchWinners.csv") |> DataFrame batchWinnersTest = first(batchWinners, 10) batchEmbedded = CSV.File(genDataPath * "/batchEmbedded.csv") |> DataFrame batchEmbeddedTest = first(batchEmbedded, 10) # test the generated data against the reference data @test refBatchWinners == batchWinnersTest @test Matrix{Float64}(refBatchDfCodes) ≈ Matrix{Float64}(batchDfCodesTest) atol = 1e-4 @test Matrix{Float64}(refBatchEmbedded) ≈ Matrix{Float64}(batchEmbeddedTest) atol = 1e-4 end end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
734
@testset "High-level operations on distributed data" begin W = addprocs(2) @everywhere using GigaSOM Random.seed!(1) dd = rand(11111, 5) buckets = rand([1, 2, 3], 11111) di1 = scatter_array(:test1, dd, W[1:1]) di2 = scatter_array(:test2, dd, W) buckets1 = scatter_array(:buckets1, buckets, W[1:1]) buckets2 = scatter_array(:buckets2, buckets, W) dc = gather_array(di1) dc[:, 1:2] = asinh.(dc[:, 1:2] ./ 1.23) dtransform_asinh(di1, [1, 2], 1.23) dtransform_asinh(di2, [1, 2], 1.23) @testset "dtransform_asinh" begin @test isapprox(gather_array(di1), dc) @test isapprox(gather_array(di2), dc) end unscatter(di1) unscatter(di2) rmprocs(W) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
983
@testset "File splitting" begin W = addprocs(8) @everywhere using GigaSOM # re-use the PBMC8 data: # try load it by parts of different size and scrutinize the parts for splitSize = 1:8 di = loadFCSSet(:test, md[:, :file_name], W[1:splitSize]) dselect(di, fcsAntigens, antigens) cols = Vector(1:length(antigens)) dtransform_asinh(di, cols, 5) dscale(di, cols) @test isapprox(pbmc8_data, gather_array(di), atol = 1e-4) splits = dmapreduce(di, d -> size(d, 1), vcat) @test sum(splits) == size(pbmc8_data, 1) @test minimum(splits) + 1 >= maximum(splits) sizes = loadFCSSizes(md[:, :file_name]) dis = distributeFCSFileVector(:testF, md[:, :file_name], W[1:splitSize]) @test dcount(length(sizes), dis) == sizes @test dcount_buckets(length(sizes), dis, length(sizes), dis) == Matrix{Int}(LinearAlgebra.Diagonal(sizes)) end rmprocs(W) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
1356
checkDir() @testset "File loading with compensation" begin _, data = loadFCS("test-compensation.fcs") @test isapprox( data[:, 7:18], [ 3332.2309256243007 8088.362793640517 538.3720631079816 144.5766025806829 -5.026619216289584 656.7371177910801 34824.02845241197 1939.2085663518994 268.10446790549787 7164.229365371252 1487.6587206861805 -103.62798381469148 466.6162342252232 6100.635084662845 471.12011441761274 4270.515980761523 237.1142731684298 154.2816233797197 8063.704826604625 2363.291912539149 250.09636142954616 -5.275245824878045 546.3837818701431 7.180492945860638 4988.506790656656 5836.121341276924 305.25138438318146 -78.2911490240366 -130.7712323646924 256.75533709823753 -28.969688160222205 2463.006063022074 -107.24661567025781 212.81623260036247 50.45721112838109 946.1078887373078 2474.009284729641 3662.411462672774 499.30026183606464 217.49388411442334 273.06602846319055 102.19931337770262 195.20362476100473 2593.704979451791 1597.8609042177852 -99.00019479802567 326.5676563660152 2481.6467014782347 3737.3002300540215 92.63719998587527 103.7345736486239 34.18875829231229 -23.820984710851445 71.25989624438593 492.24250044483324 934.9753295720772 -32.31068183338777 114.67958090123807 239.36797617353315 23.052151803822486 ], ) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
810
@testset "CSV loading" begin files = [refDataPath * "/refBatchDfCodes.csv", refDataPath * "/refParallelDfCodes.csv"] rows, cols = getCSVSize(files[1], header = true) @test rows == 10 @test cols == 10 data1 = loadCSV(files[1], header = true) data2 = loadCSV(files[2], header = true) @test typeof(data1) == Matrix{Float64} @test size(data1) == (10, 10) sizes = loadCSVSizes(files, header = true) @test sizes == [10, 10] W = addprocs(3) @everywhere using GigaSOM di = loadCSVSet(:csvTest, files, W, header = true) @test gather_array(di) == vcat(data1, data2) sizes = dmapreduce(di, size, vcat) dims = map(last, sizes) counts = map(first, sizes) @test all(dims .== 10) @test minimum(counts) + 1 >= maximum(counts) rmprocs(W) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
2374
# This loads the PBMC8 dataset that is used for later tests checkDir() #create genData and data folder and change dir to dataPath cwd = pwd() if occursin("jenkins", homedir()) || "TRAVIS" in keys(ENV) genDataPath = mktempdir() dataPath = mktempdir() else if !occursin("test", cwd) cd("test") cwd = pwd() end dataFolders = ["genData", "data"] for dir in dataFolders if !isdir(dir) mkdir(dir) end end genDataPath = cwd * "/genData" dataPath = cwd * "/data" end refDataPath = cwd * "/refData" cd(dataPath) # fetch the required data for testing and download the zip archive and unzip it dataFiles = ["PBMC8_metadata.xlsx", "PBMC8_panel.xlsx", "PBMC8_fcs_files.zip"] for f in dataFiles if !isfile(f) download("http://imlspenticton.uzh.ch/robinson_lab/cytofWorkflow/" * f, f) if occursin(".zip", f) run(`unzip PBMC8_fcs_files.zip`) end else end end # verify the data consistency using the stored checksums fileNames = readdir() csDict = Dict{String,Any}() for f in fileNames if f[end-3:end] == ".fcs" || f[end-4:end] == ".xlsx" cs = bytes2hex(sha256(f)) csDict[f] = cs end end csTest = JSON.parsefile(cwd * "/checkSums/csTest.json") if csDict != csTest @error "Downloaded dataset does not match expectations, perhaps it is corrupted?" csDict csTest error("dataset checksum error") end md = DataFrame(XLSX.readtable("PBMC8_metadata.xlsx", "Sheet1", infer_eltypes = true)...) panel = DataFrame(XLSX.readtable("PBMC8_panel.xlsx", "Sheet1", infer_eltypes = true)...) antigens = panel[panel[:, :Lineage].==1, :Antigen] _, fcsParams = loadFCSHeader(md[1, :file_name]) _, fcsAntigens = getMarkerNames(getMetaData(fcsParams)) cleanNames!(antigens) cleanNames!(fcsAntigens) di = loadFCSSet(:fcsData, md[:, :file_name], [myid()]) #prepare the data a bit dselect(di, fcsAntigens, antigens) cols = Vector(1:length(antigens)) dtransform_asinh(di, cols, 5) dscale(di, cols) pbmc8_data = gather_array(di) unscatter(di) @testset "load-time columns normalization" begin di = loadFCSSet( :fcsData, md[:, :file_name], [myid()], postLoad = selectFCSColumns(antigens), ) dtransform_asinh(di, cols, 5) dscale(di, cols) @test pbmc8_data == gather_array(di) unscatter(di) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
2050
@testset "Parallel processing" begin W = addprocs(2) @everywhere using GigaSOM som = initGigaSOM(pbmc8_data, 10, 10, seed = 1234) @testset "Check SOM dimensions" begin @test size(som.codes) == (100, 10) @test som.xdim == 10 @test som.ydim == 10 @test som.numCodes == 100 end som = trainGigaSOM(som, pbmc8_data, epochs = 2, rStart = 6.0) winners = mapToGigaSOM(som, pbmc8_data) embed = embedGigaSOM(som, pbmc8_data) @testset "Check results" begin codes = som.codes @test size(codes) == (100, 10) dfCodes = DataFrame(codes, :auto) rename!(dfCodes, Symbol.(antigens)) dfEmbed = DataFrame(embed, :auto) CSV.write(genDataPath * "/parallelDfCodes.csv", dfCodes) CSV.write(genDataPath * "/parallelWinners.csv", winners) CSV.write(genDataPath * "/parallelEmbedded.csv", dfEmbed) # load the ref data refParallelDfCodes = CSV.File(refDataPath * "/refParallelDfCodes.csv") |> DataFrame refParallelWinners = CSV.File(refDataPath * "/refParallelWinners.csv") |> DataFrame refParallelEmbedded = CSV.File(refDataPath * "/refParallelEmbedded.csv") |> DataFrame # load the generated data parallelDfCodes = CSV.File(genDataPath * "/parallelDfCodes.csv") |> DataFrame parallelDfCodesTest = first(parallelDfCodes, 10) parallelWinners = CSV.File(genDataPath * "/parallelWinners.csv") |> DataFrame parallelWinnersTest = first(parallelWinners, 10) parallelEmbedded = CSV.File(genDataPath * "/parallelEmbedded.csv") |> DataFrame parallelEmbeddedTest = first(parallelEmbedded, 10) # test the generated data against the reference data @test refParallelWinners == parallelWinnersTest @test Matrix{Float64}(refParallelDfCodes) ≈ Matrix{Float64}(parallelDfCodesTest) @test Matrix{Float64}(refParallelEmbedded) ≈ Matrix{Float64}(parallelEmbeddedTest) atol = 1e-4 end rmprocs(W) end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
1236
@testset "Dataset splitting helpers" begin @testset "slice computation" begin @test slicesof([11], 2) == [(1, 1, 1, 6), (1, 7, 1, 11)] a = [30, 40, 50] @test slicesof(a, 1) == [(1, 1, 3, 50)] @test slicesof(a, 2) == [(1, 1, 2, 30), (2, 31, 3, 50)] @test slicesof(a, 3) == [(1, 1, 2, 10), (2, 11, 3, 10), (3, 11, 3, 50)] @test slicesof(a, 4) == [(1, 1, 1, 30), (2, 1, 2, 30), (2, 31, 3, 20), (3, 21, 3, 50)] @test slicesof(a, 5) == [(1, 1, 1, 24), (1, 25, 2, 18), (2, 19, 3, 2), (3, 3, 3, 26), (3, 27, 3, 50)] @test slicesof(a, 10) == [ (1, 1, 1, 12), (1, 13, 1, 24), (1, 25, 2, 6), (2, 7, 2, 18), (2, 19, 2, 30), (2, 31, 3, 2), (3, 3, 3, 14), (3, 15, 3, 26), (3, 27, 3, 38), (3, 39, 3, 50), ] end @testset "slice collection" begin s = slicesof([4, 4], 3) @test vcollectSlice(i -> repeat([i], 4), s[1])[:, 1] == [1, 1, 1] @test vcollectSlice(i -> repeat([i], 4), s[2])[:, 1] == [1, 2, 2] @test vcollectSlice(i -> repeat([i], 4), s[3])[:, 1] == [2, 2] end end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
1868
@testset "SOM training helper functions" begin @testset "gridRectangular" begin grid = GigaSOM.gridRectangular(5, 5) @test size(grid) == (25, 2) end @testset "Kernels" begin @test isapprox( gaussianKernel(Vector{Float64}(1:7), 2.0), [0.1760326, 0.1209853, 0.0647587, 0.0269954, 0.0087641, 0.0022159, 0.0004363], atol = 1e-4, ) @test isapprox( bubbleKernel(Vector{Float64}(1:6), 5.0), [0.979796, 0.916515, 0.8, 0.6, 0, 0], atol = 0.001, ) @test isapprox( thresholdKernel(Vector{Float64}(1:10), 5.0), [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], atol = 1e-3, ) @test isapprox( thresholdKernel(Vector{Float64}(1:10), 10.1), [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0], atol = 1e-3, ) end @testset "Radii-generating functions" begin radii1 = expRadius().(5.0, 0.5, Vector(1:10), 10) radii2 = expRadius(-10.0).(10.0, 0.1, Vector(1:20), 20) radii3 = linearRadius.(50.0, 0.001, Vector(1:30), 30) @test isapprox(radii1[1], 5.0) @test isapprox(radii1[10], 0.5) @test isapprox(radii2[1], 10.0) @test isapprox(radii2[20], 0.1) @test isapprox(radii3[1], 50.0) @test isapprox(radii3[30], 0.001) @test all(isapprox.(radii1[1:9] ./ radii1[2:10], radii1[1] / radii1[2])) #note: radius2 is adjusted and thus not really exponential @test all(isapprox.(radii3[1:29] .- radii3[2:30], radii3[1] - radii3[2])) end @testset "distMatrix" begin g = GigaSOM.gridRectangular(2, 2) dm = GigaSOM.distMatrix(Euclidean())(g) @test size(dm) == (4, 4) @test all([dm[i, i] == 0 for i = 1:4]) end end
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
code
362
using Coverage cd(joinpath(@__DIR__, "..", "..")) do processed = process_folder() covered_lines, total_lines = get_summary(processed) percentage = covered_lines / total_lines * 100 println("($(percentage)%) covered") end # submit the report to codecov.io Codecov.submit_local(Codecov.process_folder(), pwd(), slug = "LCSB-BioCore/GigaSOM.jl")
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
6133
![GigaSOM.jl](https://webdav-r3lab.uni.lu/public/GigaSOM/img/logo-GigaSOM.jl.png?maxAge=0) # GigaSOM.jl <br> Huge-scale, high-performance flow cytometry clustering GigaSOM is a Julia toolkit for clustering and visualisation of really large cytometry data. Most generally, it can load FCS files, perform transformation and cleaning operations in their contents, run FlowSOM-style clustering, and visualize and export the results. GigaSOM is distributed and parallel in nature, which makes processing huge datasets a breeze -- a hundred of millions of cells with a few dozen parameters can be clustered and visualized in a few minutes. | **Documentation** | **Test Coverage** | **CI** | **SciCrunch** | |:-----------------:|:-----------------:|:-----------------------------------------------------:|:--------:| | [![doc](https://img.shields.io/badge/doc-GigaSOM-blue)](http://git.io/GigaSOM.jl) | [![coverage status](http://codecov.io/github/LCSB-BioCore/GigaSOM.jl/coverage.svg?branch=master)](http://codecov.io/github/LCSB-BioCore/GigaSOM.jl?branch=master) | [![linux](https://github.com/LCSB-BioCore/GigaSOM.jl/workflows/CI/badge.svg?branch=master)](https://github.com/LCSB-BioCore/GigaSOM.jl/actions) | [![rrid](https://img.shields.io/badge/RRID-SCR__019020-72c02c)](https://scicrunch.org/resolver/RRID:SCR_019020) | If you use GigaSOM.jl and want to refer to it in your work, use the following citation format (also available as BibTeX in [gigasom.bib](gigasom.bib)): > Miroslav Kratochvíl, Oliver Hunewald, Laurent Heirendt, Vasco Verissimo, Jiří Vondrášek, Venkata P Satagopam, Reinhard Schneider, Christophe Trefois, Markus Ollert. *GigaSOM.jl: High-performance clustering and visualization of huge cytometry datasets.* GigaScience, Volume 9, Issue 11, November 2020, giaa127, https://doi.org/10.1093/gigascience/giaa127 # How to get started ## Prerequisites and requirements - **Operating system**: Use Linux (Debian, Ubuntu or centOS), MacOS, or Windows 10 as your operating system. GigaSOM has been tested on these systems. - **Julia language**: In order to use GigaSOM, you need to install Julia 1.0 or higher. You can find the download and installation instructions for Julia [here](https://julialang.org/downloads/). - **Hardware requirements**: GigaSOM runs on any hardware that can run Julia, and can easily use resources from multiple computers interconnected by network. For processing large datasets, you require to ensure that the total amount of available RAM on all involved computers is larger than the data size. :bulb: If you are new to Julia, it is adviseable to [familiarize youself with the environment first](https://docs.julialang.org/en/v1/manual/getting-started/). Use the full Julia [documentation](https://docs.julialang.org) to solve various possible language-related problems, and the [Julia package manager docs](https://julialang.github.io/Pkg.jl/v1/getting-started/) to solve installation-related difficulties. ## Installation Using the Julia package manager to install GigaSOM is easy -- after starting Julia, type: ```julia import Pkg; Pkg.add("GigaSOM"); ``` > All these commands should be run from Julia at the `julia>` prompt. Then you can load the GigaSOM package and start using it: ```julia using GigaSOM ``` The first loading of the GigaSOM package may take several minutes to complete due to precompilation of the sources, especially on a fresh Julia install. ### Test the installation If you run a non-standard platform (e.g. a customized operating systems), or if you added any modifications to GigaSOM source code, you may want to run the test suite to ensure that everything works as expected: ```julia import Pkg; Pkg.test("GigaSOM"); ``` For debugging, it is sometimes very useful to enable the `@debug` messages from the source, as such: ```julia using Logging global_logger(ConsoleLogger(stderr, Logging.Debug)) ``` ## How to use GigaSOM A comprehensive documentation is [available online](https://lcsb-biocore.github.io/GigaSOM.jl/); several [introductory tutorials](https://lcsb-biocore.github.io/GigaSOM.jl/latest/tutorials/basicUsage/) of increasing complexity are also included. A very basic dataset (Levine13 from [FR-FCM-ZZPH](https://flowrepository.org/id/FR-FCM-ZZPH)) can be loaded, clustered and visualized as such: ```julia using GigaSOM params, fcsmatrix = loadFCS("Levine_13dim.fcs") # load the FCS file exprs = fcsmatrix[:,1:13] # extract only the data columns with expression values som = initGigaSOM(exprs, 20, 20) # random initialization of the SOM codebook som = trainGigaSOM(som, exprs) # SOM training clusters = mapToGigaSOM(som, exprs) # extraction of per-cell cluster IDs e = embedGigaSOM(som, exprs) # EmbedSOM projection to 2D ``` The example loads the data, runs the SOM training (as in FlowSOM) and computes a 2D projection of the dataset (using EmbedSOM); the total computation time (excluding the possible precompilation of the libraries) should be around 15 seconds. The results can be visualized e.g. with [GigaScatter](https://github.com/LCSB-BioCore/GigaScatter.jl#usage-with-gigasomjl) which we developed for this purpose, or by exporting the data and plotting them with any other programming language. For example, to save an embedding with highlighted expression of CD4, you can install and use GigaScatter as such: ```julia import Pkg; Pkg.add("GigaScatter") using GigaScatter savePNG("Levine13-CD4.png", solidBackground(rasterize((500,500), # bitmap size Matrix{Float64}(e'), # the embedding coordinates expressionColors( scaleNorm(Array{Float64}(exprs[:,5])), # 5th column contains CD4 expressions expressionPalette(100, alpha=0.5))))) # colors for plotting (based on RdYlBu) ``` The output may look like this (blue is negative expresison, red is positive): ![Levine13 embedding with CD4 highlighted](docs/src/assets/Levine13-CD4.png "Levine13/CD4") ## Feedback, issues, questions Please follow the [contributing guide](.github/CONTRIBUTING.md) when you have questions, want to raise issues, or just want to leave us some feedback!
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
3351
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at lcsb-r3 .at. uni.lu. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
1726
# Contributing to GigaSOM :+1::tada: Thanks for taking the time to contribute to [GigaSOM.jl](https://github.com/LCSB-BioCore/GigaSOM.jl)! :tada::+1: ## How can I contribute? A complete technical guide on how to get started contributing is given [here](https://lcsb-biocore.github.io/GigaSOM.jl/stable/howToContribute/). ## How to report a bug or suggest an enhancement Please use the [GitHub issue tracker](https://github.com/LCSB-BioCore/GigaSOM.jl/issues) to report any problems with the software, and discuss any potential questions about GigaSOM use. Before creating bug reports, please check [the open issues](https://github.com/LCSB-BioCore/GigaSOM.jl/issues) as you might find out that you don't need to create one. When you are creating a bug report, please include as many details as possible. Fill out the required template, the information it asks for helps us resolve issues faster. > If you find a Closed issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. If reporting issues, please do not forget to include a description of conditions under which the issue occurs; preferably a code snippet that can be run separately (sometimes termed "minimal crashing example"). ## How to submit a pull request (PR)? Please follow these steps to have your contribution considered by the maintainers: 1. Follow all instructions in the template 2. Submit your pull request against the `develop` branch 3. After you submit your pull request, verify that all status checks are passing After you submitted a pull request, a label might be assigned that allows us to track and manage issues and pull requests.
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
96
# Description of the proposed change *Please include a short description of enhancement here*
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
383
--- name: General issue (performance or bug) about: Describe your issue related to performance or a bug title: '' labels: '' assignees: '' --- **Summary** **Environment** *Please provide all information on your environment here, including the version of Julia* **Steps to reproduce** 1. 2. 3. **Expected behavior** **Actual behavior** **Additional information**
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
595
--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here.
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
7315
# Background ## Introduction Flow cytometry clustering for several hundred million cells has long been hampered by software limitations. Julia allows us to go beyond these limits. Through the high-performance GigaSOM.jl package, we gear up for huge-scale flow cytometry analysis, softening these limitations with an innovative approach on the existing algorithm, by implementing parallel computing with stable and robust mathematical models that would run with an HPC cluster, allowing us to run cytometry datasets as big as 500 million cells. ## Multidimensional Data Multidimensional data is a term used when combining four, five (or more) characteristics simultaneously to create a data space where each measured cell parameter becomes a dimension in the multidimensional space.\ The data generated by Flow Cytometry, Mass Cytometry or RNA-seq are good examples of multidimensional datasets, as they combine all information from all characteristics to create a multidimensional data space that preserves the integrity of the relationships between each of the parameters.[[1]](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6092027/) ### Flow and Mass Cytometry The use of flow cytometry has grown substantially in the past decade, mainly due to the development of smaller, user-friendly and less expensive instruments, but also to the increase of clinical applications, like cell counting, cell sorting, detection of biomarkers or protein engineering. Flow cytometry is an immunophenotyping technique used to identify and quantify the cells of the immune system by analysing their physical and chemical characteristics in a fluid. These cells are stained with specific, fluorescently labelled antibodies and then analysed with a flow cytometer, where the fluorescence intensity is measured using lasers and photodetectors. [[2]](http://clinchem.aaccjnls.org/content/46/8/1221) More recently, a variation of flow cytometry called mass cytometry (CyTOF) was introduced, in which antibodies are labelled with heavy metal ion tags rather than fluorochromes, breaking the limit of multiplexing capability of FACS (fluorescence-activated cell sorting) and allowing the simultaneous quantification of 40+ protein parameters within each single cell. The ability of flow cytometry and mass cytometry to analyse individual cells at high-throughput scales makes them ideal for multi-parameter cell analysis and high-speed sorting. [[3]](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4860251/) ![MassCytometry](assets/masscytometry.png)\ *General workflow of cell analysis in a mass cytometer. The cells are introduced into the nebulizer via a narrow capillary. As the cells exit from the nebulizer they are converted to a fine spray of droplets, which are then carried into the plasma where they are completely atomized and ionized. The resulting ion cloud is filtered and selected for positive ions of mass range 80–200 and measured in a TOF chamber. The data are then converted to .fcs format and analyzed using traditional flow cytometry software.* [[4]](http://dmd.aspetjournals.org/content/43/2/227) ## Self-organising maps (SOMs) Self-organising maps (also referred to as SOMs or *Kohonen* maps) are artificial neural networks introduced by Teuvo Kohonen in the 1980s. Despite of their age, SOMs are still widely used as an easy and robust unsupervised learning technique for analysis and visualisation of high-dimensional data. The SOM algorithm maps high-dimensional vectors into a lower-dimensional grid. Most often the target grid is two-dimensional, resulting into intuitively interpretable maps. After initializing a SOM grid of size n*n, each node is initialized with a random sample (row) from the dataset (training data). For each input vector (row) in the training data the distance to each node in the grid is calculated, using Chebyshev distance or Euclidean distance equations, where the closest node is called BMU (best matching unit). The row is subsequently assigned to the BMU making it move closer to the input data, influenced by the learning rate and neighborhood Gaussian function, whilst the neighborhood nodes are also adjusted closer to the BMU. This training step is repeated for each row in the complete dataset. After each iteration (epoch) the radius of the neighborhood function is reduced. After n epochs, clusters of nodes should have formed and as a final step, consensus cluster is used to reduce the data (SOM nodes) into m clusters. [[5]](https://ieeexplore.ieee.org/document/58325) ![SOMs](assets/soms.png)\ *Example of a self-organizing network with five cluster units, Yi, and seven input units, Xi. The five cluster units are arranged in a linear array.* [[6]](http://mnemstudio.org/neural-networks-kohonen-self-organizing-maps.htm) ## Implementation The high-performance [GigaSOM.jl](https://github.com/LCSB-BioCore/GigaSOM.jl) package enables the analysis and clustering of huge-scale flow cytometry data because it is HPC-ready and written in Julia, prepared to handle very large datasets. Also, the GigaSOM.jl package, provides training and visualization functions for Kohonen's self-organizing maps for Julia. Training functions are implemented in pure Julia, without depending on additional binary libraries. The SOM algorithm maps high-dimensional vectors into a lower-dimensional grid. Most often, the target grid is two-dimensional, resulting into intuitively interpretable maps. The general idea is to receive huge-scale .fcs data files as an input, load and transform them accordingly to enable the analysis and clustering of these data and automatically determine the required number of cell populations, and their sensitivity and specificity using parallel computing. In order to achieve this, GigaSOM.jl implementes a batch SOM algorithm, in which the weight vectors are only updated at the end of each epoch, and the BMU is calculated using the weight vectors from the previous epoch. Since the weight updates are not recursive, the order of the inputs does not affect the final result. In addition, there is no learning rate coefficient, which reduces the data dependency. This means that, compared to the original one, the batch algorithm has faster convergence, requires less computing, and it is the only one suitable for parallel computing. Parallel computing is the last step of our package implementation and two possible approaches exist for this kind of computation: the Model Parallelism and the Data Parallelism. In the Model Parallelism approach, the algorithm sends the same data to all the processes, and then each process is responsible for estimating different parameters and exchange their estimates with each other to come up with the right estimate for all the parameters. In the Data Parallelism approach, the algorithm distributes the data between different processes, and then each process independently tries to estimate the same parameters and then exchange their estimates with each other to come up with the right estimate. On this project, we use the Data Parallelism approaches because our nodes grid is too small for the Model Parallelism approach. ![parallel](assets/parallel.png)\ *Data Parallelism vs Model Parallelism* [[7]](https://www.slideshare.net/JunyoungPark22/common-design-for-distributed-machine-learning)
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
398
# Functions ## Data structures ```@autodocs Modules = [GigaSOM] Pages = ["structs.jl"] ``` ## Data loading and preparation ```@autodocs Modules = [GigaSOM] Pages = ["input.jl", "process.jl", "splitting.jl", "dataops.jl"] ``` ## SOM training ```@autodocs Modules = [GigaSOM] Pages = ["core.jl", "trainutils.jl"] ``` ## Embedding ```@autodocs Modules = [GigaSOM] Pages = ["embedding.jl"] ```
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git
[ "Apache-2.0" ]
0.7.0
19d26ff25ac886836456729a5e2837693b65569f
docs
3383
# How to contribute to/develop GigaSOM If you want to contribute to the `GigaSOM` package, please fork the present repository by following [these instructions](https://help.github.com/en/github/getting-started-with-github/fork-a-repo). ## Step 1: Retrieve a local version of GigaSOM There are two ways that you can retrieve a local copy of the package: one is to manually clone the forked repository, and the second one is to use the intergrated Julia package manager. ### Option 1: Manually clone your fork :warning: Please make sure you have _forked_ the repository, as described above. You can do this as follows from the command line: ```bash $ git clone git@github.com:yourUsername/GigaSOM.jl.git GigaSOM.jl $ cd GigaSOM.jl $ git checkout -b yourNewBranch origin/develop ``` where `yourUsername` is your Github username and `yourNewBranch` is the name of a new branch. Then, in order to develop the package, you can install your cloned version as follows (make sure you are in the `GigaSOM.jl` directory): ```julia (v1.1) pkg> add . ``` (press `]` to get into the packaging environment) This adds the `GigaSOM.jl` package and all its dependencies. You can verify that the installation worked by typing: ```julia (v1.1) pkg> status ``` If everything went smoothly, this should print something similar to: ```julia (v1.1) pkg> status Status `~/.julia/environments/v1.1/Project.toml` [a03a9c34] GigaSOM v0.0.5 #yourNewBranch (.) ``` Now, you can readily start using the `GigaSOM` module: ```julia julia> using GigaSOM ``` ### Option 2: Use the Julia package manager When you are used to using the Julia package manager for developing or contributing to packages, you can type: ```julia (v1.1) pkg> dev GigaSOM ``` This will install the `GigaSOM` package locally and check it out for development. You can check the location of the package with: ```julia (v1.1) pkg> status Status `~/.julia/environments/v1.1/Project.toml` [a03a9c34] GigaSOM v0.0.5 [`~/.julia/dev/GigaSOM`] ``` The default location of the package is `~/.julia/dev/GigaSOM`. You can then set your remote by executing these commands in a regular shell: ```bash $ cd ~/.julia/dev/GigaSOM $ git remote rename origin upstream # renames the origin as upstream $ git remote add origin git@github.com:yourUsername/GigaSOM.jl.git $ git fetch origin ``` where `yourUsername` is your Github username. :warning: Make sure that your fork exists under `github.com/yourUsername/GigaSOM.jl`. Then, checkout a branch `yourNewBranch`: ```bash $ cd ~/.julia/dev/GigaSOM $ git checkout -b yourNewBranch origin/develop ``` Then, you can readily use the `GigaSOM` package: ```julia julia> using GigaSOM ``` After making changes, precompile the package: ```julia (v1.1) pkg> precompile ``` ## Step 2: Activate GigaSOM :warning: Please note that you cannot use the dependencies of GigaSOM directly, unless they are installed separately or the environment has been activated: ```julia (v1.1) pkg> activate . (GigaSOM) pkg> instantiate ``` Now, the environment is activated (you can see it with the prompt change `(GigaSOM) pkg>`). Now, you can use the dependency. For instance: ```julia julia> using DataFrames ``` :warning: If you do not `activate` the environment before using any of the dependencies, you will see a red error messages prompting you to install the dependency explicity.
GigaSOM
https://github.com/LCSB-BioCore/GigaSOM.jl.git