Skip to content

Commit 7340bcb

Browse files
committed
Add generate_function for DiscreteSystem and necessary utils
1 parent 6c22015 commit 7340bcb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/systems/discrete_system/discrete_system.jl

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,33 @@ function collect_difference_variables(sys::DiscreteSystem)
164164
end
165165
return difference_vars
166166
end
167+
168+
@noinline function throw_invalid_difference(difvar, eq)
169+
msg = "The difference variable must be isolated to the left-hand " *
170+
"side of the equation like `$difvar ~ ...`.\n Got $eq."
171+
throw(InvalidSystemException(msg))
172+
end
173+
174+
function check_difference_variables(eq, expr=eq.rhs)
175+
istree(expr) || return nothing
176+
if operation(expr) isa Difference
177+
throw_invalid_difference(expr, eq)
178+
end
179+
foreach(Base.Fix1(check_difference_variables, eq), arguments(expr))
180+
end
181+
182+
function generate_function(
183+
sys::DiscreteSystem, dvs = states(sys), ps = parameters(sys);
184+
kwargs...
185+
)
186+
eqs = equations(sys)
187+
foreach(check_difference_variables, eqs)
188+
# substitute x(t) by just x
189+
rhss = [isdifference(eq.lhs) ? arguments(eq.lhs)[1] + eq.rhs : eq.rhs for eq in eqs]
190+
191+
u = map(x->time_varying_as_func(value(x), sys), dvs)
192+
p = map(x->time_varying_as_func(value(x), sys), ps)
193+
t = get_iv(sys)
194+
195+
build_function(rhss, u, p, t; kwargs...)
196+
end

0 commit comments

Comments
 (0)