Skip to content

Commit 793478c

Browse files
committed
Fix tails of Quantile transform
1 parent 87c6112 commit 793478c

File tree

3 files changed

+16
-8
lines changed

3 files changed

+16
-8
lines changed

src/distributions.jl

+6-6
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@ quantile(d::EmpiricalDistribution, p::Real) = quantile(d.values, p, sorted=true)
2222

2323
function cdf(d::EmpiricalDistribution{T}, x::T) where {T<:Real}
2424
v = d.values
25-
N = length(v)
25+
n = length(v)
2626

27-
head, mid, tail = 1, 1, N
27+
head, mid, tail = 1, 1, n
2828
while tail - head > 1
2929
mid = (head + tail) ÷ 2
3030
if x < v[mid]
@@ -37,14 +37,14 @@ function cdf(d::EmpiricalDistribution{T}, x::T) where {T<:Real}
3737
l, u = v[head], v[tail]
3838

3939
if x < l
40-
return 0.
40+
return zero(T)
4141
elseif x > u
42-
return 1.
42+
return one(T)
4343
else
4444
if head == tail
45-
return head / N
45+
return head / n
4646
else
47-
pl, pu = head / N, tail / N
47+
pl, pu = head / n, tail / n
4848
return (pu - pl) * (x - l) / (u - l) + pl
4949
end
5050
end

src/transforms/quantile.jl

+5-1
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,12 @@ end
3131

3232
# transform samples from original to target distribution
3333
function qqtransform(samples, origin, target)
34+
# avoid evaluating the quantile at 0 or 1
35+
T = eltype(samples)
36+
low = zero(T) + T(0.001)
37+
high = one(T) - T(0.001)
3438
map(samples) do sample
3539
prob = cdf(origin, sample)
36-
quantile(target, prob - eps())
40+
quantile(target, clamp(prob, low, high))
3741
end
3842
end

test/transforms.jl

+5-1
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,11 @@
204204
end
205205

206206
@testset "Quantile" begin
207-
# TODO
207+
t = (z=rand(1000),)
208+
n, c = apply(Quantile(), t)
209+
r = revert(Quantile(), n, c)
210+
@test all(-4 .< extrema(n.z) .< 4)
211+
@test all(0 .≤ extrema(r.z) .≤ 1)
208212
end
209213

210214
@testset "Functional" begin

0 commit comments

Comments
 (0)