@@ -9,18 +9,24 @@ Units may assigned with the following syntax.
9
9
``` julia
10
10
using ModelingToolkit, Unitful
11
11
@variables t [unit = u " s" ] x (t) [unit = u " m" ] g (t) w (t) [unit = " Hz" ]
12
- # Or,
12
+
13
13
@variables (t, [unit = u " s" ], x (t), [unit = u " m" ], g (t), w (t), [unit = " Hz" ])
14
- # Or,
14
+
15
15
@variables (begin
16
16
t, [unit = u " s" ],
17
17
x (t), [unit = u " m" ],
18
18
g (t),
19
19
w (t), [unit = " Hz" ]
20
20
end )
21
+
22
+ # Simultaneously set default value (use plain numbers, not quantities)
23
+ @variable x= 10 [unit = u " m" ]
24
+
25
+ # Symbolic array: unit applies to all elements
26
+ @variable x[1 : 3 ] [unit = u " m" ]
21
27
```
22
28
23
- Do not use ` quantities ` such as ` 1u"s" ` or ` 1/u"s" ` or ` u"1/s" ` as these will result in errors; instead use ` u"s" ` or ` u"s^1" ` .
29
+ Do not use ` quantities ` such as ` 1u"s" ` , ` 1/u"s" ` or ` u"1/s" ` as these will result in errors; instead use ` u"s" ` , ` u"s^-1" ` , or ` u"s"^-1 ` .
24
30
25
31
## Unit Validation & Inspection
26
32
@@ -62,8 +68,38 @@ eqs = eqs = [D(E) ~ P - E/τ,
62
68
0 ~ P ]
63
69
ModelingToolkit. validate (eqs) # Returns false while displaying a warning message
64
70
```
71
+ ## User-Defined Registered Functions and Types
72
+
73
+ In order to validate user-defined types and ` register ` ed functions, specialize ` get_unit ` . Single-parameter calls to ` get_unit `
74
+ expect an object type, while two-parameter calls expect a function type as the first argument, and a vector of arguments as the
75
+ second argument.
76
+
77
+ ``` julia
78
+ using ModelingToolkit
79
+ # Composite type parameter in registered function
80
+ @parameters t
81
+ D = Differential (t)
82
+ struct NewType
83
+ f
84
+ end
85
+ @register dummycomplex (complex:: Num , scalar)
86
+ dummycomplex (complex, scalar) = complex. f - scalar
87
+
88
+ c = NewType (1 )
89
+ MT. get_unit (x:: NewType ) = MT. get_unit (x. f)
90
+ function MT. get_unit (op:: typeof (dummycomplex),args)
91
+ argunits = MT. get_unit .(args)
92
+ MT. get_unit (- ,args)
93
+ end
94
+
95
+ sts = @variables a (t)= 0 [unit = u " cm" ]
96
+ ps = @parameters s= - 1 [unit = u " cm" ] c= c [unit = u " cm" ]
97
+ eqs = [D (a) ~ dummycomplex (c, s);]
98
+ sys = ODESystem (eqs, t, [sts... ;], [ps... ;], name= :sys )
99
+ sys_simple = structural_simplify (sys)
100
+ ```
65
101
66
- ## ` Unitful ` Literals & User-Defined Functions
102
+ ## ` Unitful ` Literals
67
103
68
104
In order for a function to work correctly during both validation & execution, the function must be unit-agnostic. That is, no unitful literals may be used. Any unitful quantity must either be a ` parameter ` or ` variable ` . For example, these equations will not validate successfully.
69
105
0 commit comments