Parsimonious way to unpack big structs

using your example, it would be

using ComponentArrays
using UnPack

p = ComponentArray(α=0.1, β=0.2, γ=0.3)

function f2(x; p=p)
    @unpack α, β, γ = p
    return x^(α) + x^(β) + x^(γ)
end

I also like to organize the parameters inside the ComponentArray, for example:

using ComponentArrays
using UnPack

# full model
function model(p; data=data)
    @unpack p1, p2 = p
    @unpack data1, data2 = data
    
    # component 1
    r1 = f1(p1; data=data1)

    # component 2
    r2 = f2(p2; data=data2)

    return sum(r1 .* r2)
end

function f1(p1; data=data)
    @unpack α, β = p1
    @unpack x, y = data
    α .* x + β .* y
end

function f2(p2; data=data)
    @unpack γ, ψ = p2
    @unpack x, y = data
    γ[1] .* x[:, 1] + γ[2] .* x[:, 2] + ψ .* y
end

data = ComponentArray(data1 = (x = rand(100), y = rand(100)),
                      data2 = (x = rand(100, 2), y = rand(100)))
p = ComponentArray(p1 = (α = 1.0, β = 0.5),
                   p2 = (γ = [10.0, 15.0], ψ = 11.0))

model(p; data=data)
2 Likes