Constraint structs with automatic parameter handlings?

Hey,

I’m looking around to see if there is somewhere in the ecosystem a package that would allow me to define structs with arbitrary constraints in them, through something like

@probably_a_macro struct MyStruct{T}
    a::T # a must be positive
    b::Vector{T} # b must belong to the simplex
    C::Matrix{T} # must be a correlation matrix
end

I am looking for this to provide :
1° A unique, strict constructor that will enforce these constraints at construction
2° A (at least surjective, bijective when possible) mapping from a vector x \in R^p to my struct, with potentially the associated jacobian.

Something like that should be produced by the macro:

struct MyStruct{T}
    a::T
    b::Vector{T}
    C::Matrix{T}
    function MyStruct(a::T,b::Vector{T},c::Matrix{T}) where T
        @assert is_positive(a) && is_in_simplex(b) && is_a_corr(c)
        return new{T}(a,b,c)
    end
end
function intrisic_dimension(::MyStruct)
        return #whatever
end
function constraint(x)
    @assert length(x) == intrinsic_dimension(::MyStruct)
    a,b,c, = automatic_mappings(x)
    return MyStruct(a,b,c)
end

others tools such as unconstrain(::Mystruct) would be nice too.

I have seen TransformVariables.jl and looked at a few others but nothing seemed to do exactly what i wanted. Is there something close to this already existing, or will i have to roll my own ?

Of course, the capacity to then construct another one :

@same_macro struct MySecond{T}
    x::MyStruct{T}
    a::T # shoudl be negative
end

would enlarge the intrisic dimension and enforce the conditions of the first one…

@Tamas_Papp maybe ?

I had my clanker help me define structs with tagged fields (using empty macros) for similar things. If you don’t have access to one I can lend a hand this week.

If you do have access to one, have it copy this.

Here is the docs entry:

Here is the source: PortfolioOptimisers.jl/src/02_Tools.jl at 63286db30789a76a2383c6742173fda0f9eccd2d · dcelisgarza/PortfolioOptimisers.jl · GitHub

Ty, i’ll look at it. I’m acually rewritting one myself right now.