@@ -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,48 @@ 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+ shape (arrt) == Unknown () && return (0 , t, true )
332+
333+ indexed_t = OffsetArrays. Origin (map (first, axes (arrt)))(Symbolics. scalarize (arrt))[idxst... ]
334+ # when indexing a registered function/callable symbolic
335+ # scalarizing and indexing leads to the same symbolic variable
336+ # which causes a StackOverflowError without this
337+ isequal (t, indexed_t) && return (0 , t, true )
338+ return linear_expansion (Symbolics. scalarize (arrt)[idxst... ], x)
321339 else
322340 for (i, arg) in enumerate (args)
341+ isequal (arg, arrx) && return (0 , 0 , false )
342+ if symbolic_type (arg) == NotSymbolic ()
343+ arg isa AbstractArray || continue
344+ _occursin_array (x, arrx, arg) && return (0 , 0 , false )
345+ continue
346+ end
323347 a, b, islinear = linear_expansion (arg, x)
324348 (_iszero (a) && islinear) || return (0 , 0 , false )
325349 end
326350 return (0 , t, true )
327351 end
328352end
329353
354+ """
355+ _occursin_array(sym, arrsym, arr)
356+
357+ Check if `sym` (or, if `sym` is an element of an array symbolic, the array symbolic
358+ `arrsym`) occursin in the non-symbolic array `arr`.
359+ """
360+ function _occursin_array (sym, arrsym, arr)
361+ for el in arr
362+ if symbolic_type (el) == NotSymbolic ()
363+ return el isa AbstractArray && _occursin_array (sym, arrsym, el)
364+ else
365+ return occursin (sym, el) || occursin (arrsym, el)
366+ end
367+ end
368+ end
369+
330370# ##
331371# ## Utilities
332372# ##
0 commit comments