Making a view of a combination of array indexes and scalars, creating an array to send to a function

I have a combination of scalar values, and values stored in vectors. Is there a good way to create a view of these and send to other functions, rather than allocating it all to a new array?

I am performance de-bugging a piece of code using the profiler. There is a part in it where I check parameter values, and send them on to some DiffEq solver. I do this fairly frequently, and it seems to be a cause for slow down.

DiffEq wants parameter values as a vector, so that is what I am trying to provide. I essentially have a function:

get_p_vector(params,idx) = [find_p_value(params,idx,i) for i in 1:5]

I think the problem is that this allocates a new vector every time, which is causing gc slowdowns. Now, this is not needed, since I do not create any new values. So I should (?) instead have get_p_vector send a view, which doesn’t allocate.

Now what happens is that params have (in this case 5) indexes, each holding either a scalar or a vector. I want to create a view of the vector which is either the scalar or the subvector at some idx. E.g.:

param = [1, [2, 20, 200], 3, 4, [5, 50, 500]]

where
get_p_vector(params,1) should return a view of

[1, 2, 3, 4, 5]

and get_p_vector(params,3) a view of

[1, 200, 3, 4, 500]

Now, I am unsure how to do this. I only know how to view of a single array, e.g. @view my_array[3:10]. Is what I want to do even possible?

DiffEq should not require you to provide a vector. You can use a tuple, a named tuple or any other struct that you like.
Unless I misunderstand your usecase, the optimal choice seems to me to create a struct that contains all your parameters (You can allocate here since you should only do this once) and then pass this struct to each call of the solution.
Note that if your struct is not always the same, you can create new instances without allocations.
It seems that you only need five values at specific points of arrays so this should be no big problem.

1 Like

If I wrote my onwn DiffEq f function that should work. In this case I am using the ModelingToolkit package, which generates these for you. Unfortunately it also means that I lose some of this control, and am rather restricted in how I parse the parameter values :frowning: .

Perhaps easiest to preallocate a Vector and write a mutating version
get_p_vector!(preallocatedVec, params, j)

1 Like

That sounds like a good idea! I will try that, thanks a lot :slight_smile:

If Its always a five element vector you could also use StaticArrays

1 Like

This seemed to work, thanks :slight_smile:

Sounds like a good idea!