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.

In [1]:
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.

In [4]:
import Laplacians: Sampler, push!, remove!, sample, pop!
In [5]:
s = Sampler(7)
Out[5]:
Laplacians.Sampler([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],0,7)
In [6]:
push!(s,7,1.0)
s
Out[6]:
Laplacians.Sampler([1.0,0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0],1,7)
In [7]:
push!(s,1,0.5)
s
Out[7]:
Laplacians.Sampler([1.5,0.0,1.5,0.0,0.0,1.0,0.5,0.0,0.0,0.0,0.0,0.0,1.0],2,7)

A uniform distribution

In [8]:
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]
Out[8]:
5-element Array{Any,1}:
 255
 263
 243
 239
   0

Sampling with probability proportional to i

In [9]:
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]
Out[9]:
5-element Array{Any,1}:
 100
 204
 297
 399
   0
In [10]:
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)
pop!(s) = 4
LoadError: No items to pop
while loading In[10], in expression starting on line 11

 in pop! at /Users/spielman/git/Laplacians.jl/src/Sampler.jl:88
s = Laplacians.Sampler([6.0,1.0,5.0,0.0,1.0,2.0,3.0,0.0,0.0],3,5)
pop!(s) = 3
s = Laplacians.Sampler([3.0,1.0,2.0,0.0,1.0,2.0,0.0,0.0,0.0],2,5)
pop!(s) = 2
s = Laplacians.Sampler([1.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0],1,5)
pop!(s) = 1
s = Laplacians.Sampler([0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],0,5)

If you try to push an item that it already there, you will get an error.

In [11]:
s = Sampler(3)
push!(s, 1, 1.0)
push!(s, 1, 1.0)
LoadError: pushed item 3 is already in the sampler.
while loading In[11], in expression starting on line 3

 in push! at /Users/spielman/git/Laplacians.jl/src/Sampler.jl:43

You can also bulk load a vector of probabilities

In [13]:
v = collect(1.0:5.0)
s = Sampler(v)
Out[13]:
Laplacians.Sampler([15.0,10.0,5.0,9.0,1.0,2.0,3.0,4.0,5.0],5,5)
In [14]:
x = zeros(1000)
for i in 1:1000
    x[i] = sample(s)
end
y = [sum(x .== i) for i in 1:5]
Out[14]:
5-element Array{Any,1}:
  74
 139
 185
 257
 345
In [ ]: