Skip to content

Commit

Permalink
Add structure to define default parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
tmigot committed Aug 15, 2024
1 parent 8cea36a commit dc6fa56
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 6 deletions.
1 change: 1 addition & 0 deletions src/SolverParameters.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import Base.values
import Base.names
import Base.convert

include("default-parameter.jl")
include("domains.jl")
include("parameters.jl")
include("parameterset.jl")
Expand Down
31 changes: 31 additions & 0 deletions src/default-parameter.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export DefaultParameter

"""
DefaultParameter{Dflt}
Structure used to simplify declaring default parameters in solvers and docstrings.
- `default::Dflt`: is the default value, it can be a Number, a Symbol or even a function.
- `str::String`: message to be printed or used in docstrings.
Constructors
DefaultParameter(default)
DefaultParameter(default, str)
"""
struct DefaultParameter{Dflt}
default::Dflt
str::String
end
DefaultParameter(default) = DefaultParameter(default, string(default))

function Base.show(io::IO, default_parameter::DefaultParameter) # Use this instead of [2]
return print(io, default_parameter.str)
end

function Base.get(default_parameter::DefaultParameter, args...)
default_parameter.default(args...)
end
function Base.get(default_parameter::DefaultParameter{<:Union{Number,Symbol}}, args...)
default_parameter.default
end
27 changes: 21 additions & 6 deletions test/test_parameters.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,29 @@ struct MockSolverParamSet{I, F} <: AbstractParameterSet
boolean::Parameter{Bool, BinaryRange{Bool}}
end

const real_inf = DefaultParameter(F -> F(42), "42")
@test "$real_inf" == "42"
const real = DefaultParameter(F -> F(1.5e-10), "1.5e-10")
@test "$real" == "1.5e-10"
const int_inf = DefaultParameter(I -> I(5), "5")
@test "$int_inf" == "5"
const int_r = DefaultParameter(I -> I(5), "5")
@test "$int_r" == "5"
const int_s = DefaultParameter(I -> I(5), "5")
@test "$int_s" == "5"
const boolean = DefaultParameter(true)
@test "$boolean" == "true"

show(real_inf)

function MockSolverParamSet(I::DataType, F::DataType)
MockSolverParamSet(
Parameter(F(42)),
Parameter(F(1.5e-10), RealInterval(F(0.0), F(1.0))),
Parameter(I(5)),
Parameter(I(5), IntegerRange(I(5), I(20))),
Parameter(I(5), IntegerSet(I[2, 4, 5, 1, 3, 7])),
Parameter(true, BinaryRange()),
Parameter(get(real_inf, F)),
Parameter(get(real, F), RealInterval(F(0.0), F(1.0))),
Parameter(get(int_inf, I)),
Parameter(get(int_r, I), IntegerRange(I(5), I(20))),
Parameter(get(int_s, I), IntegerSet(I[2, 4, 5, 1, 3, 7])),
Parameter(get(boolean), BinaryRange()),
)
end

Expand Down

0 comments on commit dc6fa56

Please sign in to comment.