This is a demo/doc of the Sampler class. It enables you to sample integers with probability in proportion to provided weights. That is, for each integer in 1 to n, you push it with a weight. It then samples them with probability proportional to that weight. It can also pop them with that probability. Here are some demos of using it.
using Laplacians
The sampler class is not exported from Laplacians, because it is meant for internal use. We could change that at some point. In the meantime, if you want to use it then you need to import all of the methods that you want to use, like this.
import Laplacians: Sampler, push!, remove!, sample, pop!
s = Sampler(7)
push!(s,7,1.0)
s
push!(s,1,0.5)
s
A uniform distribution
n = 5
k = 4
s = Sampler(n)
for i in 1:k
push!(s,i,1.0)
end
x = zeros(1000)
for i in 1:1000
x[i] = sample(s)
end
y = [sum(x .== i) for i in 1:n]
Sampling with probability proportional to i
n = 5
k = 4
s = Sampler(n)
for i in 1:k
push!(s,i,i+0.0)
end
# @show pop!(s)
x = zeros(1000)
for i in 1:1000
x[i] = sample(s)
end
y = [sum(x .== i) for i in 1:n]
n = 5
k = 4
s = Sampler(n)
for i in 1:k
push!(s,i,i+0.0)
end
for i in 1:k
@show pop!(s)
@show s
end
pop!(s)
If you try to push an item that it already there, you will get an error.
s = Sampler(3)
push!(s, 1, 1.0)
push!(s, 1, 1.0)
You can also bulk load a vector of probabilities
v = collect(1.0:5.0)
s = Sampler(v)
x = zeros(1000)
for i in 1:1000
x[i] = sample(s)
end
y = [sum(x .== i) for i in 1:5]