-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathSymbolicAD.jl
More file actions
1706 lines (1524 loc) · 50.3 KB
/
SymbolicAD.jl
File metadata and controls
1706 lines (1524 loc) · 50.3 KB
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2017: Miles Lubin and contributors
#
# Use of this source code is governed by an MIT-style license that can be found
# in the LICENSE.md file or at https://opensource.org/licenses/MIT.
module SymbolicAD
import MathOptInterface as MOI
###
### simplify
###
"""
simplify(f)
Return a simplified copy of the function `f`.
!!! warning
This function is not type stable by design.
## Example
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> f = MOI.ScalarNonlinearFunction(:^, Any[x, 1])
^(MOI.VariableIndex(1), (1))
julia> MOI.Nonlinear.SymbolicAD.simplify(f)
MOI.VariableIndex(1)
```
"""
simplify(f) = simplify!(copy(f))
###
### `simplify!`
###
"""
simplify!(f)
Simplify the function `f` in-place and return either the function `f` or a
new object if `f` can be represented in a simpler type.
!!! warning
This function is not type stable by design.
## Example
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> f = MOI.ScalarNonlinearFunction(
:+,
Any[MOI.ScalarNonlinearFunction(:+, Any[1.0, x]), 2.0 * x + 3.0],
)
+(+(1.0, MOI.VariableIndex(1)), 3.0 + 2.0 MOI.VariableIndex(1))
julia> MOI.Nonlinear.SymbolicAD.simplify!(f)
4.0 + 3.0 MOI.VariableIndex(1)
julia> f
+(1.0, MOI.VariableIndex(1), 3.0 + 2.0 MOI.VariableIndex(1))
```
"""
simplify!(f) = f
function simplify!(f::MOI.ScalarAffineFunction{T}) where {T}
f = MOI.Utilities.canonicalize!(f)
if isempty(f.terms)
return f.constant
end
if iszero(f.constant) && length(f.terms) == 1
term = only(f.terms)
if isone(term.coefficient)
return term.variable
end
end
return f
end
function simplify!(f::MOI.ScalarQuadraticFunction{T}) where {T}
f = MOI.Utilities.canonicalize!(f)
if isempty(f.quadratic_terms)
return simplify!(MOI.ScalarAffineFunction(f.affine_terms, f.constant))
end
return f
end
function simplify!(f::MOI.ScalarNonlinearFunction)
stack, result_stack = Any[f], Any[]
while !isempty(stack)
arg = pop!(stack)
if arg isa MOI.ScalarNonlinearFunction
# We need some sort of hint so that the next time we see this on the
# stack we evaluate it using the args in `result_stack`. One option
# would be a custom type. Or we can just wrap in (,) and then check
# for a Tuple, which isn't (curretly) a valid argument.
push!(stack, (arg,))
for child in arg.args
push!(stack, child)
end
elseif arg isa Tuple{<:MOI.ScalarNonlinearFunction}
result = only(arg)
for i in eachindex(result.args)
result.args[i] = pop!(result_stack)
end
# simplify!(::Val, ::Any) does not use recursion so this is safe.
result = simplify!(Val(result.head), result)
result = _eval_if_constant(result)
push!(result_stack, result)
else
push!(result_stack, arg)
end
end
return _simplify_if_quadratic!(only(result_stack))
end
function simplify!(f::MOI.VectorAffineFunction{T}) where {T}
f = MOI.Utilities.canonicalize!(f)
if isempty(f.terms)
return f.constants
end
return f
end
function simplify!(f::MOI.VectorQuadraticFunction{T}) where {T}
f = MOI.Utilities.canonicalize!(f)
if isempty(f.quadratic_terms)
if isempty(f.affine_terms)
return f.constants
end
return MOI.VectorAffineFunction(f.affine_terms, f.constants)
end
return f
end
function simplify!(f::MOI.VectorNonlinearFunction)
rows = simplify!.(f.rows)
Y = reduce(promote_type, typeof.(rows))
if isconcretetype(Y)
return MOI.Utilities.vectorize(convert(Vector{Y}, rows))
end
return MOI.VectorNonlinearFunction(rows)
end
# If a ScalarNonlinearFunction has only constant arguments, we should return
# the value.
_isnum(::Any) = false
_isnum(::Union{Bool,Integer,Float64}) = true
function _eval_if_constant(f::MOI.ScalarNonlinearFunction)
if all(_isnum, f.args) && hasproperty(Base, f.head)
return getproperty(Base, f.head)(f.args...)
end
return f
end
_eval_if_constant(f) = f
_iszero(x::Any)::Bool = _isnum(x) && iszero(x)
_isone(x::Any)::Bool = _isnum(x) && isone(x)
"""
_isexpr(f::Any, head::Symbol[, n::Int])
Return `true` if `f` is a `ScalarNonlinearFunction` with head `head` and, if
specified, `n` arguments.
"""
_isexpr(::Any, ::Symbol, n::Int = 0) = false
_isexpr(f::MOI.ScalarNonlinearFunction, head::Symbol) = f.head == head
function _isexpr(f::MOI.ScalarNonlinearFunction, head::Symbol, n::Int)
return _isexpr(f, head) && length(f.args) == n
end
"""
simplify!(::Val{head}, f::MOI.ScalarNonlinearFunction)
Simplify the function `f` in-place and return either the function `f` or a
new object if `f` can be represented in a simpler type.
## Val
The `head` in `Val{head}` is taken from `f.head`. This function should be called
as:
```julia
f = simplify!(Val(f.head), f)
```
Implementing a method that dispatches on `head` enables custom simplification
rules for different operators without needing a giant switch statement.
## Note
It is important that this function does not recursively call `simplify!`. Deal
only with the immediate operator. The children arguments will already be
simplified.
"""
simplify!(::Val, f::MOI.ScalarNonlinearFunction) = f
function simplify!(::Val{:*}, f::MOI.ScalarNonlinearFunction)
new_args = Any[]
first_constant = 0
for arg in f.args
if _isexpr(arg, :*)
# If the child is a :*, lift its arguments to the parent
append!(new_args, arg.args)
elseif _iszero(arg)
# If any argument is zero, the entire expression must be false
return false
elseif _isone(arg)
# Skip any arguments that are one
elseif arg isa Real
# Collect all constant arguments into a single value
if first_constant == 0
push!(new_args, arg)
first_constant = length(new_args)
else
new_args[first_constant] *= arg
end
else
push!(new_args, arg)
end
end
if length(new_args) == 0
# *() -> true
return true
elseif length(new_args) == 1
# *(x) -> x
return only(new_args)
end
resize!(f.args, length(new_args))
copyto!(f.args, new_args)
return f
end
function simplify!(::Val{:+}, f::MOI.ScalarNonlinearFunction)
new_args = Any[]
first_affine_term = 0
for arg in f.args
if _isexpr(arg, :+)
# If a child is a :+, lift its arguments to the parent
append!(new_args, arg.args)
elseif _iszero(arg)
# Skip any zero arguments
elseif arg isa Real
# Collect all affine arguments into a single value
if first_affine_term == 0
push!(new_args, arg)
first_affine_term = length(new_args)
else
new_args[first_affine_term] += arg
end
else
push!(new_args, arg)
end
end
if length(new_args) == 0
# +() -> false
return false
elseif length(new_args) == 1
# +(x) -> x
return only(new_args)
elseif length(f.args) == 2 && _isexpr(f.args[2], :-, 1)
# +(x, -y) -> -(x, y)
return MOI.ScalarNonlinearFunction(
:-,
Any[f.args[1], f.args[2].args[1]],
)
end
resize!(f.args, length(new_args))
copyto!(f.args, new_args)
return f
end
function simplify!(::Val{:-}, f::MOI.ScalarNonlinearFunction)
if length(f.args) == 1
if _isexpr(f.args[1], :-, 1)
# -(-(x)) => x
return f.args[1].args[1]
end
elseif length(f.args) == 2
if f.args[1] == f.args[2]
# x - x => 0
return false
elseif _iszero(f.args[1])
# 0 - x => -x
popfirst!(f.args)
return f
elseif _iszero(f.args[2])
# x - 0 => x
return f.args[1]
elseif _isexpr(f.args[2], :-, 1)
# x - -(y) => x + y
return MOI.ScalarNonlinearFunction(
:+,
Any[f.args[1], f.args[2].args[1]],
)
end
end
return f
end
function simplify!(::Val{:^}, f::MOI.ScalarNonlinearFunction)
if _iszero(f.args[2])
# x^0 => 1
return true
elseif _isone(f.args[2])
# x^1 => x
return f.args[1]
elseif _iszero(f.args[1])
# 0^x => 0
return false
elseif _isone(f.args[1])
# 1^x => 1
return true
end
return f
end
function simplify!(::Val{:ifelse}, f::MOI.ScalarNonlinearFunction)
if f.args[1] == true
# ifelse(true, x, y) => x
return f.args[2]
elseif f.args[1] == false
# ifelse(false, x, y) => y
return f.args[3]
elseif f.args[2] == f.args[3]
# ifelse(y, x, x) => x
return f.args[2]
end
return f
end
###
### variables
###
"""
variables(f::Union{Real,MOI.AbstractScalarFunction})
Return a sorted list of the `MOI.VariableIndex` present in the function `f`.
## Example
```jldoctest
julia> x = MOI.VariableIndex.(1:3)
3-element Vector{MathOptInterface.VariableIndex}:
MOI.VariableIndex(1)
MOI.VariableIndex(2)
MOI.VariableIndex(3)
julia> f = MOI.ScalarNonlinearFunction(:atan, Any[x[3], 2.0 * x[1]])
atan(MOI.VariableIndex(3), 0.0 + 2.0 MOI.VariableIndex(1))
julia> MOI.Nonlinear.SymbolicAD.variables(f)
2-element Vector{MathOptInterface.VariableIndex}:
MOI.VariableIndex(1)
MOI.VariableIndex(3)
```
"""
function variables(f::MOI.AbstractScalarFunction)
ret = MOI.VariableIndex[]
_variables(ret, f)
return sort!(ret; by = x -> x.value)
end
variables(::Real) = MOI.VariableIndex[]
_variables(::Vector{MOI.VariableIndex}, ::Real) = nothing
function _variables(ret::Vector{MOI.VariableIndex}, f::MOI.VariableIndex)
if !(f in ret)
push!(ret, f)
end
return
end
function _variables(ret::Vector{MOI.VariableIndex}, f::MOI.ScalarAffineTerm)
_variables(ret, f.variable)
return
end
function _variables(ret::Vector{MOI.VariableIndex}, f::MOI.ScalarAffineFunction)
for term in f.terms
_variables(ret, term)
end
return
end
function _variables(ret::Vector{MOI.VariableIndex}, f::MOI.ScalarQuadraticTerm)
_variables(ret, f.variable_1)
_variables(ret, f.variable_2)
return
end
function _variables(
ret::Vector{MOI.VariableIndex},
f::MOI.ScalarQuadraticFunction,
)
for term in f.affine_terms
_variables(ret, term)
end
for q_term in f.quadratic_terms
_variables(ret, q_term)
end
return
end
function _variables(
ret::Vector{MOI.VariableIndex},
f::MOI.ScalarNonlinearFunction,
)
stack = Any[f]
while !isempty(stack)
arg = pop!(stack)
if arg isa MOI.ScalarNonlinearFunction
# We need to push the args on in reverse order so that we iterate
# across the tree from left to right.
for i in reverse(1:length(arg.args))
push!(stack, arg.args[i])
end
else
_variables(ret, arg)
end
end
return
end
###
### derivative
###
"""
derivative(f::Union{Real,MOI.AbstractScalarFunction}, x::MOI.VariableIndex)
Return an expression representing the partial derivative of `f` with respect to
`x`.
## Expression swelling
With few exceptions, the algorithm used to compute the derivative does not
perform simplications. As a result, the returned expression may contain terms
like `*(false, g)` that can be trivially simplified to `false`.
In most cases, you should call `simplify!(derivative(f, x))` to return a
simplified expression of the derivative.
## Example
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> f = MOI.ScalarNonlinearFunction(:sin, Any[x])
sin(MOI.VariableIndex(1))
julia> df_dx = MOI.Nonlinear.SymbolicAD.derivative(f, x)
cos(MOI.VariableIndex(1))
```
"""
derivative(::Real, ::MOI.VariableIndex) = false
function derivative(f::MOI.VariableIndex, x::MOI.VariableIndex)
return ifelse(f == x, true, false)
end
function derivative(
f::MOI.ScalarAffineFunction{T},
x::MOI.VariableIndex,
) where {T}
ret = zero(T)
for term in f.terms
if term.variable == x
ret += term.coefficient
end
end
return ret
end
function derivative(
f::MOI.ScalarQuadraticFunction{T},
x::MOI.VariableIndex,
) where {T}
constant = zero(T)
for term in f.affine_terms
if term.variable == x
constant += term.coefficient
end
end
aff_terms = MOI.ScalarAffineTerm{T}[]
for q_term in f.quadratic_terms
if q_term.variable_1 == q_term.variable_2 == x
push!(aff_terms, MOI.ScalarAffineTerm(q_term.coefficient, x))
elseif q_term.variable_1 == x
push!(
aff_terms,
MOI.ScalarAffineTerm(q_term.coefficient, q_term.variable_2),
)
elseif q_term.variable_2 == x
push!(
aff_terms,
MOI.ScalarAffineTerm(q_term.coefficient, q_term.variable_1),
)
end
end
return MOI.ScalarAffineFunction(aff_terms, constant)
end
function _replace_expression(node::Expr, u)
for (i, arg) in enumerate(node.args)
node.args[i] = _replace_expression(arg, u)
end
@assert Meta.isexpr(node, :call)
op, args = node.args[1], node.args[2:end]
return MOI.ScalarNonlinearFunction(op, args)
end
_replace_expression(node::Any, u) = node
function _replace_expression(node::Symbol, u)
if node == :x
return u
end
return node
end
"""
__DERIVATIVE__ = "__DERIVATIVE__"
This constant is prefixed to the name of univariate operators to indicate
that we should compute their derivative.
If `f.head` is itself a __DERIVATIVE__, then this will create a second
derivative like `__DERIVATIVE____DERIVATIVE__\$(f.head)`.
Munging the `.head` field like this seems a bit hacky, but it is simpler than
the alternatives like `SNF(:derivative, Any[SNF(:f, Any[x]])])`, because this
would require changes to the already complicated expression walker for
evaluating the expression.
The String value of this constant is arbitrary. It just needs to be something
that the user would never write themselves.
"""
const __DERIVATIVE__ = "__DERIVATIVE__"
# This function helps simplify df_du * du_dx in the commonn case that `du_dx`
# is `true` (when u = x), or `false` (when x ∉ u).
function _univariate_chain_rule(df_du, du_dx)
return MOI.ScalarNonlinearFunction(:*, Any[df_du, du_dx])
end
_univariate_chain_rule(df_du, du_dx::Bool) = ifelse(du_dx, df_du, du_dx)
function derivative(f::MOI.ScalarNonlinearFunction, x::MOI.VariableIndex)
if length(f.args) == 1
u = only(f.args)
du_dx = derivative(u, x)
if f.head == :+
return du_dx
elseif f.head == :-
return MOI.ScalarNonlinearFunction(:-, Any[du_dx])
elseif f.head == :abs
df_du = MOI.ScalarNonlinearFunction(
:ifelse,
Any[MOI.ScalarNonlinearFunction(:>=, Any[u, 0]), 1, -1],
)
return _univariate_chain_rule(df_du, du_dx)
elseif f.head == :sign
return false
elseif f.head == :deg2rad
df_du = deg2rad(1)
return _univariate_chain_rule(df_du, du_dx)
elseif f.head == :rad2deg
df_du = rad2deg(1)
return _univariate_chain_rule(df_du, du_dx)
end
for (key, df, _) in MOI.Nonlinear.SYMBOLIC_UNIVARIATE_EXPRESSIONS
if key == f.head
# The chain rule: d(f(g(x))) / dx = f'(g(x)) * g'(x)
df_du = _replace_expression(copy(df), u)
return _univariate_chain_rule(df_du, du_dx)
end
end
# Delay derivative until evaluation. This may result in a later
# UnsupportedNonlinearOperator error, but we can't tell just yet.
d_op = Symbol(__DERIVATIVE__ * "$(f.head)")
df_du = MOI.ScalarNonlinearFunction(d_op, Any[u])
return _univariate_chain_rule(df_du, du_dx)
end
if f.head == :+
# d/dx(+(args...)) = +(d/dx args)
args = Any[]
for arg in f.args
d_arg_dx = derivative(arg, x)
if _iszero(d_arg_dx)
# Special case: common situation where the arugment doesn't
# depend on x
continue
end
push!(args, d_arg_dx)
end
# A few special case handlers. We don't call the full `simplify!`
# because that will allocate more, and we don't really care about
# disaggregated constants.
if isempty(args)
return false
elseif length(args) == 1
return only(args)
end
return MOI.ScalarNonlinearFunction(:+, args)
elseif f.head == :-
# d/dx(-(args...)) = -(d/dx args)
# Note that - is not unary here because that wouuld be caught above.
args = Any[derivative(arg, x) for arg in f.args]
return MOI.ScalarNonlinearFunction(:-, args)
elseif f.head == :*
# Product rule: d/dx(*(args...)) = sum(d{i}/dx * args\{i})
sum_terms = Any[]
for i in eachindex(f.args)
g = MOI.ScalarNonlinearFunction(:*, copy(f.args))
g.args[i] = derivative(f.args[i], x)
if any(_iszero, g.args)
# Special case: common situation where an argument doesn't
# depend on x
continue
end
# We call `simplify!` here to clean up any issues like *(y, true)
# or *(y).
push!(sum_terms, simplify!(Val(:*), g))
end
return simplify!(Val(:+), MOI.ScalarNonlinearFunction(:+, sum_terms))
elseif f.head == :^
# d/dx(u^p) = p*u^(p-1)*(du/dx) + u^p*log(u)*(dp/dx))
@assert length(f.args) == 2
u, p = f.args
du_dx = derivative(u, x)
dp_dx = derivative(p, x)
term_1 = MOI.ScalarNonlinearFunction(
:*,
Any[p, MOI.ScalarNonlinearFunction(:^, Any[u, p-1]), du_dx],
)
if _iszero(dp_dx) # p is constant and does not depend on x
return term_1
end
term_2 = MOI.ScalarNonlinearFunction(
:*,
Any[
MOI.ScalarNonlinearFunction(:^, Any[u, p]),
MOI.ScalarNonlinearFunction(:log, Any[u]),
dp_dx,
],
)
return MOI.ScalarNonlinearFunction(:+, Any[term_1, term_2])
elseif f.head == :/
# Quotient rule: d/dx(u / v) = (du/dx)*v - u*(dv/dx)) / v^2
@assert length(f.args) == 2
u, v = f.args
du_dx, dv_dx = derivative(u, x), derivative(v, x)
return MOI.ScalarNonlinearFunction(
:/,
Any[
MOI.ScalarNonlinearFunction(
:-,
Any[
MOI.ScalarNonlinearFunction(:*, Any[du_dx, v]),
MOI.ScalarNonlinearFunction(:*, Any[u, dv_dx]),
],
),
MOI.ScalarNonlinearFunction(:^, Any[v, 2]),
],
)
elseif f.head == :ifelse
@assert length(f.args) == 3
# Pick the derivative of the active branch
return MOI.ScalarNonlinearFunction(
:ifelse,
Any[f.args[1], derivative(f.args[2], x), derivative(f.args[3], x)],
)
elseif f.head == :atan
@assert length(f.args) == 2
u, v = f.args
du_dx, dv_dx = derivative(u, x), derivative(v, x)
u_2 = MOI.ScalarNonlinearFunction(:^, Any[u, 2])
v_2 = MOI.ScalarNonlinearFunction(:^, Any[v, 2])
u_dv_dx = MOI.ScalarNonlinearFunction(:*, Any[u, dv_dx])
v_du_dx = MOI.ScalarNonlinearFunction(:*, Any[v, du_dx])
return MOI.ScalarNonlinearFunction(
:/,
Any[
MOI.ScalarNonlinearFunction(:+, Any[u_dv_dx, v_du_dx]),
MOI.ScalarNonlinearFunction(:+, Any[u_2, v_2]),
],
)
elseif f.head == :min
g = derivative(f.args[end], x)
for i in (length(f.args)-1):-1:1
g = MOI.ScalarNonlinearFunction(
:ifelse,
Any[
MOI.ScalarNonlinearFunction(:(<=), Any[f.args[i], f]),
derivative(f.args[i], x),
g,
],
)
end
return g
elseif f.head == :max
g = derivative(f.args[end], x)
for i in (length(f.args)-1):-1:1
g = MOI.ScalarNonlinearFunction(
:ifelse,
Any[
MOI.ScalarNonlinearFunction(:(>=), Any[f.args[i], f]),
derivative(f.args[i], x),
g,
],
)
end
return g
elseif f.head in (:(>=), :(<=), :(<), :(>), :(==))
return false
end
err = MOI.UnsupportedNonlinearOperator(
f.head,
"the operator does not support symbolic differentiation",
)
return throw(err)
end
###
### gradient_and_hessian
###
"""
gradient_and_hessian(
[filter_fn::Function = x -> true,]
f::MOI.AbstractScalarFunction,
)
Compute the symbolic gradient and Hessian of `f`, and return the result as a
tuple of four elements:
1. `x::Vector{MOI.VariableIndex}`: the list of variables that appear in `f`
2. `∇f::Vector{Any}`: a vector for the first partial derivative of `f` with
respect to each element in `x`
3. `H::Vector{Tuple{Int,Int}}`: a vector of `(row, column)` tuples that list
the non-zero entries in the Hessian of `f`
4. `∇²f::Vector{Any}`: a vector of expressions, in the same order as `H`, for
the non-zero entries in the Hessian of `f`
## `filter_fn`
This argument is a function, `filter_fn(::MOI.VariableIndex)::Bool` that returns
`true` if the gradient and Hessian of `f` should be computed with respect to it.
Use this argument to filter out constant parameters from decision variables.
"""
function gradient_and_hessian(
filter_fn::F,
f::MOI.AbstractScalarFunction,
) where {F<:Function}
x = filter!(filter_fn, variables(f))
n = length(x)
∇f = Vector{Any}(undef, n)
H_by_x, ∇²f_by_x = [Tuple{Int,Int}[] for _ in 1:n], [Any[] for _ in 1:n]
for i in eachindex(x)
xi = x[i]
∇fi = simplify!(derivative(f, xi))
∇f[i] = ∇fi
for xj in filter!(filter_fn, variables(∇fi))
j = findfirst(==(xj), x)
if i > j
continue # Don't need lower triangle
end
dfij = simplify!(derivative(∇fi, xj))
if dfij != false
push!(∇²f_by_x[i], dfij)
push!(H_by_x[i], (i, j))
end
end
end
return x, ∇f, reduce(vcat, H_by_x), reduce(vcat, ∇²f_by_x)
end
function gradient_and_hessian(f::MOI.AbstractScalarFunction)
return gradient_and_hessian(x -> true, f)
end
###
### DAG
###
# operator is a (mask ⊻ id, nargs)::Tuple{Int32,Int32}, packed into an Int64
# This is based on the assumptions that:
# 1. we don't have more than typemax(Int32) >> 4 operators
# 2. we don't have more than typemax(Int32) input arguments
# both of these seem quite sensible.
function _mask_id_nargs_to_operator(mask::UInt32, id::Int, nargs::Int)
@assert nargs <= typemax(Int32)
@assert id <= (typemax(Int32) >> 4)
return xor(Int64(mask ⊻ Int32(id)) << 32, Int64(nargs))
end
function _op_nargs_to_operator(
reg::MOI.Nonlinear.OperatorRegistry,
op::Symbol,
nargs::Int,
)
if nargs == 1
op_to_id = reg.univariate_operator_to_id
if (ret = get(op_to_id, op, nothing)) !== nothing
return _mask_id_nargs_to_operator(:0x00000000, ret, nargs)
end
str_op = string(op)
prefix_hessian = __DERIVATIVE__ * __DERIVATIVE__
if startswith(str_op, prefix_hessian)
f_op = Symbol(replace(str_op, prefix_hessian => ""))
if (ret = get(op_to_id, f_op, nothing)) !== nothing
return _mask_id_nargs_to_operator(:0x20000000, ret, nargs)
end
elseif startswith(str_op, __DERIVATIVE__)
f_op = Symbol(replace(str_op, __DERIVATIVE__ => ""))
if (ret = get(op_to_id, f_op, nothing)) !== nothing
return _mask_id_nargs_to_operator(:0x10000000, ret, nargs)
end
end
end
if (ret = get(reg.multivariate_operator_to_id, op, nothing)) !== nothing
return _mask_id_nargs_to_operator(:0x30000000, ret, nargs)
end
if (ret = get(reg.logic_operator_to_id, op, nothing)) !== nothing
return _mask_id_nargs_to_operator(0x40000000, ret, nargs)
end
ret = reg.comparison_operator_to_id[op]
return _mask_id_nargs_to_operator(0x50000000, ret, nargs)
end
function _operator_to_type_id_nargs(operator::Int64)::Tuple{Symbol,UInt32,Int64}
@assert operator > 0
type_id = Int32(operator >> 32)
type = type_id & 0x70000000
id = type_id - type
nargs = operator - (Int64(type_id) << 32)
if type == 0x00000000
return :univariate, id, nargs
elseif type == 0x10000000
return :univariate_derivative, id, nargs
elseif type == 0x20000000
return :univariate_second_derivative, id, nargs
elseif type == 0x30000000
return :multivariate, id, nargs
elseif type == 0x40000000
return :logic, id, nargs
else
@assert type == 0x50000000
return :comparison, id, nargs
end
end
const _kNODE_PARAMETER = -1
const _kNODE_VARIABLE = -2
const _kNODE_VALUE = -3
"""
See the docstring of [`_DAG`](@ref).
"""
struct _Node
operator::Int64
data::Int64
end
function Base.show(io::IO, n::_Node)
print(io, "_Node(", n.operator, ", ", n.data, ")\t")
if n.operator == _kNODE_PARAMETER
print(io, "\t\t# p[", n.data, "]")
elseif n.operator == _kNODE_VARIABLE
print(io, "\t\t# x[", n.data, "]")
elseif n.operator == _kNODE_VALUE
print(io, "# ", reinterpret(Float64, n.data))
else
type, op, nargs = _operator_to_type_id_nargs(n.operator)
children = n.data .+ (0:(nargs-1))
print(io, "# $type(op = $op, children = $children)")
end
end
"""
_DAG(registry::MOI.Nonlinear.OperatorRegistry)
The [`_DAG`](@ref) represents a vector-valued function `f(x, p)`.
## Fields
### `tape::Vector{_Node}`
The list of nodes in the DAG. A `_Node` is the struct:
```julia
struct _Node
operator::Int64
data::Int64
end
```
with the following interpretation:
* If `operator == _kNODE_PARAMETER == -1`, then the `data` is the index in the
input `p` vector
* If `operator == _kNODE_VARIABLE == -2`, then the `data` is the index in the
input `x` vector`
* If `operator == _kNODE_VALUE == -3`, then the `data` is a `Float64`, encoded
as an `Int64`. Access it with `reinterpret(Float64, node.data)`.
* If `operator > 0`, then the operator is an operator from the
`MOI.Nonlinear.OperatorRegistry` in the DAG. Use
```julia
type, op, nargs = _operator_to_type_id_nargs(node.operator)
```
to retrieve the type, op-code, and the number of arguments. The `data`
field is the index of the first child in the `.children` array of the DAG.
### `nodes::Dict{UInt64,Int}`
A mapping of hash values to the index in `.tape`. This data structure is used to
de-duplicate nodes as the DAG is being built.
### `children::Vector{Int}`
An ordered list of the children for operator nodes in `tape`.
We could have stored these as a separate vector of children for each node in the
tape, where each element in the children vector is the index of the child in
`tape`. To minimize the number of unique vectors, we instead store here the
concatenation of all children vectors. The `node.data` value of an operator node
is the index in `.children` of the first child. More concretely, given an
operator node, the child nodes can be computed as:
```julia
type, op, nargs = _operator_to_type_id_nargs(node.operator)
children_indices = dag.children[node.data:node.data+nargs-1]
children_nodes = dag.tape[children_indices]
```
### `registry::MOI.Nonlinear.OperatorRegistry`
The registry containing operator information. The registry is used to evaluate
each operator via the corresponding methods in `MOI.Nonlinear`.
### `indices::Vector{Int}`
The indices of `.tape` that represent the output of the function `f(x, p)`.
These indices are mostly used when querying the result of an evaluated DAG via
`dag.result[dag.indices]`.
### `input::Vector{Float64}`
A cache for storing the input x when evaluating the DAG. This cache is useful
because the DAG's input variables are typically a subset of the full decision
vector. We could use a `view`, but instead we use this cache. The main reason is
to keep the input types as simple as possible (`Vector{Float64}` where
possible). At the cost of copying the values, we also avoid a set of
double-lookups when indexing into the full `x` via a `view`.
### `result::Vector{Float64}`
A cache for storing the result of evaluating the DAG. There is one element for
each element in `.tape`.
See also the `indices` field.
### `cache::Vector{Float64}`
A cache for evaluating multivariate operators. This will be sized such that its
length is the largest multivariate operator that may be called. Other operators
take views of the first nargs elements.
The main reason for this vector is to avoid a complicated `view` into the
`result` vector when evaluating multivariate operators.
"""
struct _DAG
tape::Vector{_Node}
nodes::Dict{UInt64,Int}
children::Vector{Int}
registry::MOI.Nonlinear.OperatorRegistry
indices::Vector{Int}
input::Vector{Float64}
result::Vector{Float64}
cache::Vector{Float64}
function _DAG(registry)
return new(
_Node[],
Dict{UInt64,Int}(),
Int[],
registry,