/
kolmogorov_smirnov.jl
218 lines (179 loc) · 7.37 KB
/
kolmogorov_smirnov.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# kolmogorov_smirnov.jl
# Kolmogorov–Smirnov
#
# Copyright (C) 2014 Christoph Sawade
#
# 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
ExactOneSampleKSTest,
ApproximateOneSampleKSTest, ApproximateTwoSampleKSTest
abstract type KSTest <: HypothesisTest end
abstract type ApproximateKSTest <: KSTest end
abstract type ExactKSTest <: KSTest end
population_param_of_interest(x::KSTest) = ("Supremum of CDF differences", 0.0, x.δ) # parameter of interest: name, value under h0, point estimate
default_tail(test::KSTest) = :both
## ONE SAMPLE KS-TEST
# compute supremum of differences between target and empirical cdf before and after the jump of the empirical cdf.
function ksstats(x::AbstractVector{T}, d::UnivariateDistribution) where T<:Real
n = length(x)
cdfs = cdf.(Ref(d), sort(x))
δp = maximum((1:n) / n - cdfs)
δn = -minimum((0:n-1) / n - cdfs)
δ = max(δn, δp)
(n, δ, δp, δn)
end
### EXACT KOLMOGOROV SMIRNOV TEST
struct ExactOneSampleKSTest <: ExactKSTest
n::Int # number of observations
δ::Float64 # supremum of CDF differences
δp::Float64 # supremum of the positive CDF differences
δn::Float64 # supremum of the negative CDF differences
end
"""
ExactOneSampleKSTest(x::AbstractVector{<:Real}, d::UnivariateDistribution)
Perform a one-sample exact Kolmogorov–Smirnov test of the null hypothesis that the data in
vector `x` comes from the distribution `d` against the alternative hypothesis that the
sample is not drawn from `d`.
Implements: [`pvalue`](@ref)
"""
function ExactOneSampleKSTest(x::AbstractVector{T}, d::UnivariateDistribution) where T<:Real
if length(x) > length(unique(x))
@warn("This test is inaccurate with ties")
end
ExactOneSampleKSTest(ksstats(x, d)...)
end
testname(::ExactOneSampleKSTest) = "Exact one sample Kolmogorov-Smirnov test"
function show_params(io::IO, x::ExactOneSampleKSTest, ident="")
println(io, ident, "number of observations: $(x.n)")
end
function StatsAPI.pvalue(x::ExactKSTest; tail=:both)
if tail == :left
pvalue(KSOneSided(x.n), x.δn; tail=:right)
elseif tail == :right
pvalue(KSOneSided(x.n), x.δp; tail=:right)
elseif tail == :both
pvalue(KSDist(x.n), x.δ; tail=:right)
else
throw(ArgumentError("tail=$(tail) is invalid"))
end
end
### APPROXIMATE KOLMOGOROV SMIRNOV TEST
struct ApproximateOneSampleKSTest <: ApproximateKSTest
n::Int # number of observations
δ::Float64 # supremum of CDF differences
δp::Float64 # supremum of the positive CDF differences
δn::Float64 # suproemum of the negative CDF differences
end
"""
ApproximateOneSampleKSTest(x::AbstractVector{<:Real}, d::UnivariateDistribution)
Perform an asymptotic one-sample Kolmogorov–Smirnov test of the null hypothesis that the
data in vector `x` comes from the distribution `d` against the alternative hypothesis
that the sample is not drawn from `d`.
Implements: [`pvalue`](@ref)
"""
function ApproximateOneSampleKSTest(x::AbstractVector{T}, d::UnivariateDistribution) where T<:Real
if length(x) > length(unique(x))
@warn("This test is inaccurate with ties")
end
ApproximateOneSampleKSTest(ksstats(x, d)...)
end
testname(::ApproximateOneSampleKSTest) = "Approximate one sample Kolmogorov-Smirnov test"
function show_params(io::IO, x::ApproximateOneSampleKSTest, ident="")
println(io, ident, "number of observations: $(x.n)")
println(io, ident, "KS-statistic: $(sqrt(x.n)*x.δ)")
end
# one-sided: http://www.encyclopediaofmath.org/index.php/Kolmogorov-Smirnov_test
function StatsAPI.pvalue(x::ApproximateOneSampleKSTest; tail=:both)
if tail == :left
exp(-2*x.n*x.δn^2)
elseif tail == :right
exp(-2*x.n*x.δp^2)
elseif tail == :both
pvalue(Kolmogorov(), sqrt(x.n)*x.δ; tail=:right)
else
throw(ArgumentError("tail=$(tail) is invalid"))
end
end
## TWO SAMPLE KS-TEST
### APPROXIMATE KOLMOGOROV SMIRNOV TEST
struct ApproximateTwoSampleKSTest <: ApproximateKSTest
n_x::Int # number of observations
n_y::Int # number of observations
δ::Float64 # supremum of CDF differences
δp::Float64 # supremum of the positive CDF differences
δn::Float64 # suproemum of the negative CDF differences
end
"""
ApproximateTwoSampleKSTest(x::AbstractVector{<:Real}, y::AbstractVector{<:Real})
Perform an asymptotic two-sample Kolmogorov–Smirnov-test of the null hypothesis that `x`
and `y` are drawn from the same distribution against the alternative hypothesis that they
come from different distributions.
Implements: [`pvalue`](@ref)
# External links
* [Approximation of one-sided test (Encyclopedia of Mathematics)
](https://www.encyclopediaofmath.org/index.php/Kolmogorov-Smirnov_test)
"""
function ApproximateTwoSampleKSTest(x::AbstractVector{T}, y::AbstractVector{S}) where {T<:Real, S<:Real}
n_x, n_y = length(x), length(y)
ApproximateTwoSampleKSTest(ksstats(x, y)...)
end
testname(::ApproximateTwoSampleKSTest) = "Approximate two sample Kolmogorov-Smirnov test"
function show_params(io::IO, x::ApproximateTwoSampleKSTest, ident="")
n = x.n_x*x.n_y/(x.n_x+x.n_y)
println(io, ident, "number of observations: [$(x.n_x),$(x.n_y)]")
println(io, ident, "KS-statistic: $(sqrt(n)*x.δ)")
end
function StatsAPI.pvalue(x::ApproximateTwoSampleKSTest; tail=:both)
n = x.n_x*x.n_y/(x.n_x+x.n_y)
if tail == :left
exp(-2*n*x.δn^2)
elseif tail == :right
exp(-2*n*x.δp^2)
elseif tail == :both
pvalue(Kolmogorov(), sqrt(n)*x.δ; tail=:right)
else
throw(ArgumentError("tail=$(tail) is invalid"))
end
end
# compute supremum of differences between empirical cdfs.
function ksstats(x::AbstractVector{T}, y::AbstractVector{S}) where {T<:Real, S<:Real}
n_x, n_y = length(x), length(y)
all_values = [x; y]
sort_idx = sortperm(all_values)
δ_y = 1 / n_y
δ_x = 1 / n_x
δ = δp = δn = zero(δ_y)
for i in 1:(n_x + n_y)
if sort_idx[i] > n_x
δ -= δ_y
else
δ += δ_x
end
# only update δp/δn if the value is about to change or at the last step.
if i == n_x + n_y || all_values[sort_idx[i]] != all_values[sort_idx[i + 1]]
if δ > δp
δp = δ
elseif δ < δn
δn = δ
end
end
end
(n_x, n_y, max(δp, -δn), δp, -δn)
end