Hi, I’ve got the following model in which it happens that (so far) the odd elements are of one type of quantity (e.g. voltages) and the evens are another (e.g. currents), although that could change as the model is elaborated. Writing the equations in u[i] notation is somewhat harder to read than if I can use more meaningful names like i[n] and v[n]. I recognize that @ode_def of ParameterizedFunctions.jl addresses that, but I’m using a for loop to create a large number of repeated sections (in this example a lumped model for a transmission line) and as a consequence I’m not sure I can use @ode_def. I’ve tried using views, but that slowed things down with a large number of allocations.
Here’s the ODE function as first written:
function lcs(du,u,p,t)
L, C, R, RT = p
n=1
du[n] = 1/L*(V0(t)-u[n+1]-R*ssq(u[n])) # di/dt
for lump in 1:NUM_LUMPS
n+=1
du[n] = 1/C*(u[n-1]-u[n+1]) # dv/dt
du[n+1] = 1/L*(u[n]-u[n+2]-R*ssq(u[n+1])) # di/dt
n+=1
end
du[n+1] = 1/C*(u[n]-u[n+1]/RT) # dv/dt
end
and here’s a version using views to allow for (slightly) more readable equations:
function lcs(du,u,p,t)
di = view(du,1:2:length(du))
i = view(u, 1:2:length(u)) # odd indices are currents
dv = view(du,2:2:length(du))
v = view(u, 2:2:length(u)) # even indices are voltages
L, C, R, RT = p
di[1] = 1/L*(V0(t)-v[1]-R*ssq(i[1]))
for n in 1:NUM_LUMPS
dv[n] = 1/C*(i[n]-i[n+1])
di[n+1] = 1/L*(v[n]-v[n+1]-R*ssq(i[n+1]))
end
n = NUM_LUMPS+1
dv[n] = 1/C*(i[n]-v[n]/RT)
end
The views version works (I appear to be getting the same results), but I go from 0.625387 seconds (3.71 M allocations: 184.470 MiB, 5.91% gc time) to 1.343471 seconds (35.14 M allocations: 671.296 MiB, 11.95% gc time).
I expected each view to create “a view into the parent array with the given indices instead of making a copy”, and did not expect additional allocations. Thanks for any insight.