-
Notifications
You must be signed in to change notification settings - Fork 63
/
MOI_wrapper.jl
4090 lines (3798 loc) · 120 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) 2013: Joey Huchette 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,
_UNSET_OBJECTIVE,
_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},
}
mutable struct _VariableInfo
index::MOI.VariableIndex
column::Int
bound::_BoundType
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.
lower_bound_if_soc::Float64
num_soc_constraints::Int
function _VariableInfo(index::MOI.VariableIndex, column::Int)
return new(index, column, _NONE, CPX_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
# CPLEX model.
name::String
_ConstraintInfo(row::Int, set::MOI.AbstractSet) = new(row, set, "")
end
mutable struct Env
ptr::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, CPLEX will
# throw an error.
finalize_called::Bool
attached_models::Int
function Env()
status_p = Ref{Cint}()
ptr = CPXopenCPLEX(status_p)
if status_p[] != 0
error(
"CPLEX Error $(status_p[]): Unable to create CPLEX environment.",
)
end
env = new(ptr, false, 0)
finalizer(env) do e
e.finalize_called = true
if e.attached_models == 0
# Only finalize the model if there are no models using it.
CPXcloseCPLEX(Ref(e.ptr))
e.ptr = C_NULL
end
end
return env
end
end
Base.cconvert(::Type{Ptr{Cvoid}}, x::Env) = x
Base.unsafe_convert(::Type{Ptr{Cvoid}}, env::Env) = env.ptr::Ptr{Cvoid}
function _get_error_string(env::Union{Env,CPXENVptr}, ret::Cint)
buffer = Array{Cchar}(undef, CPXMESSAGEBUFSIZE)
p = pointer(buffer)
return GC.@preserve buffer begin
errstr = CPXgeterrorstring(env, ret, p)
if errstr == C_NULL
"CPLEX Error $(ret): Unknown error code."
else
unsafe_string(p)
end
end
end
function _check_ret(env::Union{Env,CPXENVptr}, ret::Cint)
if ret == 0
return
end
return error(_get_error_string(env, ret))
end
# If you add a new error code that, when returned by CPLEX inside `optimize!`,
# 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,MOI.TerminationStatusCode}([
# CPLEX Code => TerminationStatus
CPXERR_NO_MEMORY => MOI.MEMORY_LIMIT,
])
# Same as _check_ret, but deals with the `model.ret_optimize` machinery.
function _check_ret_optimize(model)
if !haskey(_ERROR_TO_STATUS, model.ret_optimize)
_check_ret(model, model.ret_optimize)
end
return
end
"""
Optimizer(env::Union{Nothing, Env} = nothing)
Create a new Optimizer object.
You can share CPLEX `Env`s between models by passing an instance of `Env` as the
first argument.
Set optimizer attributes using `MOI.RawOptimizerAttribute` or
`JuMP.set_optimizer_atttribute`.
## Example
```julia
using JuMP, CPLEX
const env = CPLEX.Env()
model = JuMP.Model(() -> CPLEX.Optimizer(env)
set_optimizer_attribute(model, "CPXPARAM_ScreenOutput", 0)
```
## `CPLEX.PassNames`
By default, variable and constraint names are stored in the MOI wrapper, but are
_not_ passed to the inner CPLEX model object because doing so can lead to a
large performance degradation. The downside of not passing names is that various
log messages from CPLEX will report names like constraint "R1" and variable "C2"
instead of their actual names. You can change this behavior using
`CPLEX.PassNames` to force CPLEX.jl to pass variable and constraint names to the
inner CPLEX model object:
```julia
using JuMP, CPLEX
model = JuMP.Model(CPLEX.Optimizer)
set_optimizer_attribute(model, CPLEX.PassNames(), true)
```
"""
mutable struct Optimizer <: MOI.AbstractOptimizer
# The low-level CPLEX model.
lp::CPXLPptr
env::Env
# A flag to keep track of MOI.Silent, which over-rides the OutputFlag
# parameter.
silent::Bool
variable_primal::Union{Nothing,Vector{Float64}}
# Helpers to remember what objective is currently stored in the model.
objective_type::_ObjectiveType
objective_sense::Union{Nothing,MOI.OptimizationSense}
# A mapping from the MOI.VariableIndex to the CPLEX 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}
# 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.
# the function info is also stored in the dict
indicator_constraint_info::Dict{
Int,
Tuple{_ConstraintInfo,MOI.VectorAffineFunction{Float64}},
}
# Note: we do not have a VariableIndex_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}},
}
# CPLEX has more than one configurable memory limit, but these do not seem
# to cover all situations, for example, there are no memory limits for
# solving LPs with the many possible algorithms (simplex, barrier, etc...).
# In such situations, CPLEX does detect when it needs more memory than it
# is available, but returns an error code instead of setting the
# termination status (like it does for the configurable memory and time
# limits). For convenience, and homogeinity with other solvers, we save
# the code obtained inside `_optimize!` in `ret_optimize`, 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_optimize` field.
ret_optimize::Cint
has_primal_certificate::Bool
has_dual_certificate::Bool
certificate::Vector{Float64}
solve_time::Float64
conflict::Any # ::Union{Nothing, ConflictRefinerData}
# 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}
generic_callback::Any
# For more information on why `pass_names` is necessary, read:
# https://github.com/jump-dev/CPLEX.jl/issues/392
# The underlying problem is that we observed that add_variable, then set
# VariableName then add_variable (i.e., what CPLEX in direct-mode does) is
# faster than adding variable in batch then setting names in batch (i.e.,
# what default_copy_to does). If implementing MOI.copy_to, you should take
# this into consideration.
pass_names::Bool
function Optimizer(env::Union{Nothing,Env} = nothing)
model = new()
model.lp = C_NULL
model.env = env === nothing ? Env() : env
MOI.set(model, MOI.RawOptimizerAttribute("CPXPARAM_ScreenOutput"), 1)
model.silent = false
model.variable_primal = nothing
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.indicator_constraint_info =
Dict{Int,Tuple{_ConstraintInfo,MOI.VectorAffineFunction{Float64}}}()
model.callback_variable_primal = Float64[]
model.certificate = Float64[]
model.pass_names = false
MOI.empty!(model)
finalizer(model) do m
ret = CPXfreeprob(m.env, Ref(m.lp))
_check_ret(m, ret)
m.env.attached_models -= 1
if env === nothing
# We created this env. 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.
CPXcloseCPLEX(Ref(m.env.ptr))
m.env.ptr = C_NULL
end
end
return model
end
end
_check_ret(model::Optimizer, ret::Cint) = _check_ret(model.env, ret)
Base.show(io::IO, model::Optimizer) = show(io, model.lp)
function MOI.empty!(model::Optimizer)
if model.lp != C_NULL
ret = CPXfreeprob(model.env, Ref(model.lp))
_check_ret(model.env, ret)
model.env.attached_models -= 1
end
# Try open a new problem
stat = Ref{Cint}()
tmp = CPXcreateprob(model.env, stat, "")
if tmp == C_NULL
_check_ret(model.env, stat[])
end
model.env.attached_models += 1
model.lp = tmp
if model.silent
MOI.set(model, MOI.RawOptimizerAttribute("CPXPARAM_ScreenOutput"), 0)
end
model.objective_type = _UNSET_OBJECTIVE
model.objective_sense = nothing
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.ret_optimize = Cint(0)
empty!(model.callback_variable_primal)
empty!(model.certificate)
model.has_primal_certificate = false
model.has_dual_certificate = false
model.solve_time = NaN
model.conflict = nothing
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.variable_primal = nothing
return
end
function MOI.is_empty(model::Optimizer)
model.objective_type != _UNSET_OBJECTIVE && return false
model.objective_sense !== nothing && 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.ret_optimize !== Cint(0) && 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
"""
PassNames() <: MOI.AbstractOptimizerAttribute
An optimizer attribute to control whether CPLEX.jl should pass names to the
inner CPLEX model object. See the docstring of `CPLEX.Optimizer` for more
information.
"""
struct PassNames <: MOI.AbstractOptimizerAttribute end
function MOI.set(model::Optimizer, ::PassNames, value::Bool)
model.pass_names = value
return
end
MOI.get(::Optimizer, ::MOI.SolverName) = "CPLEX"
MOI.get(::Optimizer, ::MOI.SolverVersion) = string(_CPLEX_VERSION)
function MOI.supports(
::Optimizer,
::MOI.ObjectiveFunction{F},
) where {
F<:Union{
MOI.VariableIndex,
MOI.ScalarAffineFunction{Float64},
MOI.ScalarQuadraticFunction{Float64},
MOI.VectorAffineFunction{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 CPLEX 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.LessThan{Float64},MOI.GreaterThan{Float64}}}
# Note: CPLEX does not support quadratic equality constraints.
return true
end
MOI.supports(::Optimizer, ::MOI.VariableName, ::Type{MOI.VariableIndex}) = true
function MOI.supports(
::Optimizer,
::MOI.ConstraintName,
::Type{<:MOI.ConstraintIndex},
)
return true
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.ObjectiveSense) = true
MOI.supports(::Optimizer, ::MOI.AbsoluteGapTolerance) = true
MOI.supports(::Optimizer, ::MOI.RelativeGapTolerance) = true
MOI.supports(::Optimizer, ::MOI.RawOptimizerAttribute) = true
function MOI.set(model::Optimizer, param::MOI.RawOptimizerAttribute, value)
numP, typeP = Ref{Cint}(), Ref{Cint}()
ret = CPXgetparamnum(model.env, param.name, numP)
_check_ret(model.env, ret)
ret = CPXgetparamtype(model.env, numP[], typeP)
_check_ret(model.env, ret)
ret = if typeP[] == CPX_PARAMTYPE_NONE
Cint(0)
elseif typeP[] == CPX_PARAMTYPE_INT
CPXsetintparam(model.env, numP[], value)
elseif typeP[] == CPX_PARAMTYPE_DOUBLE
CPXsetdblparam(model.env, numP[], value)
elseif typeP[] == CPX_PARAMTYPE_STRING
CPXsetstrparam(model.env, numP[], value)
else
@assert typeP[] == CPX_PARAMTYPE_LONG
CPXsetlongparam(model.env, numP[], value)
end
_check_ret(model.env, ret)
return
end
function MOI.get(model::Optimizer, param::MOI.RawOptimizerAttribute)
numP, typeP = Ref{Cint}(), Ref{Cint}()
ret = CPXgetparamnum(model.env, param.name, numP)
_check_ret(model.env, ret)
ret = CPXgetparamtype(model.env, numP[], typeP)
_check_ret(model.env, ret)
if typeP[] == CPX_PARAMTYPE_NONE
Cint(0)
elseif typeP[] == CPX_PARAMTYPE_INT
valueP = Ref{Cint}()
ret = CPXgetintparam(model.env, numP[], valueP)
_check_ret(model.env, ret)
return Int(valueP[])
elseif typeP[] == CPX_PARAMTYPE_DOUBLE
valueP = Ref{Cdouble}()
ret = CPXgetdblparam(model.env, numP[], valueP)
_check_ret(model.env, ret)
return valueP[]
elseif typeP[] == CPX_PARAMTYPE_STRING
buffer = Array{Cchar}(undef, CPXMESSAGEBUFSIZE)
valueP = pointer(buffer)
GC.@preserve buffer begin
ret = CPXgetstrparam(model.env, numP[], valueP)
_check_ret(model, ret)
return unsafe_string(valueP)
end
else
@assert typeP[] == CPX_PARAMTYPE_LONG
valueP = Ref{CPXLONG}()
ret = CPXgetlongparam(model.env, numP[], valueP)
_check_ret(model.env, ret)
return valueP[]
end
_check_ret(model.env, ret)
return
end
const _TIME_LIMIT_DEFAULT = 1.0e75
function MOI.set(
model::Optimizer,
::MOI.TimeLimitSec,
limit::Union{Nothing,Real},
)
new_limit = something(limit, _TIME_LIMIT_DEFAULT)
MOI.set(model, MOI.RawOptimizerAttribute("CPXPARAM_TimeLimit"), new_limit)
return
end
function MOI.get(model::Optimizer, ::MOI.TimeLimitSec)
limit = MOI.get(model, MOI.RawOptimizerAttribute("CPXPARAM_TimeLimit"))
return limit === _TIME_LIMIT_DEFAULT ? nothing : limit
end
MOI.supports_incremental_interface(::Optimizer) = true
# !!! info
# If modifying this function, read the comment in the defintion of Optimizer
# about the need for `pass_names`.
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)
attributes = MOI.AbstractModelAttribute[]
if model.objective_sense !== nothing
push!(attributes, MOI.ObjectiveSense())
end
if model.objective_type != _UNSET_OBJECTIVE
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(::Optimizer, ::MOI.ListOfConstraintAttributesSet)
return MOI.AbstractConstraintAttribute[MOI.ConstraintName()]
end
function MOI.get(
::Optimizer,
::MOI.ListOfConstraintAttributesSet{MOI.VariableIndex},
)
return MOI.AbstractConstraintAttribute[]
end
function _indices_and_coefficients(
indices::AbstractVector{Cint},
coefficients::AbstractVector{Float64},
model::Optimizer,
f::MOI.ScalarAffineFunction{Float64},
)
for (i, term) in enumerate(f.terms)
indices[i] = Cint(column(model, term.variable) - 1)
coefficients[i] = term.coefficient
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{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] = Cint(column(model, term.variable_1) - 1)
J[i] = Cint(column(model, term.variable_2) - 1)
V[i] = term.coefficient
# CPLEX returns a list of terms. MOI requires 0.5 x' Q x. So, to get
# from
# CPLEX -> MOI => multiply diagonals by 2.0
# MOI -> CPLEX => 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|
# CPLEX 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] = Cint(column(model, term.variable) - 1)
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{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}) = (Cchar('L'), s.upper)
_sense_and_rhs(s::MOI.GreaterThan{Float64}) = (Cchar('G'), s.lower)
_sense_and_rhs(s::MOI.EqualTo{Float64}) = (Cchar('E'), 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::MOI.VariableIndex)
Return the 1-indexed column associated with `x`.
The C API requires 0-indexed columns.
"""
function column(model::Optimizer, x::MOI.VariableIndex)
return _info(model, x).column
end
function column(model::Optimizer, x::Vector{MOI.VariableIndex})
return [_info(model, xi).column for xi in x]
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)
info.index = index
info.column = length(model.variable_info)
ret = CPXnewcols(
model.env,
model.lp,
1,
C_NULL,
[-Inf],
C_NULL,
C_NULL,
C_NULL,
)
_check_ret(model, ret)
return index
end
function MOI.add_variables(model::Optimizer, N::Int)
ret = CPXnewcols(
model.env,
model.lp,
N,
C_NULL,
fill(-Inf, N),
C_NULL,
C_NULL,
C_NULL,
)
_check_ret(model, ret)
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)
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
# Helper function used inside MOI.delete (vector version). Takes a list of
# numbers (MOI.VariableIndex) sorted by increasing values, return two lists
# representing the same set of numbers but in the form of intervals.
# Ex.: _intervalize([1, 3, 4, 5, 8, 10, 11]) -> ([1, 3, 8, 10], [1, 5, 8, 11])
function _intervalize(xs)
starts, ends = empty(xs), empty(xs)
for x in xs
if isempty(starts) || x != last(ends) + 1
push!(starts, x)
push!(ends, x)
else
ends[end] = x
end
end
return starts, ends
end
function MOI.delete(model::Optimizer, indices::Vector{<:MOI.VariableIndex})
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))
starts, ends = _intervalize(sorted_del_cols)
for ri in reverse(1:length(starts))
ret = CPXdelcols(
model.env,
model.lp,
Cint(starts[ri] - 1),
Cint(ends[ri] - 1),
)
_check_ret(model, ret)
end
for var_idx in indices
delete!(model.variable_info, var_idx)
end
# When the deleted variables are not contiguous, the main advantage of this
# method is that the loop below is O(n*log(m)) instead of the O(m*n) of the
# repeated application of single variable delete (n is the total number of
# variables in the model, m is the number of deleted variables).
for other_info in values(model.variable_info)
# The trick here is: `searchsortedlast` returns, in O(log n), the
# last index with a row smaller than `other_info.row`, over
# `sorted_del_cols` this is the same as the number of rows deleted
# before it, and how much its value need to be shifted.
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 VariableIndex
# constraint names without v.
model.name_to_constraint_index = nothing
return
end
function MOI.delete(model::Optimizer, v::MOI.VariableIndex)
info = _info(model, v)
if info.num_soc_constraints > 0
throw(MOI.DeleteNotAllowed(v))
end
ret = CPXdelcols(
model.env,
model.lp,
Cint(info.column - 1),
Cint(info.column - 1),
)
_check_ret(model, ret)
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 VariableIndex
# 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)
if model.pass_names && info.name != name && isascii(name)
ret = CPXchgname(
model.env,
model.lp,
Cchar('c'),
Cint(info.column - 1),
name,
)
_check_ret(model, ret)
end
info.name = name
model.name_to_variable = nothing
return
end
###
### Objectives
###
function _zero_objective(model::Optimizer)
num_vars = length(model.variable_info)
n = fill(Cint(0), num_vars)
ret = CPXcopyquad(model.env, model.lp, n, n, Cint[], Cdouble[])
_check_ret(model, ret)
ind = convert(Vector{Cint}, 0:(num_vars-1))
obj = zeros(Float64, num_vars)
ret = CPXchgobj(model.env, model.lp, length(ind), ind, obj)
_check_ret(model, ret)
ret = CPXchgobjoffset(model.env, model.lp, 0.0)
_check_ret(model, ret)
return
end
function MOI.set(
model::Optimizer,
::MOI.ObjectiveSense,
sense::MOI.OptimizationSense,
)
ret = if sense == MOI.MIN_SENSE
CPXchgobjsen(model.env, model.lp, CPX_MIN)
elseif sense == MOI.MAX_SENSE
CPXchgobjsen(model.env, model.lp, CPX_MAX)
else
@assert sense == MOI.FEASIBILITY_SENSE
_zero_objective(model)
CPXchgobjsen(model.env, model.lp, CPX_MIN)
end
_check_ret(model, ret)
model.objective_sense = sense
return
end
function MOI.get(model::Optimizer, ::MOI.ObjectiveSense)
return something(model.objective_sense, MOI.FEASIBILITY_SENSE)
end
function MOI.set(
model::Optimizer,
::MOI.ObjectiveFunction{F},
f::F,
) where {F<:MOI.VariableIndex}
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.VariableIndex})
obj = MOI.get(
model,
MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(),
)
return convert(MOI.VariableIndex, obj)
end
function MOI.set(
model::Optimizer,
::MOI.ObjectiveFunction{F},
f::F,
) where {F<:MOI.ScalarAffineFunction{Float64}}
num_vars = length(model.variable_info)
if model.objective_type == _SCALAR_QUADRATIC
# We need to zero out the existing quadratic objective.
ret = CPXcopyquad(
model.env,
model.lp,
fill(Cint(0), num_vars),
fill(Cint(0), num_vars),
Ref{Cint}(),
Ref{Cdouble}(),
)
_check_ret(model, ret)
end
obj = zeros(Float64, num_vars)
for term in f.terms
col = column(model, term.variable)
obj[col] += term.coefficient
end
ind = convert(Vector{Cint}, 0:(num_vars-1))
ret = CPXchgobj(model.env, model.lp, num_vars, ind, obj)
_check_ret(model, ret)
ret = CPXchgobjoffset(model.env, model.lp, f.constant)
_check_ret(model, ret)
model.objective_type = _SCALAR_AFFINE
return
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).",