-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathfunctions.jl
2285 lines (1970 loc) · 61.7 KB
/
functions.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
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.
# Functions convertible to a ScalarAffineFunction
const ScalarAffineLike{T} =
Union{T,MOI.VariableIndex,MOI.ScalarAffineFunction{T}}
# Functions convertible to a ScalarQuadraticFunction
const ScalarQuadraticLike{T} =
Union{ScalarAffineLike{T},MOI.ScalarQuadraticFunction{T}}
# `ScalarLike` for which `T` is defined to avoid defining, e.g.,
# `+(::VariableIndex, ::Any)` which should rather be
# `+(::VariableIndex, ::Number)`.
const TypedScalarLike{T} =
Union{MOI.ScalarAffineFunction{T},MOI.ScalarQuadraticFunction{T}}
# Used for overloading Base operator functions so `T` is not in the union to
# avoid overloading e.g. `+(::Float64, ::Float64)`
const ScalarLike{T} = Union{MOI.VariableIndex,TypedScalarLike{T}}
# Functions convertible to a VectorAffineFunction
const VectorAffineLike{T} =
Union{Vector{T},MOI.VectorOfVariables,MOI.VectorAffineFunction{T}}
# Functions convertible to a VectorQuadraticFunction
const VectorQuadraticLike{T} =
Union{VectorAffineLike{T},MOI.VectorQuadraticFunction{T}}
# `VectorLike` for which `T` is defined to avoid defining, e.g.,
# `+(::VectorOfVariables, ::Any)` which should rather be
# `+(::VectorOfVariables, ::Number)`.
const TypedVectorLike{T} =
Union{MOI.VectorAffineFunction{T},MOI.VectorQuadraticFunction{T}}
# Used for overloading Base operator functions so `T` is not in the union to
# avoid overloading e.g. `+(::Float64, ::Float64)`
const VectorLike{T} = Union{MOI.VectorOfVariables,TypedVectorLike{T}}
const TypedLike{T} = Union{TypedScalarLike{T},TypedVectorLike{T}}
const ObjectWithoutIndex = Union{
AbstractString,
Enum,
Function,
Nothing,
Number,
Symbol,
Type,
MOI.AbstractSet,
MOI.AnyAttribute,
MOI.ModelLike,
MOI.NLPBlockData,
}
const ObjectOrTupleWithoutIndex =
Union{ObjectWithoutIndex,Tuple{Vararg{ObjectWithoutIndex}}}
const ObjectOrTupleOrArrayWithoutIndex = Union{
ObjectOrTupleWithoutIndex,
AbstractArray{<:ObjectOrTupleWithoutIndex},
AbstractArray{<:AbstractArray{<:ObjectOrTupleWithoutIndex}},
}
"""
variable_function_type(::Type{<:MOI.AbstractSet})
Return the variable type associated with a set, that is, [`MOI.VariableIndex`](@ref)
for scalar sets and [`MOI.VectorOfVariables`](@ref) for vector sets.
"""
variable_function_type(::Type{<:MOI.AbstractScalarSet}) = MOI.VariableIndex
variable_function_type(::Type{<:MOI.AbstractVectorSet}) = MOI.VectorOfVariables
"""
value_type(::Type{T}, ::Type{F}) where {T,F<:MOI.AbstractFunction}
Returns the output type that results if a function of type `F` is evaluated
using variables with numeric type `T`.
In other words, this is the return type for
`MOI.Utilities.eval_variables(value_fn::Function, f::F)` for a function
`value_fn(::MOI.VariableIndex)::T`.
"""
function value_type end
value_type(::Type{T}, ::Type{MOI.VariableIndex}) where {T} = T
function value_type(
::Type{T},
::Type{<:Union{MOI.ScalarAffineFunction{C},MOI.ScalarQuadraticFunction{C}}},
) where {C,T}
return MA.promote_operation(*, C, T)
end
function value_type(
::Type{T},
::Type{F},
) where {T,F<:MOI.AbstractVectorFunction}
return Vector{value_type(T, scalar_type(F))}
end
"""
eval_variables(value_fn::Function, f::MOI.AbstractFunction)
Returns the value of function `f` if each variable index `vi` is evaluated as
`value_fn(vi)`.
Note that `value_fn` must return a Number. See [`substitute_variables`](@ref)
for a similar function where `value_fn` returns an
[`MOI.AbstractScalarFunction`](@ref).
"""
function eval_variables end
function eval_variables(value_fn::Function, t::MOI.ScalarAffineTerm)
return t.coefficient * value_fn(t.variable)
end
function eval_variables(value_fn::Function, t::MOI.ScalarQuadraticTerm)
out = t.coefficient * value_fn(t.variable_1) * value_fn(t.variable_2)
return t.variable_1 == t.variable_2 ? out / 2 : out
end
eval_variables(value_fn::Function, f::MOI.VariableIndex) = value_fn(f)
function eval_variables(value_fn::Function, f::MOI.ScalarAffineFunction)
out = f.constant
for t in f.terms
out += eval_variables(value_fn, t)
end
return out
end
function eval_variables(value_fn::Function, f::MOI.ScalarQuadraticFunction)
out = f.constant
for a in f.affine_terms
out += eval_variables(value_fn, a)
end
for q in f.quadratic_terms
out += eval_variables(value_fn, q)
end
return out
end
function eval_variables(value_fn::Function, f::MOI.VectorOfVariables)
return value_fn.(f.variables)
end
function eval_variables(value_fn::Function, f::MOI.VectorAffineFunction)
out = copy(f.constants)
for t in f.terms
out[t.output_index] += eval_variables(value_fn, t.scalar_term)
end
return out
end
function eval_variables(value_fn::Function, f::MOI.VectorQuadraticFunction)
out = copy(f.constants)
for t in f.affine_terms
out[t.output_index] += eval_variables(value_fn, t.scalar_term)
end
for t in f.quadratic_terms
out[t.output_index] += eval_variables(value_fn, t.scalar_term)
end
return out
end
"""
map_indices(index_map::Function, attr::MOI.AnyAttribute, x::X)::X where {X}
Substitute any [`MOI.VariableIndex`](@ref) (resp. [`MOI.ConstraintIndex`](@ref))
in `x` by the [`MOI.VariableIndex`](@ref) (resp. [`MOI.ConstraintIndex`](@ref))
of the same type given by `index_map(x)`.
## When to implement this method for new types `X`
This function is used by implementations of [`MOI.copy_to`](@ref) on
constraint functions, attribute values and submittable values. If you define a
new attribute whose values `x::X` contain variable or constraint indices, you
must also implement this function.
"""
map_indices(f, ::MOI.AnyAttribute, x) = map_indices(f, x)
# RawOptimizerAttribute values are passed through un-changed.
map_indices(::Any, ::MOI.RawOptimizerAttribute, x) = x
"""
map_indices(
variable_map::AbstractDict{T,T},
x::X,
)::X where {T<:MOI.Index,X}
Shortcut for `map_indices(vi -> variable_map[vi], x)`.
"""
function map_indices(
variable_map::AbstractDict{T,T},
x::X,
)::X where {T<:MOI.Index,X}
return map_indices(Base.Fix1(getindex, variable_map), x)
end
map_indices(::F, x::ObjectOrTupleOrArrayWithoutIndex) where {F<:Function} = x
function map_indices(index_map::F, vi::MOI.VariableIndex) where {F<:Function}
return index_map(vi)
end
function map_indices(index_map::F, ci::MOI.ConstraintIndex) where {F<:Function}
return index_map(ci)
end
function map_indices(index_map::F, x::AbstractArray) where {F<:Function}
return [map_indices(index_map, xi) for xi in x]
end
function map_indices(index_map::F, t::MOI.ScalarAffineTerm) where {F<:Function}
return MOI.ScalarAffineTerm(t.coefficient, index_map(t.variable))
end
function map_indices(
index_map::F,
t::MOI.ScalarQuadraticTerm,
) where {F<:Function}
return MOI.ScalarQuadraticTerm(
t.coefficient,
index_map(t.variable_1),
index_map(t.variable_2),
)
end
function map_indices(index_map::F, t::MOI.VectorAffineTerm) where {F<:Function}
return MOI.VectorAffineTerm(
t.output_index,
map_indices(index_map, t.scalar_term),
)
end
function map_indices(
index_map::F,
t::MOI.VectorQuadraticTerm,
) where {F<:Function}
return MOI.VectorQuadraticTerm(
t.output_index,
map_indices(index_map, t.scalar_term),
)
end
function map_indices(
index_map::F,
f::MOI.ScalarAffineFunction,
) where {F<:Function}
return MOI.ScalarAffineFunction(
map_indices(index_map, f.terms),
MOI.constant(f),
)
end
function map_indices(
index_map::F,
f::MOI.ScalarQuadraticFunction,
) where {F<:Function}
return MOI.ScalarQuadraticFunction(
map_indices(index_map, f.quadratic_terms),
map_indices(index_map, f.affine_terms),
MOI.constant(f),
)
end
function map_indices(index_map::F, f::MOI.VectorOfVariables) where {F<:Function}
return MOI.VectorOfVariables(map_indices(index_map, f.variables))
end
function map_indices(
index_map::F,
f::MOI.VectorAffineFunction,
) where {F<:Function}
return MOI.VectorAffineFunction(
map_indices(index_map, f.terms),
MOI.constant(f),
)
end
function map_indices(
index_map::F,
f::MOI.VectorQuadraticFunction,
) where {F<:Function}
return MOI.VectorQuadraticFunction(
map_indices(index_map, f.quadratic_terms),
map_indices(index_map, f.affine_terms),
MOI.constant(f),
)
end
function map_indices(
index_map::F,
f::MOI.ScalarNonlinearFunction,
) where {F<:Function}
return MOI.ScalarNonlinearFunction(
f.head,
convert(Vector{Any}, map_indices(index_map, f.args)),
)
end
map_indices(::F, change::MOI.ScalarConstantChange) where {F<:Function} = change
map_indices(::F, change::MOI.VectorConstantChange) where {F<:Function} = change
function map_indices(
index_map::F,
change::MOI.ScalarCoefficientChange,
) where {F<:Function}
return MOI.ScalarCoefficientChange(
index_map(change.variable),
change.new_coefficient,
)
end
function map_indices(
index_map::F,
change::MOI.MultirowChange,
) where {F<:Function}
return MOI.MultirowChange(
index_map(change.variable),
change.new_coefficients,
)
end
# For performance reason, we assume that the type of the function does not
# change in `substitute_variables`.
"""
substitute_variables(variable_map::Function, x)
Substitute any [`MOI.VariableIndex`](@ref) in `x` by `variable_map(x)`. The
`variable_map` function returns either [`MOI.VariableIndex`](@ref) or
[`MOI.ScalarAffineFunction`](@ref), see [`eval_variables`](@ref) for a similar
function where `variable_map` returns a number.
This function is used by bridge optimizers on constraint functions, attribute
values and submittable values when at least one variable bridge is used hence it
needs to be implemented for custom types that are meant to be used as attribute
or submittable value.
!!! note
When implementing a new method, don't use `substitute_variables(::Function`,
because Julia will not specialize on it. Use instead
`substitute_variables(::F, ...) where {F<:Function}`.
"""
function substitute_variables end
function substitute_variables(
::F,
x::ObjectOrTupleOrArrayWithoutIndex,
) where {F<:Function}
return x
end
function substitute_variables(
variable_map::F,
x::MOI.VariableIndex,
) where {F<:Function}
f = variable_map(x)
if f != x
error("Cannot substitute `$x` as it is bridged into `$f`.")
end
return x
end
# This method is used when submitting `HeuristicSolution`.
function substitute_variables(
variable_map::F,
x::Vector{MOI.VariableIndex},
) where {F<:Function}
return substitute_variables.(variable_map, x)
end
function substitute_variables(
variable_map::F,
term::MOI.ScalarAffineTerm{T},
) where {T,F<:Function}
# We could have `T = Complex{Float64}` and `variable_map(term.variable)`
# be a `MOI.ScalarAffineFunction{Float64}` with the Hermitian to PSD bridge.
# We convert to `MOI.ScalarAffineFunction{T}` to avoid any issue.
f = convert(MOI.ScalarAffineFunction{T}, variable_map(term.variable))
return operate(*, T, term.coefficient, f)::MOI.ScalarAffineFunction{T}
end
function substitute_variables(
variable_map::F,
term::MOI.ScalarQuadraticTerm{T},
) where {T,F<:Function}
# We could have `T = Complex{Float64}` and `variable_map(term.variable)`
# be a `MOI.ScalarAffineFunction{Float64}` with the Hermitian to PSD bridge.
# We convert to `MOI.ScalarAffineFunction{T}` to avoid any issue.
f1 = convert(MOI.ScalarAffineFunction{T}, variable_map(term.variable_1))
f2 = convert(MOI.ScalarAffineFunction{T}, variable_map(term.variable_2))
f12 = operate(*, T, f1, f2)::MOI.ScalarQuadraticFunction{T}
coef = term.coefficient
# The quadratic terms are evaluated as x'Qx/2 so a diagonal term should
# be divided by 2 while an off-diagonal term appears twice in the matrix
# and is divided by 2 so it stays the same.
if term.variable_1 == term.variable_2
coef /= 2
end
return operate!(*, T, f12, coef)
end
function substitute_variables(
variable_map::F,
f::MOI.ScalarAffineFunction{T},
) where {T,F<:Function}
g = MOI.ScalarAffineFunction(MOI.ScalarAffineTerm{T}[], MOI.constant(f))
for term in f.terms
# This works because substitute_variables actually returns a function,
# not a term.
g = operate!(+, T, g, substitute_variables(variable_map, term))
end
return g
end
function substitute_variables(
variable_map::F,
f::MOI.ScalarQuadraticFunction{T},
) where {T,F<:Function}
g = MOI.ScalarQuadraticFunction(
MOI.ScalarQuadraticTerm{T}[],
MOI.ScalarAffineTerm{T}[],
MOI.constant(f),
)
for a_term in f.affine_terms
g = operate!(+, T, g, substitute_variables(variable_map, a_term))
end
for q_term in f.quadratic_terms
g = operate!(+, T, g, substitute_variables(variable_map, q_term))
end
return g
end
function substitute_variables(
variable_map::F,
f::MOI.VectorAffineFunction{T},
) where {T,F<:Function}
g = MOI.VectorAffineFunction(
MOI.VectorAffineTerm{T}[],
copy(MOI.constant(f)),
)
for term in f.terms
term_f = substitute_variables(variable_map, term.scalar_term)
operate_output_index!(+, T, term.output_index, g, term_f)
end
return g
end
function substitute_variables(
variable_map::F,
f::MOI.VectorQuadraticFunction{T},
) where {T,F<:Function}
g = MOI.VectorQuadraticFunction(
MOI.VectorQuadraticTerm{T}[],
MOI.VectorAffineTerm{T}[],
copy(MOI.constant(f)),
)
for term in f.affine_terms
sub = substitute_variables(variable_map, term.scalar_term)
operate_output_index!(+, T, term.output_index, g, sub)
end
for term in f.quadratic_terms
sub = substitute_variables(variable_map, term.scalar_term)
operate_output_index!(+, T, term.output_index, g, sub)
end
return g
end
"""
scalar_type(F::Type{<:MOI.AbstractVectorFunction})
Type of functions obtained by indexing objects obtained by calling `eachscalar`
on functions of type `F`.
"""
function scalar_type end
scalar_type(::Type{<:AbstractVector{T}}) where {T} = T
scalar_type(::Type{MOI.VectorOfVariables}) = MOI.VariableIndex
function scalar_type(::Type{MOI.VectorAffineFunction{T}}) where {T}
return MOI.ScalarAffineFunction{T}
end
function scalar_type(::Type{MOI.VectorQuadraticFunction{T}}) where {T}
return MOI.ScalarQuadraticFunction{T}
end
"""
vector_type(::Type{<:MOI.AbstractScalarFunction})
Return the [`MOI.AbstractVectorFunction`](@ref) associated with the scalar type
`F`.
"""
function vector_type end
vector_type(::Type{T}) where {T} = Vector{T}
vector_type(::Type{MOI.VariableIndex}) = MOI.VectorOfVariables
function vector_type(::Type{MOI.ScalarAffineFunction{T}}) where {T}
return MOI.VectorAffineFunction{T}
end
function vector_type(::Type{MOI.ScalarQuadraticFunction{T}}) where {T}
return MOI.VectorQuadraticFunction{T}
end
"""
ScalarFunctionIterator{F<:MOI.AbstractVectorFunction}
A type that allows iterating over the scalar-functions that comprise an
`AbstractVectorFunction`.
"""
struct ScalarFunctionIterator{F<:MOI.AbstractVectorFunction,C}
f::F
# Cache that can be used to store a precomputed datastructure that allows
# an efficient implementation of `getindex`.
cache::C
end
function ScalarFunctionIterator(func::MOI.AbstractVectorFunction)
return ScalarFunctionIterator(func, scalar_iterator_cache(func))
end
scalar_iterator_cache(func::MOI.AbstractVectorFunction) = nothing
function output_index_iterator(terms::AbstractVector, output_dimension)
start = zeros(Int, output_dimension)
next = Vector{Int}(undef, length(terms))
last = zeros(Int, output_dimension)
for i in eachindex(terms)
j = terms[i].output_index
if iszero(last[j])
start[j] = i
else
next[last[j]] = i
end
last[j] = i
end
for j in eachindex(last)
if !iszero(last[j])
next[last[j]] = 0
end
end
return ChainedIterator(start, next)
end
struct ChainedIterator
start::Vector{Int}
next::Vector{Int}
end
struct ChainedIteratorAtIndex
start::Int
next::Vector{Int}
end
function ChainedIteratorAtIndex(it::ChainedIterator, index::Int)
return ChainedIteratorAtIndex(it.start[index], it.next)
end
#TODO We could also precompute the length for each `output_index`,
# check that it's a win.
Base.IteratorSize(::ChainedIteratorAtIndex) = Base.SizeUnknown()
function Base.iterate(it::ChainedIteratorAtIndex, i = it.start)
if iszero(i)
return nothing
end
return i, it.next[i]
end
function ScalarFunctionIterator(f::MOI.VectorAffineFunction)
return ScalarFunctionIterator(
f,
output_index_iterator(f.terms, MOI.output_dimension(f)),
)
end
function ScalarFunctionIterator(f::MOI.VectorQuadraticFunction)
return ScalarFunctionIterator(
f,
(
output_index_iterator(f.quadratic_terms, MOI.output_dimension(f)),
output_index_iterator(f.affine_terms, MOI.output_dimension(f)),
),
)
end
"""
eachscalar(f::MOI.AbstractVectorFunction)
Returns an iterator for the scalar components of the vector function.
See also [`scalarize`](@ref).
"""
eachscalar(f::MOI.AbstractVectorFunction) = ScalarFunctionIterator(f)
"""
eachscalar(f::MOI.AbstractVector)
Returns an iterator for the scalar components of the vector.
"""
eachscalar(f::AbstractVector) = f
function Base.iterate(it::ScalarFunctionIterator, state = 1)
if state > length(it)
return nothing
end
return (it[state], state + 1)
end
function Base.length(it::ScalarFunctionIterator{<:MOI.AbstractVectorFunction})
return MOI.output_dimension(it.f)
end
function Base.eltype(::ScalarFunctionIterator{MOI.VectorOfVariables})
return MOI.VariableIndex
end
function Base.eltype(
::ScalarFunctionIterator{MOI.VectorAffineFunction{T}},
) where {T}
return MOI.ScalarAffineFunction{T}
end
function Base.eltype(
::ScalarFunctionIterator{MOI.VectorQuadraticFunction{T}},
) where {T}
return MOI.ScalarQuadraticFunction{T}
end
Base.lastindex(it::ScalarFunctionIterator) = length(it)
function Base.getindex(
it::ScalarFunctionIterator{MOI.VectorOfVariables},
output_index::Integer,
)
return it.f.variables[output_index]
end
function Base.getindex(
it::ScalarFunctionIterator{MOI.VectorOfVariables},
output_indices::AbstractVector{<:Integer},
)
return MOI.VectorOfVariables(it.f.variables[output_indices])
end
function Base.getindex(
it::ScalarFunctionIterator{MOI.VectorAffineFunction{T}},
output_index::Integer,
) where {T}
return MOI.ScalarAffineFunction{T}(
MOI.ScalarAffineTerm{T}[
it.f.terms[i].scalar_term for
i in ChainedIteratorAtIndex(it.cache, output_index)
],
it.f.constants[output_index],
)
end
function Base.getindex(
it::ScalarFunctionIterator{MOI.VectorAffineFunction{T}},
output_indices::AbstractVector{<:Integer},
) where {T}
terms = MOI.VectorAffineTerm{T}[]
for (i, output_index) in enumerate(output_indices)
for j in ChainedIteratorAtIndex(it.cache, output_index)
push!(terms, MOI.VectorAffineTerm(i, it.f.terms[j].scalar_term))
end
end
return MOI.VectorAffineFunction(terms, it.f.constants[output_indices])
end
function Base.getindex(
it::ScalarFunctionIterator{MOI.VectorQuadraticFunction{T}},
output_index::Integer,
) where {T}
return MOI.ScalarQuadraticFunction(
MOI.ScalarQuadraticTerm{T}[
it.f.quadratic_terms[i].scalar_term for
i in ChainedIteratorAtIndex(it.cache[1], output_index)
],
MOI.ScalarAffineTerm{T}[
it.f.affine_terms[i].scalar_term for
i in ChainedIteratorAtIndex(it.cache[2], output_index)
],
it.f.constants[output_index],
)
end
function Base.getindex(
it::ScalarFunctionIterator{MOI.VectorQuadraticFunction{T}},
output_indices::AbstractVector{<:Integer},
) where {T}
vat = MOI.VectorAffineTerm{T}[]
vqt = MOI.VectorQuadraticTerm{T}[]
for (i, output_index) in enumerate(output_indices)
for j in ChainedIteratorAtIndex(it.cache[2], output_index)
push!(
vat,
MOI.VectorAffineTerm(i, it.f.affine_terms[j].scalar_term),
)
end
for j in ChainedIteratorAtIndex(it.cache[1], output_index)
push!(
vqt,
MOI.VectorQuadraticTerm(i, it.f.quadratic_terms[j].scalar_term),
)
end
end
return MOI.VectorQuadraticFunction(vqt, vat, it.f.constants[output_indices])
end
"""
zero_with_output_dimension(::Type{T}, output_dimension::Integer) where {T}
Create an instance of type `T` with the output dimension `output_dimension`.
This is mostly useful in Bridges, when code needs to be agnostic to the type of
vector-valued function that is passed in.
"""
function zero_with_output_dimension end
function zero_with_output_dimension(::Type{Vector{T}}, n::Integer) where {T}
return zeros(T, n)
end
function zero_with_output_dimension(
::Type{MOI.VectorAffineFunction{T}},
n::Integer,
) where {T}
return MOI.VectorAffineFunction{T}(MOI.VectorAffineTerm{T}[], zeros(T, n))
end
function zero_with_output_dimension(
::Type{MOI.VectorQuadraticFunction{T}},
n::Integer,
) where {T}
return MOI.VectorQuadraticFunction{T}(
MOI.VectorQuadraticTerm{T}[],
MOI.VectorAffineTerm{T}[],
zeros(T, n),
)
end
"""
unsafe_add(t1::MOI.ScalarAffineTerm, t2::MOI.ScalarAffineTerm)
Sums the coefficients of `t1` and `t2` and returns an output
`MOI.ScalarAffineTerm`. It is unsafe because it uses the `variable` of `t1` as
the `variable` of the output without checking that it is equal to that of `t2`.
"""
function unsafe_add(t1::MOI.ScalarAffineTerm, t2::MOI.ScalarAffineTerm)
return MOI.ScalarAffineTerm(t1.coefficient + t2.coefficient, t1.variable)
end
"""
unsafe_add(t1::MOI.ScalarQuadraticTerm, t2::MOI.ScalarQuadraticTerm)
Sums the coefficients of `t1` and `t2` and returns an output
`MOI.ScalarQuadraticTerm`. It is unsafe because it uses the `variable`'s
of `t1` as the `variable`'s of the output without checking that they are
the same (up to permutation) to those of `t2`.
"""
function unsafe_add(t1::MOI.ScalarQuadraticTerm, t2::MOI.ScalarQuadraticTerm)
return MOI.ScalarQuadraticTerm(
t1.coefficient + t2.coefficient,
t1.variable_1,
t1.variable_2,
)
end
"""
unsafe_add(t1::MOI.VectorAffineTerm, t2::MOI.VectorAffineTerm)
Sums the coefficients of `t1` and `t2` and returns an output
`MOI.VectorAffineTerm`. It is unsafe because it uses the `output_index` and
`variable` of `t1` as the `output_index` and `variable` of the output term
without checking that they are equal to those of `t2`.
"""
function unsafe_add(
t1::T,
t2::T,
) where {T<:Union{MOI.VectorAffineTerm,MOI.VectorQuadraticTerm}}
scalar_term = unsafe_add(t1.scalar_term, t2.scalar_term)
return T(t1.output_index, scalar_term)
end
is_canonical(::MOI.AbstractFunction) = false
is_canonical(::Union{MOI.VariableIndex,MOI.VectorOfVariables}) = true
"""
is_canonical(f::Union{ScalarAffineFunction, VectorAffineFunction})
Returns a Bool indicating whether the function is in canonical form.
See [`canonical`](@ref).
"""
function is_canonical(
f::Union{MOI.ScalarAffineFunction,MOI.VectorAffineFunction},
)
return _is_strictly_sorted(f.terms)
end
"""
is_canonical(f::Union{ScalarQuadraticFunction, VectorQuadraticFunction})
Returns a Bool indicating whether the function is in canonical form.
See [`canonical`](@ref).
"""
function is_canonical(
f::Union{MOI.ScalarQuadraticFunction,MOI.VectorQuadraticFunction},
)
return _is_strictly_sorted(f.affine_terms) &&
_is_strictly_sorted(f.quadratic_terms)
end
function _is_strictly_sorted(x::Vector)
if isempty(x)
return true
end
@inbounds current_x = x[1]
if iszero(MOI.coefficient(current_x))
return false
end
current_fx = MOI.term_indices(current_x)
@inbounds for i in 2:length(x)
next_x = x[i]
if iszero(MOI.coefficient(next_x))
return false
end
next_fx = MOI.term_indices(next_x)
if next_fx <= current_fx
return false
end
current_x, current_fx = next_x, next_fx
end
return true
end
"""
canonical(f::MOI.AbstractFunction)
Returns the function in a canonical form, i.e.
* A term appear only once.
* The coefficients are nonzero.
* The terms appear in increasing order of variable where there the order of the
variables is the order of their value.
* For a `AbstractVectorFunction`, the terms are sorted in ascending order of
output index.
The output of `canonical` can be assumed to be a copy of `f`, even for
`VectorOfVariables`.
## Examples
If `x` (resp. `y`, `z`) is `VariableIndex(1)` (resp. 2, 3). The canonical
representation of `ScalarAffineFunction([y, x, z, x, z], [2, 1, 3, -2, -3], 5)`
is `ScalarAffineFunction([x, y], [-1, 2], 5)`.
"""
function canonical(f::MOI.AbstractFunction)
g = copy(f)
if !is_canonical(g)
canonicalize!(g)
end
return g
end
canonicalize!(f::Union{MOI.VectorOfVariables,MOI.VariableIndex}) = f
"""
canonicalize!(f::Union{ScalarAffineFunction, VectorAffineFunction})
Convert a function to canonical form in-place, without allocating a copy to hold
the result. See [`canonical`](@ref).
"""
function canonicalize!(
f::Union{MOI.ScalarAffineFunction,MOI.VectorAffineFunction},
)
_sort_and_compress!(f.terms)
return f
end
canonicalize!(f::MOI.ScalarNonlinearFunction) = f
"""
canonicalize!(f::Union{ScalarQuadraticFunction, VectorQuadraticFunction})
Convert a function to canonical form in-place, without allocating a copy to hold
the result. See [`canonical`](@ref).
"""
function canonicalize!(
f::Union{MOI.ScalarQuadraticFunction,MOI.VectorQuadraticFunction},
)
_sort_and_compress!(f.affine_terms)
_sort_and_compress!(f.quadratic_terms)
return f
end
"""
_sort_and_compress!(x::Vector)
Sort the vector `x` in-place using `by` as the function from elements to
comparable keys, then combine all entries for which `by(x[i]) == by(x[j])` using
the function `x[i] = combine(x[i], x[j])`, and remove any entries for which
`keep(x[i]) == false`. This may result in `x` being resized to a shorter length.
"""
function _sort_and_compress!(x::Vector)
if length(x) == 0
return
end
sort!(x, QuickSort, Base.Order.ord(isless, MOI.term_indices, false))
i = 1
@inbounds for j in 2:length(x)
if MOI.term_indices(x[i]) == MOI.term_indices(x[j])
x[i] = unsafe_add(x[i], x[j])
elseif iszero(MOI.coefficient(x[i]))
x[i] = x[j]
else
x[i+1] = x[j]
i += 1
end
end
if iszero(MOI.coefficient(x[i]))
i -= 1
end
resize!(x, i)
return
end
"""
all_coefficients(p::Function, f::MOI.AbstractFunction)
Determine whether predicate `p` returns `true` for all coefficients of `f`,
returning `false` as soon as the first coefficient of `f` for which `p`
returns `false` is encountered (short-circuiting). Similar to `all`.
"""
function all_coefficients end
function all_coefficients(p::Function, f::MOI.ScalarAffineFunction)
return p(f.constant) && all(t -> p(MOI.coefficient(t)), f.terms)
end
function all_coefficients(p::Function, f::MOI.ScalarQuadraticFunction)
return p(f.constant) &&
all(t -> p(MOI.coefficient(t)), f.affine_terms) &&
all(t -> p(MOI.coefficient(t)), f.quadratic_terms)
end
"""
isapprox_zero(f::MOI.AbstractFunction, tol)
Return a `Bool` indicating whether the function `f` is approximately zero using
`tol` as a tolerance.
## Important note
This function assumes that `f` does not contain any duplicate terms, you might
want to first call [`canonical`](@ref) if that is not guaranteed.
For instance, given
```julia
f = MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.([1, -1], [x, x]), 0)
```
then `isapprox_zero(f)` is `false` but `isapprox_zero(MOIU.canonical(f))` is
`true`.
"""
function isapprox_zero end
isapprox_zero(α::AbstractFloat, tol) = -tol <= α <= tol
isapprox_zero(α::Union{Integer,Rational}, tol) = iszero(α)
function isapprox_zero(f::MOI.AbstractFunction, tol)
return all_coefficients(α -> isapprox_zero(α, tol), f)
end
_is_constant(f::MOI.ScalarAffineFunction) = isempty(f.terms)
function _is_constant(f::MOI.ScalarQuadraticFunction)
return isempty(f.affine_terms) && isempty(f.quadratic_terms)
end
Base.iszero(::MOI.VariableIndex) = false
function Base.iszero(
f::Union{MOI.ScalarAffineFunction,MOI.ScalarQuadraticFunction},
)
return iszero(MOI.constant(f)) && _is_constant(canonical(f))
end
Base.isone(::MOI.VariableIndex) = false
function Base.isone(