-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathoperators.jl
More file actions
1136 lines (1018 loc) · 30.3 KB
/
operators.jl
File metadata and controls
1136 lines (1018 loc) · 30.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
# Copyright (c) 2017: Google Inc.
#
# 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.
function _create_binary_switch(ids, exprs)
if length(exprs) <= 3
out = Expr(:if, Expr(:call, :(==), :id, ids[1]), exprs[1])
if length(exprs) > 1
push!(out.args, _create_binary_switch(ids[2:end], exprs[2:end]))
end
return out
end
mid = length(exprs) >>> 1
return Expr(
:if,
Expr(:call, :(<=), :id, ids[mid]),
_create_binary_switch(ids[1:mid], exprs[1:mid]),
_create_binary_switch(ids[(mid+1):end], exprs[(mid+1):end]),
)
end
function _generate_eval_univariate()
exprs = map(SYMBOLIC_UNIVARIATE_EXPRESSIONS) do arg
return :(return $(arg[1])(x), $(arg[2]))
end
return _create_binary_switch(1:length(exprs), exprs)
end
@eval @inline function _eval_univariate(id, x::T) where {T}
$(_generate_eval_univariate())
return error("Invalid id for univariate operator: $id")
end
function _generate_eval_univariate_2nd_deriv()
exprs = map(arg -> :(return $(arg[3])), SYMBOLIC_UNIVARIATE_EXPRESSIONS)
return _create_binary_switch(1:length(exprs), exprs)
end
@eval @inline function _eval_univariate_2nd_deriv(id, x::T) where {T}
$(_generate_eval_univariate_2nd_deriv())
return error("Invalid id for univariate operator: $id")
end
struct _UnivariateOperator{F,F′,F′′}
f::F
f′::F′
f′′::F′′
function _UnivariateOperator(
f::Function,
f′::Function,
f′′::Union{Nothing,Function} = nothing,
)
return new{typeof(f),typeof(f′),typeof(f′′)}(f, f′, f′′)
end
end
function eval_univariate_function(operator::_UnivariateOperator, x::T) where {T}
ret = operator.f(x)
check_return_type(T, ret)
return ret::T
end
function eval_univariate_gradient(operator::_UnivariateOperator, x::T) where {T}
ret = operator.f′(x)
check_return_type(T, ret)
return ret::T
end
function eval_univariate_hessian(operator::_UnivariateOperator, x::T) where {T}
ret = operator.f′′(x)
check_return_type(T, ret)
return ret::T
end
function eval_univariate_function_and_gradient(
operator::_UnivariateOperator,
x::T,
) where {T}
ret_f = eval_univariate_function(operator, x)
ret_f′ = eval_univariate_gradient(operator, x)
return ret_f, ret_f′
end
struct _MultivariateOperator{F,F′,F′′}
N::Int
f::F
∇f::F′
∇²f::F′′
function _MultivariateOperator{N}(
f::Function,
∇f::Function,
∇²f::Union{Nothing,Function} = nothing,
) where {N}
return new{typeof(f),typeof(∇f),typeof(∇²f)}(N, f, ∇f, ∇²f)
end
end
"""
DEFAULT_UNIVARIATE_OPERATORS
The list of univariate operators that are supported by default.
## Example
```jldoctest
julia> import MathOptInterface as MOI
julia> MOI.Nonlinear.DEFAULT_UNIVARIATE_OPERATORS
73-element Vector{Symbol}:
:+
:-
:abs
:sign
:sqrt
:cbrt
:abs2
:inv
:log
:log10
⋮
:airybi
:airyaiprime
:airybiprime
:besselj0
:besselj1
:bessely0
:bessely1
:erfcx
:dawson
```
"""
const DEFAULT_UNIVARIATE_OPERATORS = first.(SYMBOLIC_UNIVARIATE_EXPRESSIONS)
"""
DEFAULT_MULTIVARIATE_OPERATORS
The list of multivariate operators that are supported by default.
## Example
```jldoctest
julia> import MathOptInterface as MOI
julia> MOI.Nonlinear.DEFAULT_MULTIVARIATE_OPERATORS
9-element Vector{Symbol}:
:+
:-
:*
:^
:/
:ifelse
:atan
:min
:max
```
"""
const DEFAULT_MULTIVARIATE_OPERATORS =
[:+, :-, :*, :^, :/, :ifelse, :atan, :min, :max]
"""
OperatorRegistry()
Create a new `OperatorRegistry` to store and evaluate univariate and
multivariate operators.
"""
struct OperatorRegistry
# NODE_CALL_UNIVARIATE
univariate_operators::Vector{Symbol}
univariate_operator_to_id::Dict{Symbol,Int}
univariate_user_operator_start::Int
registered_univariate_operators::Vector{_UnivariateOperator}
# NODE_CALL_MULTIVARIATE
multivariate_operators::Vector{Symbol}
multivariate_operator_to_id::Dict{Symbol,Int}
multivariate_user_operator_start::Int
registered_multivariate_operators::Vector{_MultivariateOperator}
# NODE_LOGIC
logic_operators::Vector{Symbol}
logic_operator_to_id::Dict{Symbol,Int}
# NODE_COMPARISON
comparison_operators::Vector{Symbol}
comparison_operator_to_id::Dict{Symbol,Int}
function OperatorRegistry()
univariate_operators = copy(DEFAULT_UNIVARIATE_OPERATORS)
multivariate_operators = copy(DEFAULT_MULTIVARIATE_OPERATORS)
logic_operators = [:&&, :||]
comparison_operators = [:<=, :(==), :>=, :<, :>]
return new(
# NODE_CALL_UNIVARIATE
univariate_operators,
Dict{Symbol,Int}(
op => i for (i, op) in enumerate(univariate_operators)
),
length(univariate_operators),
_UnivariateOperator[],
# NODE_CALL
multivariate_operators,
Dict{Symbol,Int}(
op => i for (i, op) in enumerate(multivariate_operators)
),
length(multivariate_operators),
_MultivariateOperator[],
# NODE_LOGIC
logic_operators,
Dict{Symbol,Int}(op => i for (i, op) in enumerate(logic_operators)),
# NODE_COMPARISON
comparison_operators,
Dict{Symbol,Int}(
op => i for (i, op) in enumerate(comparison_operators)
),
)
end
end
function MOI.get(
registry::OperatorRegistry,
::MOI.ListOfSupportedNonlinearOperators,
)
ops = vcat(
registry.univariate_operators,
registry.multivariate_operators,
registry.logic_operators,
registry.comparison_operators,
)
return unique(ops)
end
const _FORWARD_DIFF_METHOD_ERROR_HELPER = raw"""
Common reasons for this include:
* The function takes `f(x::Vector)` as input, instead of the splatted
`f(x...)`.
* The function assumes `Float64` will be passed as input, it must work for any
generic `Real` type.
* The function allocates temporary storage using `zeros(3)` or similar. This
defaults to `Float64`, so use `zeros(T, 3)` instead.
As examples, instead of:
```julia
my_function(x::Vector) = sum(x.^2)
```
use:
```julia
my_function(x::T...) where {T<:Real} = sum(x[i]^2 for i in 1:length(x))
```
Instead of:
```julia
function my_function(x::Float64...)
y = zeros(length(x))
for i in 1:length(x)
y[i] = x[i]^2
end
return sum(y)
end
```
use:
```julia
function my_function(x::T...) where {T<:Real}
y = zeros(T, length(x))
for i in 1:length(x)
y[i] = x[i]^2
end
return sum(y)
end
```
Review the stacktrace below for more information, but it can often be hard to
understand why and where your function is failing. You can also debug this
outside of JuMP as follows:
```julia
import ForwardDiff
# If the input dimension is 1
x = 1.0
my_function(a) = a^2
ForwardDiff.derivative(my_function, x)
# If the input dimension is more than 1
x = [1.0, 2.0]
my_function(a, b) = a^2 + b^2
ForwardDiff.gradient(x -> my_function(x...), x)
```
"""
_intercept_ForwardDiff_MethodError(err, ::Symbol) = rethrow(err)
function _intercept_ForwardDiff_MethodError(::MethodError, op::Symbol)
return error(
"JuMP's autodiff of the user-defined function $(op) failed with a " *
"MethodError.\n\n$(_FORWARD_DIFF_METHOD_ERROR_HELPER)",
)
end
function _checked_derivative(f::F, op::Symbol) where {F}
return function (x)
try
return ForwardDiff.derivative(f, x)
catch err
_intercept_ForwardDiff_MethodError(err, op)
end
end
end
"""
_validate_register_assumptions(
f::Function,
name::Symbol,
dimension::Integer,
)
A function that attempts to check if `f` is suitable for registration via
[`register`](@ref) and throws an informative error if it is not.
Because we don't know the domain of `f`, this function may encounter false
negatives. But it should catch the majority of cases in which users supply
non-differentiable functions that rely on `::Float64` assumptions.
"""
function _validate_register_assumptions(
f::Function,
name::Symbol,
dimension::Integer,
)
# Assumption 1: check that `f` can be called with `Float64` arguments.
y = 0.0
try
if dimension == 1
y = f(0.0)
else
y = f(zeros(dimension)...)
end
catch
# We hit some other error, perhaps we called a function like log(-1).
# Ignore for now, and hope that a useful error is shown to the user
# during the solve.
end
if !(y isa Real)
error(
"Expected return type of `Float64` from the user-defined " *
"function :$(name), but got `$(typeof(y))`.",
)
end
# Assumption 2: check that `f` can be differentiated using `ForwardDiff`.
try
if dimension == 1
ForwardDiff.derivative(f, 0.0)
else
ForwardDiff.gradient(x -> f(x...), zeros(dimension))
end
catch err
if err isa MethodError
error(
"Unable to register the function :$name.\n\n" *
_FORWARD_DIFF_METHOD_ERROR_HELPER,
)
end
# We hit some other error, perhaps we called a function like log(-1).
# Ignore for now, and hope that a useful error is shown to the user
# during the solve.
end
return
end
function _UnivariateOperator(op::Symbol, f::Function)
_validate_register_assumptions(f, op, 1)
f′ = _checked_derivative(f, op)
return _UnivariateOperator(op, f, f′)
end
function _UnivariateOperator(op::Symbol, f::Function, f′::Function)
try
_validate_register_assumptions(f′, op, 1)
f′′ = _checked_derivative(f′, op)
return _UnivariateOperator(f, f′, f′′)
catch
return _UnivariateOperator(f, f′, nothing)
end
end
function _UnivariateOperator(::Symbol, f::Function, f′::Function, f′′::Function)
return _UnivariateOperator(f, f′, f′′)
end
function _MultivariateOperator{N}(op::Symbol, f::Function) where {N}
_validate_register_assumptions(f, op, N)
g = x -> f(x...)
∇f = function (ret, x)
try
ForwardDiff.gradient!(ret, g, x)
catch err
_intercept_ForwardDiff_MethodError(err, op)
end
return
end
return _MultivariateOperator{N}(g, ∇f)
end
function _MultivariateOperator{N}(::Symbol, f::Function, ∇f::Function) where {N}
return _MultivariateOperator{N}(x -> f(x...), (g, x) -> ∇f(g, x...))
end
function _MultivariateOperator{N}(
::Symbol,
f::Function,
∇f::Function,
∇²f::Function,
) where {N}
return _MultivariateOperator{N}(
x -> f(x...),
(g, x) -> ∇f(g, x...),
(H, x) -> ∇²f(H, x...),
)
end
function register_operator(
registry::OperatorRegistry,
op::Symbol,
nargs::Int,
f::Function...,
)
if nargs == 1
if haskey(registry.univariate_operator_to_id, op)
error("Operator $op is already registered.")
elseif haskey(registry.multivariate_operator_to_id, op)
error("Operator $op is already registered.")
end
operator = _UnivariateOperator(op, f...)
push!(registry.univariate_operators, op)
push!(registry.registered_univariate_operators, operator)
registry.univariate_operator_to_id[op] =
length(registry.univariate_operators)
else
if haskey(registry.multivariate_operator_to_id, op)
error("Operator $op is already registered.")
elseif haskey(registry.univariate_operator_to_id, op)
error("Operator $op is already registered.")
end
operator = _MultivariateOperator{nargs}(op, f...)
push!(registry.multivariate_operators, op)
push!(registry.registered_multivariate_operators, operator)
registry.multivariate_operator_to_id[op] =
length(registry.multivariate_operators)
end
return
end
function _is_registered(registry::OperatorRegistry, op::Symbol, nargs::Int)
if op in (:<=, :>=, :(==), :<, :>, :&&, :||)
return true
end
if nargs == 1 && haskey(registry.univariate_operator_to_id, op)
return true
end
return haskey(registry.multivariate_operator_to_id, op)
end
function _warn_auto_register(op::Symbol, nargs::Int)
@warn("""Function $op automatically registered with $nargs arguments.
Calling the function with a different number of arguments will result in an
error.
While you can safely ignore this warning, we recommend that you manually
register the function as follows:
```Julia
model = Model()
register(model, :$op, $nargs, $op; autodiff = true)
```""")
return
end
"""
register_operator_if_needed(
registry::OperatorRegistry,
op::Symbol,
nargs::Int,
f::Function;
)
Similar to [`register_operator`](@ref), but this function warns if the function
is not registered, and skips silently if it already is.
"""
function register_operator_if_needed(
registry::OperatorRegistry,
op::Symbol,
nargs::Int,
f::Function,
)
if !_is_registered(registry, op, nargs)
register_operator(registry, op, nargs, f)
_warn_auto_register(op, nargs)
end
return
end
"""
assert_registered(registry::OperatorRegistry, op::Symbol, nargs::Int)
Throw an error if `op` is not registered in `registry` with `nargs` arguments.
"""
function assert_registered(registry::OperatorRegistry, op::Symbol, nargs::Int)
if !_is_registered(registry, op, nargs)
msg = """
Unrecognized function \"$(op)\" used in nonlinear expression.
You must register it as a user-defined function before building
the model. For example, replacing `N` with the appropriate number
of arguments, do:
```julia
model = Model()
register(model, :$(op), N, $(op), autodiff=true)
# ... variables and constraints ...
```
"""
error(msg)
end
return
end
"""
check_return_type(::Type{T}, ret::S) where {T,S}
Overload this method for new types `S` to throw an informative error if a
user-defined function returns the type `S` instead of `T`.
"""
check_return_type(::Type{T}, ret::T) where {T} = nothing
function check_return_type(::Type{T}, ret) where {T}
return error(
"Expected return type of $T from a user-defined function, but got " *
"$(typeof(ret)).",
)
end
"""
eval_univariate_function(
registry::OperatorRegistry,
op::Union{Symbol,Integer},
x::T,
) where {T}
Evaluate the operator `op(x)::T`, where `op` is a univariate function in
`registry`.
If `op isa Integer`, then `op` is the index in
`registry.univariate_operators[op]`.
## Example
```jldoctest
julia> import MathOptInterface as MOI
julia> r = MOI.Nonlinear.OperatorRegistry();
julia> MOI.Nonlinear.eval_univariate_function(r, :abs, -1.2)
1.2
julia> r.univariate_operators[3]
:abs
julia> MOI.Nonlinear.eval_univariate_function(r, 3, -1.2)
1.2
```
"""
function eval_univariate_function(
registry::OperatorRegistry,
op::Symbol,
x::T,
) where {T}
id = registry.univariate_operator_to_id[op]
return eval_univariate_function(registry, id, x)
end
function eval_univariate_function(
registry::OperatorRegistry,
id::Integer,
x::T,
) where {T}
if id <= registry.univariate_user_operator_start
f, _ = _eval_univariate(id, x)
return f::T
end
offset = id - registry.univariate_user_operator_start
operator = registry.registered_univariate_operators[offset]
return eval_univariate_function(operator, x)
end
"""
eval_univariate_gradient(
registry::OperatorRegistry,
op::Union{Symbol,Integer},
x::T,
) where {T}
Evaluate the first-derivative of the operator `op(x)::T`, where `op` is a
univariate function in `registry`.
If `op isa Integer`, then `op` is the index in
`registry.univariate_operators[op]`.
## Example
```jldoctest
julia> import MathOptInterface as MOI
julia> r = MOI.Nonlinear.OperatorRegistry();
julia> MOI.Nonlinear.eval_univariate_gradient(r, :abs, -1.2)
-1.0
julia> r.univariate_operators[3]
:abs
julia> MOI.Nonlinear.eval_univariate_gradient(r, 3, -1.2)
-1.0
```
"""
function eval_univariate_gradient(
registry::OperatorRegistry,
op::Symbol,
x::T,
) where {T}
id = registry.univariate_operator_to_id[op]
return eval_univariate_gradient(registry, id, x)
end
function eval_univariate_gradient(
registry::OperatorRegistry,
id::Integer,
x::T,
) where {T}
if id <= registry.univariate_user_operator_start
_, f′ = _eval_univariate(id, x)
return f′::T
end
offset = id - registry.univariate_user_operator_start
operator = registry.registered_univariate_operators[offset]
return eval_univariate_gradient(operator, x)
end
"""
eval_univariate_function_and_gradient(
registry::OperatorRegistry,
op::Union{Symbol,Integer},
x::T,
)::Tuple{T,T} where {T}
Evaluate the function and first-derivative of the operator `op(x)::T`, where
`op` is a univariate function in `registry`.
If `op isa Integer`, then `op` is the index in
`registry.univariate_operators[op]`.
## Example
```jldoctest
julia> import MathOptInterface as MOI
julia> r = MOI.Nonlinear.OperatorRegistry();
julia> MOI.Nonlinear.eval_univariate_function_and_gradient(r, :abs, -1.2)
(1.2, -1.0)
julia> r.univariate_operators[3]
:abs
julia> MOI.Nonlinear.eval_univariate_function_and_gradient(r, 3, -1.2)
(1.2, -1.0)
```
"""
function eval_univariate_function_and_gradient(
registry::OperatorRegistry,
op::Symbol,
x::T,
) where {T}
id = registry.univariate_operator_to_id[op]
return eval_univariate_function_and_gradient(registry, id, x)
end
function eval_univariate_function_and_gradient(
registry::OperatorRegistry,
id::Integer,
x::T,
) where {T}
if id <= registry.univariate_user_operator_start
return _eval_univariate(id, x)::Tuple{T,T}
end
offset = id - registry.univariate_user_operator_start
operator = registry.registered_univariate_operators[offset]
return eval_univariate_function_and_gradient(operator, x)
end
"""
eval_univariate_hessian(
registry::OperatorRegistry,
op::Union{Symbol,Integer},
x::T,
) where {T}
Evaluate the second-derivative of the operator `op(x)::T`, where `op` is a
univariate function in `registry`.
If `op isa Integer`, then `op` is the index in
`registry.univariate_operators[op]`.
## Example
```jldoctest
julia> import MathOptInterface as MOI
julia> r = MOI.Nonlinear.OperatorRegistry();
julia> MOI.Nonlinear.eval_univariate_hessian(r, :sin, 1.0)
-0.8414709848078965
julia> r.univariate_operators[16]
:sin
julia> MOI.Nonlinear.eval_univariate_hessian(r, 16, 1.0)
-0.8414709848078965
julia> -sin(1.0)
-0.8414709848078965
```
"""
function eval_univariate_hessian(
registry::OperatorRegistry,
op::Symbol,
x::T,
) where {T}
id = registry.univariate_operator_to_id[op]
return eval_univariate_hessian(registry, id, x)
end
function eval_univariate_hessian(
registry::OperatorRegistry,
id::Integer,
x::T,
) where {T}
if id <= registry.univariate_user_operator_start
ret = _eval_univariate_2nd_deriv(id, x)
if ret === nothing
op = registry.univariate_operators[id]
error("Hessian is not defined for operator $op")
end
return ret::T
end
offset = id - registry.univariate_user_operator_start
operator = registry.registered_univariate_operators[offset]
return eval_univariate_hessian(operator, x)
end
"""
_nan_pow(x, y)
An alternative for `x^y` that avoids throwing an error in common situations like
`(-1.0)^1.5`. This optimization applies only to Float32 and Float64 inputs; if
a different type is provided as input we fallback to `x^y`.
"""
_nan_pow(x::T, y::T) where {T<:Union{Float32,Float64}} = pow(x, y)
_nan_pow(x, y) = x^y
"""
eval_multivariate_function(
registry::OperatorRegistry,
op::Symbol,
x::AbstractVector{T},
) where {T}
Evaluate the operator `op(x)::T`, where `op` is a multivariate function in
`registry`.
"""
function eval_multivariate_function(
registry::OperatorRegistry,
op::Symbol,
x::AbstractVector{T},
)::T where {T}
if op == :+
return sum(x; init = zero(T))
elseif op == :-
@assert length(x) == 2
return x[1] - x[2]
elseif op == :*
return prod(x; init = one(T))
elseif op == :^
@assert length(x) == 2
# Use _nan_pow here to avoid throwing an error in common situations like
# (-1.0)^1.5.
return _nan_pow(x[1], x[2])
elseif op == :/
@assert length(x) == 2
return x[1] / x[2]
elseif op == :ifelse
@assert length(x) == 3
return ifelse(Bool(x[1]), x[2], x[3])
elseif op == :atan
@assert length(x) == 2
return atan(x[1], x[2])
elseif op == :min
return minimum(x)
elseif op == :max
return maximum(x)
end
id = registry.multivariate_operator_to_id[op]
offset = id - registry.multivariate_user_operator_start
operator = registry.registered_multivariate_operators[offset]
@assert length(x) == operator.N
ret = operator.f(x)
check_return_type(T, ret)
return ret::T
end
"""
eval_multivariate_gradient(
registry::OperatorRegistry,
op::Symbol,
g::AbstractVector{T},
x::AbstractVector{T},
) where {T}
Evaluate the gradient of operator `g .= ∇op(x)`, where `op` is a multivariate
function in `registry`.
"""
function eval_multivariate_gradient(
registry::OperatorRegistry,
op::Symbol,
g::AbstractVector{T},
x::AbstractVector{T},
) where {T}
@assert length(g) == length(x)
if op == :+
fill!(g, one(T))
elseif op == :-
g[1] = one(T)
g[2] = -one(T)
elseif op == :*
# Special case performance optimizations for common cases.
if length(x) == 1
g[1] = one(T)
elseif length(x) == 2
g[1] = x[2]
g[2] = x[1]
else
total = prod(x)
if iszero(total)
for i in eachindex(x)
g[i] = prod(x[j] for j in eachindex(x) if i != j)
end
else
for i in eachindex(x)
g[i] = total / x[i]
end
end
end
elseif op == :^
@assert length(x) == 2
if x[2] == one(T)
g[1] = one(T)
elseif x[2] == T(2)
g[1] = T(2) * x[1]
else
g[1] = x[2] * _nan_pow(x[1], x[2] - one(T))
end
if x[1] > zero(T)
g[2] = _nan_pow(x[1], x[2]) * log(x[1])
else
g[2] = T(NaN)
end
elseif op == :/
@assert length(x) == 2
g[1] = one(T) / x[2]
g[2] = -x[1] / x[2]^2
elseif op == :ifelse
@assert length(x) == 3
g[1] = zero(T) # It doesn't matter what this is.
g[2] = x[1] == one(T)
g[3] = x[1] == zero(T)
elseif op == :atan
@assert length(x) == 2
base = x[1]^2 + x[2]^2
g[1] = x[2] / base
g[2] = -x[1] / base
elseif op == :min
fill!(g, zero(T))
_, i = findmin(x)
g[i] = one(T)
elseif op == :max
fill!(g, zero(T))
_, i = findmax(x)
g[i] = one(T)
else
id = registry.multivariate_operator_to_id[op]
offset = id - registry.multivariate_user_operator_start
operator = registry.registered_multivariate_operators[offset]
@assert length(x) == operator.N
operator.∇f(g, x)
end
return
end
_nan_to_zero(x) = isnan(x) ? 0.0 : x
"""
eval_multivariate_hessian(
registry::OperatorRegistry,
op::Symbol,
H::AbstractMatrix,
x::AbstractVector{T},
)::Bool where {T}
Evaluate the Hessian of operator `∇²op(x)`, where `op` is a multivariate
function in `registry`.
The Hessian is stored in the lower-triangular part of the matrix `H`.
Returns a `Bool` indicating whether non-zeros were stored in the matrix.
!!! note
Implementations of the Hessian operators will not fill structural zeros.
Therefore, before calling this function you should pre-populate the matrix
`H` with `0`.
"""
function eval_multivariate_hessian(
registry::OperatorRegistry,
op::Symbol,
H,
x::AbstractVector{T},
) where {T}
if op in (:+, :-, :ifelse)
return false
end
if op == :*
# f(x) = *(x[i] for i in 1:N)
#
# ∇fᵢ(x) = *(x[j] for j in 1:N if i != j)
#
# ∇fᵢⱼ(x) = *(x[k] for k in 1:N if i != k & j != k)
N = length(x)
if N == 1
# Hessian is zero
elseif N == 2
H[2, 1] = one(T)
else
for i in 1:N, j in (i+1):N
H[j, i] =
prod(x[k] for k in 1:N if k != i && k != j; init = one(T))
end
end
elseif op == :^
# f(x) = x[1]^x[2]
#
# ∇f(x) = x[2]*x[1]^(x[2]-1)
# x[1]^x[2]*log(x[1])
#
# ∇²f(x) = x[2]*(x[2]-1)*x[1]^(x[2]-2)
# x[1]^(x[2]-1)*(x[2]*log(x[1])+1) x[1]^x[2]*log(x[1])^2
ln = x[1] > 0 ? log(x[1]) : NaN
if x[2] == one(T)
H[2, 1] = _nan_to_zero(ln + one(T))
H[2, 2] = _nan_to_zero(x[1] * ln^2)
elseif x[2] == T(2)
H[1, 1] = T(2)
H[2, 1] = _nan_to_zero(x[1] * (T(2) * ln + one(T)))
H[2, 2] = _nan_to_zero(ln^2 * x[1]^2)
else
H[1, 1] = _nan_to_zero(x[2] * (x[2] - 1) * _nan_pow(x[1], x[2] - 2))
H[2, 1] = _nan_to_zero(_nan_pow(x[1], x[2] - 1) * (x[2] * ln + 1))
H[2, 2] = _nan_to_zero(ln^2 * _nan_pow(x[1], x[2]))
end
elseif op == :/
# f(x) = x[1]/x[2]
#
# ∇f(x) = 1/x[2]
# -x[1]/x[2]^2
#
# ∇²(x) = 0.0
# -1/x[2]^2 2x[1]/x[2]^3
d = 1 / x[2]^2
H[2, 1] = -d
H[2, 2] = 2 * x[1] * d / x[2]
elseif op == :atan
# f(x) = atan(y, x)
#
# ∇f(x) = +x/(x^2+y^2)
# -y/(x^2+y^2)
#
# ∇²(x) = -(2xy)/(x^2+y^2)^2
# (y^2-x^2)/(x^2+y^2)^2 (2xy)/(x^2+y^2)^2
base = (x[1]^2 + x[2]^2)^2
H[1, 1] = -2 * x[2] * x[1] / base
H[2, 1] = (x[1]^2 - x[2]^2) / base
H[2, 2] = 2 * x[2] * x[1] / base
elseif op == :min
_, i = findmin(x)
H[i, i] = one(T)
elseif op == :max
_, i = findmax(x)
H[i, i] = one(T)