Skip to content

Commit 8a9884b

Browse files
Merge pull request #142 from JuliaComputing/as/index-with-var
fix: handle `x[i]` where `i` is a variable in `TearingState` constructor
2 parents e998c7d + ff9da3e commit 8a9884b

2 files changed

Lines changed: 39 additions & 5 deletions

File tree

lib/ModelingToolkitTearing/src/tearingstate.jl

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -249,12 +249,26 @@ function TearingState(sys::System, source_info::Union{Nothing, MTKBase.EquationS
249249

250250
if !in(v, dvs)
251251
arr, isidx = MTKBase.split_indexed_var(v)
252-
# Handles cases list `D(x[1:2])`
253-
if isidx && SU.is_array_shape(SU.shape(v)) && SU.shape(v) isa SU.ShapeVecT
254-
for idx in SU.stable_eachindex(v)
255-
push!(auxiliary_vars, v[idx])
252+
if isidx
253+
# Handles cases list `D(x[1:2])`.
254+
if SU.is_array_shape(SU.shape(v)) && SU.shape(v) isa SU.ShapeVecT
255+
for idx in SU.stable_eachindex(v)
256+
push!(auxiliary_vars, v[idx])
257+
end
258+
continue
259+
end
260+
# Handles cases like `x[i]` where `i` is a variable.
261+
if any(!SU.isconst, Iterators.drop(arguments(v), 1)) && SU.shape(arr) isa SU.ShapeVecT
262+
for idx in SU.stable_eachindex(arr)
263+
push!(auxiliary_vars, arr[idx])
264+
end
265+
for arg in Iterators.drop(arguments(v), 1)
266+
SU.search_variables!(
267+
auxiliary_vars, arg; is_atomic = MTKBase.OperatorIsAtomic{SU.Operator}()
268+
)
269+
end
270+
continue
256271
end
257-
continue
258272
end
259273
isvalid = @match v begin
260274
BSImpl.Term(; f, args) => f isa Shift || isempty(args) || f isa SU.Operator && is_transparent_operator(f)::Bool

lib/ModelingToolkitTearing/test/runtests.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,3 +493,23 @@ end
493493
@test ts_deferred.eqs_source == [[:a], [:a], [:a], [:b]]
494494
end
495495
end
496+
497+
@testset "`TearingState` ctor for `x[i]` where `i` is a variable" begin
498+
N = 3
499+
dt = 0.1
500+
clock1 = Clock(dt)
501+
k = ShiftIndex(clock1)
502+
503+
@variables u(t) y(t) i(t)::Int
504+
@variables x(t)[1:N] = zeros(N)
505+
506+
eqs = Equation[
507+
u ~ sin(t);
508+
[x[i + 1](k) ~ u(k - i) for i in 0:(N - 1)];
509+
y(k) ~ x(k)[Symbolics.unwrap(i)];
510+
i(k) ~ ifelse(i(k - 1) + 1 > N, 1, i(k - 1) + 1)
511+
]
512+
513+
@named cl = System(eqs, t)
514+
@test_nowarn TearingState(cl)
515+
end

0 commit comments

Comments
 (0)