Skip to content

Commit f75d225

Browse files
committed
refactor: define constants in mtkmodel crisply
+ Adds an indirect test which validates units and check that metadata is correctly set.
1 parent 0ccb8c9 commit f75d225

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

src/systems/model_parsing.jl

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -406,8 +406,9 @@ function parse_constants!(exprs, dict, body, mod)
406406
Expr(:(=), Expr(:(::), a, type), Expr(:tuple, b, metadata)) || Expr(:(=), Expr(:(::), a, type), b) => begin
407407
type = getfield(mod, type)
408408
b = _type_check!(get_var(mod, b), a, type, :constants)
409-
constant = first(@constants $a::type = b)
410-
push!(exprs, :($a = $constant))
409+
push!(exprs,
410+
:($(Symbolics._parse_vars(
411+
:constants, type, [:($a = $b), metadata], toconstant))))
411412
dict[:constants][a] = Dict(:value => b, :type => type)
412413
if @isdefined metadata
413414
for data in metadata.args
@@ -416,16 +417,18 @@ function parse_constants!(exprs, dict, body, mod)
416417
end
417418
end
418419
Expr(:(=), a, Expr(:tuple, b, metadata)) => begin
419-
constant = first(@constants $a = b)
420-
push!(exprs, :($a = $constant))
420+
push!(exprs,
421+
:($(Symbolics._parse_vars(
422+
:constants, Real, [:($a = $b), metadata], toconstant))))
421423
dict[:constants][a] = Dict{Symbol, Any}(:value => get_var(mod, b))
422424
for data in metadata.args
423425
dict[:constants][a][data.args[1]] = data.args[2]
424426
end
425427
end
426428
Expr(:(=), a, b) => begin
427-
constant = first(@constants $a = b)
428-
push!(exprs, :($a = $constant))
429+
push!(exprs,
430+
:($(Symbolics._parse_vars(
431+
:constants, Real, [:($a = $b)], toconstant))))
429432
dict[:constants][a] = Dict(:value => get_var(mod, b))
430433
end
431434
_ => error("""Malformed constant definition `$arg`. Please use the following syntax:

test/model_parsing.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,10 +184,15 @@ resistor = getproperty(rc, :resistor; namespace = false)
184184
@testset "Constants" begin
185185
@mtkmodel PiModel begin
186186
@constants begin
187-
_p::Irrational = π, [description = "Value of Pi."]
187+
_p::Irrational = π, [description = "Value of Pi.", unit = u"V"]
188188
end
189189
@parameters begin
190190
p = _p, [description = "Assign constant `_p` value."]
191+
e, [unit = u"V"]
192+
end
193+
@equations begin
194+
# This validates units; indirectly verifies that metadata was correctly passed.
195+
e ~ _p
191196
end
192197
end
193198

0 commit comments

Comments
 (0)