From ca7a2e17137b8e1d8ecf866819b5f3cee2373439 Mon Sep 17 00:00:00 2001 From: contradict Date: Thu, 29 Aug 2024 13:03:49 -0700 Subject: [PATCH 1/2] Fix unit conversion for expressions When a parameter is specified in terms of other parameters, no unit conversion should be attempted until the full expression is evaluted. --- src/systems/model_parsing.jl | 8 ++++++++ test/units.jl | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/systems/model_parsing.jl b/src/systems/model_parsing.jl index 51a61e33bf..f7466235f5 100644 --- a/src/systems/model_parsing.jl +++ b/src/systems/model_parsing.jl @@ -663,6 +663,14 @@ function convert_units(varunits::Unitful.FreeUnits, value::AbstractArray{T}) whe Unitful.ustrip.(varunits, value) end +function convert_units(varunits::Unitful.FreeUnits, value::Num) + value +end + +function convert_units(varunits::DynamicQuantities.Quantity, value::Num) + value +end + function parse_variable_arg(dict, mod, arg, varclass, kwargs, where_types) vv, def, metadata_with_exprs = parse_variable_def!( dict, mod, arg, varclass, kwargs, where_types) diff --git a/test/units.jl b/test/units.jl index 4b8aace4c9..a792ae3400 100644 --- a/test/units.jl +++ b/test/units.jl @@ -223,3 +223,21 @@ end @variables x(t) @test ModelingToolkit.get_unit(sin(x)) == ModelingToolkit.unitless + +@mtkmodel ExpressionParametersTest begin + @parameters begin + v = 1.0, [unit = u"m/s"] + τ = 1.0, [unit = u"s"] + end + @components begin + pt = ParamTest(; a = v * τ) + end +end + +@named sys = ExpressionParametersTest(; v = 2.0u"m/s", τ = 3.0u"s") +sys = complete(sys) +# TODO: Is there a way to evalute this expression and compare to 6.0? +@test isequal(ModelingToolkit.getdefault(sys.pt.a), sys.v * sys.τ) +@test ModelingToolkit.getdefault(sys.v) ≈ 2.0 +@test ModelingToolkit.getdefault(sys.τ) ≈ 3.0 + From e078c1d4c835ef3ee051a1ebf29cb2b1854ae2f3 Mon Sep 17 00:00:00 2001 From: contradict Date: Thu, 29 Aug 2024 13:12:27 -0700 Subject: [PATCH 2/2] Fix spelling --- test/units.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/units.jl b/test/units.jl index a792ae3400..f0fcfdfb98 100644 --- a/test/units.jl +++ b/test/units.jl @@ -236,7 +236,7 @@ end @named sys = ExpressionParametersTest(; v = 2.0u"m/s", τ = 3.0u"s") sys = complete(sys) -# TODO: Is there a way to evalute this expression and compare to 6.0? +# TODO: Is there a way to evaluate this expression and compare to 6.0? @test isequal(ModelingToolkit.getdefault(sys.pt.a), sys.v * sys.τ) @test ModelingToolkit.getdefault(sys.v) ≈ 2.0 @test ModelingToolkit.getdefault(sys.τ) ≈ 3.0