Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix sampling from GammaShapeRate #339

Merged
merged 3 commits into from
Jul 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/distributions/gamma_shape_rate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,12 @@ function Random.rand(rng::AbstractRNG, dist::GammaShapeRate)
return convert(eltype(dist), rand(rng, convert(GammaShapeScale, dist)))
end

# This method is identical to the next one, but we need it
# See issue https://github.com/biaslab/ReactiveMP.jl/issues/337
function Random.rand(rng::AbstractRNG, dist::GammaShapeRate, n::Int64)
return convert(AbstractArray{eltype(dist)}, rand(rng, convert(GammaShapeScale, dist), n))
end

function Random.rand(rng::AbstractRNG, dist::GammaShapeRate, n::Integer)
return convert(AbstractArray{eltype(dist)}, rand(rng, convert(GammaShapeScale, dist), n))
end
Expand Down
21 changes: 21 additions & 0 deletions test/distributions/test_gamma.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ using Test
using ReactiveMP
using Random
using Distributions
using StableRNGs

import SpecialFunctions: loggamma
import ReactiveMP: xtlog
Expand Down Expand Up @@ -41,6 +42,26 @@ import ReactiveMP: xtlog
@test eltype(GammaShapeRate(1.0f0, 2.0f0)) === Float32
end

@testset "rand" begin
for shape in (1, 2), scale in (1, 2)
rng = StableRNG(42)
dist1 = GammaShapeScale(shape, scale)
dist2 = GammaShapeRate(shape, inv(scale))

# Check that the result makes sense
for dist in (dist1, dist2)
@test rand(rng, dist) > 0.0
@test all(>(0.0), rand(rng, dist, 10))
@test all(>(0.0), rand!(rng, dist, Vector{Float64}(undef, 10)))
end

# Check that the result is almost identical and does not depend on the parametrisation
@test rand(StableRNG(42), dist1) ≈ rand(StableRNG(42), dist2)
@test all(rand(StableRNG(42), dist1, 10) .≈ rand(StableRNG(42), dist2, 10))
@test all(rand!(StableRNG(42), dist1, Vector{Float64}(undef, 10)) .≈ rand!(StableRNG(42), dist2, Vector{Float64}(undef, 10)))
end
end

@testset "vague" begin
vague(GammaShapeScale) == Gamma(1.0, ReactiveMP.huge)
vague(GammaShapeRate) == Gamma(1.0, ReactiveMP.tiny)
Expand Down
Loading