-
Notifications
You must be signed in to change notification settings - Fork 87
/
attributes.jl
1797 lines (1459 loc) · 58.7 KB
/
attributes.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
# Attributes
"""
AbstractOptimizerAttribute
Abstract supertype for attribute objects that can be used to set or get attributes (properties) of the optimizer.
### Note
The difference between `AbstractOptimizerAttribute` and `AbstractModelAttribute`
lies in the behavior of `is_empty`, `empty!` and `copy_to`. Typically optimizer
attributes only affect how the model is solved.
"""
abstract type AbstractOptimizerAttribute end
"""
AbstractModelAttribute
Abstract supertype for attribute objects that can be used to set or get attributes (properties) of the model.
"""
abstract type AbstractModelAttribute end
"""
AbstractVariableAttribute
Abstract supertype for attribute objects that can be used to set or get attributes (properties) of variables in the model.
"""
abstract type AbstractVariableAttribute end
"""
AbstractConstraintAttribute
Abstract supertype for attribute objects that can be used to set or get attributes (properties) of constraints in the model.
"""
abstract type AbstractConstraintAttribute end
# Attributes should not contain any `VariableIndex` or `ConstraintIndex` as the
# set is passed unmodifed during `copy_to`.
const AnyAttribute = Union{
AbstractOptimizerAttribute,
AbstractModelAttribute,
AbstractVariableAttribute,
AbstractConstraintAttribute,
}
# This allows to use attributes in broadcast calls without the need to
# embed it in a `Ref`
Base.broadcastable(attribute::AnyAttribute) = Ref(attribute)
"""
struct UnsupportedAttribute{AttrType} <: UnsupportedError
attr::AttrType
message::String
end
An error indicating that the attribute `attr` is not supported by the model,
i.e. that [`supports`](@ref) returns `false`.
"""
struct UnsupportedAttribute{AttrType<:AnyAttribute} <: UnsupportedError
attr::AttrType
message::String
end
UnsupportedAttribute(attr::AnyAttribute) = UnsupportedAttribute(attr, "")
element_name(err::UnsupportedAttribute) = "Attribute $(err.attr)"
"""
struct SetAttributeNotAllowed{AttrType} <: NotAllowedError
attr::AttrType
message::String # Human-friendly explanation why the attribute cannot be set
end
An error indicating that the attribute `attr` is supported (see
[`supports`](@ref)) but cannot be set for some reason (see the error string).
"""
struct SetAttributeNotAllowed{AttrType<:AnyAttribute} <: NotAllowedError
attr::AttrType
message::String # Human-friendly explanation why the attribute cannot be set
end
SetAttributeNotAllowed(attr::AnyAttribute) = SetAttributeNotAllowed(attr, "")
operation_name(err::SetAttributeNotAllowed) = "Setting attribute $(err.attr)"
message(err::SetAttributeNotAllowed) = err.message
"""
AbstractSubmittable
Abstract supertype for objects that can be submitted to the model.
"""
abstract type AbstractSubmittable end
# This allows to use submittable in broadcast calls without the need to embed
# it in a `Ref`.
Base.broadcastable(sub::AbstractSubmittable) = Ref(sub)
"""
struct UnsupportedSubmittable{SubmitType} <: UnsupportedError
sub::SubmitType
message::String
end
An error indicating that the submittable `sub` is not supported by the model,
i.e. that [`supports`](@ref) returns `false`.
"""
struct UnsupportedSubmittable{SubmitType<:AbstractSubmittable} <:
UnsupportedError
sub::SubmitType
message::String
end
"""
struct SubmitNotAllowed{SubmitTyp<:AbstractSubmittable} <: NotAllowedError
sub::SubmitType
message::String # Human-friendly explanation why the attribute cannot be set
end
An error indicating that the submittable `sub` is supported (see
[`supports`](@ref)) but cannot be added for some reason (see the error string).
"""
struct SubmitNotAllowed{SubmitType<:AbstractSubmittable} <: NotAllowedError
sub::SubmitType
message::String # Human-friendly explanation why the attribute cannot be set
end
SubmitNotAllowed(sub::AbstractSubmittable) = SubmitNotAllowed(sub, "")
operation_name(err::SubmitNotAllowed) = "Submitting $(err.sub)"
message(err::SubmitNotAllowed) = err.message
struct ResultIndexBoundsError{AttrType} <: Exception
attr::AttrType
result_count::Int
end
function check_result_index_bounds(model::ModelLike, attr)
result_count = get(model, ResultCount())
if !(1 <= attr.result_index <= result_count)
throw(ResultIndexBoundsError(attr, result_count))
end
end
function Base.showerror(io::IO, err::ResultIndexBoundsError)
return print(
io,
"Result index of attribute $(err.attr) out of bounds. There are " *
"currently $(err.result_count) solution(s) in the model.",
)
end
"""
supports(model::ModelLike, sub::AbstractSubmittable)::Bool
Return a `Bool` indicating whether `model` supports the submittable `sub`.
supports(model::ModelLike, attr::AbstractOptimizerAttribute)::Bool
Return a `Bool` indicating whether `model` supports the optimizer attribute
`attr`. That is, it returns `false` if `copy_to(model, src)` shows a warning in
case `attr` is in the [`ListOfOptimizerAttributesSet`](@ref) of `src`; see
[`copy_to`](@ref) for more details on how unsupported optimizer attributes are
handled in copy.
supports(model::ModelLike, attr::AbstractModelAttribute)::Bool
Return a `Bool` indicating whether `model` supports the model attribute `attr`.
That is, it returns `false` if `copy_to(model, src)` cannot be performed in case
`attr` is in the [`ListOfModelAttributesSet`](@ref) of `src`.
supports(model::ModelLike, attr::AbstractVariableAttribute, ::Type{VariableIndex})::Bool
Return a `Bool` indicating whether `model` supports the variable attribute
`attr`. That is, it returns `false` if `copy_to(model, src)` cannot be performed
in case `attr` is in the [`ListOfVariableAttributesSet`](@ref) of `src`.
supports(model::ModelLike, attr::AbstractConstraintAttribute, ::Type{ConstraintIndex{F,S}})::Bool where {F,S}
Return a `Bool` indicating whether `model` supports the constraint attribute
`attr` applied to an `F`-in-`S` constraint. That is, it returns `false` if
`copy_to(model, src)` cannot be performed in case `attr` is in the
[`ListOfConstraintAttributesSet`](@ref) of `src`.
For all five methods, if the attribute is only not supported in specific
circumstances, it should still return `true`.
Note that `supports` is only defined for attributes for which
[`is_copyable`](@ref) returns `true` as other attributes do not appear in the
list of attributes set obtained by `ListOf...AttributesSet`.
"""
function supports end
supports(::ModelLike, ::AbstractSubmittable) = false
function supports(model::ModelLike, attr::AnyAttribute, args...)
return supports_fallback(model, attr, args...)
end
function supports_fallback(
::ModelLike,
attr::Union{AbstractModelAttribute,AbstractOptimizerAttribute},
)
if !is_copyable(attr)
throw(
ArgumentError(
"`supports` is not defined for $attr, it is only" *
" defined for attributes such that `is_copyable`" *
" returns `true`.",
),
)
end
return false
end
function supports_fallback(
::ModelLike,
attr::Union{AbstractVariableAttribute,AbstractConstraintAttribute},
::Type{<:Index},
)
if !is_copyable(attr)
throw(
ArgumentError(
"`supports` is not defined for $attr, it is only" *
" defined for attributes such that `is_copyable`" *
" returns `true`.",
),
)
end
return false
end
"""
get(optimizer::AbstractOptimizer, attr::AbstractOptimizerAttribute)
Return an attribute `attr` of the optimizer `optimizer`.
get(model::ModelLike, attr::AbstractModelAttribute)
Return an attribute `attr` of the model `model`.
get(model::ModelLike, attr::AbstractVariableAttribute, v::VariableIndex)
If the attribute `attr` is set for the variable `v` in the model `model`, return
its value, return `nothing` otherwise. If the attribute `attr` is not supported
by `model` then an error should be thrown instead of returning `nothing`.
get(model::ModelLike, attr::AbstractVariableAttribute, v::Vector{VariableIndex})
Return a vector of attributes corresponding to each variable in the collection `v` in the model `model`.
get(model::ModelLike, attr::AbstractConstraintAttribute, c::ConstraintIndex)
If the attribute `attr` is set for the constraint `c` in the model `model`,
return its value, return `nothing` otherwise. If the attribute `attr` is not
supported by `model` then an error should be thrown instead of returning
`nothing`.
get(model::ModelLike, attr::AbstractConstraintAttribute, c::Vector{ConstraintIndex{F,S}})
Return a vector of attributes corresponding to each constraint in the collection `c` in the model `model`.
get(model::ModelLike, ::Type{VariableIndex}, name::String)
If a variable with name `name` exists in the model `model`, return the
corresponding index, otherwise return `nothing`. Errors if two variables
have the same name.
get(model::ModelLike, ::Type{ConstraintIndex{F,S}}, name::String) where {F<:AbstractFunction,S<:AbstractSet}
If an `F`-in-`S` constraint with name `name` exists in the model `model`, return
the corresponding index, otherwise return `nothing`. Errors if two constraints
have the same name.
get(model::ModelLike, ::Type{ConstraintIndex}, name::String)
If *any* constraint with name `name` exists in the model `model`, return the
corresponding index, otherwise return `nothing`. This version is available for
convenience but may incur a performance penalty because it is not type stable.
Errors if two constraints have the same name.
### Examples
```julia
get(model, ObjectiveValue())
get(model, VariablePrimal(), ref)
get(model, VariablePrimal(5), [ref1, ref2])
get(model, OtherAttribute("something specific to cplex"))
get(model, VariableIndex, "var1")
get(model, ConstraintIndex{ScalarAffineFunction{Float64},LessThan{Float64}}, "con1")
get(model, ConstraintIndex, "con1")
```
"""
function get end
# We want to avoid being too specific in the type arguments to avoid method ambiguity.
# For model, get(::ModelLike, ::AbstractVariableAttribute, ::Vector{VariableIndex}) would not allow
# to define get(::SomeModel, ::AnyAttribute, ::Vector)
function get(model::ModelLike, attr::AnyAttribute, idxs::Vector)
return get.(model, attr, idxs)
end
function get(model::ModelLike, attr::AnyAttribute, args...)
return get_fallback(model, attr, args...)
end
function get_fallback(
model::ModelLike,
attr::Union{AbstractModelAttribute,AbstractOptimizerAttribute},
)
return throw(
ArgumentError(
"$(typeof(model)) does not support getting the attribute $(attr).",
),
)
end
function get_fallback(
model::ModelLike,
attr::AbstractVariableAttribute,
::VariableIndex,
)
return throw(
ArgumentError(
"$(typeof(model)) does not support getting the attribute $(attr).",
),
)
end
function get_fallback(
model::ModelLike,
attr::AbstractConstraintAttribute,
::ConstraintIndex,
)
return throw(
ArgumentError(
"$(typeof(model)) does not support getting the attribute $(attr).",
),
)
end
function get_fallback(::ModelLike, attr::AnyAttribute, args...)
return throw(
ArgumentError(
"Unable to get attribute $(attr): invalid arguments $(args).",
),
)
end
"""
get!(output, model::ModelLike, args...)
An in-place version of [`get`](@ref).
The signature matches that of [`get`](@ref) except that the the result is placed
in the vector `output`.
"""
function get!(output, model::ModelLike, attr::AnyAttribute, args...)
output .= get(model, attr, args...)
return
end
"""
set(optimizer::AbstractOptimizer, attr::AbstractOptimizerAttribute, value)
Assign `value` to the attribute `attr` of the optimizer `optimizer`.
set(model::ModelLike, attr::AbstractModelAttribute, value)
Assign `value` to the attribute `attr` of the model `model`.
set(model::ModelLike, attr::AbstractVariableAttribute, v::VariableIndex, value)
Assign `value` to the attribute `attr` of variable `v` in model `model`.
set(model::ModelLike, attr::AbstractVariableAttribute, v::Vector{VariableIndex}, vector_of_values)
Assign a value respectively to the attribute `attr` of each variable in the collection `v` in model `model`.
set(model::ModelLike, attr::AbstractConstraintAttribute, c::ConstraintIndex, value)
Assign a value to the attribute `attr` of constraint `c` in model `model`.
set(model::ModelLike, attr::AbstractConstraintAttribute, c::Vector{ConstraintIndex{F,S}}, vector_of_values)
Assign a value respectively to the attribute `attr` of each constraint in the collection `c` in model `model`.
An [`UnsupportedAttribute`](@ref) error is thrown if `model` does not support
the attribute `attr` (see [`supports`](@ref)) and a [`SetAttributeNotAllowed`](@ref)
error is thrown if it supports the attribute `attr` but it cannot be set.
### Replace set in a constraint
set(model::ModelLike, ::ConstraintSet, c::ConstraintIndex{F,S}, set::S)
Change the set of constraint `c` to the new set `set` which should be of the
same type as the original set.
#### Examples
If `c` is a `ConstraintIndex{F,Interval}`
```julia
set(model, ConstraintSet(), c, Interval(0, 5))
set(model, ConstraintSet(), c, GreaterThan(0.0)) # Error
```
### Replace function in a constraint
set(model::ModelLike, ::ConstraintFunction, c::ConstraintIndex{F,S}, func::F)
Replace the function in constraint `c` with `func`. `F` must match the original
function type used to define the constraint.
#### Note
Setting the constraint function is not allowed if `F` is
[`SingleVariable`](@ref), it throws a
[`SettingSingleVariableFunctionNotAllowed`](@ref) error. Indeed, it would
require changing the index `c` as the index of `SingleVariable` constraints
should be the same as the index of the variable.
#### Examples
If `c` is a `ConstraintIndex{ScalarAffineFunction,S}` and `v1` and `v2` are
`VariableIndex` objects,
```julia
set(model, ConstraintFunction(), c,
ScalarAffineFunction(ScalarAffineTerm.([1.0, 2.0], [v1, v2]), 5.0))
set(model, ConstraintFunction(), c, SingleVariable(v1)) # Error
```
"""
function set end
# See note with get
function set(
model::ModelLike,
attr::Union{AbstractVariableAttribute,AbstractConstraintAttribute},
idxs::Vector,
vector_of_values::Vector,
)
if length(idxs) != length(vector_of_values)
throw(
DimensionMismatch(
"Number of indices ($(length(idxs))) does " *
"not match the number of values " *
"($(length(vector_of_values))) set to `$attr`.",
),
)
end
return set.(model, attr, idxs, vector_of_values)
end
function set(model::ModelLike, attr::AnyAttribute, args...)
return throw_set_error_fallback(model, attr, args...)
end
# throw_set_error_fallback is included so that we can return type-specific error
# messages without needing to overload set and cause ambiguity errors. For
# examples, see ConstraintSet and ConstraintFunction. throw_set_error_fallback should
# not be overloaded by users of MOI.
function throw_set_error_fallback(
model::ModelLike,
attr::Union{AbstractModelAttribute,AbstractOptimizerAttribute},
value;
error_if_supported = SetAttributeNotAllowed(attr),
)
if supports(model, attr)
throw(error_if_supported)
else
throw(UnsupportedAttribute(attr))
end
end
function throw_set_error_fallback(
model::ModelLike,
attr::Union{AbstractVariableAttribute,AbstractConstraintAttribute},
index::Index,
value;
error_if_supported = SetAttributeNotAllowed(attr),
)
if supports(model, attr, typeof(index))
throw(error_if_supported)
else
throw(UnsupportedAttribute(attr))
end
end
"""
SettingSingleVariableFunctionNotAllowed()
Error type that should be thrown when the user calls [`set`](@ref) to change
the [`ConstraintFunction`](@ref) of a [`SingleVariable`](@ref) constraint.
"""
struct SettingSingleVariableFunctionNotAllowed <: Exception end
"""
submit(optimizer::AbstractOptimizer, sub::AbstractSubmittable,
values...)::Nothing
Submit `values` to the submittable `sub` of the optimizer `optimizer`.
An [`UnsupportedSubmittable`](@ref) error is thrown if `model` does not support
the attribute `attr` (see [`supports`](@ref)) and a [`SubmitNotAllowed`](@ref)
error is thrown if it supports the submittable `sub` but it cannot be submitted.
""" # TODO add an example once we have an attribute which can be submitted, e.g. Lazy constraint
function submit end
function submit(model::ModelLike, sub::AbstractSubmittable, args...)
if supports(model, sub)
throw(
ArgumentError(
"Submitting $(typeof.(args)) for `$(typeof(sub))` is not valid.",
),
)
else
throw(
UnsupportedSubmittable(
sub,
"submit(::$(typeof(model)), ::$(typeof(sub))) is not supported.",
),
)
end
end
## Submittables
"""
LazyConstraint(callback_data)
Lazy constraint `func`-in-`set` submitted as `func, set`. The optimal
solution returned by [`VariablePrimal`](@ref) will satisfy all lazy
constraints that have been submitted.
This can be submitted only from the [`LazyConstraintCallback`](@ref). The
field `callback_data` is a solver-specific callback type that is passed as the
argument to the feasible solution callback.
## Examples
Suppose `fx = MOI.SingleVariable(x)` and `fx = MOI.SingleVariable(y)`
where `x` and `y` are [`VariableIndex`](@ref)s of `optimizer`. To add a
`LazyConstraint` for `2x + 3y <= 1`, write
```julia
func = 2.0fx + 3.0fy
set = MOI.LessThan(1.0)
MOI.submit(optimizer, MOI.LazyConstraint(callback_data), func, set)
```
inside a [`LazyConstraintCallback`](@ref) of data `callback_data`.
"""
struct LazyConstraint{CallbackDataType} <: AbstractSubmittable
callback_data::CallbackDataType
end
"""
HeuristicSolutionStatus
An Enum of possible return values for [`submit`](@ref) with
[`HeuristicSolution`](@ref).
This informs whether the heuristic solution was accepted or rejected.
Possible values are:
* `HEURISTIC_SOLUTION_ACCEPTED`: The heuristic solution was accepted.
* `HEURISTIC_SOLUTION_REJECTED`: The heuristic solution was rejected.
* `HEURISTIC_SOLUTION_UNKNOWN`: No information available on the acceptance.
"""
@enum(
HeuristicSolutionStatus,
HEURISTIC_SOLUTION_ACCEPTED,
HEURISTIC_SOLUTION_REJECTED,
HEURISTIC_SOLUTION_UNKNOWN
)
"""
HeuristicSolution(callback_data)
Heuristically obtained feasible solution. The solution is submitted as
`variables, values` where `values[i]` gives the value of `variables[i]`,
similarly to [`set`](@ref). The [`submit`](@ref) call returns a
[`HeuristicSolutionStatus`](@ref) indicating whether the provided solution
was accepted or rejected.
This can be submitted only from the [`HeuristicCallback`](@ref). The
field `callback_data` is a solver-specific callback type that is passed as the
argument to the heuristic callback.
Some solvers require a complete solution, others only partial solutions.
"""
struct HeuristicSolution{CallbackDataType} <: AbstractSubmittable
callback_data::CallbackDataType
end
"""
UserCut(callback_data)
Constraint `func`-to-`set` suggested to help the solver detect the solution
given by [`CallbackVariablePrimal`](@ref) as infeasible. The cut is submitted
as `func, set`.
Typically [`CallbackVariablePrimal`](@ref) will violate integrality constraints,
and a cut would be of the form [`ScalarAffineFunction`](@ref)-in-[`LessThan`](@ref)
or [`ScalarAffineFunction`](@ref)-in-[`GreaterThan`](@ref). Note that, as
opposed to [`LazyConstraint`](@ref), the provided constraint cannot modify the
feasible set, the constraint should be redundant, e.g., it may be a consequence
of affine and integrality constraints.
This can be submitted only from the [`UserCutCallback`](@ref). The
field `callback_data` is a solver-specific callback type that is passed as the
argument to the infeasible solution callback.
Note that the solver may silently ignore the provided constraint.
"""
struct UserCut{CallbackDataType} <: AbstractSubmittable
callback_data::CallbackDataType
end
"""
struct InvalidCallbackUsage{C, S} <: Exception
callback::C
submittable::S
end
An error indicating that `submittable` cannot be submitted inside `callback`.
For example, [`UserCut`](@ref) cannot be submitted inside
[`LazyConstraintCallback`](@ref).
"""
struct InvalidCallbackUsage{C,S} <: Exception
callback::C
submittable::S
end
function Base.showerror(io::IO, err::InvalidCallbackUsage)
return print(
io,
"InvalidCallbackUsage: Cannot submit $(err.submittable) inside a $(err.callback).",
)
end
"""
CallbackNodeStatusCode
An Enum of possible return values from calling [`get`](@ref) with
[`CallbackNodeStatus`](@ref).
Possible values are:
* `CALLBACK_NODE_STATUS_INTEGER`: the primal solution available from
[`CallbackVariablePrimal`](@ref) is integer feasible.
* `CALLBACK_NODE_STATUS_FRACTIONAL`: the primal solution available from
[`CallbackVariablePrimal`](@ref) is integer infeasible.
* `CALLBACK_NODE_STATUS_UNKNOWN`: the primal solution available from
[`CallbackVariablePrimal`](@ref) might be integer feasible or infeasible.
"""
@enum(
CallbackNodeStatusCode,
CALLBACK_NODE_STATUS_INTEGER,
CALLBACK_NODE_STATUS_FRACTIONAL,
CALLBACK_NODE_STATUS_UNKNOWN,
)
"""
CallbackNodeStatus(callback_data)
An optimizer attribute describing the (in)feasibility of the primal solution
available from [`CallbackVariablePrimal`](@ref) during a callback identified by
`callback_data`.
Returns a [`CallbackNodeStatusCode`](@ref) Enum.
"""
struct CallbackNodeStatus{CallbackDataType} <: AbstractOptimizerAttribute
callback_data::CallbackDataType
end
is_set_by_optimize(::CallbackNodeStatus) = true
## Optimizer attributes
"""
ListOfOptimizerAttributesSet()
An optimizer attribute for the `Vector{AbstractOptimizerAttribute}` of all optimizer attributes that were set.
"""
struct ListOfOptimizerAttributesSet <: AbstractOptimizerAttribute end
"""
SolverName()
An optimizer attribute for the string identifying the solver/optimizer.
"""
struct SolverName <: AbstractOptimizerAttribute end
"""
Silent()
An optimizer attribute for silencing the output of an optimizer. When `set`
to `true`, it takes precedence over any other attribute controlling verbosity
and requires the solver to produce no output. The default value is `false`
which has no effect. In this case the verbosity is controlled by other
attributes.
## Note
Every optimizer should have verbosity on by default. For instance, if a solver
has a solver-specific log level attribute, the MOI implementation should set it
to `1` by default. If the user sets `Silent` to `true`, then the log level
should be set to `0`, even if the user specifically sets a value of log level.
If the value of `Silent` is `false` then the log level set to the solver is the
value given by the user for this solver-specific parameter or `1` if none is
given.
"""
struct Silent <: AbstractOptimizerAttribute end
"""
TimeLimitSec()
An optimizer attribute for setting a time limit for an optimization. When `set`
to `nothing`, it deactivates the solver time limit. The default value is
`nothing`. The time limit is in seconds.
""" # TODO add a test checking if the solver returns TIME_LIMIT status when the time limit is hit
struct TimeLimitSec <: AbstractOptimizerAttribute end
"""
RawOptimizerAttribute(name::String)
An optimizer attribute for the solver-specific parameter identified by `name`.
"""
struct RawOptimizerAttribute <: AbstractOptimizerAttribute
name::String
end
"""
NumberOfThreads()
An optimizer attribute for setting the number of threads used for an
optimization. When set to `nothing` uses solver default. Values are positive
integers. The default value is `nothing`.
"""
struct NumberOfThreads <: AbstractOptimizerAttribute end
### Callbacks
"""
struct OptimizeInProgress{AttrType<:AnyAttribute} <: Exception
attr::AttrType
end
Error thrown from optimizer when `MOI.get(optimizer, attr)` is called inside an
[`AbstractCallback`](@ref) while it is only defined once [`optimize!`](@ref) has
completed. This can only happen when `is_set_by_optimize(attr)` is `true`.
"""
struct OptimizeInProgress{AttrType<:AnyAttribute} <: Exception
attr::AttrType
end
function Base.showerror(io::IO, err::OptimizeInProgress)
return print(
io,
typeof(err),
": Cannot get result as the `MOI.optimize!` has not",
" finished.",
)
end
"""
abstract type AbstractCallback <: AbstractModelAttribute end
Abstract type for a model attribute representing a callback function. The
value set to subtypes of `AbstractCallback` is a function that may be called
during [`optimize!`](@ref). As [`optimize!`](@ref) is in progress, the result
attributes (i.e, the attributes `attr` such that `is_set_by_optimize(attr)`)
may not be accessible from the callback, hence trying to get result attributes
might throw a [`OptimizeInProgress`](@ref) error.
At most one callback of each type can be registered. If an optimizer already
has a function for a callback type, and the user registers a new function,
then the old one is replaced.
The value of the attribute should be a function taking only one argument,
commonly called `callback_data`, that can be used for instance in
[`LazyConstraintCallback`](@ref), [`HeuristicCallback`](@ref) and
[`UserCutCallback`](@ref).
"""
abstract type AbstractCallback <: AbstractModelAttribute end
"""
LazyConstraintCallback() <: AbstractCallback
The callback can be used to reduce the feasible set given the current primal
solution by submitting a [`LazyConstraint`](@ref). For instance, it may be
called at an incumbent of a mixed-integer problem. Note that there is no
guarantee that the callback is called at *every* feasible primal solution.
The current primal solution is accessed through
[`CallbackVariablePrimal`](@ref). Trying to access other result
attributes will throw [`OptimizeInProgress`](@ref) as discussed in
[`AbstractCallback`](@ref).
## Examples
```julia
x = MOI.add_variables(optimizer, 8)
MOI.set(optimizer, MOI.LazyConstraintCallback(), callback_data -> begin
sol = MOI.get(optimizer, MOI.CallbackVariablePrimal(callback_data), x)
if # should add a lazy constraint
func = # computes function
set = # computes set
MOI.submit(optimizer, MOI.LazyConstraint(callback_data), func, set)
end
end)
```
"""
struct LazyConstraintCallback <: AbstractCallback end
"""
HeuristicCallback() <: AbstractCallback
The callback can be used to submit [`HeuristicSolution`](@ref) given the
current primal solution.
For instance, it may be called at fractional (i.e., non-integer) nodes in the
branch and bound tree of a mixed-integer problem. Note that there is not
guarantee that the callback is called *everytime* the solver has an infeasible
solution.
The current primal solution is accessed through
[`CallbackVariablePrimal`](@ref). Trying to access other result
attributes will throw [`OptimizeInProgress`](@ref) as discussed in
[`AbstractCallback`](@ref).
## Examples
```julia
x = MOI.add_variables(optimizer, 8)
MOI.set(optimizer, MOI.HeuristicCallback(), callback_data -> begin
sol = MOI.get(optimizer, MOI.CallbackVariablePrimal(callback_data), x)
if # can find a heuristic solution
values = # computes heuristic solution
MOI.submit(optimizer, MOI.HeuristicSolution(callback_data), x,
values)
end
end
```
"""
struct HeuristicCallback <: AbstractCallback end
"""
UserCutCallback() <: AbstractCallback
The callback can be used to submit [`UserCut`](@ref) given the current primal
solution. For instance, it may be called at fractional (i.e., non-integer) nodes
in the branch and bound tree of a mixed-integer problem. Note that there is not
guarantee that the callback is called *everytime* the solver has an infeasible
solution.
The infeasible solution is accessed through
[`CallbackVariablePrimal`](@ref). Trying to access other result
attributes will throw [`OptimizeInProgress`](@ref) as discussed in
[`AbstractCallback`](@ref).
## Examples
```julia
x = MOI.add_variables(optimizer, 8)
MOI.set(optimizer, MOI.UserCutCallback(), callback_data -> begin
sol = MOI.get(optimizer, MOI.CallbackVariablePrimal(callback_data), x)
if # can find a user cut
func = # computes function
set = # computes set
MOI.submit(optimizer, MOI.UserCut(callback_data), func, set)
end
end
```
"""
struct UserCutCallback <: AbstractCallback end
## Model attributes
"""
ListOfModelAttributesSet()
A model attribute for the `Vector{AbstractModelAttribute}` of all model
attributes `attr` such that 1) `is_copyable(attr)` returns `true` and 2) the
attribute was set to the model.
"""
struct ListOfModelAttributesSet <: AbstractModelAttribute end
"""
Name()
A model attribute for the string identifying the model. It has a default value
of `""` if not set`.
"""
struct Name <: AbstractModelAttribute end
"""
ObjectiveSense()
A model attribute for the objective sense of the objective function, which
must be an `OptimizationSense`: `MIN_SENSE`, `MAX_SENSE`, or
`FEASIBILITY_SENSE`. The default is `FEASIBILITY_SENSE`.
"""
struct ObjectiveSense <: AbstractModelAttribute end
@enum OptimizationSense MIN_SENSE MAX_SENSE FEASIBILITY_SENSE
"""
NumberOfVariables()
A model attribute for the number of variables in the model.
"""
struct NumberOfVariables <: AbstractModelAttribute end
"""
ListOfVariableIndices()
A model attribute for the `Vector{VariableIndex}` of all variable indices present in the model
(i.e., of length equal to the value of `NumberOfVariables()`) in the order in
which they were added.
"""
struct ListOfVariableIndices <: AbstractModelAttribute end
"""
ListOfConstraintIndices{F,S}()
A model attribute for the `Vector{ConstraintIndex{F,S}}` of all constraint indices of type
`F`-in-`S` in the model (i.e., of length equal to the value of
`NumberOfConstraints{F,S}()`) in the order in which they were added.
"""
struct ListOfConstraintIndices{F,S} <: AbstractModelAttribute end
"""
NumberOfConstraints{F,S}()
A model attribute for the number of constraints of the type `F`-in-`S` present in the model.
"""
struct NumberOfConstraints{F,S} <: AbstractModelAttribute end
"""
ListOfConstraintTypesPresent()
A model attribute for the list of tuples of the form `(F,S)`, where `F` is a function type
and `S` is a set type indicating that the attribute `NumberOfConstraints{F,S}()`
has value greater than zero.
"""
struct ListOfConstraintTypesPresent <: AbstractModelAttribute end
@deprecate ListOfConstraints ListOfConstraintTypesPresent
"""
ObjectiveFunction{F<:AbstractScalarFunction}()
A model attribute for the objective function which has a type `F<:AbstractScalarFunction`.
`F` should be guaranteed to be equivalent but not necessarily identical to the function type provided by the user.
Throws an `InexactError` if the objective function cannot be converted to `F`,
e.g. the objective function is quadratic and `F` is `ScalarAffineFunction{Float64}` or
it has non-integer coefficient and `F` is `ScalarAffineFunction{Int}`.
"""
struct ObjectiveFunction{F<:AbstractScalarFunction} <: AbstractModelAttribute end
"""
ObjectiveFunctionType()
A model attribute for the type `F` of the objective function set using the
`ObjectiveFunction{F}` attribute.
## Examples
In the following code, `attr` should be equal to `MOI.SingleVariable`:
```julia
x = MOI.add_variable(model)
MOI.set(model, MOI.ObjectiveFunction{MOI.SingleVariable}(),
MOI.SingleVariable(x))
attr = MOI.get(model, MOI.ObjectiveFunctionType())
```
"""
struct ObjectiveFunctionType <: AbstractModelAttribute end
## Optimizer attributes
"""
ObjectiveValue(result_index::Int = 1)
A model attribute for the objective value of the primal solution `result_index`.
See [`ResultCount`](@ref) for information on how the results are ordered.
"""
struct ObjectiveValue <: AbstractModelAttribute
result_index::Int
ObjectiveValue(result_index::Int = 1) = new(result_index)
end
"""
DualObjectiveValue(result_index::Int = 1)
A model attribute for the value of the objective function of the dual problem
for the `result_index`th dual result.
See [`ResultCount`](@ref) for information on how the results are ordered.
"""
struct DualObjectiveValue <: AbstractModelAttribute
result_index::Int
DualObjectiveValue(result_index::Int = 1) = new(result_index)
end
"""
ObjectiveBound()
A model attribute for the best known bound on the optimal objective value.
"""
struct ObjectiveBound <: AbstractModelAttribute end
"""
RelativeGap()
A model attribute for the final relative optimality gap, defined as ``\\frac{|b-f|}{|f|}``, where ``b`` is the best bound and ``f`` is the best feasible objective value.