-
Notifications
You must be signed in to change notification settings - Fork 156
/
variable.jl
554 lines (464 loc) · 16.3 KB
/
variable.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
using SymbolicUtils: FnType, Sym, metadata
using Setfield
const IndexMap = Dict{Char,Char}(
'-' => '₋',
'0' => '₀',
'1' => '₁',
'2' => '₂',
'3' => '₃',
'4' => '₄',
'5' => '₅',
'6' => '₆',
'7' => '₇',
'8' => '₈',
'9' => '₉')
abstract type AbstractVariableMetadata end
struct VariableDefaultValue <: AbstractVariableMetadata end
struct VariableSource <: AbstractVariableMetadata end
function recurse_and_apply(f, x)
if symtype(x) <: AbstractArray
getindex_posthook(x) do r,x,i...
recurse_and_apply(f, r)
end
else
f(x)
end
end
function set_scalar_metadata(x, V, val)
if symtype(x) <: AbstractArray
x = if val isa AbstractArray
getindex_posthook(x) do r,x,i...
set_scalar_metadata(r, V, val[i...])
end
else
getindex_posthook(x) do r,x,i...
set_scalar_metadata(r, V, val)
end
end
end
setmetadata(x, V, val)
end
setdefaultval(x, val) = set_scalar_metadata(x, VariableDefaultValue, val)
struct GetindexParent end
function scalarize_getindex(x, parent=Ref{Any}(x))
if symtype(x) <: AbstractArray
parent[] = getindex_posthook(x) do r,x,i...
scalarize_getindex(r, parent)
end
else
xx = unwrap(scalarize(x))
xx = metadata(xx, metadata(x))
if symtype(xx) <: FnType
setmetadata(CallWithMetadata(xx, metadata(xx)), GetindexParent, parent[])
else
setmetadata(xx, GetindexParent, parent[])
end
end
end
function map_subscripts(indices)
str = string(indices)
join(IndexMap[c] for c in str)
end
function unwrap_runtime_var(v)
isruntime = Meta.isexpr(v, :$) && length(v.args) == 1
isruntime && (v = v.args[1])
return isruntime, v
end
# Build variables more easily
function _parse_vars(macroname, type, x, transform=identity)
ex = Expr(:block)
var_names = Symbol[]
# if parsing things in the form of
# begin
# x
# y
# z
# end
x = x isa Tuple && first(x) isa Expr && first(x).head == :tuple ? first(x).args : x # tuple handling
x = flatten_expr!(x)
cursor = 0
isoption(ex) = Meta.isexpr(ex, [:vect, :vcat, :hcat])
while cursor < length(x)
cursor += 1
v = x[cursor]
# We need lookahead to the next `v` to parse
# `@variables x [connect=Flow,unit=u]`
nv = cursor < length(x) ? x[cursor+1] : nothing
val = unit = connect = options = nothing
# x = 1, [connect = flow; unit = u"m^3/s"]
if Meta.isexpr(v, :(=))
v, val = v.args
if Meta.isexpr(val, :tuple) && length(val.args) == 2 && isoption(val.args[2])
options = val.args[2].args
val = val.args[1]
end
end
type′ = type
if Meta.isexpr(v, :(::))
v, type′ = v.args
type′ = type′ === :Complex ? Complex{type} : type′
end
# x [connect = flow; unit = u"m^3/s"]
if isoption(nv)
options = nv.args
cursor += 1
end
isruntime, v = unwrap_runtime_var(v)
iscall = Meta.isexpr(v, :call)
isarray = Meta.isexpr(v, :ref)
if iscall && Meta.isexpr(v.args[1], :ref)
@warn("The variable syntax $v is deprecated. Use $(Expr(:ref, Expr(:call, v.args[1].args[1], v.args[2]), v.args[1].args[2:end]...)) instead.
The former creates an array of functions, while the latter creates an array valued function.
The deprecated syntax will cause an error in the next major release of Symbolics.
This change will facilitate better implementation of various features of Symbolics.")
end
issym = v isa Symbol
@assert iscall || isarray || issym "@$macroname expects a tuple of expressions or an expression of a tuple (`@$macroname x y z(t) v[1:3] w[1:2,1:4]` or `@$macroname x y z(t) v[1:3] w[1:2,1:4] k=1.0`)"
if isarray && Meta.isexpr(v.args[1], :call)
# This is the new syntax
isruntime, fname = unwrap_runtime_var(v.args[1].args[1])
call_args = map(last∘unwrap_runtime_var, @view v.args[1].args[2:end])
size = v.args[2:end]
var_name, expr = construct_dep_array_vars(macroname, fname, type′, call_args, size, val, options, transform, isruntime)
elseif iscall
isruntime, fname = unwrap_runtime_var(v.args[1])
call_args = map(last∘unwrap_runtime_var, @view v.args[2:end])
var_name, expr = construct_vars(macroname, fname, type′, call_args, val, options, transform, isruntime)
else
var_name, expr = construct_vars(macroname, v, type′, nothing, val, options, transform, isruntime)
end
push!(var_names, var_name)
push!(ex.args, expr)
end
rhs = build_expr(:vect, var_names)
push!(ex.args, rhs)
return ex
end
function construct_dep_array_vars(macroname, lhs, type, call_args, indices, val, prop, transform, isruntime)
ndim = :($length(($(indices...),)))
vname = !isruntime ? Meta.quot(lhs) : lhs
if call_args[1] == :..
ex = :($CallWithMetadata($Sym{$FnType{Tuple, Array{$type, $ndim}}}($vname)))
else
ex = :($Sym{$FnType{Tuple, Array{$type, $ndim}}}($vname)(map($unwrap, ($(call_args...),))...))
end
ex = :($setmetadata($ex, $ArrayShapeCtx, ($(indices...),)))
if val !== nothing
ex = :($setdefaultval($ex, $val))
end
ex = setprops_expr(ex, prop, macroname, Meta.quot(lhs))
#ex = :($scalarize_getindex($ex))
ex = :($wrap($ex))
if call_args[1] == :..
ex = :($transform($ex))
end
if isruntime
lhs = gensym(lhs)
end
lhs, :($lhs = $ex)
end
function construct_vars(macroname, v, type, call_args, val, prop, transform, isruntime)
issym = v isa Symbol
isarray = isa(v, Expr) && v.head == :ref
if isarray
var_name = v.args[1]
if Meta.isexpr(var_name, :(::))
var_name, type′ = var_name.args
type = type′ === :Complex ? Complex{type} : type′
end
isruntime, var_name = unwrap_runtime_var(var_name)
indices = v.args[2:end]
expr = _construct_array_vars(macroname, isruntime ? var_name : Meta.quot(var_name), type, call_args, val, prop, indices...)
else
var_name = v
if Meta.isexpr(v, :(::))
var_name, type′ = v.args
type = type′ === :Complex ? Complex{type} : type′
end
expr = construct_var(macroname, isruntime ? var_name : Meta.quot(var_name), type, call_args, val, prop)
end
lhs = isruntime ? gensym(var_name) : var_name
rhs = :($transform($expr))
lhs, :($lhs = $rhs)
end
function option_to_metadata_type(::Val{opt}) where {opt}
throw(Base.Meta.ParseError("unknown property type $opt"))
end
function setprops_expr(expr, props, macroname, varname)
expr = :($setmetadata($expr, $VariableSource, ($(Meta.quot(macroname)), $varname,)))
isnothing(props) && return expr
for opt in props
if !Meta.isexpr(opt, :(=))
throw(Base.Meta.ParseError(
"Variable properties must be in " *
"the form of `a = b`. Got $opt."))
end
lhs, rhs = opt.args
@assert lhs isa Symbol "the lhs of an option must be a symbol"
expr = :($set_scalar_metadata($expr,
$(option_to_metadata_type(Val{lhs}())),
$rhs))
end
expr
end
struct CallWithMetadata{T,M} <: Symbolic{T}
f::Symbolic{T}
metadata::M
end
for f in [:istree, :operation, :arguments]
@eval SymbolicUtils.$f(x::CallWithMetadata) = $f(x.f)
end
SymbolicUtils.Code.toexpr(x::CallWithMetadata, st) = SymbolicUtils.Code.toexpr(x.f, st)
CallWithMetadata(f) = CallWithMetadata(f, nothing)
function Base.show(io::IO, c::CallWithMetadata)
show(io, c.f)
print(io, "⋆")
end
function (f::CallWithMetadata)(args...)
metadata(unwrap(f.f(map(unwrap, args)...)), metadata(f))
end
function construct_var(macroname, var_name, type, call_args, val, prop)
expr = if call_args === nothing
:($Sym{$type}($var_name))
elseif !isempty(call_args) && call_args[end] == :..
:($CallWithMetadata($Sym{$FnType{Tuple, $type}}($var_name)))
else
:($Sym{$FnType{NTuple{$(length(call_args)), Any}, $type}}($var_name)($(map(x->:($value($x)), call_args)...)))
end
if val !== nothing
expr = :($setdefaultval($expr, $val))
end
:($wrap($(setprops_expr(expr, prop, macroname, var_name))))
end
struct CallWith
args
end
(c::CallWith)(f) = unwrap(f(c.args...))
function _construct_array_vars(macroname, var_name, type, call_args, val, prop, indices...)
# TODO: just use Sym here
ndim = :($length(($(indices...),)))
need_scalarize = false
expr = if call_args === nothing
ex = :($Sym{Array{$type, $ndim}}($var_name))
:($setmetadata($ex, $ArrayShapeCtx, ($(indices...),)))
elseif !isempty(call_args) && call_args[end] == :..
need_scalarize = true
ex = :($Sym{Array{$FnType{Tuple, $type}, $ndim}}($var_name))
ex = :($setmetadata($ex, $ArrayShapeCtx, ($(indices...),)))
:($map($CallWithMetadata, $ex))
else
# [(R -> R)(R) ....]
need_scalarize = true
ex = :($Sym{Array{$FnType{Tuple, $type}, $ndim}}($var_name))
ex = :($setmetadata($ex, $ArrayShapeCtx, ($(indices...),)))
:($map($CallWith(($(call_args...),)), $ex))
end
if val !== nothing
expr = :($setdefaultval($expr, $val))
end
expr = setprops_expr(expr, prop, macroname, var_name)
if need_scalarize
expr = :($scalarize_getindex($expr))
end
expr = :($wrap($expr))
return expr
end
"""
Define one or more unknown variables.
```julia
@variables t α σ(..) β[1:2]
@variables w(..) x(t) y z(t, α, x)
expr = β[1]* x + y^α + σ(3) * (z - t) - β[2] * w(t - 1)
```
`(..)` signifies that the value should be left uncalled.
Symbolics supports creating variables that denote an array of some size.
```julia
julia> @variables x[1:3]
1-element Vector{Symbolics.Arr{Num, 1}}:
x[1:3]
julia> @variables y[1:3, 1:6] # support for tensors
1-element Vector{Symbolics.Arr{Num, 2}}:
y[1:3,1:6]
julia> @variables t z(t)[1:3] # also works for dependent variables
2-element Vector{Any}:
t
(z(t))[1:3]
```
A symbol or expression that represents an array can be turned into an array of
symbols or expressions using the `scalarize` function.
```julia
julia> Symbolics.scalarize(z)
3-element Vector{Num}:
(z(t))[1]
(z(t))[2]
(z(t))[3]
```
Note that `@variables` returns a vector of all the defined variables.
`@variables` can also take runtime symbol values by the `\$` interpolation
operator, and in this case, `@variables` doesn't automatically assign the value,
instead, it only returns a vector of symbolic variables. All the rest of the
syntax also applies here.
```julia
julia> a, b, c = :runtime_symbol_value, :value_b, :value_c
(:runtime_symbol_value, :value_b, :value_c)
julia> vars = @variables t \$a \$b(t) \$c(t)[1:3]
4-element Vector{Any}:
t
runtime_symbol_value
value_b(t)
(value_c(t))[1:3]
julia> (t, a, b, c)
(t, :runtime_symbol_value, :value_b, :value_c)
```
"""
macro variables(xs...)
esc(_parse_vars(:variables, Real, xs))
end
TreeViews.hastreeview(x::Symbolic) = issym(x)
function TreeViews.treelabel(io::IO,x::Symbolic,
mime::MIME"text/plain" = MIME"text/plain"())
show(io,mime,Text(getname(x)))
end
const _fail = Dict()
_getname(x, _) = nameof(x)
_getname(x::Symbol, _) = x
function _getname(x::Symbolic, val)
issym(x) && return nameof(x)
if istree(x) && issym(operation(x))
return nameof(operation(x))
end
if !hasmetadata(x, Symbolics.GetindexParent) && istree(x) && operation(x) == getindex
return _getname(arguments(x)[1], val)
end
ss = getsource(x, nothing)
if ss === nothing
ss = getsource(getparent(x), val)
end
ss === _fail && throw(ArgumentError("Variable $x doesn't have a source defined."))
ss[2]
end
getsource(x, val=_fail) = getmetadata(unwrap(x), VariableSource, val)
getname(x, val=_fail) = _getname(unwrap(x), val)
function getparent(x, val=_fail)
maybe_parent = getmetadata(x, Symbolics.GetindexParent, nothing)
if maybe_parent !== nothing
return maybe_parent
else
if istree(x) && operation(x) === getindex
return arguments(x)[1]
end
end
val === _fail && throw(ArgumentError("Cannot find the parent of $x."))
return val
end
function getdefaultval(x, val=_fail)
x = unwrap(x)
val = getmetadata(x, VariableDefaultValue, val)
if val !== _fail
return val
else
error("$x has no default value")
end
end
"""
variables(name::Symbol, indices...)
Create a multi-dimensional array of individual variables named with subscript
notation. Use `@variables` instead to create symbolic array variables (as
opposed to array of variables). See `variable` to create one variable with
subscripts.
```julia-repl
julia> Symbolics.variables(:x, 1:3, 3:6)
3×4 Matrix{Num}:
x₁ˏ₃ x₁ˏ₄ x₁ˏ₅ x₁ˏ₆
x₂ˏ₃ x₂ˏ₄ x₂ˏ₅ x₂ˏ₆
x₃ˏ₃ x₃ˏ₄ x₃ˏ₅ x₃ˏ₆
```
"""
function variables(name, indices...; T=Real)
[variable(name, ij...; T=T) for ij in Iterators.product(indices...)]
end
"""
variable(name::Symbol, idx::Integer...; T=Real)
Create a variable with the given name along with subscripted indices with the
`symtype=T`. When `T=FnType`, it creates a symbolic function.
```julia-repl
julia> Symbolics.variable(:x, 4, 2, 0)
x₄ˏ₂ˏ₀
julia> Symbolics.variable(:x, 4, 2, 0, T=Symbolics.FnType)
x₄ˏ₂ˏ₀⋆
```
Also see `variables`.
"""
function variable(name, idx...; T=Real)
name_ij = Symbol(name, join(map_subscripts.(idx), "ˏ"))
if T <: FnType
first(@variables $name_ij(..))
else
first(@variables $name_ij::T)
end
end
##### Renaming #####
# getname
# rename
# getindex parent
# calls
# symbolic function x[1:3](..)
#
# x_t
# sys.x
function rename_getindex_source(x, parent=x)
getindex_posthook(x) do r,x,i...
hasmetadata(r, GetindexParent) ? setmetadata(r, GetindexParent, parent) : r
end
end
function rename_metadata(from, to, name)
if hasmetadata(from, VariableSource)
s = getmetadata(from, VariableSource)
to = setmetadata(to, VariableSource, (s[1], name))
end
if hasmetadata(from, GetindexParent)
s = getmetadata(from, GetindexParent)
to = setmetadata(to, GetindexParent, rename(s, name))
end
return to
end
rename(x::Union{Num, Arr}, name) = wrap(rename(unwrap(x), name))
function rename(x::ArrayOp, name)
t = x.term
args = arguments(t)
# Hack:
@assert operation(t) === (map) && (args[1] isa CallWith || args[1] == CallWithMetadata)
rn = rename(args[2], name)
xx = metadata(operation(t)(args[1], rn), metadata(x))
rename_getindex_source(rename_metadata(x, xx, name))
end
function rename(x::CallWithMetadata, name)
rename_metadata(x, CallWithMetadata(rename(x.f, name), x.metadata), name)
end
function rename(x::Symbolic, name)
if issym(x)
xx = @set! x.name = name
xx = rename_metadata(x, xx, name)
symtype(xx) <: AbstractArray ? rename_getindex_source(xx) : xx
elseif istree(x) && operation(x) === getindex
rename(arguments(x)[1], name)[arguments(x)[2:end]...]
elseif istree(x) && symtype(operation(x)) <: FnType || operation(x) isa CallWithMetadata
xx = @set x.f = rename(operation(x), name)
@set! xx.hash = Ref{UInt}(0)
return rename_metadata(x, xx, name)
else
error("can't rename $x to $name")
end
end
# Deprecation below
struct Variable{T} end
function (::Type{Variable{T}})(s, i...) where {T}
Base.depwarn("Variable{T}(name, idx...) is deprecated, use variable(name, idx...; T=T)", :Variable, force=true)
variable(s, i...; T=T)
end
(::Type{Variable})(s, i...) = Variable{Real}(s, i...)
function (::Type{Sym{T}})(s, x, i...) where {T}
Base.depwarn("Sym{T}(name, x, idx...) is deprecated, use variable(name, x, idx...; T=T)", :Variable, force=true)
variable(s, x, i...; T=T)
end
(::Type{Sym})(s, x, i...) = Sym{Real}(s, x, i...)