Skip to content

Commit

Permalink
Allow only keyword arguments for DifferentialEvolution`
Browse files Browse the repository at this point in the history
  • Loading branch information
scheidan committed Dec 2, 2024
1 parent 3e358db commit faaab7d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/proposals.jl
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ end

"""
```
DifferentialEvolution(γ0, σ_gamma = 1e-5)
DifferentialEvolution(; n_para, σ_gamma = 1e-5)
DifferentialEvolution(; γ0, σ_gamma = 1e-5)
```
Differential Evolution proposal, default values corresponding to EMCEE.
Expand All @@ -85,13 +85,17 @@ Integrations And Differential Evolution Markov Chain Monte Carlo. ApJS
struct DifferentialEvolution <: Proposal
γ0::Float64
σ_gamma::Float64
end

DifferentialEvolution(λ0) = DifferentialEvolution(λ0, 1e-5)

function DifferentialEvolution(; n_para, σ_gamma = 1e-5)
γ0 = 2.38/sqrt(2*n_para)
DifferentialEvolution(γ0, σ_gamma)
function DifferentialEvolution(; γ0 = nothing, n_para = nothing, σ_gamma = 1e-5)
if !isnothing(γ0) && isnothing(n_para)
new(γ0, σ_gamma)
elseif !isnothing(n_para) && isnothing(γ0)
γ0 = 2.38/sqrt(2*n_para)
new(γ0, σ_gamma)
else
throw(ArgumentError("Provide either `γ0` or `n_para`, not both."))
end
end
end

function (de::DifferentialEvolution)(θ, population)
Expand Down
9 changes: 9 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,15 @@ end

@testset "proposals generation" verbose = true begin

@testset "constructors" begin
# disallow positional arguments
@test_throws MethodError DifferentialEvolution(1, 0.1)
@test_throws MethodError DifferentialEvolution(1)
# you can only pass `γ0` or `n_para`, not both
@test_throws ArgumentError DifferentialEvolution(γ0=1, n_para=5)
@test_throws ArgumentError DifferentialEvolution(γ0=1, n_para=5, σ_gamma=1.4)
end

@testset "1-dim" begin
## Define model
f_dist(θ) = abs(0.0 - mean(rand(Normal(θ[1], 1), 100)))
Expand Down

0 comments on commit faaab7d

Please sign in to comment.