jonniedie / ComponentArrays.jl

Arrays with arbitrarily nested named components.
MIT License
289 stars 34 forks source link

Should the underlying Arraytype be preserved during KeepIndex subsetting? #136

Open bgctw opened 2 years ago

bgctw commented 2 years ago

Currently, KeepIndex subsetting on a ComponentVector based on LabelledVector or OffsetArray returns a ComponenVector based on plain Vector.

using OffsetArrays, LabelledArrays
oaca = ComponentArray(OffsetArray(collect(1:5), -1), Axis(a = 0, b=1:2, c=3, d=4))
oaca[KeepIndex(:b)] |> typeof # does not preserve underlying OffsetArray

na = SLVector(a1=1.1, a2=2.2, a3=3.3)
cv = ComponentVector(na, Axis(:b1,:b2,:b3))
cv[KeepIndex(:b2)] |> typeof # does not preserve underlying AbstractArray

Contrary, it does preserve the type for NamedArrays.

    na = NamedArray(1:3, ([:a1,:a2,:a3],))
    cv = ComponentVector(na, Axis(:b1,:b2,:b3))
    c2 = cv[KeepIndex(:b2)]
    @test getdata(c2)[:a2] == 2

When should the underlying AbstractArray type be preserved and when not?

jonniedie commented 2 years ago

I don't think it should in cases where indexing into the underlying array creates a new array type. OffsetArrays, for example, returns a plain Array when indexing into it. More than anything, though, it's just surprisingly difficult to reconstruct arbitrary array types. I've tried multiple times to get something similar working where you could have inner components that were different array types and it would rewrap them when you accessed the component. The fact that many common array types don't encode all of the information in the type domain required to convert back to them from a plain Array made this too difficult for me to figure out.

bgctw commented 2 years ago

ok, I see.

Would it be possible to support returning StaticVectors on KeepIndex indexing as a special case? This would be a common case with DifferentialEquations.jl for not-too-large state and parameter vectors.