How to define a Sampler for an object?

Hey all,

I am getting an error when trying to use the Rand function for my custom type. The error is:

ERROR: LoadError: ArgumentError: Sampler for this object is not defined

I read the docs here and here but it is not clear to me where I need to define the Sampler or what the syntax I should use to do so would be.

I cannot share a MWE as the code is private, unfortunately. Any suggestions on how set up the Sampler would be much appreciated!

Here is the Rand function:

function rand(rng::AbstractRNG, p::VDPTagPOMDP{CardinalBarriers})
    # p is just some arbitrary type used to dispatch correctly.
    return TagState([0.0, 0.0], 8.0*rand(rng, 2) .- 4.0)

end

struct TagState
    agent::Vec2
    target::Vec2
end

Without an MWE, it would be great if you could explain what is not clear in the docs. All examples there are meant to be adapted for practical use easily.

Generally, if you need precalculated data, go with a SamplerSimple, otherwise a SamplerTrivial will do.

2 Likes

I second @Tamas_Papp’s answer, but in your example of rand method, the second argument is of type VDPTagPOMDP, is it a subtype of Random.Sampler? The API requires that.

2 Likes

I previously had:

function rand(rng::AbstractRNG, p::VDPTagPOMDP{CardinalBarriers})
    # return TagState([0.0, 0.0], 8.0*rand(rng, 2)-4.0)
    sp = Random.Sampler(AbstractRNG, VDPTagPOMDP{CardinalBarriers}, Val(Inf))

    return TagState([0.0, 0.0], 8.0*rand(rng, sp) .- 4.0) # sp used to be 2

end

but I ended up getting the same error as before.

This other version doesn’t change the property of VPDTagPOMDP being a subtype of Sampler. It’s the second argument of the rand definition which must be a subtype of it.
I don’t know what is VPDTagPOMDP, but if it’s not already a Sampler, it looks like your signature should be rand(rng::AbstractRNG, p::Random.SamplerTrivial{VDPTagPOMDP{CardinalBarriers}}).

2 Likes

Thanks @rfourquet, I was no aware I had to do rand(rng::AbstractRNG, p::Random.SamplerTrivial{VDPTagPOMDP{CardinalBarriers}}) but this seems to have solved my issue. Thanks again!