Skip to content

Commit 7a6c1ee

Browse files
committed
fix: pass VariableUnit of diff var while converting it to a Term
Units are defined only in MTK, so pass this piece of info to `Symbolics.diff2term` to add this to the returning term-var.
1 parent a119d82 commit 7a6c1ee

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/variables.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,14 @@ function default_toterm(x)
109109
end
110110
x = normalize_to_differential(op)(arguments(x)...)
111111
end
112-
Symbolics.diff2term(x)
112+
term_unit = if operation(x) isa Differential
113+
_unit = safe_get_unit(
114+
x, "Ignoring the unit while converting `$x` to a term.\n")
115+
_unit !== nothing ? Dict(VariableUnit => _unit) : nothing
116+
else
117+
nothing
118+
end
119+
Symbolics.diff2term(x, term_unit)
113120
else
114121
x
115122
end

test/variable_utils.jl

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ new = (((1 / β - 1) + δ) / γ)^(1 / (γ - 1))
1919
using ModelingToolkit: isdifferential, vars, collect_differential_variables,
2020
collect_ivs
2121
@variables t u(t) y(t)
22-
D = Differential(t)
22+
using ModelingToolkit: D
2323
eq = D(y) ~ u
2424
v = vars(eq)
2525
@test v == Set([D(y), u])
@@ -32,3 +32,16 @@ aov = ModelingToolkit.collect_applied_operators(eq, Differential)
3232

3333
ts = collect_ivs([eq])
3434
@test ts == Set([t])
35+
36+
# Test units of diff vars of `Term` type.
37+
using ModelingToolkit: t, get_unit, default_toterm
38+
using DynamicQuantities
39+
@variables k(t) [unit = u"kg"]
40+
k2 = value(D(D(k)))
41+
@test get_unit(default_toterm(k2)) == get_unit(k2)
42+
43+
@variables l(t) [unit = u"mg"]
44+
l2 = value(D(D(l)))
45+
@test_logs (:warn,
46+
"""Ignoring the unit while converting `Differential(t)(Differential(t)(l(t)))` to a term.
47+
1.0e-6 kg uses non SI unit. Please use SI unit only.""") default_toterm(value(l2))

0 commit comments

Comments
 (0)