-
Notifications
You must be signed in to change notification settings - Fork 17
/
transducer.jl
97 lines (79 loc) · 2.7 KB
/
transducer.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
struct Sample{A<:Random.AbstractRNG,M<:AbstractModel,S<:AbstractSampler,K} <:
Transducers.Transducer
rng::A
model::M
sampler::S
kwargs::K
end
function Sample(model::AbstractModel, sampler::AbstractSampler; kwargs...)
return Sample(Random.GLOBAL_RNG, model, sampler; kwargs...)
end
"""
Sample([rng, ]model, sampler; kwargs...)
Create a transducer that returns samples from the `model` with the Markov chain Monte Carlo
`sampler`.
# Examples
```jldoctest; setup=:(using AbstractMCMC: Sample)
julia> struct MyModel <: AbstractMCMC.AbstractModel end
julia> struct MySampler <: AbstractMCMC.AbstractSampler end
julia> function AbstractMCMC.step(rng, ::MyModel, ::MySampler, state=nothing; kwargs...)
# all samples are zero
return 0.0, state
end
julia> transducer = Sample(MyModel(), MySampler());
julia> collect(transducer(1:10)) == zeros(10)
true
```
"""
function Sample(
rng::Random.AbstractRNG, model::AbstractModel, sampler::AbstractSampler; kwargs...
)
return Sample(rng, model, sampler, kwargs)
end
# Initial sample.
function Transducers.start(rf::Transducers.R_{<:Sample}, result)
# Unpack transducer.
td = Transducers.xform(rf)
rng = td.rng
model = td.model
sampler = td.sampler
kwargs = td.kwargs
discard_initial = get(kwargs, :discard_initial, 0)::Int
# Start sampling algorithm and discard initial samples if desired.
sample, state = step(rng, model, sampler; kwargs...)
for _ in 1:discard_initial
sample, state = step(rng, model, sampler, state; kwargs...)
end
return Transducers.wrap(
rf, (sample, state), Transducers.start(Transducers.inner(rf), result)
)
end
# Subsequent samples.
function Transducers.next(rf::Transducers.R_{<:Sample}, result, input)
# Unpack transducer.
td = Transducers.xform(rf)
rng = td.rng
model = td.model
sampler = td.sampler
kwargs = td.kwargs
thinning = get(kwargs, :thinning, 1)::Int
let rng = rng,
model = model,
sampler = sampler,
kwargs = kwargs,
thinning = thinning,
inner_rf = Transducers.inner(rf)
Transducers.wrapping(rf, result) do (sample, state), iresult
iresult2 = Transducers.next(inner_rf, iresult, sample)
# Perform thinning if desired.
for _ in 1:(thinning - 1)
_, state = step(rng, model, sampler, state; kwargs...)
end
return step(rng, model, sampler, state; kwargs...), iresult2
end
end
end
function Transducers.complete(rf::Transducers.R_{Sample}, result)
_, inner_result = Transducers.unwrap(rf, result)
return Transducers.complete(Transducers.inner(rf), inner_result)
end