-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathfunctions.jl
More file actions
1417 lines (1150 loc) · 39.8 KB
/
functions.jl
File metadata and controls
1417 lines (1150 loc) · 39.8 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.
"""
output_dimension(f::AbstractFunction)
Return 1 if `f` is an [`AbstractScalarFunction`](@ref), or the number of output
components if `f` is an [`AbstractVectorFunction`](@ref).
"""
function output_dimension end
output_dimension(::AbstractScalarFunction) = 1
"""
constant(f::AbstractFunction[, ::Type{T}]) where {T}
Returns the constant term of a scalar-valued function, or the constant vector of
a vector-valued function.
If `f` is untyped and `T` is provided, returns `zero(T)`.
"""
constant(f::AbstractFunction, ::Type{T}) where {T} = constant(f)
"""
coefficient(t::ScalarAffineTerm)
coefficient(t::ScalarQuadraticTerm)
coefficient(t::VectorAffineTerm)
coefficient(t::VectorQuadraticTerm)
Finds the coefficient stored in the term `t`.
"""
function coefficient end
"""
term_indices(t::ScalarAffineTerm)
term_indices(t::ScalarQuadraticTerm)
term_indices(t::VectorAffineTerm)
term_indices(t::VectorQuadraticTerm)
Returns the indices of the input term `t` as a tuple of `Int`s.
* For `t::ScalarAffineTerm`, this is a 1-tuple of the variable index.
* For `t::ScalarQuadraticTerm`, this is a 2-tuple of the variable indices
in non-decreasing order.
* For `t::VectorAffineTerm`, this is a 2-tuple of the row/output and
variable indices.
* For `t::VectorQuadraticTerm`, this is a 3-tuple of the row/output and
variable indices in non-decreasing order.
"""
function term_indices end
"""
term_pair(t::ScalarAffineTerm)
term_pair(t::ScalarQuadraticTerm)
term_pair(t::VectorAffineTerm)
term_pair(t::VectorQuadraticTerm)
Returns the pair [`term_indices`](@ref) `=>` [`coefficient`](@ref) of the term.
"""
function term_pair end
# VariableIndex is defined in indextypes.jl
constant(::VariableIndex, ::Type{T}) where {T} = zero(T)
Base.copy(x::VariableIndex) = x
Base.isapprox(x::VariableIndex, y::VariableIndex; kwargs...) = x == y
"""
ScalarAffineTerm{T}(coefficient::T, variable::VariableIndex) where {T}
Represents the scalar-valued term `coefficient * variable`.
## Example
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> MOI.ScalarAffineTerm(2.0, x)
MathOptInterface.ScalarAffineTerm{Float64}(2.0, MOI.VariableIndex(1))
```
"""
struct ScalarAffineTerm{T}
coefficient::T
variable::VariableIndex
end
coefficient(t::ScalarAffineTerm) = t.coefficient
term_indices(t::ScalarAffineTerm) = (t.variable.value,)
term_pair(t::ScalarAffineTerm) = term_indices(t) => coefficient(t)
# !!! developer note
#
# ScalarAffineFunction is mutable because its `constant` field is likely of
# an immutable type, while its `terms` field is of a mutable type, meaning
# that creating a `ScalarAffineFunction` allocates, and it is desirable to
# provide a zero-allocation option for working with ScalarAffineFunctions.
#
# See https://github.com/jump-dev/MathOptInterface.jl/pull/343.
"""
ScalarAffineFunction{T}(
terms::Vector{ScalarAffineTerm{T}},
constant::T,
) where {T}
Represents the scalar-valued affine function ``a^\\top x + b``, where:
* ``a^\\top x`` is represented by the vector of [`ScalarAffineTerm`](@ref)s
* ``b`` is a scalar `constant::T`
## Duplicates
Duplicate variable indices in `terms` are accepted, and the corresponding
coefficients are summed together.
## Example
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> terms = [MOI.ScalarAffineTerm(2.0, x), MOI.ScalarAffineTerm(3.0, x)]
2-element Vector{MathOptInterface.ScalarAffineTerm{Float64}}:
MathOptInterface.ScalarAffineTerm{Float64}(2.0, MOI.VariableIndex(1))
MathOptInterface.ScalarAffineTerm{Float64}(3.0, MOI.VariableIndex(1))
julia> f = MOI.ScalarAffineFunction(terms, 4.0)
4.0 + 2.0 MOI.VariableIndex(1) + 3.0 MOI.VariableIndex(1)
```
"""
mutable struct ScalarAffineFunction{T} <: AbstractScalarFunction
terms::Vector{ScalarAffineTerm{T}}
constant::T
end
constant(f::ScalarAffineFunction) = f.constant
function Base.copy(f::ScalarAffineFunction)
return ScalarAffineFunction(copy(f.terms), copy(f.constant))
end
function ScalarAffineFunction{T}(x::VariableIndex) where {T}
return ScalarAffineFunction([ScalarAffineTerm(one(T), x)], zero(T))
end
"""
ScalarQuadraticTerm{T}(
coefficient::T,
variable_1::VariableIndex,
variable_2::VariableIndex,
) where {T}
Represents the scalar-valued term ``c x_i x_j`` where ``c`` is `coefficient`,
``x_i`` is `variable_1` and ``x_j`` is `variable_2`.
## Example
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> MOI.ScalarQuadraticTerm(2.0, x, x)
MathOptInterface.ScalarQuadraticTerm{Float64}(2.0, MOI.VariableIndex(1), MOI.VariableIndex(1))
```
"""
struct ScalarQuadraticTerm{T}
coefficient::T
variable_1::VariableIndex
variable_2::VariableIndex
end
coefficient(t::ScalarQuadraticTerm) = t.coefficient
function term_indices(t::ScalarQuadraticTerm)
return minmax(t.variable_1.value, t.variable_2.value)
end
term_pair(t::ScalarQuadraticTerm) = term_indices(t) => coefficient(t)
# !!! developer note
#
# ScalarQuadraticFunction is mutable because its `constant` field is likely
# of an immutable type, while its `terms` field is of a mutable type,
# meaning that creating a `ScalarQuadraticFunction` allocates, and it is
# desirable to provide a zero-allocation option for working with
# ScalarQuadraticFunctions.
#
# See https://github.com/jump-dev/MathOptInterface.jl/pull/343.
"""
ScalarQuadraticFunction{T}(
quadratic_terms::Vector{ScalarQuadraticTerm{T}},
affine_terms::Vector{ScalarAffineTerm{T}},
constant::T,
) wher {T}
The scalar-valued quadratic function ``\\frac{1}{2}x^\\top Q x + a^\\top x + b``,
where:
* ``Q`` is the symmetric matrix given by the vector of [`ScalarQuadraticTerm`](@ref)s
* ``a^\\top x`` is a sparse vector given by the vector of [`ScalarAffineTerm`](@ref)s
* ``b`` is the scalar `constant::T`.
## Duplicates
Duplicate indices in `quadratic_terms` or `affine_terms` are accepted, and the
corresponding coefficients are summed together.
In `quadratic_terms`, "mirrored" indices, `(q, r)` and `(r, q)` where `r` and
`q` are [`VariableIndex`](@ref)es, are considered duplicates; only one needs to
be specified.
## The 0.5 factor
Coupled with the interpretation of mirrored indices, the `0.5` factor in front
of the ``Q`` matrix is a common source of bugs.
As a rule, to represent ``a * x^2 + b * x * y``:
* The coefficient ``a`` in front of squared variables (diagonal elements in
``Q``) must be doubled when creating a [`ScalarQuadraticTerm`](@ref)
* The coefficient ``b`` in front of off-diagonal elements in ``Q`` should be
left as ``b``, be cause the mirrored index ``b * y * x`` will be implicitly
added.
## Example
To represent the function ``f(x, y) = 2 * x^2 + 3 * x * y + 4 * x + 5``, do:
```jldoctest
julia> x = MOI.VariableIndex(1);
julia> y = MOI.VariableIndex(2);
julia> constant = 5.0;
julia> affine_terms = [MOI.ScalarAffineTerm(4.0, x)];
julia> quadratic_terms = [
MOI.ScalarQuadraticTerm(4.0, x, x), # Note the changed coefficient
MOI.ScalarQuadraticTerm(3.0, x, y),
]
2-element Vector{MathOptInterface.ScalarQuadraticTerm{Float64}}:
MathOptInterface.ScalarQuadraticTerm{Float64}(4.0, MOI.VariableIndex(1), MOI.VariableIndex(1))
MathOptInterface.ScalarQuadraticTerm{Float64}(3.0, MOI.VariableIndex(1), MOI.VariableIndex(2))
julia> f = MOI.ScalarQuadraticFunction(quadratic_terms, affine_terms, constant)
5.0 + 4.0 MOI.VariableIndex(1) + 2.0 MOI.VariableIndex(1)² + 3.0 MOI.VariableIndex(1)*MOI.VariableIndex(2)
```
"""
mutable struct ScalarQuadraticFunction{T} <: AbstractScalarFunction
quadratic_terms::Vector{ScalarQuadraticTerm{T}}
affine_terms::Vector{ScalarAffineTerm{T}}
constant::T
end
constant(f::ScalarQuadraticFunction) = f.constant
function Base.copy(f::ScalarQuadraticFunction)
return ScalarQuadraticFunction(
copy(f.quadratic_terms),
copy(f.affine_terms),
copy(f.constant),
)
end
"""
ScalarNonlinearFunction(head::Symbol, args::Vector{Any})
The scalar-valued nonlinear function `head(args...)`, represented as a symbolic
expression tree, with the call operator `head` and ordered arguments in `args`.
## `head`
The `head::Symbol` must be an operator supported by the model.
The default list of supported univariate operators is given by:
* [`Nonlinear.DEFAULT_UNIVARIATE_OPERATORS`](@ref)
and the default list of supported multivariate operators is given by:
* [`Nonlinear.DEFAULT_MULTIVARIATE_OPERATORS`](@ref)
Additional operators can be registered by setting a [`UserDefinedFunction`](@ref)
attribute.
See the full list of operators supported by a [`ModelLike`](@ref) by querying
[`ListOfSupportedNonlinearOperators`](@ref).
## `args`
The vector `args` contains the arguments to the nonlinear function. If the
operator is univariate, it must contain one element. Otherwise, it may contain
multiple elements.
Each element must be one of the following:
* A constant value of type `T<:Real`
* A [`VariableIndex`](@ref)
* A [`ScalarAffineFunction`](@ref)
* A [`ScalarQuadraticFunction`](@ref)
* A [`ScalarNonlinearFunction`](@ref)
## Unsupported operators
If the optimizer does not support `head`, an [`UnsupportedNonlinearOperator`](@ref)
error will be thrown.
There is no guarantee about when this error will be thrown; it may be thrown
when the function is first added to the model, or it may be thrown when
[`optimize!`](@ref) is called.
## Example
To represent the function ``f(x) = sin(x)^2``, do:
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> MOI.ScalarNonlinearFunction(
:^,
Any[MOI.ScalarNonlinearFunction(:sin, Any[x]), 2],
)
^(sin(MOI.VariableIndex(1)), (2))
```
"""
struct ScalarNonlinearFunction <: AbstractScalarFunction
head::Symbol
args::Vector{Any}
function ScalarNonlinearFunction(head::Symbol, args::AbstractVector)
# TODO(odow): should we do this?
# for arg in args
# if !(arg isa Real || arg isa AbstractScalarFunction)
# error("Unsupported object in nonlinear expression: $arg")
# end
# end
return new(head, convert(Vector{Any}, args))
end
end
# copy() doesn't recursively copy the children, and deepcopy seems to have a
# performance problem for deeply nested structs.
function Base.copy(f::ScalarNonlinearFunction)
stack, result_stack = Any[f], Any[]
while !isempty(stack)
arg = pop!(stack)
if arg isa 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 (currently) a valid argument.
push!(stack, (arg,))
for child in arg.args
push!(stack, child)
end
elseif arg isa Tuple{<:ScalarNonlinearFunction}
result = only(arg)
args = Any[pop!(result_stack) for i in 1:length(result.args)]
push!(result_stack, ScalarNonlinearFunction(result.head, args))
else
push!(result_stack, copy(arg))
end
end
return only(result_stack)
end
constant(f::ScalarNonlinearFunction, ::Type{T} = Float64) where {T} = zero(T)
"""
UnsupportedNonlinearOperator(head::Symbol[, message::String]) <: UnsupportedError
An error thrown by optimizers if they do not support the operator `head` in a
[`ScalarNonlinearFunction`](@ref).
## Example
```jldoctest
julia> throw(MOI.UnsupportedNonlinearOperator(:black_box))
ERROR: MathOptInterface.UnsupportedNonlinearOperator: The nonlinear operator `:black_box` is not supported by the model.
Stacktrace:
[...]
```
"""
struct UnsupportedNonlinearOperator <: UnsupportedError
head::Symbol
message::String
function UnsupportedNonlinearOperator(head::Symbol, message::String = "")
return new(head, message)
end
end
function element_name(err::UnsupportedNonlinearOperator)
return "The nonlinear operator `:$(err.head)`"
end
"""
abstract type AbstractVectorFunction <: AbstractFunction
Abstract supertype for vector-valued [`AbstractFunction`](@ref)s.
## Required methods
All subtypes of `AbstractVectorFunction` must implement:
* [`output_dimension`](@ref)
"""
abstract type AbstractVectorFunction <: AbstractFunction end
"""
VectorOfVariables(variables::Vector{VariableIndex}) <: AbstractVectorFunction
The vector-valued function `f(x) = variables`, where `variables` is a subset of
[`VariableIndex`](@ref)es in the model.
The list of `variables` may contain duplicates.
## Example
```jldoctest
julia> x = MOI.VariableIndex.(1:2)
2-element Vector{MathOptInterface.VariableIndex}:
MOI.VariableIndex(1)
MOI.VariableIndex(2)
julia> f = MOI.VectorOfVariables([x[1], x[2], x[1]])
┌ ┐
│MOI.VariableIndex(1)│
│MOI.VariableIndex(2)│
│MOI.VariableIndex(1)│
└ ┘
julia> MOI.output_dimension(f)
3
```
"""
struct VectorOfVariables <: AbstractVectorFunction
variables::Vector{VariableIndex}
end
output_dimension(f::VectorOfVariables) = length(f.variables)
function constant(f::VectorOfVariables, ::Type{T}) where {T}
return zeros(T, output_dimension(f))
end
Base.copy(f::VectorOfVariables) = VectorOfVariables(copy(f.variables))
function Base.:(==)(f::VectorOfVariables, g::VectorOfVariables)
return f.variables == g.variables
end
Base.isapprox(x::VectorOfVariables, y::VectorOfVariables; kwargs...) = x == y
"""
VectorAffineTerm{T}(
output_index::Int64,
scalar_term::ScalarAffineTerm{T},
) where {T}
A `VectorAffineTerm` is a `scalar_term` that appears in the `output_index` row
of the vector-valued [`VectorAffineFunction`](@ref) or
[`VectorQuadraticFunction`](@ref).
## Example
```jldoctest
julia> x = MOI.VariableIndex(1);
julia> MOI.VectorAffineTerm(Int64(2), MOI.ScalarAffineTerm(3.0, x))
MathOptInterface.VectorAffineTerm{Float64}(2, MathOptInterface.ScalarAffineTerm{Float64}(3.0, MOI.VariableIndex(1)))
```
"""
struct VectorAffineTerm{T}
output_index::Int64
scalar_term::ScalarAffineTerm{T}
end
function VectorAffineTerm(
output_index::Base.Integer,
scalar_term::ScalarAffineTerm,
)
return VectorAffineTerm(convert(Int64, output_index), scalar_term)
end
coefficient(t::VectorAffineTerm) = t.scalar_term.coefficient
function term_indices(t::VectorAffineTerm)
return (t.output_index, term_indices(t.scalar_term)...)
end
term_pair(t::VectorAffineTerm) = term_indices(t) => coefficient(t)
"""
VectorAffineFunction{T}(
terms::Vector{VectorAffineTerm{T}},
constants::Vector{T},
) where {T}
The vector-valued affine function ``A x + b``, where:
* ``A x`` is the sparse matrix given by the vector of [`VectorAffineTerm`](@ref)s
* ``b`` is the vector `constants`
## Duplicates
Duplicate indices in the ``A`` are accepted, and the corresponding coefficients
are summed together.
## Example
```jldoctest
julia> x = MOI.VariableIndex(1);
julia> terms = [
MOI.VectorAffineTerm(Int64(1), MOI.ScalarAffineTerm(2.0, x)),
MOI.VectorAffineTerm(Int64(2), MOI.ScalarAffineTerm(3.0, x)),
];
julia> f = MOI.VectorAffineFunction(terms, [4.0, 5.0])
┌ ┐
│4.0 + 2.0 MOI.VariableIndex(1)│
│5.0 + 3.0 MOI.VariableIndex(1)│
└ ┘
julia> MOI.output_dimension(f)
2
```
"""
struct VectorAffineFunction{T} <: AbstractVectorFunction
terms::Vector{VectorAffineTerm{T}}
constants::Vector{T}
end
output_dimension(f::VectorAffineFunction) = length(f.constants)
constant(f::VectorAffineFunction) = f.constants
function Base.copy(f::VectorAffineFunction)
return VectorAffineFunction(copy(f.terms), copy(f.constants))
end
function VectorAffineFunction{T}(f::VectorOfVariables) where {T}
terms = map(1:output_dimension(f)) do i
return VectorAffineTerm(i, ScalarAffineTerm(one(T), f.variables[i]))
end
constants = zeros(T, output_dimension(f))::Vector{T}
return VectorAffineFunction(terms, constants)
end
"""
VectorQuadraticTerm{T}(
output_index::Int64,
scalar_term::ScalarQuadraticTerm{T},
) where {T}
A `VectorQuadraticTerm` is a [`ScalarQuadraticTerm`](@ref) `scalar_term` that
appears in the `output_index` row of the vector-valued
[`VectorQuadraticFunction`](@ref).
## Example
```jldoctest
julia> x = MOI.VariableIndex(1);
julia> MOI.VectorQuadraticTerm(Int64(2), MOI.ScalarQuadraticTerm(3.0, x, x))
MathOptInterface.VectorQuadraticTerm{Float64}(2, MathOptInterface.ScalarQuadraticTerm{Float64}(3.0, MOI.VariableIndex(1), MOI.VariableIndex(1)))
```
"""
struct VectorQuadraticTerm{T}
output_index::Int64
scalar_term::ScalarQuadraticTerm{T}
end
function VectorQuadraticTerm(
output_index::Base.Integer,
scalar_term::ScalarQuadraticTerm,
)
return VectorQuadraticTerm(convert(Int64, output_index), scalar_term)
end
coefficient(t::VectorQuadraticTerm) = t.scalar_term.coefficient
function term_indices(t::VectorQuadraticTerm)
return (t.output_index, term_indices(t.scalar_term)...)
end
term_pair(t::VectorQuadraticTerm) = term_indices(t) => coefficient(t)
"""
VectorQuadraticFunction{T}(
quadratic_terms::Vector{VectorQuadraticTerm{T}},
affine_terms::Vector{VectorAffineTerm{T}},
constants::Vector{T},
) where {T}
The vector-valued quadratic function with i`th` component ("output index")
defined as ``\\frac{1}{2}x^\\top Q_i x + a_i^\\top x + b_i``, where:
* ``\\frac{1}{2}x^\\top Q_i x`` is the symmetric matrix given by the
[`VectorQuadraticTerm`](@ref) elements in `quadratic_terms` with
`output_index == i`
* ``a_i^\\top x`` is the sparse vector given by the [`VectorAffineTerm`](@ref)
elements in `affine_terms` with `output_index == i`
* ``b_i`` is a scalar given by `constants[i]`
## Duplicates
Duplicate indices in `quadratic_terms` and `affine_terms` with the same
`output_index` are handled in the same manner as duplicates in
[`ScalarQuadraticFunction`](@ref).
## Example
```jldoctest
julia> x = MOI.VariableIndex(1);
julia> y = MOI.VariableIndex(2);
julia> constants = [4.0, 5.0];
julia> affine_terms = [
MOI.VectorAffineTerm(Int64(1), MOI.ScalarAffineTerm(2.0, x)),
MOI.VectorAffineTerm(Int64(2), MOI.ScalarAffineTerm(3.0, x)),
];
julia> quad_terms = [
MOI.VectorQuadraticTerm(Int64(1), MOI.ScalarQuadraticTerm(2.0, x, x)),
MOI.VectorQuadraticTerm(Int64(2), MOI.ScalarQuadraticTerm(3.0, x, y)),
];
julia> f = MOI.VectorQuadraticFunction(quad_terms, affine_terms, constants)
┌ ┐
│4.0 + 2.0 MOI.VariableIndex(1) + 1.0 MOI.VariableIndex(1)² │
│5.0 + 3.0 MOI.VariableIndex(1) + 3.0 MOI.VariableIndex(1)*MOI.VariableIndex(2)│
└ ┘
julia> MOI.output_dimension(f)
2
```
"""
struct VectorQuadraticFunction{T} <: AbstractVectorFunction
quadratic_terms::Vector{VectorQuadraticTerm{T}}
affine_terms::Vector{VectorAffineTerm{T}}
constants::Vector{T}
end
output_dimension(f::VectorQuadraticFunction) = length(f.constants)
constant(f::VectorQuadraticFunction) = f.constants
function Base.copy(f::VectorQuadraticFunction)
return VectorQuadraticFunction(
copy(f.quadratic_terms),
copy(f.affine_terms),
copy(f.constants),
)
end
"""
VectorNonlinearFunction(args::Vector{ScalarNonlinearFunction})
The vector-valued nonlinear function composed of a vector of
[`ScalarNonlinearFunction`](@ref).
## `args`
The vector `args` contains the scalar elements of the nonlinear function. Each
element must be a [`ScalarNonlinearFunction`](@ref), but if you pass a
`Vector{Any}`, the elements can be automatically converted from one of the
following:
* A constant value of type `T<:Real`
* A [`VariableIndex`](@ref)
* A [`ScalarAffineFunction`](@ref)
* A [`ScalarQuadraticFunction`](@ref)
* A [`ScalarNonlinearFunction`](@ref)
## Example
To represent the function ``f(x) = [sin(x)^2, x]``, do:
```jldoctest
julia> x = MOI.VariableIndex(1)
MOI.VariableIndex(1)
julia> g = MOI.ScalarNonlinearFunction(
:^,
Any[MOI.ScalarNonlinearFunction(:sin, Any[x]), 2.0],
)
^(sin(MOI.VariableIndex(1)), 2.0)
julia> MOI.VectorNonlinearFunction([g, x])
┌ ┐
│^(sin(MOI.VariableIndex(1)), 2.0)│
│+(MOI.VariableIndex(1)) │
└ ┘
```
Note the automatic conversion from `x` to `+(x)`.
"""
struct VectorNonlinearFunction <: AbstractVectorFunction
rows::Vector{ScalarNonlinearFunction}
end
output_dimension(f::VectorNonlinearFunction) = length(f.rows)
function constant(f::VectorNonlinearFunction, ::Type{T}) where {T}
return zeros(T, output_dimension(f))
end
Base.copy(f::VectorNonlinearFunction) = VectorNonlinearFunction(copy(f.rows))
function Base.:(==)(f::VectorNonlinearFunction, g::VectorNonlinearFunction)
return f.rows == g.rows
end
function Base.isapprox(
x::VectorNonlinearFunction,
y::VectorNonlinearFunction;
kwargs...,
)
return all(isapprox(xi, yi; kwargs...) for (xi, yi) in zip(x.rows, y.rows))
end
# Function modifications
"""
AbstractFunctionModification
An abstract supertype for structs which specify partial modifications to
functions, to be used for making small modifications instead of replacing the
functions entirely.
"""
abstract type AbstractFunctionModification end
"""
ScalarConstantChange{T}(new_constant::T)
A struct used to request a change in the constant term of a scalar-valued
function.
Applicable to [`ScalarAffineFunction`](@ref) and [`ScalarQuadraticFunction`](@ref).
"""
struct ScalarConstantChange{T} <: AbstractFunctionModification
new_constant::T
end
"""
VectorConstantChange{T}(new_constant::Vector{T})
A struct used to request a change in the constant vector of a vector-valued
function.
Applicable to [`VectorAffineFunction`](@ref) and [`VectorQuadraticFunction`](@ref).
"""
struct VectorConstantChange{T} <: AbstractFunctionModification
new_constant::Vector{T}
end
"""
ScalarCoefficientChange{T}(variable::VariableIndex, new_coefficient::T)
A struct used to request a change in the linear coefficient of a single variable
in a scalar-valued function.
Applicable to [`ScalarAffineFunction`](@ref) and [`ScalarQuadraticFunction`](@ref).
"""
struct ScalarCoefficientChange{T} <: AbstractFunctionModification
variable::VariableIndex
new_coefficient::T
end
"""
ScalarQuadraticCoefficientChange{T}(
variable_1::VariableIndex,
variable_2::VariableIndex,
new_coefficient::T,
)
A struct used to request a change in the quadratic coefficient of a
[`ScalarQuadraticFunction`](@ref).
## Scaling factors
A [`ScalarQuadraticFunction`](@ref) has an implicit `0.5` scaling factor in
front of the `Q` matrix. This modification applies to terms in the `Q` matrix.
If `variable_1 == variable_2`, this modification sets the corresponding diagonal
element of the `Q` matrix to `new_coefficient`.
If `variable_1 != variable_2`, this modification is equivalent to setting both
the corresponding upper- and lower-triangular elements of the `Q` matrix to
`new_coefficient`.
As a consequence:
* to modify the term `x^2` to become `2x^2`, `new_coefficient` must be `4`
* to modify the term `xy` to become `2xy`, `new_coefficient` must be `2`
"""
struct ScalarQuadraticCoefficientChange{T} <: AbstractFunctionModification
variable_1::VariableIndex
variable_2::VariableIndex
new_coefficient::T
end
# !!! developer note
# MultiRowChange is mutable because its `variable` field of an immutable
# type, while `new_coefficients` is of a mutable type, meaning that creating
# a `MultiRowChange` allocates, and it is desirable to provide a
# zero-allocation option for working with MultiRowChanges.
#
# See https://github.com/jump-dev/MathOptInterface.jl/pull/343.
"""
MultirowChange{T}(
variable::VariableIndex,
new_coefficients::Vector{Tuple{Int64,T}},
) where {T}
A struct used to request a change in the linear coefficients of a single
variable in a vector-valued function.
New coefficients are specified by `(output_index, coefficient)` tuples.
Applicable to [`VectorAffineFunction`](@ref) and [`VectorQuadraticFunction`](@ref).
"""
mutable struct MultirowChange{T} <: AbstractFunctionModification
variable::VariableIndex
new_coefficients::Vector{Tuple{Int64,T}}
end
function MultirowChange(
variable::VariableIndex,
new_coefficients::Vector{Tuple{Ti,T}},
) where {Ti<:Base.Integer,T}
return MultirowChange(
variable,
[(convert(Int64, i), j) for (i, j) in new_coefficients],
)
end
# isapprox
# For affine and quadratic functions, terms are compressed in a dictionary using
# `_dicts` and then the dictionaries are compared with `dict_compare`
function dict_compare(d1::Dict, d2::Dict{<:Any,T}, compare::Function) where {T}
for key in union(keys(d1), keys(d2))
if !compare(Base.get(d1, key, zero(T)), Base.get(d2, key, zero(T)))
return false
end
end
return true
end
# Build a dictionary where the duplicate keys are summed
function sum_dict(kvs::Vector{Pair{K,V}}) where {K,V}
d = Dict{K,V}()
for (key, value) in kvs
d[key] = value + Base.get(d, key, zero(V))
end
return d
end
function _dicts(f::Union{ScalarAffineFunction,VectorAffineFunction})
return (sum_dict(term_pair.(f.terms)),)
end
function _dicts(f::Union{ScalarQuadraticFunction,VectorQuadraticFunction})
return (
sum_dict(term_pair.(f.quadratic_terms)),
sum_dict(term_pair.(f.affine_terms)),
)
end
function Base.isapprox(
f::F,
g::G;
kwargs...,
) where {
F<:Union{
ScalarAffineFunction,
ScalarQuadraticFunction,
VectorAffineFunction,
VectorQuadraticFunction,
},
G<:Union{
ScalarAffineFunction,
ScalarQuadraticFunction,
VectorAffineFunction,
VectorQuadraticFunction,
},
}
return isapprox(constant(f), constant(g); kwargs...) && all(
dict_compare.(
_dicts(f),
_dicts(g),
(α, β) -> isapprox(α, β; kwargs...),
),
)
end
# This method is used by CBF in testing.
function Base.isapprox(f::VectorOfVariables, g::VectorAffineFunction; kwargs...)
return isapprox(convert(typeof(g), f), g; kwargs...)
end
_is_approx(x, y; kwargs...) = isapprox(x, y; kwargs...)
function _is_approx(x::AbstractArray, y::AbstractArray; kwargs...)
return size(x) == size(y) &&
all(z -> _is_approx(z[1], z[2]; kwargs...), zip(x, y))
end
function Base.isapprox(
f::ScalarNonlinearFunction,
g::ScalarNonlinearFunction;
kwargs...,
)
if f.head != g.head || length(f.args) != length(g.args)
return false
end
for (fi, gi) in zip(f.args, g.args)
if !_is_approx(fi, gi; kwargs...)
return false
end
end
return true
end
###
### Base.convert
###
# VariableIndex
function Base.convert(::Type{VariableIndex}, f::ScalarAffineFunction)
if !iszero(f.constant)
throw(InexactError(:convert, VariableIndex, f))
end
scalar_term = nothing
for term in f.terms
if isone(term.coefficient) && scalar_term === nothing
scalar_term = term
elseif !iszero(term.coefficient)
throw(InexactError(:convert, VariableIndex, f))
end
end
if scalar_term === nothing
throw(InexactError(:convert, VariableIndex, f))
end
return scalar_term.variable::VariableIndex
end
function Base.convert(
::Type{VariableIndex},
f::ScalarQuadraticFunction{T},
) where {T}
return convert(VariableIndex, convert(ScalarAffineFunction{T}, f))
end
# ScalarAffineFunction
function Base.convert(::Type{ScalarAffineFunction{T}}, α::T) where {T}
return ScalarAffineFunction{T}(ScalarAffineTerm{T}[], α)
end
function Base.convert(
::Type{ScalarAffineFunction{T}},
f::VariableIndex,
) where {T}
return ScalarAffineFunction{T}(f)
end
function Base.convert(
::Type{ScalarAffineTerm{T}},
t::ScalarAffineTerm,
) where {T}
return ScalarAffineTerm{T}(t.coefficient, t.variable)
end
function Base.convert(
::Type{ScalarAffineFunction{T}},
f::ScalarAffineFunction,
) where {T}
return ScalarAffineFunction{T}(f.terms, f.constant)
end