Sampling from custom distribution: "No method matching iterate..."

alexdmeyer
Tue, 29 Oct 2024 15:33:18 +0000
Probabilistic Programming

Hello fellow Julians,

I’m trying to use a custom distribution/sampleable for inference in Turing.jl, and I’ve encountered a problem I can’t solve. Following the instructions on the Turing docs, I made the following minimal working example – a uniform distribution on [0,L]:

    struct MyUniformDist <: ContinuousUnivariateDistribution
        L::Real
    end
    Distributions.logpdf(d::MyUniformDist, x::Real) = 0 ≤ x ≤ d.L ? log(1/d.L) : -Inf
    Distributions.rand(rng::AbstractRNG, d::MyUniformDist) = rand(rng) * d.L
    Distributions.minimum(d::MyUniformDist) = 0.
    Distributions.maximum(d::MyUniformDist) = d.L

I try to sample from it,

foo = MyUniformDist(3)
rand(foo)

and get the following error:

ERROR: MethodError: no method matching iterate(::MyUniformDist)

Closest candidates are:
  iterate(::LLVM.StructTypeElementSet)
   @ LLVM ~/.julia/packages/LLVM/bzSzE/src/core/type.jl:246
  iterate(::LLVM.StructTypeElementSet, ::Any)
   @ LLVM ~/.julia/packages/LLVM/bzSzE/src/core/type.jl:246
  iterate(::CSV.Chunks)
   @ CSV ~/.julia/packages/CSV/XLcqT/src/chunks.jl:91
  ...

Stacktrace:
 [1] copyto!(dest::Vector{Float64}, src::MyUniformDist)
   @ Base ./abstractarray.jl:943
 [2] _collect(cont::UnitRange{Int64}, itr::MyUniformDist, ::Base.HasEltype, isz::Base.HasLength)
   @ Base ./array.jl:765
 [3] collect(itr::MyUniformDist)
   @ Base ./array.jl:759
 [4] quantile(itr::MyUniformDist, p::Float64; sorted::Bool, alpha::Float64, beta::Float64)
   @ Statistics /Applications/Julia-1.10.app/Contents/Resources/julia/share/julia/stdlib/v1.10/Statistics/src/Statistics.jl:1086
 [5] rand(rng::Random.TaskLocalRNG, d::MyUniformDist)
   @ Distributions ~/.julia/packages/Distributions/uuqsE/src/univariates.jl:157
 [6] rand(::MyUniformDist)
   @ Distributions ~/.julia/packages/Distributions/uuqsE/src/genericrand.jl:22
 [7] top-level scope
   @ ~/path/to/my/file.jl:268

Can anyone give me some insight into what’s going on?

Thanks so much,

Alex M

Edit: fixed some remnants of my actual use-case in the MWE, but the problem remains the same.

6 posts - 2 participants