From ba064a93a98ff325e3a67b176bdc58fe233dd762 Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Thu, 19 Nov 2026 21:43:08 +0100 Subject: [PATCH] refactor(src): typed errors and simpler parameter merge (T1 of #449) - Metadata and reference files: the load-time checks throw `IncorrectArgument` instead of `error(...)` (EXC1). - `features(:unknown)` throws `IncorrectArgument` instead of `UndefVarError`. - `Catalogue.status` reads `Metadata.problem_metadata`, with its check. - `Metadata.merge` (four methods shadowing `Base.merge`) removed: `parameters_data(problem, parameters)` handles `nothing` and uses `Base.merge`, without catching and rethrowing. - ModelingToolkit named in the docstrings of the package and `Modelings`. Refs #449 Co-Authored-By: Claude Opus 5.5 --- src/Catalogue/selection.jl | 7 +- src/Metadata/access.jl | 127 +++-------------------------- src/Metadata/loading.jl | 26 ++++-- src/Modelings/Modelings.jl | 6 +- src/OptimalControlProblems.jl | 2 +- src/Problems/problem.jl | 1 + src/References/objectives.jl | 19 ++++- test/suite/core/test_modelings.jl | 3 + test/suite/core/test_parameters.jl | 30 +++++-- test/suite/core/test_references.jl | 4 +- 10 files changed, 76 insertions(+), 149 deletions(-) diff --git a/src/Catalogue/selection.jl b/src/Catalogue/selection.jl index bd17d7a06..9079e5420 100644 --- a/src/Catalogue/selection.jl +++ b/src/Catalogue/selection.jl @@ -92,10 +92,5 @@ $(TYPEDSIGNATURES) Return the status of `problem` in each modeling where it exists. """ function status(problem::Symbol) - haskey(Metadata.METADATA_STORAGE, problem) || throw( - CTBase.Exceptions.IncorrectArgument( - "There is no problem named $problem in metadata" - ), - ) - return Metadata.METADATA_STORAGE[problem][:status] + return Metadata.problem_metadata(problem)[:status] end diff --git a/src/Metadata/access.jl b/src/Metadata/access.jl index bdb8aac05..3b8644330 100644 --- a/src/Metadata/access.jl +++ b/src/Metadata/access.jl @@ -89,108 +89,6 @@ end """ $(TYPEDSIGNATURES) -Merge two `Nothing` values. - -# Arguments - -- `::Nothing`: first argument. -- `::Nothing`: second argument. - -# Returns - -- `nothing::Nothing`: always returns `nothing`. - -# Example - -```julia-repl -julia> merge(nothing, nothing) -nothing -``` -""" -merge(::Nothing, ::Nothing) = nothing - -""" -$(TYPEDSIGNATURES) - -Merge a `NamedTuple` with `nothing`. - -# Arguments - -- `A::NamedTuple`: a named tuple to keep. -- `::Nothing`: placeholder, ignored. - -# Returns - -- `::NamedTuple`: returns `A` unchanged. - -# Example - -```julia-repl -julia> merge((a=1,), nothing) -(a = 1,) -``` -""" -merge(A::NamedTuple, ::Nothing) = A - -""" -$(TYPEDSIGNATURES) - -Throw an error when attempting to merge `nothing` with a `NamedTuple`. - -# Arguments - -- `::Nothing`: indicates there is no data to merge. -- `::NamedTuple`: the data that cannot be merged. - -# Returns - -- This function always throws `CTBase.Exceptions.PreconditionError`. - -# Example - -```julia-repl -julia> merge(nothing, (a=1,)) -ERROR: PreconditionError: there is nothing to merge -``` -""" -function merge(::Nothing, ::NamedTuple) - return throw( - CTBase.Exceptions.PreconditionError( - "there is nothing to merge"; - reason="parameters are given to update, but there are no defaults to update", - ), - ) -end - -""" -$(TYPEDSIGNATURES) - -Merge two `NamedTuple`s, with the second one overriding keys from the first when duplicated. - -# Arguments - -- `A::NamedTuple`: first set of key–value pairs. -- `B::NamedTuple`: second set of key–value pairs, takes precedence if keys overlap. - -# Returns - -- `::NamedTuple`: merged named tuple containing keys from both `A` and `B`. - -# Example - -```julia-repl -julia> merge((a=1, b=2), (b=3, c=4)) -(a = 1, b = 3, c = 4) -``` -""" -function merge(A::NamedTuple, B::NamedTuple) - f(; kwargs...) = kwargs - return NamedTuple(f(; A..., B...)) -end - -""" -$(TYPEDSIGNATURES) - Return the parameter set associated with a given problem. # Arguments @@ -236,21 +134,16 @@ julia> parameters_data(:beam, (tf = 2,)) ``` """ function parameters_data(problem::Symbol, parameters::Union{Nothing,NamedTuple}) - try - return merge(parameters_data(problem), parameters) - catch e - if e isa CTBase.Exceptions.PreconditionError - throw( - CTBase.Exceptions.PreconditionError( - "there are no parameters to merge"; - reason="problem $(problem) has no parameters", - suggestion="call $(problem) without the parameters keyword", - ), - ) - else - rethrow(e) - end - end + defaults = parameters_data(problem) + isnothing(parameters) && return defaults + isnothing(defaults) && throw( + CTBase.Exceptions.PreconditionError( + "there are no parameters to merge"; + reason="problem $(problem) has no parameters", + suggestion="call $(problem) without the parameters keyword", + ), + ) + return Base.merge(defaults, parameters) end """ diff --git a/src/Metadata/loading.jl b/src/Metadata/loading.jl index add546a53..8fd91969b 100644 --- a/src/Metadata/loading.jl +++ b/src/Metadata/loading.jl @@ -18,24 +18,32 @@ const METADATA_SCHEMA = ( ) const METADATA_STORAGE = OrderedDict{Symbol,OrderedDict}() +# A field of a metadata file that is missing, unknown or of the wrong type. +function _metadata_error(problem, key, got, expected) + return CTBase.Exceptions.IncorrectArgument( + "invalid metadata field $(key) of $(problem)"; + got, + expected, + suggestion="fix ext/MetaData/$(problem).jl, see METADATA_SCHEMA", + ) +end + for problem in PROBLEM_NAMES raw = eval(Symbol(problem, :_meta)) data = OrderedDict{Symbol,Any}() for (key, T) in pairs(METADATA_SCHEMA.required) - haskey(raw, key) || error("Missing metadata $(key) for $(problem)") - raw[key] isa T || error( - "Type mismatch: Expected $(T) for $(key) of $(problem), but got $(typeof(raw[key]))", - ) + haskey(raw, key) || throw(_metadata_error(problem, key, "no field", "a $(T)")) + raw[key] isa T || + throw(_metadata_error(problem, key, "a $(typeof(raw[key]))", "a $(T)")) data[key] = raw[key] end for (key, value) in raw haskey(METADATA_SCHEMA.required, key) && continue - haskey(METADATA_SCHEMA.optional, key) || - error("Unknown metadata $(key) for $(problem)") - T = METADATA_SCHEMA.optional[key] - value isa T || error( - "Type mismatch: Expected $(T) for $(key) of $(problem), but got $(typeof(value))", + haskey(METADATA_SCHEMA.optional, key) || throw( + _metadata_error(problem, key, "an unknown field", "a field of METADATA_SCHEMA"), ) + T = METADATA_SCHEMA.optional[key] + value isa T || throw(_metadata_error(problem, key, "a $(typeof(value))", "a $(T)")) data[key] = value end METADATA_STORAGE[problem] = data diff --git a/src/Modelings/Modelings.jl b/src/Modelings/Modelings.jl index 199aaaef6..95ea56670 100644 --- a/src/Modelings/Modelings.jl +++ b/src/Modelings/Modelings.jl @@ -1,8 +1,8 @@ """ The modelings of the collection: the backend types that select one (`JuMPBackend`, -`OptimalControlBackend`, `OptimalControlScalarizedBackend`) and the modeling table, the -single place where a modeling is declared (its name, its backend, the directory of its -models in `ext/`, the weak dependency that loads them). +`ModelingToolkitBackend`, `OptimalControlBackend`, `OptimalControlScalarizedBackend`) and +the modeling table, the single place where a modeling is declared (its name, its backend, +the directory of its models in `ext/`, the weak dependency that loads them). Depends on no other submodule. """ diff --git a/src/OptimalControlProblems.jl b/src/OptimalControlProblems.jl index d96b1308d..564fb85ac 100644 --- a/src/OptimalControlProblems.jl +++ b/src/OptimalControlProblems.jl @@ -1,6 +1,6 @@ """ A collection of optimal control problems, each available in one or more modelings -(OptimalControl, its scalarized form, JuMP), loaded by the extensions. +(OptimalControl, its scalarized form, JuMP, ModelingToolkit), loaded by the extensions. The code is split into submodules (ct-conventions `MOD1`, `MOD2`), in dependency order: `Modelings`, `Metadata`, `References`, `Catalogue`, `Problems`. The package re-exports their diff --git a/src/Problems/problem.jl b/src/Problems/problem.jl index 69d40aa88..1e205aba8 100644 --- a/src/Problems/problem.jl +++ b/src/Problems/problem.jl @@ -124,6 +124,7 @@ julia> OptimalControlProblems.features(:beam).cost ``` """ function features(problem::Symbol) + Metadata.problem_metadata(problem) # throws on an unknown problem return features(getfield(Catalogue, problem)(Modelings.OptimalControlBackend())) end diff --git a/src/References/objectives.jl b/src/References/objectives.jl index c39ef90c5..b6b13f9ba 100644 --- a/src/References/objectives.jl +++ b/src/References/objectives.jl @@ -37,11 +37,22 @@ function _references( Base.include_dependency(file) entries = Pair{Symbol,NamedTuple}[] for (scheme, table) in TOML.parsefile(file) - table isa AbstractDict || - error("Reference objective $(scheme) of $(problem): not a table") + table isa AbstractDict || throw( + CTBase.Exceptions.IncorrectArgument( + "invalid reference objective $(scheme) of $(problem)"; + got="a $(typeof(table))", + expected="a table", + suggestion="write $(file) again with tools/references/update.jl", + ), + ) values = map(keys(REFERENCE_FIELDS)) do key - haskey(table, string(key)) || error( - "Missing field $(key) in the reference objective $(scheme) of $(problem)", + haskey(table, string(key)) || throw( + CTBase.Exceptions.IncorrectArgument( + "invalid reference objective $(scheme) of $(problem)"; + got="no field $(key)", + expected="the fields $(join(keys(REFERENCE_FIELDS), ", "))", + suggestion="write $(file) again with tools/references/update.jl", + ), ) return REFERENCE_FIELDS[key](table[string(key)]) end diff --git a/test/suite/core/test_modelings.jl b/test/suite/core/test_modelings.jl index 6007137d7..219840b3e 100644 --- a/test/suite/core/test_modelings.jl +++ b/test/suite/core/test_modelings.jl @@ -79,6 +79,9 @@ function test_modelings() Test.@test_throws CTBase.Exceptions.ExtensionError OptimalControlProblems.features( problem ) + Test.@test_throws CTBase.Exceptions.IncorrectArgument OptimalControlProblems.features( + :not_a_problem + ) end Test.@testset "generated documentation" verbose = VERBOSE showtiming = SHOWTIMING begin diff --git a/test/suite/core/test_parameters.jl b/test/suite/core/test_parameters.jl index 1ae983360..4e94a7ae5 100644 --- a/test/suite/core/test_parameters.jl +++ b/test/suite/core/test_parameters.jl @@ -8,15 +8,29 @@ const VERBOSE = isdefined(Main, :TestOptions) ? Main.TestOptions.VERBOSE : true const SHOWTIMING = isdefined(Main, :TestOptions) ? Main.TestOptions.SHOWTIMING : true function test_parameters() - Test.@testset "merge (parameters)" verbose = VERBOSE showtiming = SHOWTIMING begin - Test.@test OptimalControlProblems.Metadata.merge(nothing, nothing) === nothing - Test.@test OptimalControlProblems.Metadata.merge((tf=1,), nothing) == (tf=1,) - Test.@test OptimalControlProblems.Metadata.merge((tf=1,), (tf=2,)) == (tf=2,) - Test.@test OptimalControlProblems.Metadata.merge((tf=1, a=2), (tf=2,)) == - (tf=2, a=2) - Test.@test_throws CTBase.Exceptions.PreconditionError OptimalControlProblems.Metadata.merge( - nothing, (tf=1,) + Test.@testset "parameters_data (merge)" verbose = VERBOSE showtiming = SHOWTIMING begin + problem = first(OptimalControlProblems.problems(; status=:all)) + defaults = OptimalControlProblems.parameters_data(problem) + key = first(keys(defaults)) + Test.@test OptimalControlProblems.parameters_data(problem, nothing) == defaults + merged = OptimalControlProblems.parameters_data(problem, NamedTuple{(key,)}((-1,))) + Test.@test keys(merged) == keys(defaults) + Test.@test merged[key] == -1 + # a problem without parameters takes none: no problem of the collection has + # none, so one is added for the test + storage = OptimalControlProblems.Metadata.METADATA_STORAGE + storage[:_no_parameters] = OptimalControlProblems.Metadata.OrderedDict{Symbol,Any}( + :parameters => nothing ) + try + Test.@test OptimalControlProblems.parameters_data(:_no_parameters, nothing) === + nothing + Test.@test_throws CTBase.Exceptions.PreconditionError OptimalControlProblems.parameters_data( + :_no_parameters, (tf=1,) + ) + finally + delete!(storage, :_no_parameters) + end end Test.@testset "problem_metadata" verbose = VERBOSE showtiming = SHOWTIMING begin problem = first(OptimalControlProblems.problems(; status=:all)) diff --git a/test/suite/core/test_references.jl b/test/suite/core/test_references.jl index e709296ae..1a3fbdf62 100644 --- a/test/suite/core/test_references.jl +++ b/test/suite/core/test_references.jl @@ -210,7 +210,9 @@ function test_references() # a file that misses a field is an error at load time broken = joinpath(dir, "broken.toml") write(broken, "[trapeze]\nvalue = 1.0\n") - Test.@test_throws ErrorException OCP.References._references(:alpha, broken) + Test.@test_throws CTBase.Exceptions.IncorrectArgument OCP.References._references( + :alpha, broken + ) Test.@test isnothing(OCP.References._references(:alpha, joinpath(dir, "none.toml"))) # a file written before #409 loads, without references, so that the tool can write