Skip to content

Commit

Permalink
feat: add label metadata to symbolic variables
Browse files Browse the repository at this point in the history
  • Loading branch information
ven-k committed Dec 5, 2023
1 parent cf282d2 commit 2114f99
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 1 deletion.
8 changes: 8 additions & 0 deletions docs/src/basics/Variable_metadata.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ help?> u
Symbolics.VariableSource: (:variables, :u)
```

## Label

Label is descriptive name of a symbolic variable. It can be defined as:

```@example metadata
@parameters R [label = "Resistance"]
```

## Connect

Variables in connectors can have `connect` metadata which describes the type of connections.
Expand Down
2 changes: 1 addition & 1 deletion src/ModelingToolkit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ export connect, domain_connect, @connector, Connection, Flow, Stream, instream
export @component, @mtkmodel, @mtkbuild
export isinput, isoutput, getbounds, hasbounds, isdisturbance, istunable, getdist, hasdist,
tunable_parameters, isirreducible, getdescription, hasdescription, isbinaryvar,
isintegervar
isintegervar, getlabel, haslabel
export ode_order_lowering, dae_order_lowering, liouville_transform
export PDESystem
export Differential, expand_derivatives, @derivatives
Expand Down
19 changes: 19 additions & 0 deletions src/variables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,25 @@ function hasdescription(x)
getdescription(x) != ""
end

## Label =================================================================
struct VariableLabel end
Symbolics.option_to_metadata_type(::Val{:label}) = VariableLabel

getlabel(x::Num) = getlabel(Symbolics.unwrap(x))

"""
getlabel(x)
Return labels attached to variables `x`. If no label is attached, an empty string is returned.
"""
function getlabel(x)
p = Symbolics.getparent(x, nothing)
p === nothing || (x = p)
Symbolics.getmetadata(x, VariableLabel, "")
end

haslabel(x) = (getlabel(x) != "")

## binary variables =================================================================
struct VariableBinary end
Symbolics.option_to_metadata_type(::Val{:binary}) = VariableBinary
Expand Down
9 changes: 9 additions & 0 deletions test/test_variable_metadata.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@ sp = Set(p)
@test getdescription(u) == ""
@test !hasdescription(u)

## Labels
@variables l [label = "Label"]
@test getlabel(l) == "Label"
@test haslabel(l)

@variables l
@test getlabel(l) == ""
@test !haslabel(l)

@parameters t
@variables u(t) [description = "A short description of u"]
@parameters p [description = "A description of p"]
Expand Down

0 comments on commit 2114f99

Please sign in to comment.