Skip to content

Commit dc16cb7

Browse files
committed
chains: support concrete round trips and index bounds
Assisted-by: Codex <codex@openai.com>
1 parent 3bbffa7 commit dc16cb7

4 files changed

Lines changed: 47 additions & 50 deletions

File tree

‎Project.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ uuid = "80f14c24-f653-4e6a-9b94-39d6b0f70001"
33
keywords = ["markov chain monte carlo", "probabilistic programming"]
44
license = "MIT"
55
desc = "A lightweight interface for common MCMC methods."
6-
version = "5.17.0-DEV"
6+
version = "5.17.0"
77

88
[deps]
99
BangBang = "198e06fe-97b7-11e9-32a5-e1d131e6ad66"

‎src/chains.jl‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ iteration indices before thinning.
1010
`sampling_stats` contains one `SamplingStats` or `missing` per chain, and `sampler_states`
1111
contains one saved state or `missing` per chain. Both default to `missing`; sampler states
1212
are retained only when sampling with `save_state=true`.
13+
Specialize `Base.show(io::IO, ::MIME"text/plain", ::SamplingOutput{<:MyDraw})` for custom display.
1314
"""
1415
struct SamplingOutput{T,I<:AbstractRange{<:Integer},S<:Union{SamplingStats,Missing},L} <:
1516
AbstractChains
@@ -38,6 +39,8 @@ end
3839

3940
Base.size(chain::SamplingOutput, args...) = size(chain.samples, args...)
4041
Base.getindex(chain::SamplingOutput, args...) = getindex(chain.samples, args...)
42+
Base.firstindex(chain::SamplingOutput, args...) = firstindex(chain.samples, args...)
43+
Base.lastindex(chain::SamplingOutput, args...) = lastindex(chain.samples, args...)
4144

4245
function Base.show(io::IO, ::MIME"text/plain", output::SamplingOutput)
4346
n, m = size(output)
@@ -80,6 +83,8 @@ function _bundle_samples(
8083
return convert(C, chain)
8184
end
8285

86+
chainsstack(chains::AbstractVector{<:SamplingOutput}) = chainscat(chains...)
87+
8388
function chainscat(chain::SamplingOutput, chains::SamplingOutput...)
8489
all(c -> c.iterations == chain.iterations, chains) ||
8590
throw(ArgumentError("chains must have matching iteration indices"))
@@ -92,8 +97,13 @@ function chainscat(chain::SamplingOutput, chains::SamplingOutput...)
9297
)
9398
end
9499

95-
function to_samples(::Type{T}, chain::SamplingOutput{<:T}) where {T}
96-
return chain.samples
100+
function to_samples(::Type{T}, chain::SamplingOutput) where {T}
101+
return convert(Matrix{T}, chain.samples)
97102
end
98103

99104
from_samples(::Type{SamplingOutput}, samples::Matrix) = SamplingOutput(samples)
105+
function from_samples(::Type{C}, samples::Matrix) where {T,C<:SamplingOutput{T}}
106+
chain = SamplingOutput(convert(Matrix{T}, samples))
107+
chain isa C || throw(ArgumentError("cannot reconstruct $C from samples alone"))
108+
return chain
109+
end

‎src/interface.jl‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,11 @@ Bundle all `samples` that were sampled from the `model` with the given `sampler`
2727
The final `state` of the `sampler` can be included in the chain. The type of the chain can
2828
be specified with the `chain_type` argument.
2929
30-
For an `AbstractChains` output type, the default implementation collects a vector or matrix
31-
of samples and its metadata in a [`SamplingOutput`](@ref), then calls `convert(chain_type, chain)`.
32-
Chain packages can implement this conversion instead of overloading `bundle_samples`.
30+
For an `AbstractChains` output type, the default `_bundle_samples` collects a vector or matrix
31+
of samples and its metadata in a [`SamplingOutput`](@ref), AbstractMCMC's internal chain
32+
representation, then calls `convert(chain_type, chain)`. Chain packages can implement
33+
`Base.convert(::Type{MyChains}, output::SamplingOutput)` and use this default without
34+
overloading `bundle_samples` or its internal helper `_bundle_samples`.
3335
Otherwise, this method returns `samples` (or converts its entries for `Vector{T}` output).
3436
"""
3537
function bundle_samples(

‎test/chains.jl‎

Lines changed: 29 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
module SamplingOutputTests
2-
3-
using AbstractMCMC
4-
using Random
5-
using Test
2+
using AbstractMCMC, Random, Test
3+
using AbstractMCMC: bundle_samples, chainscat, chainsstack, from_samples, to_samples
64

75
struct Model <: AbstractMCMC.AbstractModel end
86
struct Sampler <: AbstractMCMC.AbstractSampler end
@@ -16,11 +14,28 @@ end
1614
Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(chain)
1715

1816
@testset "SamplingOutput" begin
17+
opts = (; discard_initial=2, thinning=3, save_state=true, progress=false)
1918
samples = reshape([(x=1,), (x=2,)], :, 1)
2019
chain = SamplingOutput(samples)
2120
@test chain[2, 1] == (x=2,)
22-
@test AbstractMCMC.to_samples(NamedTuple, chain) === samples
23-
@test AbstractMCMC.from_samples(SamplingOutput, samples).samples === samples
21+
@test to_samples(eltype(samples), chain) === samples
22+
@test to_samples(NamedTuple, chain) isa Matrix{NamedTuple}
23+
@test to_samples(NamedTuple, chain) == samples
24+
@test to_samples(Float64, SamplingOutput(ones(Int, 1, 1))) isa Matrix{Float64}
25+
@test from_samples(SamplingOutput, samples).samples === samples
26+
@test from_samples(typeof(chain), to_samples(NamedTuple, chain)) isa typeof(chain)
27+
@test from_samples(typeof(chain), samples).samples === samples
28+
@test from_samples(SamplingOutput{Float64}, ones(Int, 1, 1)) isa SamplingOutput{Float64}
29+
many = [SamplingOutput(fill(i, 128, 1)) for i in 1:64]
30+
@test chainsstack(many).samples == repeat(reshape(1:64, 1, :), 128)
31+
@test (@allocated chainsstack(many)) < 4 * 128 * 64 * sizeof(Int)
32+
matrix = [(x=i, walker=j) for i in 1:3, j in 1:2]
33+
indexed = SamplingOutput(matrix)
34+
@test indexed[begin] == matrix[begin]
35+
@test indexed[end] == matrix[end]
36+
@test indexed[begin, end] == matrix[begin, end]
37+
@test indexed[end, begin] == matrix[end, begin]
38+
@test indexed[begin:end, begin:end] == matrix
2439
@test convert(SamplingOutput, chain) === chain
2540
@test convert(typeof(chain), chain) === chain
2641
@test all(ismissing, chain.sampling_stats)
@@ -37,61 +52,32 @@ Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(cha
3752
samples; sampling_stats=[missing, missing]
3853
)
3954
@test_throws DimensionMismatch SamplingOutput(samples; sampler_states=[])
40-
@test_throws ArgumentError AbstractMCMC.chainscat(
41-
chain, SamplingOutput(samples; iterations=2:3)
42-
)
55+
@test_throws ArgumentError chainscat(chain, SamplingOutput(samples; iterations=2:3))
4356

44-
converted =
45-
sample(
46-
Xoshiro(1),
47-
Model(),
48-
Sampler(),
49-
3;
50-
chain_type=ConvertedChain,
51-
discard_initial=2,
52-
thinning=3,
53-
save_state=true,
54-
progress=false,
55-
).chain
57+
converted = sample(
58+
Xoshiro(1), Model(), Sampler(), 3; chain_type=ConvertedChain, opts...
59+
)
60+
converted = converted.chain
5661
@test converted.iterations == 3:3:9
5762
@test converted.sampler_states == [9]
5863
@test only(converted.sampling_stats).duration >= 0
64+
@test_throws ArgumentError from_samples(typeof(converted), converted.samples)
5965
for chain_type in (Any, Vector{NamedTuple})
6066
raw = sample(Xoshiro(1), Model(), Sampler(), 3; chain_type, progress=false)
6167
@test raw isa Vector{<:NamedTuple}
6268
end
63-
64-
matrix = [(x=i, walker=j) for i in 1:3, j in 1:2]
6569
for draws in (matrix, view(matrix, :, :))
66-
chain = AbstractMCMC.bundle_samples(
67-
draws,
68-
Model(),
69-
Sampler(),
70-
9,
71-
SamplingOutput;
72-
discard_initial=2,
73-
thinning=3,
74-
save_state=true,
75-
)
70+
chain = bundle_samples(draws, Model(), Sampler(), 9, SamplingOutput; opts...)
7671
@test chain.samples == matrix
7772
@test chain.iterations == 3:3:9
7873
@test chain.sampler_states == [9, 9]
7974
@test all(ismissing, chain.sampling_stats)
8075
draws === matrix && @test chain.samples === matrix
8176
end
82-
8377
@testset "sampling: $ensemble" for ensemble in (nothing, MCMCSerial(), MCMCThreads())
8478
args = ensemble === nothing ? (3,) : (ensemble, 3, 2)
8579
chain = sample(
86-
Xoshiro(1),
87-
Model(),
88-
Sampler(),
89-
args...;
90-
chain_type=SamplingOutput,
91-
discard_initial=2,
92-
thinning=3,
93-
save_state=true,
94-
progress=false,
80+
Xoshiro(1), Model(), Sampler(), args...; chain_type=SamplingOutput, opts...
9581
)
9682
@test size(chain) == (3, ensemble === nothing ? 1 : 2)
9783
@test chain.iterations == 3:3:9
@@ -100,5 +86,4 @@ Base.convert(::Type{ConvertedChain}, chain::SamplingOutput) = ConvertedChain(cha
10086
@test all(c -> getproperty.(c, :iteration) == 3:3:9, eachcol(chain.samples))
10187
end
10288
end
103-
10489
end

0 commit comments

Comments
 (0)