forked from jump-dev/Gurobi.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MOI_wrapper.jl
3206 lines (2911 loc) · 107 KB
/
MOI_wrapper.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
import MathOptInterface
const MOI = MathOptInterface
const CleverDicts = MOI.Utilities.CleverDicts
@enum(VariableType, CONTINUOUS, BINARY, INTEGER, SEMIINTEGER, SEMICONTINUOUS)
@enum(BoundType, NONE, LESS_THAN, GREATER_THAN, LESS_AND_GREATER_THAN, INTERVAL, EQUAL_TO)
@enum(ObjectiveType, SINGLE_VARIABLE, SCALAR_AFFINE, SCALAR_QUADRATIC)
@enum(CallbackState, CB_NONE, CB_GENERIC, CB_LAZY, CB_USER_CUT, CB_HEURISTIC)
const SCALAR_SETS = Union{
MOI.GreaterThan{Float64}, MOI.LessThan{Float64},
MOI.EqualTo{Float64}, MOI.Interval{Float64}
}
mutable struct VariableInfo
index::MOI.VariableIndex
column::Int
bound::BoundType
# Both fields below are cached values to avoid triggering a model_update!
# if the variable bounds are queried. They are non-NaN only if `bound` is
# different from NONE. EQUAL_TO sets both of them. See also
# `lower_bound_if_soc`.
lower_bound_if_bounded::Float64
upper_bound_if_bounded::Float64
type::VariableType
start::Union{Float64, Nothing}
name::String
# Storage for constraint names associated with variables because Gurobi
# can only store names for variables and proper constraints.
# We can perform an optimization and only store three strings for the
# constraint names because, at most, there can be three SingleVariable
# constraints, e.g., LessThan, GreaterThan, and Integer.
lessthan_name::String
greaterthan_interval_or_equalto_name::String
type_constraint_name::String
# Storage for the lower bound if the variable is the `t` variable in a
# second order cone. Theoretically, if both `lower_bound_if_bounded` and
# `lower_bound_if_soc` are non-NaN, then they have the same value,
# but you can also just have SOC constraints, or just have bounds, or
# have a bound and have a SOC constraint that does not need to set
# `lower_bound_if_soc` (in all such cases just one of them is NaN).
lower_bound_if_soc::Float64
num_soc_constraints::Int
function VariableInfo(index::MOI.VariableIndex, column::Int)
return new(index, column, NONE, NaN, NaN, CONTINUOUS, nothing, "", "", "", "", NaN, 0)
end
end
mutable struct ConstraintInfo
row::Int
set::MOI.AbstractSet
# Storage for constraint names. Where possible, these are also stored in the
# Gurobi model.
name::String
ConstraintInfo(row::Int, set) = new(row, set, "")
end
mutable struct Optimizer <: MOI.AbstractOptimizer
# The low-level Gurobi model.
inner::Model
# The Gurobi environment. If `nothing`, a new environment will be created
# on `MOI.empty!`.
env::Union{Nothing, Env}
# The current user-provided parameters for the model.
params::Dict{String, Any}
# The next field is used to cleverly manage calls to `update_model!`.
# `needs_update` is used to record whether an update should be called before
# accessing a model attribute (such as the value of a RHS term).
needs_update::Bool
# A flag to keep track of MOI.Silent, which over-rides the OutputFlag
# parameter.
silent::Bool
# An enum to remember what objective is currently stored in the model.
objective_type::ObjectiveType
# A flag to keep track of MOI.FEASIBILITY_SENSE, since Gurobi only stores
# MIN_SENSE or MAX_SENSE. This allows us to differentiate between MIN_SENSE
# and FEASIBILITY_SENSE.
is_feasibility::Bool
# A mapping from the MOI.VariableIndex to the Gurobi column. VariableInfo
# also stores some additional fields like what bounds have been added, the
# variable type, and the names of SingleVariable-in-Set constraints.
variable_info::CleverDicts.CleverDict{MOI.VariableIndex, VariableInfo}
# An index that is incremented for each new constraint (regardless of type).
# We can check if a constraint is valid by checking if it is in the correct
# xxx_constraint_info. We should _not_ reset this to zero, since then new
# constraints cannot be distinguished from previously created ones.
last_constraint_index::Int
# ScalarAffineFunction{Float64}-in-Set storage.
affine_constraint_info::Dict{Int, ConstraintInfo}
# ScalarQuadraticFunction{Float64}-in-Set storage.
quadratic_constraint_info::Dict{Int, ConstraintInfo}
# VectorOfVariables-in-Set storage.
sos_constraint_info::Dict{Int, ConstraintInfo}
# Note: we do not have a singlevariable_constraint_info dictionary. Instead,
# data associated with these constraints are stored in the VariableInfo
# objects.
# Mappings from variable and constraint names to their indices. These are
# lazily built on-demand, so most of the time, they are `nothing`.
name_to_variable::Union{Nothing, Dict{String, Union{Nothing, MOI.VariableIndex}}}
name_to_constraint_index::Union{Nothing, Dict{String, Union{Nothing, MOI.ConstraintIndex}}}
# These two flags allow us to distinguish between FEASIBLE_POINT and
# INFEASIBILITY_CERTIFICATE when querying VariablePrimal and ConstraintDual.
has_unbounded_ray::Bool
has_infeasibility_cert::Bool
# Callback fields.
callback_variable_primal::Vector{Float64}
has_generic_callback::Bool
callback_state::CallbackState
lazy_callback::Union{Nothing, Function}
user_cut_callback::Union{Nothing, Function}
heuristic_callback::Union{Nothing, Function}
"""
Optimizer(env = nothing; kwargs...)
Create a new Optimizer object.
You can share Gurobi `Env`s between models by passing an instance of `Env`
as the first argument. By default, a new environment is created for every
model.
"""
function Optimizer(env::Union{Nothing, Env} = nothing; kwargs...)
model = new()
model.env = env
model.silent = false
model.params = Dict{String, Any}()
model.variable_info = CleverDicts.CleverDict{MOI.VariableIndex, VariableInfo}()
model.affine_constraint_info = Dict{Int, ConstraintInfo}()
model.quadratic_constraint_info = Dict{Int, ConstraintInfo}()
model.sos_constraint_info = Dict{Int, ConstraintInfo}()
model.callback_variable_primal = Float64[]
MOI.empty!(model) # MOI.empty!(model) re-sets the `.inner` field.
for (name, value) in kwargs
model.params[string(name)] = value
setparam!(model.inner, string(name), value)
end
return model
end
end
Base.show(io::IO, model::Optimizer) = show(io, model.inner)
function MOI.empty!(model::Optimizer)
if model.env === nothing
model.inner = Model(Env(), "", finalize_env = true)
else
model.inner = Model(model.env, "", finalize_env = false)
end
for (name, value) in model.params
setparam!(model.inner, name, value)
end
if model.silent
# Set the parameter on the internal model, but don't modify the entry in
# model.params so that if Silent() is set to `true`, the user-provided
# value will be restored.
setparam!(model.inner, "OutputFlag", 0)
end
model.needs_update = false
model.objective_type = SCALAR_AFFINE
model.is_feasibility = true
empty!(model.variable_info)
empty!(model.affine_constraint_info)
empty!(model.quadratic_constraint_info)
empty!(model.sos_constraint_info)
model.name_to_variable = nothing
model.name_to_constraint_index = nothing
model.has_unbounded_ray = false
model.has_infeasibility_cert = false
empty!(model.callback_variable_primal)
model.callback_state = CB_NONE
model.has_generic_callback = false
model.lazy_callback = nothing
model.user_cut_callback = nothing
model.heuristic_callback = nothing
return
end
function MOI.is_empty(model::Optimizer)
model.needs_update && return false
model.objective_type != SCALAR_AFFINE && return false
model.is_feasibility == false && return false
!isempty(model.variable_info) && return false
length(model.affine_constraint_info) != 0 && return false
length(model.quadratic_constraint_info) != 0 && return false
length(model.sos_constraint_info) != 0 && return false
model.name_to_variable !== nothing && return false
model.name_to_constraint_index !== nothing && return false
model.has_unbounded_ray && return false
model.has_infeasibility_cert && return false
length(model.callback_variable_primal) != 0 && return false
model.callback_state != CB_NONE && return false
model.has_generic_callback && return false
model.lazy_callback !== nothing && return false
model.user_cut_callback !== nothing && return false
model.heuristic_callback !== nothing && return false
return true
end
"""
_require_update(model::Optimizer)
Sets the `model.needs_update` flag. Call this at the end of any mutating method.
"""
function _require_update(model::Optimizer)
model.needs_update = true
return
end
"""
_update_if_necessary(model::Optimizer)
Calls `update_model!`, but only if the `model.needs_update` flag is set.
"""
function _update_if_necessary(model::Optimizer)
if model.needs_update
update_model!(model.inner)
model.needs_update = false
end
return
end
MOI.get(::Optimizer, ::MOI.SolverName) = "Gurobi"
function MOI.supports(
::Optimizer,
::MOI.ObjectiveFunction{F}
) where {F <: Union{
MOI.SingleVariable,
MOI.ScalarAffineFunction{Float64},
MOI.ScalarQuadraticFunction{Float64}
}}
return true
end
function MOI.supports_constraint(
::Optimizer, ::Type{MOI.SingleVariable}, ::Type{F}
) where {F <: Union{
MOI.EqualTo{Float64}, MOI.LessThan{Float64}, MOI.GreaterThan{Float64},
MOI.Interval{Float64}, MOI.ZeroOne, MOI.Integer,
MOI.Semicontinuous{Float64}, MOI.Semiinteger{Float64}
}}
return true
end
function MOI.supports_constraint(
::Optimizer, ::Type{MOI.VectorOfVariables}, ::Type{F}
) where {F <: Union{MOI.SOS1{Float64}, MOI.SOS2{Float64}, MOI.SecondOrderCone}}
return true
end
# We choose _not_ to support ScalarAffineFunction-in-Interval and
# ScalarQuadraticFunction-in-Interval because Gurobi introduces some slack
# variables that makes it hard to keep track of the column indices.
function MOI.supports_constraint(
::Optimizer, ::Type{MOI.ScalarAffineFunction{Float64}}, ::Type{F}
) where {F <: Union{
MOI.EqualTo{Float64}, MOI.LessThan{Float64}, MOI.GreaterThan{Float64}
}}
return true
end
function MOI.supports_constraint(
::Optimizer, ::Type{MOI.ScalarQuadraticFunction{Float64}}, ::Type{F}
) where {F <: Union{
MOI.EqualTo{Float64}, MOI.LessThan{Float64}, MOI.GreaterThan{Float64}
}}
return true
end
MOI.supports(::Optimizer, ::MOI.VariableName, ::Type{MOI.VariableIndex}) = true
MOI.supports(::Optimizer, ::MOI.ConstraintName, ::Type{<:MOI.ConstraintIndex}) = true
MOI.supports(::Optimizer, ::MOI.Name) = true
MOI.supports(::Optimizer, ::MOI.Silent) = true
MOI.supports(::Optimizer, ::MOI.TimeLimitSec) = true
MOI.supports(::Optimizer, ::MOI.ObjectiveSense) = true
MOI.supports(::Optimizer, ::MOI.RawParameter) = true
MOI.supports(::Optimizer, ::MOI.ConstraintPrimalStart) = false
MOI.supports(::Optimizer, ::MOI.ConstraintDualStart) = false
function MOI.set(model::Optimizer, param::MOI.RawParameter, value)
model.params[param.name] = value
setparam!(model.inner, param.name, value)
return
end
function MOI.get(model::Optimizer, param::MOI.RawParameter)
return getparam(model.inner, param.name)
end
function MOI.set(model::Optimizer, ::MOI.TimeLimitSec, limit::Real)
MOI.set(model, MOI.RawParameter("TimeLimit"), limit)
return
end
function MOI.get(model::Optimizer, ::MOI.TimeLimitSec)
return MOI.get(model, MOI.RawParameter("TimeLimit"))
end
MOI.Utilities.supports_default_copy_to(::Optimizer, ::Bool) = true
function MOI.copy_to(dest::Optimizer, src::MOI.ModelLike; kwargs...)
return MOI.Utilities.automatic_copy_to(dest, src; kwargs...)
end
function MOI.get(model::Optimizer, ::MOI.ListOfVariableAttributesSet)
return MOI.AbstractVariableAttribute[MOI.VariableName()]
end
function MOI.get(model::Optimizer, ::MOI.ListOfModelAttributesSet)
attributes = Any[MOI.ObjectiveSense()]
typ = MOI.get(model, MOI.ObjectiveFunctionType())
if typ !== nothing
push!(attributes, MOI.ObjectiveFunction{typ}())
end
if MOI.get(model, MOI.Name()) != ""
push!(attributes, MOI.Name())
end
return attributes
end
function MOI.get(model::Optimizer, ::MOI.ListOfConstraintAttributesSet)
return MOI.AbstractConstraintAttribute[MOI.ConstraintName()]
end
function _indices_and_coefficients(
indices::AbstractVector{Int}, coefficients::AbstractVector{Float64},
model::Optimizer, f::MOI.ScalarAffineFunction{Float64}
)
i = 1
for term in f.terms
indices[i] = _info(model, term.variable_index).column
coefficients[i] = term.coefficient
i += 1
end
return indices, coefficients
end
function _indices_and_coefficients(
model::Optimizer, f::MOI.ScalarAffineFunction{Float64}
)
f_canon = MOI.Utilities.canonical(f)
nnz = length(f_canon.terms)
indices = Vector{Int}(undef, nnz)
coefficients = Vector{Float64}(undef, nnz)
_indices_and_coefficients(indices, coefficients, model, f_canon)
return indices, coefficients
end
function _indices_and_coefficients(
I::AbstractVector{Int}, J::AbstractVector{Int}, V::AbstractVector{Float64},
indices::AbstractVector{Int}, coefficients::AbstractVector{Float64},
model::Optimizer, f::MOI.ScalarQuadraticFunction
)
for (i, term) in enumerate(f.quadratic_terms)
I[i] = _info(model, term.variable_index_1).column
J[i] = _info(model, term.variable_index_2).column
V[i] = term.coefficient
# Gurobi returns a list of terms. MOI requires 0.5 x' Q x. So, to get
# from
# Gurobi -> MOI => multiply diagonals by 2.0
# MOI -> Gurobi => multiply diagonals by 0.5
# Example: 2x^2 + x*y + y^2
# |x y| * |a b| * |x| = |ax+by bx+cy| * |x| = 0.5ax^2 + bxy + 0.5cy^2
# |b c| |y| |y|
# Gurobi needs: (I, J, V) = ([0, 0, 1], [0, 1, 1], [2, 1, 1])
# MOI needs:
# [SQT(4.0, x, x), SQT(1.0, x, y), SQT(2.0, y, y)]
if I[i] == J[i]
V[i] *= 0.5
end
end
for (i, term) in enumerate(f.affine_terms)
indices[i] = _info(model, term.variable_index).column
coefficients[i] = term.coefficient
end
return
end
function _indices_and_coefficients(
model::Optimizer, f::MOI.ScalarQuadraticFunction
)
f_canon = MOI.Utilities.canonical(f)
nnz_quadratic = length(f_canon.quadratic_terms)
nnz_affine = length(f_canon.affine_terms)
I = Vector{Int}(undef, nnz_quadratic)
J = Vector{Int}(undef, nnz_quadratic)
V = Vector{Float64}(undef, nnz_quadratic)
indices = Vector{Int}(undef, nnz_affine)
coefficients = Vector{Float64}(undef, nnz_affine)
_indices_and_coefficients(I, J, V, indices, coefficients, model, f_canon)
return indices, coefficients, I, J, V
end
_sense_and_rhs(s::MOI.LessThan{Float64}) = (Cchar('<'), s.upper)
_sense_and_rhs(s::MOI.GreaterThan{Float64}) = (Cchar('>'), s.lower)
_sense_and_rhs(s::MOI.EqualTo{Float64}) = (Cchar('='), s.value)
###
### Variables
###
# Short-cuts to return the VariableInfo associated with an index.
function _info(model::Optimizer, key::MOI.VariableIndex)
if haskey(model.variable_info, key)
return model.variable_info[key]
end
throw(MOI.InvalidIndex(key))
end
function MOI.add_variable(model::Optimizer)
# Initialize `VariableInfo` with a dummy `VariableIndex` and a column,
# because we need `add_item` to tell us what the `VariableIndex` is.
index = CleverDicts.add_item(
model.variable_info, VariableInfo(MOI.VariableIndex(0), 0)
)
info = _info(model, index)
# Now, set `.index` and `.column`.
info.index = index
info.column = length(model.variable_info)
add_cvar!(model.inner, 0.0)
_require_update(model)
return index
end
function MOI.add_variables(model::Optimizer, N::Int)
add_cvars!(model.inner, zeros(N))
_require_update(model)
indices = Vector{MOI.VariableIndex}(undef, N)
num_variables = length(model.variable_info)
for i in 1:N
# Initialize `VariableInfo` with a dummy `VariableIndex` and a column,
# because we need `add_item` to tell us what the `VariableIndex` is.
index = CleverDicts.add_item(
model.variable_info, VariableInfo(MOI.VariableIndex(0), 0)
)
info = _info(model, index)
# Now, set `.index` and `.column`.
info.index = index
info.column = num_variables + i
indices[i] = index
end
return indices
end
function MOI.is_valid(model::Optimizer, v::MOI.VariableIndex)
return haskey(model.variable_info, v)
end
function MOI.delete(model::Optimizer, indices::Vector{<:MOI.VariableIndex})
_update_if_necessary(model)
info = [_info(model, var_idx) for var_idx in indices]
soc_idx = findfirst(e -> e.num_soc_constraints > 0, info)
soc_idx !== nothing && throw(MOI.DeleteNotAllowed(indices[soc_idx]))
sorted_del_cols = sort!(collect(i.column for i in info))
del_vars!(model.inner, convert(Vector{Cint}, sorted_del_cols))
_require_update(model)
for var_idx in indices
delete!(model.variable_info, var_idx)
end
for other_info in values(model.variable_info)
other_info.column -= searchsortedlast(
sorted_del_cols, other_info.column
)
end
model.name_to_variable = nothing
# We throw away name_to_constraint_index so we will rebuild SingleVariable
# constraint names without v.
model.name_to_constraint_index = nothing
return
end
function MOI.delete(model::Optimizer, v::MOI.VariableIndex)
_update_if_necessary(model)
info = _info(model, v)
if info.num_soc_constraints > 0
throw(MOI.DeleteNotAllowed(v))
end
del_vars!(model.inner, Cint[info.column])
_require_update(model)
delete!(model.variable_info, v)
for other_info in values(model.variable_info)
if other_info.column > info.column
other_info.column -= 1
end
end
model.name_to_variable = nothing
# We throw away name_to_constraint_index so we will rebuild SingleVariable
# constraint names without v.
model.name_to_constraint_index = nothing
return
end
function MOI.get(model::Optimizer, ::Type{MOI.VariableIndex}, name::String)
if model.name_to_variable === nothing
_rebuild_name_to_variable(model)
end
if haskey(model.name_to_variable, name)
variable = model.name_to_variable[name]
if variable === nothing
error("Duplicate variable name detected: $(name)")
end
return variable
end
return nothing
end
function _rebuild_name_to_variable(model::Optimizer)
model.name_to_variable = Dict{String, Union{Nothing, MOI.VariableIndex}}()
for (index, info) in model.variable_info
if info.name == ""
continue
end
if haskey(model.name_to_variable, info.name)
model.name_to_variable[info.name] = nothing
else
model.name_to_variable[info.name] = index
end
end
return
end
function MOI.get(model::Optimizer, ::MOI.VariableName, v::MOI.VariableIndex)
return _info(model, v).name
end
function MOI.set(
model::Optimizer, ::MOI.VariableName, v::MOI.VariableIndex, name::String
)
info = _info(model, v)
info.name = name
set_strattrelement!(model.inner, "VarName", info.column, name)
_require_update(model)
model.name_to_variable = nothing
return
end
###
### Objectives
###
function _zero_objective(model::Optimizer)
num_vars = length(model.variable_info)
obj = zeros(Float64, num_vars)
_update_if_necessary(model)
delq!(model.inner)
set_dblattrarray!(model.inner, "Obj", 1, num_vars, obj)
set_dblattr!(model.inner, "ObjCon", 0.0)
_require_update(model)
end
function MOI.set(
model::Optimizer, ::MOI.ObjectiveSense, sense::MOI.OptimizationSense
)
if sense == MOI.MIN_SENSE
set_sense!(model.inner, :minimize)
model.is_feasibility = false
elseif sense == MOI.MAX_SENSE
set_sense!(model.inner, :maximize)
model.is_feasibility = false
elseif sense == MOI.FEASIBILITY_SENSE
_zero_objective(model)
set_sense!(model.inner, :minimize)
model.is_feasibility = true
else
error("Invalid objective sense: $(sense)")
end
_require_update(model)
return
end
function MOI.get(model::Optimizer, ::MOI.ObjectiveSense)
_update_if_necessary(model)
sense = model_sense(model.inner)
if model.is_feasibility
return MOI.FEASIBILITY_SENSE
elseif sense == :maximize
return MOI.MAX_SENSE
elseif sense == :minimize
return MOI.MIN_SENSE
end
error("Invalid objective sense: $(sense)")
end
function MOI.set(
model::Optimizer, ::MOI.ObjectiveFunction{F}, f::F
) where {F <: MOI.SingleVariable}
MOI.set(
model, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(),
convert(MOI.ScalarAffineFunction{Float64}, f)
)
model.objective_type = SINGLE_VARIABLE
return
end
function MOI.get(model::Optimizer, ::MOI.ObjectiveFunction{MOI.SingleVariable})
obj = MOI.get(model, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}())
return convert(MOI.SingleVariable, obj)
end
function MOI.set(
model::Optimizer, ::MOI.ObjectiveFunction{F}, f::F
) where {F <: MOI.ScalarAffineFunction{Float64}}
if model.objective_type == SCALAR_QUADRATIC
# We need to zero out the existing quadratic objective.
delq!(model.inner)
end
num_vars = length(model.variable_info)
obj = zeros(Float64, num_vars)
for term in f.terms
column = _info(model, term.variable_index).column
obj[column] += term.coefficient
end
# This update is needed because we might have added some variables.
_update_if_necessary(model)
set_dblattrarray!(model.inner, "Obj", 1, num_vars, obj)
set_dblattr!(model.inner, "ObjCon", f.constant)
_require_update(model)
model.objective_type = SCALAR_AFFINE
end
function MOI.get(
model::Optimizer, ::MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}
)
if model.objective_type == SCALAR_QUADRATIC
error("Unable to get objective function. Currently: $(model.objective_type).")
end
_update_if_necessary(model)
dest = zeros(length(model.variable_info))
get_dblattrarray!(dest, model.inner, "Obj", 1)
terms = MOI.ScalarAffineTerm{Float64}[]
for (index, info) in model.variable_info
coefficient = dest[info.column]
iszero(coefficient) && continue
push!(terms, MOI.ScalarAffineTerm(coefficient, index))
end
constant = get_dblattr(model.inner, "ObjCon")
return MOI.ScalarAffineFunction(terms, constant)
end
function MOI.set(
model::Optimizer, ::MOI.ObjectiveFunction{F}, f::F
) where {F <: MOI.ScalarQuadraticFunction{Float64}}
affine_indices, affine_coefficients, I, J, V = _indices_and_coefficients(model, f)
_update_if_necessary(model)
# We need to zero out any existing linear objective.
obj = zeros(length(model.variable_info))
for (i, c) in zip(affine_indices, affine_coefficients)
obj[i] = c
end
set_dblattrarray!(model.inner, "Obj", 1, length(obj), obj)
set_dblattr!(model.inner, "ObjCon", f.constant)
# We need to zero out the existing quadratic objective.
delq!(model.inner)
add_qpterms!(model.inner, I, J, V)
_require_update(model)
model.objective_type = SCALAR_QUADRATIC
return
end
function MOI.get(
model::Optimizer,
::MOI.ObjectiveFunction{MOI.ScalarQuadraticFunction{Float64}}
)
_update_if_necessary(model)
dest = zeros(length(model.variable_info))
get_dblattrarray!(dest, model.inner, "Obj", 1)
terms = MOI.ScalarAffineTerm{Float64}[]
for (index, info) in model.variable_info
coefficient = dest[info.column]
iszero(coefficient) && continue
push!(terms, MOI.ScalarAffineTerm(coefficient, index))
end
constant = get_dblattr(model.inner, "ObjCon")
q_terms = MOI.ScalarQuadraticTerm{Float64}[]
I, J, V = getq(model.inner)
for (i, j, v) in zip(I, J, V)
iszero(v) && continue
# See note in `_indices_and_coefficients`.
new_v = i == j ? 2v : v
push!(
q_terms,
MOI.ScalarQuadraticTerm(
new_v,
model.variable_info[CleverDicts.LinearIndex(i + 1)].index,
model.variable_info[CleverDicts.LinearIndex(j + 1)].index
)
)
end
return MOI.ScalarQuadraticFunction(terms, q_terms, constant)
end
function MOI.modify(
model::Optimizer,
::MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}},
chg::MOI.ScalarConstantChange{Float64}
)
set_dblattr!(model.inner, "ObjCon", chg.new_constant)
_require_update(model)
return
end
##
## SingleVariable-in-Set constraints.
##
function _info(
model::Optimizer, c::MOI.ConstraintIndex{MOI.SingleVariable, <:Any}
)
var_index = MOI.VariableIndex(c.value)
if haskey(model.variable_info, var_index)
return _info(model, var_index)
end
return throw(MOI.InvalidIndex(c))
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.LessThan{Float64}}
)
if haskey(model.variable_info, MOI.VariableIndex(c.value))
info = _info(model, c)
return info.bound == LESS_THAN || info.bound == LESS_AND_GREATER_THAN
end
return false
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.GreaterThan{Float64}}
)
if haskey(model.variable_info, MOI.VariableIndex(c.value))
info = _info(model, c)
return info.bound == GREATER_THAN || info.bound == LESS_AND_GREATER_THAN
end
return false
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.Interval{Float64}}
)
return haskey(model.variable_info, MOI.VariableIndex(c.value)) &&
_info(model, c).bound == INTERVAL
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.EqualTo{Float64}}
)
return haskey(model.variable_info, MOI.VariableIndex(c.value)) &&
_info(model, c).bound == EQUAL_TO
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.ZeroOne}
)
return haskey(model.variable_info, MOI.VariableIndex(c.value)) &&
_info(model, c).type == BINARY
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.Integer}
)
return haskey(model.variable_info, MOI.VariableIndex(c.value)) &&
_info(model, c).type == INTEGER
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.Semicontinuous{Float64}}
)
return haskey(model.variable_info, MOI.VariableIndex(c.value)) &&
_info(model, c).type == SEMICONTINUOUS
end
function MOI.is_valid(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.Semiinteger{Float64}}
)
return haskey(model.variable_info, MOI.VariableIndex(c.value)) &&
_info(model, c).type == SEMIINTEGER
end
function MOI.get(
model::Optimizer, ::MOI.ConstraintFunction,
c::MOI.ConstraintIndex{MOI.SingleVariable, <:Any}
)
MOI.throw_if_not_valid(model, c)
return MOI.SingleVariable(MOI.VariableIndex(c.value))
end
function MOI.set(
model::Optimizer, ::MOI.ConstraintFunction,
c::MOI.ConstraintIndex{MOI.SingleVariable, <:Any}, ::MOI.SingleVariable
)
return throw(MOI.SettingSingleVariableFunctionNotAllowed())
end
_bounds(s::MOI.GreaterThan{Float64}) = (s.lower, nothing)
_bounds(s::MOI.LessThan{Float64}) = (nothing, s.upper)
_bounds(s::MOI.EqualTo{Float64}) = (s.value, s.value)
_bounds(s::MOI.Interval{Float64}) = (s.lower, s.upper)
function _throw_if_existing_lower(
bound::BoundType, var_type::VariableType, new_set::Type{<:MOI.AbstractSet},
variable::MOI.VariableIndex
)
existing_set = if bound == LESS_AND_GREATER_THAN || bound == GREATER_THAN
MOI.GreaterThan{Float64}
elseif bound == INTERVAL
MOI.Interval{Float64}
elseif bound == EQUAL_TO
MOI.EqualTo{Float64}
elseif var_type == SEMIINTEGER
MOI.Semiinteger{Float64}
elseif var_type == SEMICONTINUOUS
MOI.Semicontinuous{Float64}
else
nothing # Also covers `NONE` and `LESS_THAN`.
end
if existing_set !== nothing
throw(MOI.LowerBoundAlreadySet{existing_set, new_set}(variable))
end
end
function _throw_if_existing_upper(
bound::BoundType, var_type::VariableType, new_set::Type{<:MOI.AbstractSet},
variable::MOI.VariableIndex
)
existing_set = if bound == LESS_AND_GREATER_THAN || bound == LESS_THAN
MOI.LessThan{Float64}
elseif bound == INTERVAL
MOI.Interval{Float64}
elseif bound == EQUAL_TO
MOI.EqualTo{Float64}
elseif var_type == SEMIINTEGER
MOI.Semiinteger{Float64}
elseif var_type == SEMICONTINUOUS
MOI.Semicontinuous{Float64}
else
nothing # Also covers `NONE` and `GREATER_THAN`.
end
if existing_set !== nothing
throw(MOI.UpperBoundAlreadySet{existing_set, new_set}(variable))
end
end
function MOI.add_constraint(
model::Optimizer, f::MOI.SingleVariable, s::S
) where {S <: SCALAR_SETS}
info = _info(model, f.variable)
if S <: MOI.LessThan{Float64}
_throw_if_existing_upper(info.bound, info.type, S, f.variable)
info.bound = info.bound == GREATER_THAN ? LESS_AND_GREATER_THAN : LESS_THAN
info.upper_bound_if_bounded = s.upper
elseif S <: MOI.GreaterThan{Float64}
_throw_if_existing_lower(info.bound, info.type, S, f.variable)
info.bound = info.bound == LESS_THAN ? LESS_AND_GREATER_THAN : GREATER_THAN
info.lower_bound_if_bounded = s.lower
elseif S <: MOI.EqualTo{Float64}
_throw_if_existing_lower(info.bound, info.type, S, f.variable)
_throw_if_existing_upper(info.bound, info.type, S, f.variable)
info.bound = EQUAL_TO
info.upper_bound_if_bounded = info.lower_bound_if_bounded = s.value
else
@assert S <: MOI.Interval{Float64}
_throw_if_existing_lower(info.bound, info.type, S, f.variable)
_throw_if_existing_upper(info.bound, info.type, S, f.variable)
info.bound = INTERVAL
info.upper_bound_if_bounded = s.upper
info.lower_bound_if_bounded = s.lower
end
index = MOI.ConstraintIndex{MOI.SingleVariable, typeof(s)}(f.variable.value)
# This sets the bounds in the inner model and set the cache in VariableInfo
# again (we could just set them there, but then VariableInfo is in a
# invalid state that trigger some asserts, i.e., has bound but no cache).
MOI.set(model, MOI.ConstraintSet(), index, s)
return index
end
function MOI.add_constraints(
model::Optimizer, f::Vector{MOI.SingleVariable}, s::Vector{S}
) where {S <: SCALAR_SETS}
for (fi, si) in zip(f, s)
info = _info(model, fi.variable)
if S <: MOI.LessThan{Float64}
_throw_if_existing_upper(info.bound, info.type, S, fi.variable)
info.bound = info.bound == GREATER_THAN ? LESS_AND_GREATER_THAN : LESS_THAN
info.upper_bound_if_bounded = si.upper
elseif S <: MOI.GreaterThan{Float64}
_throw_if_existing_lower(info.bound, info.type, S, fi.variable)
info.bound = info.bound == LESS_THAN ? LESS_AND_GREATER_THAN : GREATER_THAN
info.lower_bound_if_bounded = si.lower
elseif S <: MOI.EqualTo{Float64}
_throw_if_existing_lower(info.bound, info.type, S, fi.variable)
_throw_if_existing_upper(info.bound, info.type, S, fi.variable)
info.bound = EQUAL_TO
info.upper_bound_if_bounded = info.lower_bound_if_bounded = si.value
else
@assert S <: MOI.Interval{Float64}
_throw_if_existing_lower(info.bound, info.type, S, fi.variable)
_throw_if_existing_upper(info.bound, info.type, S, fi.variable)
info.bound = INTERVAL
info.upper_bound_if_bounded = si.upper
info.lower_bound_if_bounded = si.lower
end
end
indices = [
MOI.ConstraintIndex{MOI.SingleVariable, eltype(s)}(fi.variable.value)
for fi in f
]
_set_bounds(model, indices, s)
return indices
end
function MOI.delete(
model::Optimizer,
c::MOI.ConstraintIndex{MOI.SingleVariable, MOI.LessThan{Float64}}
)
MOI.throw_if_not_valid(model, c)
info = _info(model, c)
set_dblattrelement!(model.inner, "UB", info.column, Inf)
_require_update(model)
if info.bound == LESS_AND_GREATER_THAN
info.bound = GREATER_THAN
else
info.bound = NONE
end
info.upper_bound_if_bounded = NaN
info.lessthan_name = ""
model.name_to_constraint_index = nothing
return
end
"""
_set_variable_lower_bound(model, info, value)
This function is used to indirectly set the lower bound of a variable.
We need to do it this way to account for potential lower bounds of 0.0 added by
VectorOfVariables-in-SecondOrderCone constraints.
This does not look at `info.bound` and does not update
`info.lower_bound_if_bounded`.
See also `_get_variable_lower_bound`.
"""
function _set_variable_lower_bound(model, info, value)
if info.num_soc_constraints == 0
# No SOC constraints, set directly.
@assert isnan(info.lower_bound_if_soc)
set_dblattrelement!(model.inner, "LB", info.column, value)
_require_update(model)
elseif value >= 0.0
# Regardless of whether there are SOC constraints, this is a valid bound
# for the SOC constraint and should over-ride any previous bounds.
info.lower_bound_if_soc = NaN
set_dblattrelement!(model.inner, "LB", info.column, value)
_require_update(model)
elseif isnan(info.lower_bound_if_soc)
# Previously, we had a non-negative lower bound (i.e., it was set in the
# case above). Now we're setting this with a negative one, but there are
# still some SOC constraints, so we cache `value` and set the variable
# lower bound to `0.0`.
@assert value < 0.0
set_dblattrelement!(model.inner, "LB", info.column, 0.0)
_require_update(model)
info.lower_bound_if_soc = value
else
# Previously, we had a negative lower bound. We're setting this with
# another negative one, but there are still some SOC constraints.
@assert info.lower_bound_if_soc < 0.0
info.lower_bound_if_soc = value
end
end
"""
_get_variable_lower_bound(model, info)
Get the current variable lower bound, ignoring a potential bound of `0.0` set
by a second order cone constraint, if an adequate `SingleVariable` constraint
is set (i.e., `info.bound` is not `NONE` or `LESS_THAN`) then use a cached
value; otherwise update the model if necessary and query the LB from it.
See also `_set_variable_lower_bound`.
"""