ComponentArray of ArrayPartition

Hello,

I am trying to use a ArrayPartition inside a ComponentArray.

Here is a MRE:

using ComponentArrays

using RecursiveArrayTools

var1 = ArrayPartition(randn(10), randn(10));

var2 = ComponentArray(a=randn(10), b=var1);

I like ArrayPartition because of the indexing: var1.x[1], var1.x[2]

However, I don’t get this ability when the ArrayPartition inside of a ComponentArray.

var2.b will show the whole array (no longer partitioned).

Is there a way to make it sustain the functionality inside a ComponentArray?
Is it possible to index a ComponentArray in the same way as a ArrayPartition (like: var2.x[1], var2.x[2])?

Alternatively, can I create a ComponentArray from list comprehension?

My expectation is that you should be able to access the partition with

var2.b.x

I wonder whether that is a bug.

Update

I just realized the accessor var2.a returns a view rather than a copy (don’t remember if that has always been the behavior). So maybe the behavior is expected because the view is of the data rather than the indices.

var2.b.x yields ERROR: type SubArray has no field x

Yeah. I agree. Initially, I thought adding var1 would mean having another layer of nesting and so I expected var2.b.x to work just as var1.x. But I think the issue is that it returns a view of the data rather than a copy, which means the indices of var1 are not available. At least that is what I think.

The following code appears to do what you want:

using ComponentArrays
using RecursiveArrayTools

var1 = ArrayPartition(randn(10), randn(10))
var2 = ComponentArray(a=randn(10), b = [xi for xi ∈ var1.x] )

You can then access var1.x[1] as var2.b[1] and var1.x[2] as var2.b[2].

2 Likes

Will the line b = [xi for xi ∈ var1.x] create a copy of each vector in var.x?

Yes. You can see that var1.x[1] === var2.b[1] returns false. Do you not want a copy?

One of the main purposes of ComponentArrays is to have a single flat array as the storage for the data. Thus, I don’t think it’s possible to construct a ComponentArray that does not copy data into this flat structure.

1 Like

This. I’m not sure it makes sense. ArrayPartition of ComponentArrays, maybe, but the point of ComponentArrays is that it has a flat vector so this direction that you want will have lots of oddities.

The idea is to have ComponentArrays with ArrayPartition. Not the other way around. For my purposes I think I can use both ArrayPartition and ComponentArrays interchangeably. However, It would be nice If ComponentArrays could have a similar interface to ArrayPartitions. If no name is provided, use a uniform syntax like .x[1], .x[2].