@@ -3,6 +3,7 @@ module SystemStructures
3
3
using DataStructures
4
4
using Symbolics: linear_expansion, unwrap
5
5
using SymbolicUtils: istree, operation, arguments, Symbolic
6
+ using SymbolicUtils: quick_cancel, similarterm
6
7
using .. ModelingToolkit
7
8
import .. ModelingToolkit: isdiffeq, var_from_nested_derivative, vars!, flatten,
8
9
value, InvalidSystemException, isdifferential, _iszero, isparameter,
@@ -13,6 +14,14 @@ using UnPack
13
14
using Setfield
14
15
using SparseArrays
15
16
17
+ quick_cancel_expr (expr) = Rewriters. Postwalk (
18
+ quick_cancel,
19
+ similarterm= (x, f, args) -> similarterm (
20
+ x, f, args, SymbolicUtils. symtype (x);
21
+ metadata= SymbolicUtils. metadata (x)
22
+ )
23
+ )(expr)
24
+
16
25
#=
17
26
When we don't do subsitution, variable information is split into two different
18
27
places, i.e. `states` and the right-hand-side of `observed`.
@@ -86,7 +95,7 @@ algvars_range(s::SystemStructure) = Iterators.filter(Base.Fix1(isalgvar, s), eac
86
95
isalgeq (s:: SystemStructure , eq:: Integer ) = s. algeqs[eq]
87
96
isdiffeq (s:: SystemStructure , eq:: Integer ) = ! isalgeq (s, eq)
88
97
89
- function initialize_system_structure (sys)
98
+ function initialize_system_structure (sys; quick_cancel = false )
90
99
sys = flatten (sys)
91
100
ivs = independent_variables (sys)
92
101
eqs = copy (equations (sys))
@@ -109,9 +118,12 @@ function initialize_system_structure(sys)
109
118
vars = OrderedSet ()
110
119
for (i, eq′) in enumerate (eqs)
111
120
if _iszero (eq′. lhs)
121
+ rhs = quick_cancel ? quick_cancel_expr (eq′. rhs) : eq′. rhs
112
122
eq = eq′
113
123
else
114
- eq = 0 ~ eq′. rhs - eq′. lhs
124
+ lhs = quick_cancel ? quick_cancel_expr (eq′. lhs) : eq′. lhs
125
+ rhs = quick_cancel ? quick_cancel_expr (eq′. rhs) : eq′. rhs
126
+ eq = 0 ~ rhs - lhs
115
127
end
116
128
vars! (vars, eq. rhs)
117
129
isalgeq = true
@@ -141,6 +153,8 @@ function initialize_system_structure(sys)
141
153
algeqs[i] = isalgeq
142
154
if isalgeq
143
155
eqs[i] = eq
156
+ else
157
+ eqs[i] = eqs[i]. lhs ~ rhs
144
158
end
145
159
end
146
160
0 commit comments