-
Notifications
You must be signed in to change notification settings - Fork 81
/
MOI_wrapper.jl
4462 lines (4120 loc) · 138 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
# Copyright (c) 2015 Dahua Lin, Miles Lubin, Joey Huchette, Iain Dunning, and
# contributors
#
# 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.
import MathOptInterface
const MOI = MathOptInterface
const CleverDicts = MOI.Utilities.CleverDicts
@enum(
_BoundType,
_NONE,
_LESS_THAN,
_GREATER_THAN,
_LESS_AND_GREATER_THAN,
_INTERVAL,
_EQUAL_TO
)
@enum(
_ObjectiveType,
_SINGLE_VARIABLE,
_SCALAR_AFFINE,
_SCALAR_QUADRATIC,
_VECTOR_AFFINE,
)
@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},
}
# Union used by many methods because interval constraints are not supported.
const _SUPPORTED_SCALAR_SETS =
Union{MOI.GreaterThan{Float64},MOI.LessThan{Float64},MOI.EqualTo{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 NaN only if `bound` is
# _NONE. _EQUAL_TO sets both of them. See also `lower_bound_if_soc`.
lower_bound_if_bounded::Float64
upper_bound_if_bounded::Float64
type::Char
start::Union{Float64,Nothing}
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: (1) just have SOC constraints; (2) just have bounds;
# (3) have a bound and 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,
GRB_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 Env
ptr_env::Ptr{Cvoid}
# These fields keep track of how many models the `Env` is used for to help
# with finalizing. If you finalize an Env first, then the model, Gurobi will
# throw an error.
finalize_called::Bool
attached_models::Int
function Env(;
output_flag::Int = 1,
memory_limit::Union{Nothing,Real} = nothing,
started::Bool = true,
)
a = Ref{Ptr{Cvoid}}()
ret = GRBemptyenv(a)
env = new(a[], false, 0)
_check_ret(env, ret)
ret = GRBsetintparam(env.ptr_env, GRB_INT_PAR_OUTPUTFLAG, output_flag)
_check_ret(env, ret)
if _GUROBI_VERSION >= v"9.5.0" && memory_limit !== nothing
ret = GRBsetdblparam(env, GRB_DBL_PAR_MEMLIMIT, memory_limit)
_check_ret(env, ret)
end
if started
ret = GRBstartenv(env.ptr_env)
end
finalizer(env) do e
e.finalize_called = true
if e.attached_models == 0
# Only finalize the model if there are no models using it.
GRBfreeenv(e.ptr_env)
e.ptr_env = C_NULL
end
end
# Even if the loadenv fails, the pointer is still valid.
_check_ret(env, ret)
return env
end
end
"""
Env(
server_address::String,
server_password::Union{String,Nothing} = nothing;
started::Bool = true,
)
Create a new remote Gurobi environment object.
Specify `server_address` in the format `"address:port"` and optionally provide
the server password.
The extra keyword argument `started` delays starting the environment if set to false.
Gurobi defaults to connecting to the server when the environment is started.
## Example
```julia
using JuMP, Gurobi
const env = Gurobi.Env("localhost:61000")
model = JuMP.Model(() -> Gurobi.Optimizer(env))
```
"""
function Env(
server_address::String,
server_password::Union{String,Nothing} = nothing;
started::Bool = true,
)
env = Env(; started = false)
ret = GRBsetstrparam(env.ptr_env, GRB_STR_PAR_COMPUTESERVER, server_address)
_check_ret(env, ret)
if server_password !== nothing
ret = GRBsetstrparam(
env.ptr_env,
GRB_STR_PAR_SERVERPASSWORD,
server_password,
)
_check_ret(env, ret)
end
if started
ret = GRBstartenv(env.ptr_env)
_check_ret(env, ret)
end
return env
end
Base.cconvert(::Type{Ptr{Cvoid}}, x::Env) = x
Base.unsafe_convert(::Type{Ptr{Cvoid}}, env::Env) = env.ptr_env::Ptr{Cvoid}
const _HASH = CleverDicts.key_to_index
const _INVERSE_HASH = x -> CleverDicts.index_to_key(MOI.VariableIndex, x)
"""
Optimizer(
env::Union{Nothing,Env} = nothing;
enable_interrupts::Bool = true,
)
Create a new Optimizer object.
You can share Gurobi `Env`s between models by passing an instance of `Env`
as the first argument.
In order to enable interrupts via `CTRL+C`, a no-op callback is added to the
model by default. In most cases, this has negligible effect on solution
times. However, you can disable it (at the cost of not being able to
interrupt a solve) by passing `enable_interrupts = false`.
Set optimizer attributes using `MOI.RawOptimizerAttribute` or
`JuMP.set_optimizer_atttribute`.
## Example
```julia
using JuMP, Gurobi
const env = Gurobi.Env()
model = JuMP.Model(() -> Gurobi.Optimizer(env; enable_interrupts=false))
set_optimizer_attribute(model, "OutputFlag", 0)
```
"""
mutable struct Optimizer <: MOI.AbstractOptimizer
# The low-level Gurobi model.
inner::Ptr{Cvoid}
# 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
# track whether objective function is set and the state of objective sense
is_objective_set::Bool
objective_sense::Union{Nothing,MOI.OptimizationSense}
# 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 VariableIndex-in-Set constraints.
variable_info::CleverDicts.CleverDict{
MOI.VariableIndex,
_VariableInfo,
typeof(_HASH),
typeof(_INVERSE_HASH),
}
# If you add variables to a model that had variables deleted AND has
# not called `update_model!` since the deletion, then the newly created
# variables may have attributes set, but their column index before the
# call to `update_model!` is different than after the `update_model!`.
# Before the `update_model!` their column is the same as if no variables
# were deleted, after the `update_model!` the columns indexes are
# shifted (by being being subtracted by the number of variables deleted
# with column indexes smaller than them). To control this the two
# fields below are used:
# `next_column`: The column index of the next variable/column added. It is
# updated when variables are added, and when the `_update_if_necessary!` is
# called AND `columns_deleted_since_last_update` is not empty.
# `columns_deleted_since_last_update`: Stores the column indexes of all
# columns that were deleted since the last call to `_update_if_necessary!`,
# after such call the vector is emptied.
next_column::Int
columns_deleted_since_last_update::Vector{Int}
# 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}
# VectorAffineFunction-in-Set storage.
indicator_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}},
}
# Gurobi does not have a configurable memory limit (different of time),
# but it does detect when it needs more memory than it is available,
# and it stops the optimization returning a specific error code.
# This is a different mechanism than Gurobi "Status" (that is used for
# reporting why an optimization finished) and, in fact, may be triggered in
# other cases than optimization (for example, when assembling the model).
# For convenience, and homogeinity with other solvers, we save the code
# returned by `GRBoptimize` in `ret_GRBoptimize`, and do not throw
# an exception case it should be interpreted as a termination status.
# Then, when/if the termination status is queried, we may override the
# result taking into account the `ret_GRBoptimize` field.
ret_GRBoptimize::Cint
# 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.
enable_interrupts::Bool
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}
generic_callback::Any
conflict::Cint
function Optimizer(
env::Union{Nothing,Env} = nothing;
enable_interrupts::Bool = true,
)
model = new()
model.inner = C_NULL
model.env = env === nothing ? Env() : env
model.enable_interrupts = enable_interrupts
model.params = Dict{String,Any}()
model.silent = false
model.variable_info =
CleverDicts.CleverDict{MOI.VariableIndex,_VariableInfo}(
_HASH,
_INVERSE_HASH,
)
model.next_column = 1
model.last_constraint_index = 0
model.columns_deleted_since_last_update = Int[]
model.affine_constraint_info = Dict{Int,_ConstraintInfo}()
model.quadratic_constraint_info = Dict{Int,_ConstraintInfo}()
model.sos_constraint_info = Dict{Int,_ConstraintInfo}()
model.indicator_constraint_info = Dict{Int,_ConstraintInfo}()
model.callback_variable_primal = Float64[]
MOI.empty!(model)
finalizer(model) do m
ret = GRBfreemodel(m.inner)
_check_ret(m, ret)
m.env.attached_models -= 1
if env === nothing
@assert m.env.attached_models == 0
# We created this environment. Finalize it now.
finalize(m.env)
elseif m.env.finalize_called && m.env.attached_models == 0
# We delayed finalizing `m.env` earlier because there were still
# models attached. Finalize it now.
GRBfreeenv(m.env.ptr_env)
m.env.ptr_env = C_NULL
end
end
return model
end
end
Base.cconvert(::Type{Ptr{Cvoid}}, x::Optimizer) = x
function Base.unsafe_convert(::Type{Ptr{Cvoid}}, model::Optimizer)
return model.inner::Ptr{Cvoid}
end
function _check_ret(model::Optimizer, ret::Cint)
if ret != 0
msg = unsafe_string(GRBgetmerrormsg(model))
throw(ErrorException("Gurobi Error $(ret): $(msg)"))
end
return
end
# If you add a new error code that, when returned by GRBoptimize,
# should be treated as a TerminationStatus by MOI, to the global `Dict`
# below, then the rest of the code should pick up on this seamlessly.
const _ERROR_TO_STATUS = Dict{Cint,Tuple{MOI.TerminationStatusCode,String}}([
# Code => (TerminationStatus, RawStatusString)
GRB_ERROR_OUT_OF_MEMORY =>
(MOI.MEMORY_LIMIT, "Available memory was exhausted."),
])
# Same as _check_ret, but deals with the `model.ret_GRBoptimize` machinery.
function _check_ret_GRBoptimize(model)
if !haskey(_ERROR_TO_STATUS, model.ret_GRBoptimize)
_check_ret(model, model.ret_GRBoptimize)
end
return
end
function _check_ret(env, ret::Cint)
if ret != 0
msg = unsafe_string(GRBgeterrormsg(env))
throw(ErrorException("Gurobi Error $(ret): $(msg)"))
end
return
end
function Base.show(io::IO, model::Optimizer)
if model.inner == C_NULL
println(io, "Gurobi Model: NULL")
return
end
p = Ref{Cint}()
GRBgetintattr(model, "ModelSense", p)
println(io, " sense : $(p[] > 0 ? :minimize : :maximize)")
GRBgetintattr(model, "NumVars", p)
println(io, " number of variables = $(p[])")
GRBgetintattr(model, "NumConstrs", p)
println(io, " number of linear constraints = $(p[])")
GRBgetintattr(model, "NumQConstrs", p)
println(io, " number of quadratic constraints = $(p[])")
GRBgetintattr(model, "NumSOS", p)
println(io, " number of sos constraints = $(p[])")
GRBgetintattr(model, "NumNZs", p)
println(io, " number of non-zero coeffs = $(p[])")
GRBgetintattr(model, "NumQNZs", p)
println(io, " number of non-zero qp objective terms = $(p[])")
GRBgetintattr(model, "NumQCNZs", p)
println(io, " number of non-zero qp constraint terms = $(p[])")
return
end
function MOI.empty!(model::Optimizer)
# Free the current model, if it exists.
if model.inner != C_NULL
ret = GRBfreemodel(model.inner)
_check_ret(model, ret)
model.env.attached_models -= 1
end
# Then create a new one
a = Ref{Ptr{Cvoid}}()
ret =
GRBnewmodel(model.env, a, "", 0, C_NULL, C_NULL, C_NULL, C_NULL, C_NULL)
model.inner = a[]
model.env.attached_models += 1
_check_ret(model, ret)
# Reset the parameters in this new environment
if model.silent
MOI.set(model, MOI.Silent(), true)
end
for (name, value) in model.params
MOI.set(model, MOI.RawOptimizerAttribute(name), value)
end
model.needs_update = false
model.objective_type = _SCALAR_AFFINE
model.is_objective_set = false
model.objective_sense = nothing
empty!(model.variable_info)
model.next_column = 1
empty!(model.columns_deleted_since_last_update)
empty!(model.affine_constraint_info)
empty!(model.quadratic_constraint_info)
empty!(model.sos_constraint_info)
empty!(model.indicator_constraint_info)
model.name_to_variable = nothing
model.name_to_constraint_index = nothing
model.ret_GRBoptimize = Cint(0)
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
model.generic_callback = nothing
model.conflict = Cint(-1)
return
end
function MOI.is_empty(model::Optimizer)
model.needs_update && return false
model.objective_type != _SCALAR_AFFINE && return false
model.is_objective_set == true && return false
model.objective_sense !== nothing && return false
!isempty(model.variable_info) && return false
!isone(model.next_column) && return false
!isempty(model.columns_deleted_since_last_update) && return false
!isempty(model.affine_constraint_info) && return false
!isempty(model.quadratic_constraint_info) && return false
!isempty(model.sos_constraint_info) && return false
model.name_to_variable !== nothing && return false
model.name_to_constraint_index !== nothing && return false
!iszero(model.ret_GRBoptimize) && return false
model.has_unbounded_ray && return false
model.has_infeasibility_cert && return false
!isempty(model.callback_variable_primal) && 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
sort!(model.columns_deleted_since_last_update)
for var_info in values(model.variable_info)
# The trick here is: searchsortedlast returns, in O(log n), the
# last index with a column smaller than var_info.column, over
# columns_deleted_since_last_update this is the same as the number
# of columns deleted before it, and how much its value need to be
# shifted.
var_info.column -= searchsortedlast(
model.columns_deleted_since_last_update,
var_info.column,
)
end
model.next_column -= length(model.columns_deleted_since_last_update)
empty!(model.columns_deleted_since_last_update)
ret = GRBupdatemodel(model)
_check_ret(model, ret)
model.needs_update = false
else
@assert isempty(model.columns_deleted_since_last_update)
end
return
end
MOI.get(::Optimizer, ::MOI.SolverName) = "Gurobi"
MOI.get(::Optimizer, ::MOI.SolverVersion) = string(_GUROBI_VERSION)
function MOI.supports(
::Optimizer,
::MOI.ObjectiveFunction{F},
) where {
F<:Union{
MOI.VariableIndex,
MOI.ScalarAffineFunction{Float64},
MOI.ScalarQuadraticFunction{Float64},
},
}
return true
end
function MOI.supports_constraint(
::Optimizer,
::Type{MOI.VariableIndex},
::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
function MOI.supports(
::Optimizer,
::MOI.ConstraintName,
::Type{MOI.ConstraintIndex{F,S}},
) where {F,S}
return F != MOI.VariableIndex
end
MOI.supports(::Optimizer, ::MOI.Name) = true
MOI.supports(::Optimizer, ::MOI.Silent) = true
MOI.supports(::Optimizer, ::MOI.NumberOfThreads) = true
MOI.supports(::Optimizer, ::MOI.TimeLimitSec) = true
MOI.supports(::Optimizer, ::MOI.AbsoluteGapTolerance) = true
MOI.supports(::Optimizer, ::MOI.RelativeGapTolerance) = true
MOI.supports(::Optimizer, ::MOI.ObjectiveSense) = true
MOI.supports(::Optimizer, ::MOI.RawOptimizerAttribute) = true
MOI.supports(::Optimizer, ::MOI.ConstraintPrimalStart) = false
MOI.supports(::Optimizer, ::MOI.ConstraintDualStart) = false
function MOI.set(model::Optimizer, raw::MOI.RawOptimizerAttribute, value)
env = GRBgetenv(model)
param = raw.name
model.params[param] = value
param_type = GRBgetparamtype(env, param)
ret = if param_type == -1
throw(MOI.UnsupportedAttribute(MOI.RawOptimizerAttribute(param)))
elseif param_type == 1
GRBsetintparam(env, param, value)
elseif param_type == 2
GRBsetdblparam(env, param, value)
else
@assert param_type == 3
GRBsetstrparam(env, param, value)
end
_check_ret(env, ret)
return
end
function MOI.get(model::Optimizer, raw::MOI.RawOptimizerAttribute)
env = GRBgetenv(model)
param = raw.name
param_type = GRBgetparamtype(env, param)
if param_type == -1
throw(MOI.UnsupportedAttribute(MOI.RawOptimizerAttribute(param)))
elseif param_type == 1
a = Ref{Cint}()
ret = GRBgetintparam(env, param, a)
_check_ret(env, ret)
return a[]
elseif param_type == 2
a = Ref{Cdouble}()
ret = GRBgetdblparam(env, param, a)
_check_ret(env, ret)
return a[]
else
@assert param_type == 3
valueP = Vector{Cchar}(undef, GRB_MAX_STRLEN)
ret = GRBgetstrparam(env, param, valueP)
_check_ret(env, ret)
GC.@preserve valueP begin
return unsafe_string(pointer(valueP))
end
end
end
function MOI.set(
model::Optimizer,
::MOI.TimeLimitSec,
limit::Union{Real,Nothing},
)
float_limit = convert(Float64, something(limit, GRB_INFINITY))
MOI.set(model, MOI.RawOptimizerAttribute("TimeLimit"), float_limit)
return
end
function MOI.get(model::Optimizer, ::MOI.TimeLimitSec)
limit = MOI.get(model, MOI.RawOptimizerAttribute("TimeLimit"))
return limit == GRB_INFINITY ? nothing : limit
end
MOI.supports_incremental_interface(::Optimizer) = true
function MOI.copy_to(dest::Optimizer, src::MOI.ModelLike)
return MOI.Utilities.default_copy_to(dest, src)
end
function MOI.get(model::Optimizer, ::MOI.ListOfVariableAttributesSet)
ret = MOI.AbstractVariableAttribute[]
found_name, found_start = false, false
for info in values(model.variable_info)
if !found_name && !isempty(info.name)
push!(ret, MOI.VariableName())
found_name = true
end
if !found_start && info.start !== nothing
push!(ret, MOI.VariablePrimalStart())
found_start = true
end
if found_start && found_name
return ret
end
end
return ret
end
function MOI.get(model::Optimizer, ::MOI.ListOfModelAttributesSet)
if MOI.is_empty(model)
return Any[]
end
attributes = Any[]
if model.objective_sense !== nothing
push!(attributes, MOI.ObjectiveSense())
end
if model.is_objective_set
F = MOI.get(model, MOI.ObjectiveFunctionType())
push!(attributes, MOI.ObjectiveFunction{F}())
end
if MOI.get(model, MOI.Name()) != ""
push!(attributes, MOI.Name())
end
return attributes
end
function MOI.get(
model::Optimizer,
::MOI.ListOfConstraintAttributesSet{F,S},
) where {S,F}
if F == MOI.VariableIndex
# Does not support ConstraintName
return MOI.AbstractConstraintAttribute[]
end
for index in MOI.get(model, MOI.ListOfConstraintIndices{F,S}())
if !isempty(MOI.get(model, MOI.ConstraintName(), index))
return MOI.AbstractConstraintAttribute[MOI.ConstraintName()]
end
end
return MOI.AbstractConstraintAttribute[]
end
function _indices_and_coefficients(
indices::AbstractVector{Cint},
coefficients::AbstractVector{Float64},
model::Optimizer,
f::MOI.ScalarAffineFunction{Float64},
)
i = 1
for term in f.terms
indices[i] = c_column(model, term.variable)
coefficients[i] = term.coefficient
i += 1
end
return indices, coefficients
end
function _indices_and_coefficients(
model::Optimizer,
f::MOI.ScalarAffineFunction{Float64},
)
f_canon = if MOI.Utilities.is_canonical(f)
f
else
MOI.Utilities.canonical(f)
end
nnz = length(f_canon.terms)
indices = Vector{Cint}(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{Cint},
J::AbstractVector{Cint},
V::AbstractVector{Float64},
indices::AbstractVector{Cint},
coefficients::AbstractVector{Float64},
model::Optimizer,
f::MOI.ScalarQuadraticFunction,
)
for (i, term) in enumerate(f.quadratic_terms)
I[i] = c_column(model, term.variable_1)
J[i] = c_column(model, term.variable_2)
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] = c_column(model, term.variable)
coefficients[i] = term.coefficient
end
return
end
function _indices_and_coefficients(
model::Optimizer,
f::MOI.ScalarQuadraticFunction,
)
f_canon = if MOI.Utilities.is_canonical(f)
f
else
MOI.Utilities.canonical(f)
end
nnz_quadratic = length(f_canon.quadratic_terms)
nnz_affine = length(f_canon.affine_terms)
I = Vector{Cint}(undef, nnz_quadratic)
J = Vector{Cint}(undef, nnz_quadratic)
V = Vector{Float64}(undef, nnz_quadratic)
indices = Vector{Cint}(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}) = (GRB_LESS_EQUAL, s.upper)
_sense_and_rhs(s::MOI.GreaterThan{Float64}) = (GRB_GREATER_EQUAL, s.lower)
_sense_and_rhs(s::MOI.EqualTo{Float64}) = (GRB_EQUAL, 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
return throw(MOI.InvalidIndex(key))
end
"""
column(
model::Optimizer,
x::Union{MOI.VariableIndex,<:MOI.ConstraintIndex{MOI.VariableIndex}},
) --> Int
Return the 1-indexed column associated with `x`.
For use with the C API, see `Gurobi.c_column`.
"""
function column(
model::Optimizer,
x::Union{MOI.VariableIndex,<:MOI.ConstraintIndex{MOI.VariableIndex}},
)
return _info(model, x).column
end
"""
c_column(
model::Optimizer,
x::Union{MOI.VariableIndex,<:MOI.ConstraintIndex{MOI.VariableIndex}},
) --> Cint
Return the `Cint` 0-indexed column associated with `x` for use with the C API.
"""
function c_column(
model::Optimizer,
x::Union{MOI.VariableIndex,<:MOI.ConstraintIndex{MOI.VariableIndex}},
)
return Cint(column(model, x) - 1)
end
function _get_next_column(model::Optimizer)
model.next_column += 1
return model.next_column - 1
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 = _get_next_column(model)
ret =
GRBaddvar(model, 0, C_NULL, C_NULL, 0.0, -Inf, Inf, GRB_CONTINUOUS, "")
_check_ret(model, ret)
_require_update(model)
return index
end
function MOI.add_variables(model::Optimizer, N::Int)
ret = GRBaddvars(
model,
N,
0,
C_NULL,
C_NULL,
C_NULL,
C_NULL,
fill(-Inf, N),
C_NULL,
C_NULL,
C_NULL,
)
_check_ret(model, ret)
indices = Vector{MOI.VariableIndex}(undef, N)
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 = _get_next_column(model)
indices[i] = index
end
_require_update(model)
return indices
end
# We implement a specialized version here to avoid calling into Gurobi twice.
# Using the standard implementation, we would first create a variable in Gurobi
# with GRBaddvar that has bounds of (-Inf,+Inf), and then immediately after
# reset those bounds using the attributes interface. Instead, we just pass the
# desired bounds directly to GRBaddvar.
function MOI.add_constrained_variable(
model::Optimizer,
set::S,
)::Tuple{
MOI.VariableIndex,
MOI.ConstraintIndex{MOI.VariableIndex,S},
} where {S<:_SCALAR_SETS}
vi = CleverDicts.add_item(
model.variable_info,
_VariableInfo(MOI.VariableIndex(0), 0),
)
info = _info(model, vi)
# Now, set `.index` and `.column`.
info.index = vi
info.column = _get_next_column(model)
lb = -Inf
ub = Inf
if S <: MOI.LessThan{Float64}
ub = set.upper
info.upper_bound_if_bounded = ub
info.bound = _LESS_THAN
elseif S <: MOI.GreaterThan{Float64}
lb = set.lower
info.lower_bound_if_bounded = lb
info.bound = _GREATER_THAN
elseif S <: MOI.EqualTo{Float64}
lb = set.value
ub = set.value
info.lower_bound_if_bounded = lb
info.upper_bound_if_bounded = ub
info.bound = _EQUAL_TO
else
@assert S <: MOI.Interval{Float64}
lb = set.lower
ub = set.upper
info.lower_bound_if_bounded = lb
info.upper_bound_if_bounded = ub
info.bound = _INTERVAL
end
ret = GRBaddvar(model, 0, C_NULL, C_NULL, 0.0, lb, ub, GRB_CONTINUOUS, "")
_check_ret(model, ret)
_require_update(model)
ci = MOI.ConstraintIndex{MOI.VariableIndex,typeof(set)}(vi.value)
return vi, ci
end
function MOI.is_valid(model::Optimizer, v::MOI.VariableIndex)
return haskey(model.variable_info, v)
end