How to define an overload constructor across an abstract type?

I have various structs of parameters that I am using for things like running ODEs and least squares optimizations, i.e.:

abstract type model_A end

struct params1 <: model_A
    a::Float64
end

struct params2 <: model_A
    a::Float64
    b::Float64
end

I have a utility function that lets my generate different parameter sets as I run optimizations or etc:

function range_of_model_parameters(
    model_type::Type{T}, args...
) where {T <: model_A}
    return vec([ T(param_set...) for param_set in Iterators.product(args...) ])
end

# example
p2 = range_of_model_parameters(params2, [1.0,2.1], 3)

I would like to be able to define a new constructor that applies to all the model_A types, such that I could run

p2 = params2([1.0, 2.1], 3)
p1 = params1([3.2, 5.6])
...

after only one definition of the constructor for the abstract type.

Any ideas on how to do this?

P.S. the reason I want to do this is because I need to re-define the parameter struct for each computation of the objective function when I optimize over a given parameter. Since the solvers are vectorized, when I re-define the struct the objective function is trying to pass in a vector of parameters and I get a type error. So it would be nice to have a method that automatically accepts the vector of parameters without having to redefine this for each argument and each concrete struct type

You could do something like the following:

abstract type model_A end

struct params1 <: model_A
    a::Float64
    params1(a::Number) = new(a)
end

struct params2 <: model_A
    a::Float64
    b::Float64
    params2(a::Number, b::Number) = new(a, b)
end

function (::Type{P})(args...) where P <: model_A
    [P(params...) for params in Iterators.product(args...)]
end

Then you get

julia> params1([1.0, 2.1])
2-element Vector{params1}:
 params1(1.0)
 params1(2.1)

julia> params2([1.0, 2.1], 3)
2-element Vector{params2}:
 params2(1.0, 3.0)
 params2(2.1, 3.0)

The inner constructor for each concrete type is needed to resolve method ambiguities.

1 Like