@@ -276,6 +276,13 @@ function _linear_expansion(t, x)
276276 op, args = operation (t), arguments (t)
277277 expansion_check (op)
278278
279+ if iscall (x) && operation (x) == getindex
280+ arrx, idxsx... = arguments (x)
281+ else
282+ arrx = nothing
283+ idxsx = nothing
284+ end
285+
279286 if op === (+ )
280287 a₁ = b₁ = 0
281288 islinear = true
@@ -318,15 +325,47 @@ function _linear_expansion(t, x)
318325 a₁, b₁, islinear = linear_expansion (args[1 ], x)
319326 # (a₁ x + b₁)/b₂
320327 return islinear ? (a₁ / b₂, b₁ / b₂, islinear) : (0 , 0 , false )
328+ elseif op === getindex
329+ arrt, idxst... = arguments (t)
330+ isequal (arrt, arrx) && return (0 , t, true )
331+
332+ indexed_t = Symbolics. scalarize (arrt)[idxst... ]
333+ # when indexing a registered function/callable symbolic
334+ # scalarizing and indexing leads to the same symbolic variable
335+ # which causes a StackOverflowError without this
336+ isequal (t, indexed_t) && return (0 , t, true )
337+ return linear_expansion (Symbolics. scalarize (arrt)[idxst... ], x)
321338 else
322339 for (i, arg) in enumerate (args)
340+ isequal (arg, arrx) && return (0 , 0 , false )
341+ if symbolic_type (arg) == NotSymbolic ()
342+ arg isa AbstractArray || continue
343+ _occursin_array (x, arrx, arg) && return (0 , 0 , false )
344+ continue
345+ end
323346 a, b, islinear = linear_expansion (arg, x)
324347 (_iszero (a) && islinear) || return (0 , 0 , false )
325348 end
326349 return (0 , t, true )
327350 end
328351end
329352
353+ """
354+ _occursin_array(sym, arrsym, arr)
355+
356+ Check if `sym` (or, if `sym` is an element of an array symbolic, the array symbolic
357+ `arrsym`) occursin in the non-symbolic array `arr`.
358+ """
359+ function _occursin_array (sym, arrsym, arr)
360+ for el in arr
361+ if symbolic_type (el) == NotSymbolic ()
362+ return el isa AbstractArray && _occursin_array (sym, arrsym, el)
363+ else
364+ return occursin (sym, el) || occursin (arrsym, el)
365+ end
366+ end
367+ end
368+
330369# ##
331370# ## Utilities
332371# ##
0 commit comments