forked from jump-dev/JuMP.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstraints.jl
1534 lines (1275 loc) · 44.2 KB
/
constraints.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 2017, Iain Dunning, Joey Huchette, Miles Lubin, and contributors
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
#############################################################################
# JuMP
# An algebraic modeling language for Julia
# See https://github.com/jump-dev/JuMP.jl
#############################################################################
"""
ConstraintRef
Holds a reference to the model and the corresponding MOI.ConstraintIndex.
"""
struct ConstraintRef{M<:AbstractModel,C,Shape<:AbstractShape}
model::M
index::C
shape::Shape
end
function Base.getindex(x::Array{<:ConstraintRef}; kwargs...)
if isempty(kwargs)
if length(x) == 1
return first(x)
end
throw(BoundsError(x, tuple()))
end
return throw(_get_index_keyword_indexing_error())
end
"""
index(cr::ConstraintRef)::MOI.ConstraintIndex
Return the index of the constraint that corresponds to `cr` in the MOI backend.
"""
index(cr::ConstraintRef) = cr.index
"""
struct ConstraintNotOwned{C <: ConstraintRef} <: Exception
constraint_ref::C
end
The constraint `constraint_ref` was used in a model different to
`owner_model(constraint_ref)`.
"""
struct ConstraintNotOwned{C<:ConstraintRef} <: Exception
constraint_ref::C
end
"""
owner_model(con_ref::ConstraintRef)
Returns the model to which `con_ref` belongs.
"""
owner_model(con_ref::ConstraintRef) = con_ref.model
"""
check_belongs_to_model(con_ref::ConstraintRef, model::AbstractModel)
Throw `ConstraintNotOwned` if `owner_model(con_ref)` is not `model`.
"""
function check_belongs_to_model(con_ref::ConstraintRef, model::AbstractModel)
if owner_model(con_ref) !== model
throw(ConstraintNotOwned(con_ref))
end
end
Base.broadcastable(con_ref::ConstraintRef) = Ref(con_ref)
"""
dual_start_value(con_ref::ConstraintRef)
Return the dual start value (MOI attribute `ConstraintDualStart`) of the
constraint `con_ref`.
Note: If no dual start value has been set, `dual_start_value` will return
`nothing`.
See also [`set_dual_start_value`](@ref).
"""
function dual_start_value(
con_ref::ConstraintRef{<:AbstractModel,<:MOI.ConstraintIndex},
)
return reshape_vector(_dual_start(con_ref), dual_shape(con_ref.shape))
end
function _value_type(
::Type{M},
::Type{F},
) where {M<:AbstractModel,F<:MOI.AbstractFunction}
return MOI.Utilities.value_type(value_type(M), F)
end
_value_type(::Any, ::Any) = Any
function _value_type(::ConstraintRef{M,<:MOI.ConstraintIndex{F}}) where {M,F}
return _value_type(M, F)
end
# Returns the value of MOI.ConstraintDualStart in a type-stable way
function _dual_start(
con_ref::ConstraintRef{M,MOI.ConstraintIndex{F,S}},
)::Union{Nothing,_value_type(M, F)} where {M<:AbstractModel,F,S}
return MOI.get(owner_model(con_ref), MOI.ConstraintDualStart(), con_ref)
end
"""
set_dual_start_value(con_ref::ConstraintRef, value)
Set the dual start value (MOI attribute `ConstraintDualStart`) of the constraint
`con_ref` to `value`. To remove a dual start value set it to `nothing`.
See also [`dual_start_value`](@ref).
"""
function set_dual_start_value(
con_ref::ConstraintRef{
<:AbstractModel,
<:MOI.ConstraintIndex{
<:MOI.AbstractVectorFunction,
<:MOI.AbstractVectorSet,
},
},
value,
)
vectorized_value = vectorize(value, dual_shape(con_ref.shape))
MOI.set(
owner_model(con_ref),
MOI.ConstraintDualStart(),
con_ref,
_convert_if_something(_value_type(con_ref), vectorized_value),
)
return
end
function set_dual_start_value(
con_ref::ConstraintRef{
<:AbstractModel,
<:MOI.ConstraintIndex{
<:MOI.AbstractVectorFunction,
<:MOI.AbstractVectorSet,
},
},
::Nothing,
)
MOI.set(owner_model(con_ref), MOI.ConstraintDualStart(), con_ref, nothing)
return
end
function set_dual_start_value(
con_ref::ConstraintRef{
<:AbstractModel,
<:MOI.ConstraintIndex{
<:MOI.AbstractScalarFunction,
<:MOI.AbstractScalarSet,
},
},
value,
)
v = _convert_if_something(_value_type(con_ref), value)
MOI.set(owner_model(con_ref), MOI.ConstraintDualStart(), con_ref, v)
return
end
"""
set_start_value(con_ref::ConstraintRef, value)
Set the primal start value ([`MOI.ConstraintPrimalStart`](@ref)) of the
constraint `con_ref` to `value`. To remove a primal start value set it to
`nothing`.
See also [`start_value`](@ref).
"""
function set_start_value(
con_ref::ConstraintRef{
<:AbstractModel,
<:MOI.ConstraintIndex{
<:MOI.AbstractVectorFunction,
<:MOI.AbstractVectorSet,
},
},
value,
)
vectorized_value = vectorize(value, con_ref.shape)
MOI.set(
owner_model(con_ref),
MOI.ConstraintPrimalStart(),
con_ref,
_convert_if_something(_value_type(con_ref), vectorized_value),
)
return
end
function set_start_value(
con_ref::ConstraintRef{
<:AbstractModel,
<:MOI.ConstraintIndex{
<:MOI.AbstractVectorFunction,
<:MOI.AbstractVectorSet,
},
},
::Nothing,
)
MOI.set(owner_model(con_ref), MOI.ConstraintPrimalStart(), con_ref, nothing)
return
end
function set_start_value(
con_ref::ConstraintRef{
<:AbstractModel,
<:MOI.ConstraintIndex{
<:MOI.AbstractScalarFunction,
<:MOI.AbstractScalarSet,
},
},
value,
)
v = _convert_if_something(_value_type(con_ref), value)
MOI.set(owner_model(con_ref), MOI.ConstraintPrimalStart(), con_ref, v)
return
end
"""
start_value(con_ref::ConstraintRef)
Return the primal start value ([`MOI.ConstraintPrimalStart`](@ref)) of the
constraint `con_ref`.
Note: If no primal start value has been set, `start_value` will return
`nothing`.
See also [`set_start_value`](@ref).
"""
function start_value(
con_ref::ConstraintRef{<:AbstractModel,<:MOI.ConstraintIndex},
)
return reshape_vector(
MOI.get(owner_model(con_ref), MOI.ConstraintPrimalStart(), con_ref),
con_ref.shape,
)
end
"""
name(con_ref::ConstraintRef)
Get a constraint's name attribute.
"""
function name(
con_ref::ConstraintRef{<:AbstractModel,C},
) where {C<:MOI.ConstraintIndex}
model = owner_model(con_ref)
if !MOI.supports(backend(model), MOI.ConstraintName(), C)
return ""
end
return MOI.get(model, MOI.ConstraintName(), con_ref)::String
end
# The name of VariableIndex constraints is empty.
function name(
::ConstraintRef{<:AbstractModel,<:MOI.ConstraintIndex{MOI.VariableIndex}},
)
return ""
end
"""
set_name(con_ref::ConstraintRef, s::AbstractString)
Set a constraint's name attribute.
"""
function set_name(
con_ref::ConstraintRef{<:AbstractModel,<:MOI.ConstraintIndex},
s::String,
)
return MOI.set(con_ref.model, MOI.ConstraintName(), con_ref, s)
end
"""
constraint_by_name(model::AbstractModel,
name::String)::Union{ConstraintRef, Nothing}
Return the reference of the constraint with name attribute `name` or `Nothing`
if no constraint has this name attribute. Throws an error if several
constraints have `name` as their name attribute.
constraint_by_name(model::AbstractModel,
name::String,
F::Type{<:Union{AbstractJuMPScalar,
Vector{<:AbstractJuMPScalar},
MOI.AbstactFunction}},
S::Type{<:MOI.AbstractSet})::Union{ConstraintRef, Nothing}
Similar to the method above, except that it throws an error if the constraint is
not an `F`-in-`S` contraint where `F` is either the JuMP or MOI type of the
function, and `S` is the MOI type of the set. This method is recommended if you
know the type of the function and set since its returned type can be inferred
while for the method above (i.e. without `F` and `S`), the exact return type of
the constraint index cannot be inferred.
```jldoctest objective_function; filter = r"Stacktrace:.*"s
julia> model = Model();
julia> @variable(model, x)
x
julia> @constraint(model, con, x^2 == 1)
con : x² = 1
julia> constraint_by_name(model, "kon")
julia> constraint_by_name(model, "con")
con : x² = 1
julia> constraint_by_name(model, "con", AffExpr, MOI.EqualTo{Float64})
julia> constraint_by_name(model, "con", QuadExpr, MOI.EqualTo{Float64})
con : x² = 1
```
"""
function constraint_by_name end
function constraint_by_name(model::GenericModel, name::String)
index = MOI.get(backend(model), MOI.ConstraintIndex, name)
if index isa Nothing
return nothing
else
return constraint_ref_with_index(model, index)
end
end
function constraint_by_name(
model::GenericModel,
name::String,
F::Type{<:MOI.AbstractFunction},
S::Type{<:MOI.AbstractSet},
)
index = MOI.get(backend(model), MOI.ConstraintIndex{F,S}, name)
if index isa Nothing
return nothing
else
return constraint_ref_with_index(model, index)
end
end
function constraint_by_name(
model::GenericModel,
name::String,
F::Type{<:Union{ScalarType,Vector{ScalarType}}},
S::Type,
) where {ScalarType<:AbstractJuMPScalar}
return constraint_by_name(model, name, moi_function_type(F), S)
end
"""
constraint_ref_with_index(model::AbstractModel, index::MOI.ConstraintIndex)
Return a `ConstraintRef` of `model` corresponding to `index`.
"""
function constraint_ref_with_index(
model::AbstractModel,
index::MOI.ConstraintIndex{
<:MOI.AbstractScalarFunction,
<:MOI.AbstractScalarSet,
},
)
return ConstraintRef(model, index, ScalarShape())
end
function constraint_ref_with_index(
model::AbstractModel,
index::MOI.ConstraintIndex{
<:MOI.AbstractVectorFunction,
<:MOI.AbstractVectorSet,
},
)
return ConstraintRef(model, index, get(model.shapes, index, VectorShape()))
end
"""
delete(model::GenericModel, con_ref::ConstraintRef)
Delete the constraint associated with `constraint_ref` from the model `model`.
Note that `delete` does not unregister the name from the model, so adding a new
constraint of the same name will throw an error. Use [`unregister`](@ref) to
unregister the name after deletion.
## Example
```jldoctest
julia> model = Model();
julia> @variable(model, x);
julia> @constraint(model, c, 2x <= 1)
c : 2 x ≤ 1
julia> delete(model, c)
julia> unregister(model, :c)
julia> print(model)
Feasibility
Subject to
julia> model[:c]
ERROR: KeyError: key :c not found
Stacktrace:
[...]
```
"""
function delete(model::GenericModel, con_ref::ConstraintRef)
if model !== con_ref.model
error(
"The constraint reference you are trying to delete does not " *
"belong to the model.",
)
end
model.is_model_dirty = true
return MOI.delete(backend(model), index(con_ref))
end
"""
delete(model::GenericModel, con_refs::Vector{<:ConstraintRef})
Delete the constraints associated with `con_refs` from the model `model`.
Solvers may implement specialized methods for deleting multiple constraints of
the same concrete type, i.e., when `isconcretetype(eltype(con_refs))`. These
may be more efficient than repeatedly calling the single constraint delete
method.
See also: [`unregister`](@ref)
"""
function delete(
model::GenericModel,
con_refs::Vector{<:ConstraintRef{<:AbstractModel}},
)
if any(c -> model !== c.model, con_refs)
error("A constraint reference you are trying to delete does not" * "
belong to the model.")
end
model.is_model_dirty = true
MOI.delete(backend(model), index.(con_refs))
return
end
"""
is_valid(model::GenericModel, con_ref::ConstraintRef{<:AbstractModel})
Return `true` if `constraint_ref` refers to a valid constraint in `model`.
"""
function is_valid(model::GenericModel, con_ref::ConstraintRef{<:AbstractModel})
return (
model === con_ref.model && MOI.is_valid(backend(model), con_ref.index)
)
end
#############################################################################
# AbstractConstraint
"""
abstract type AbstractConstraint
An abstract base type for all constraint types. `AbstractConstraint`s store the
function and set directly, unlike [`ConstraintRef`](@ref)s that are merely
references to constraints stored in a model. `AbstractConstraint`s do not need
to be attached to a model.
"""
abstract type AbstractConstraint end
"""
BridgeableConstraint(
constraint::C,
bridge_type::B;
coefficient_type::Type{T} = Float64,
) where {C<:AbstractConstraint,B<:Type{<:MOI.Bridges.AbstractBridge},T}
An [`AbstractConstraint`](@ref) representinng that `constraint` that can be
bridged by the bridge of type `bridge_type{coefficient_type}`.
Adding a `BridgeableConstraint` to a model is equivalent to:
```julia
add_bridge(model, bridge_type; coefficient_type = coefficient_type)
add_constraint(model, constraint)
```
## Example
Given a new scalar set type `CustomSet` with a bridge `CustomBridge` that can
bridge `F`-in-`CustomSet` constraints, when the user does:
```julia
model = Model()
@variable(model, x)
@constraint(model, x + 1 in CustomSet())
optimize!(model)
```
with an optimizer that does not support `F`-in-`CustomSet` constraints, the
constraint will not be bridged unless they first call
`add_bridge(model, CustomBridge)`.
In order to automatically add the `CustomBridge` to any model to
which an `F`-in-`CustomSet` is added, add the following method:
```julia
function JuMP.build_constraint(
error_fn::Function,
func::AbstractJuMPScalar,
set::CustomSet,
)
constraint = ScalarConstraint(func, set)
return BridgeableConstraint(constraint, CustomBridge)
end
```
## Note
JuMP extensions should extend `JuMP.build_constraint` only if they also defined
`CustomSet`, for three reasons:
1. It is problematic if multiple extensions overload the same JuMP method.
2. A missing method will not inform the users that they forgot to load the
extension module defining the `build_constraint` method.
3. Defining a method where neither the function nor any of the argument types
are defined in the package is called [*type piracy*](https://docs.julialang.org/en/v1/manual/style-guide/index.html#Avoid-type-piracy-1)
and is discouraged in the Julia style guide.
"""
struct BridgeableConstraint{C,B,T} <: AbstractConstraint
constraint::C
bridge_type::B
coefficient_type::Type{T}
function BridgeableConstraint(
constraint::C,
bridge_type::B;
coefficient_type::Type{T} = Float64,
) where {C,B,T}
return new{C,B,T}(constraint, bridge_type, T)
end
end
function add_constraint(
model::GenericModel,
con::BridgeableConstraint,
name::String = "",
)
add_bridge(model, con.bridge_type; coefficient_type = con.coefficient_type)
return add_constraint(model, con.constraint, name)
end
"""
jump_function(constraint::AbstractConstraint)
Return the function of the constraint `constraint` in the function-in-set form
as a `AbstractJuMPScalar` or `Vector{AbstractJuMPScalar}`.
"""
jump_function(constraint::AbstractConstraint) = constraint.func
"""
moi_function(constraint::AbstractConstraint)
Return the function of the constraint `constraint` in the function-in-set form
as a `MathOptInterface.AbstractFunction`.
"""
function moi_function(constraint::AbstractConstraint)
return moi_function(jump_function(constraint))
end
"""
moi_set(constraint::AbstractConstraint)
Return the set of the constraint `constraint` in the function-in-set form as a
`MathOptInterface.AbstractSet`.
moi_set(s::AbstractVectorSet, dim::Int)
Returns the MOI set of dimension `dim` corresponding to the JuMP set `s`.
moi_set(s::AbstractScalarSet)
Returns the MOI set corresponding to the JuMP set `s`.
"""
moi_set(constraint::AbstractConstraint) = constraint.set
"""
constraint_object(con_ref::ConstraintRef)
Return the underlying constraint data for the constraint referenced by `ref`.
"""
function constraint_object end
"""
struct ScalarConstraint
The data for a scalar constraint. The `func` field contains a JuMP object
representing the function and the `set` field contains the MOI set.
See also the [documentation](@ref Constraints) on JuMP's representation of
constraints for more background.
"""
struct ScalarConstraint{
F<:Union{Number,AbstractJuMPScalar},
S<:MOI.AbstractScalarSet,
} <: AbstractConstraint
func::F
set::S
end
reshape_set(set::MOI.AbstractScalarSet, ::ScalarShape) = set
shape(::ScalarConstraint) = ScalarShape()
function constraint_object(
con_ref::ConstraintRef{
<:AbstractModel,
MOI.ConstraintIndex{FuncType,SetType},
},
) where {FuncType<:MOI.AbstractScalarFunction,SetType<:MOI.AbstractScalarSet}
model = con_ref.model
f = MOI.get(model, MOI.ConstraintFunction(), con_ref)::FuncType
s = MOI.get(model, MOI.ConstraintSet(), con_ref)::SetType
return ScalarConstraint(jump_function(model, f), s)
end
function check_belongs_to_model(con::ScalarConstraint, model)
return check_belongs_to_model(con.func, model)
end
"""
struct VectorConstraint
The data for a vector constraint. The `func` field contains a JuMP object
representing the function and the `set` field contains the MOI set. The
`shape` field contains an [`AbstractShape`](@ref) matching the form in which
the constraint was constructed (e.g., by using matrices or flat vectors).
See also the [documentation](@ref Constraints) on JuMP's representation of
constraints.
"""
struct VectorConstraint{
F<:Union{Number,AbstractJuMPScalar},
S<:MOI.AbstractVectorSet,
Shape<:AbstractShape,
} <: AbstractConstraint
func::Vector{F}
set::S
shape::Shape
end
function VectorConstraint(
func::Vector{<:Union{Number,AbstractJuMPScalar}},
set::MOI.AbstractVectorSet,
)
if length(func) != MOI.dimension(set)
throw(
DimensionMismatch(
"Dimension of the function $(length(func)) does not match the " *
"dimension of the set $(set).",
),
)
end
return VectorConstraint(func, set, VectorShape())
end
function VectorConstraint(
func::AbstractVector{<:Union{Number,AbstractJuMPScalar}},
set::MOI.AbstractVectorSet,
)
# collect() is not used here so that DenseAxisArray will work
f = [func[idx] for idx in eachindex(func)]
return VectorConstraint(f, set)
end
reshape_set(set::MOI.AbstractVectorSet, ::VectorShape) = set
shape(con::VectorConstraint) = con.shape
function constraint_object(
con_ref::ConstraintRef{
<:AbstractModel,
MOI.ConstraintIndex{FuncType,SetType},
},
) where {FuncType<:MOI.AbstractVectorFunction,SetType<:MOI.AbstractVectorSet}
model = con_ref.model
f = MOI.get(model, MOI.ConstraintFunction(), con_ref)::FuncType
s = MOI.get(model, MOI.ConstraintSet(), con_ref)::SetType
return VectorConstraint(jump_function(model, f), s, con_ref.shape)
end
function check_belongs_to_model(con::VectorConstraint, model)
for func in con.func
check_belongs_to_model(func, model)
end
end
function _moi_add_constraint(
model::MOI.ModelLike,
f::F,
s::S,
) where {F<:MOI.AbstractFunction,S<:MOI.AbstractSet}
if !MOI.supports_constraint(model, F, S)
error(
"Constraints of type $(F)-in-$(S) are not supported by the " *
"solver.\n\nIf you expected the solver to support your problem, " *
"you may have an error in your formulation. Otherwise, consider " *
"using a different solver.\n\nThe list of available solvers, " *
"along with the problem types they support, is available at " *
"https://jump.dev/JuMP.jl/stable/installation/#Supported-solvers.",
)
end
return MOI.add_constraint(model, f, s)
end
"""
add_constraint(model::GenericModel, con::AbstractConstraint, name::String="")
Add a constraint `con` to `Model model` and sets its name.
"""
function add_constraint(
model::GenericModel,
con::AbstractConstraint,
name::String = "",
)
con = model_convert(model, con)
# The type of backend(model) is unknown so we directly redirect to another
# function.
check_belongs_to_model(con, model)
func, set = moi_function(con), moi_set(con)
cindex = _moi_add_constraint(
backend(model),
func,
set,
)::MOI.ConstraintIndex{typeof(func),typeof(set)}
cshape = shape(con)
if !(cshape isa ScalarShape) && !(cshape isa VectorShape)
model.shapes[cindex] = cshape
end
con_ref = ConstraintRef(model, cindex, cshape)
# Only set names if appropriate!
if !(func isa MOI.VariableIndex) &&
!isempty(name) &&
MOI.supports(backend(model), MOI.ConstraintName(), typeof(cindex))
set_name(con_ref, name)
end
model.is_model_dirty = true
return con_ref
end
"""
set_normalized_rhs(constraint::ConstraintRef, value)
Set the right-hand side term of `constraint` to `value`.
Note that prior to this step, JuMP will aggregate all constant terms onto the
right-hand side of the constraint. For example, given a constraint `2x + 1 <=
2`, `set_normalized_rhs(con, 4)` will create the constraint `2x <= 4`, not `2x +
1 <= 4`.
## Example
```jldoctest; filter=r"≤|<="
julia> model = Model();
julia> @variable(model, x);
julia> @constraint(model, con, 2x + 1 <= 2)
con : 2 x ≤ 1
julia> set_normalized_rhs(con, 4)
julia> con
con : 2 x ≤ 4
```
"""
function set_normalized_rhs(
con_ref::ConstraintRef{<:AbstractModel,MOI.ConstraintIndex{F,S}},
value,
) where {
T,
S<:Union{MOI.LessThan{T},MOI.GreaterThan{T},MOI.EqualTo{T}},
F<:Union{MOI.ScalarAffineFunction{T},MOI.ScalarQuadraticFunction{T}},
}
MOI.set(
owner_model(con_ref),
MOI.ConstraintSet(),
con_ref,
S(convert(T, value)),
)
return
end
"""
normalized_rhs(constraint::ConstraintRef)
Return the right-hand side term of `constraint` after JuMP has converted the
constraint into its normalized form.
See also [`set_normalized_rhs`](@ref).
## Example
```jldoctest; filter=r"≤|<="
julia> model = Model();
julia> @variable(model, x);
julia> @constraint(model, con, 2x + 1 <= 2)
con : 2 x ≤ 1
julia> normalized_rhs(con)
1.0
```
"""
function normalized_rhs(
con_ref::ConstraintRef{<:AbstractModel,MOI.ConstraintIndex{F,S}},
) where {
T,
S<:Union{MOI.LessThan{T},MOI.GreaterThan{T},MOI.EqualTo{T}},
F<:Union{MOI.ScalarAffineFunction{T},MOI.ScalarQuadraticFunction{T}},
}
con = constraint_object(con_ref)
return MOI.constant(con.set)
end
function _moi_add_to_function_constant(
model::MOI.ModelLike,
ci::MOI.ConstraintIndex{
<:MOI.AbstractScalarFunction,
<:MOI.AbstractScalarSet,
},
value,
)
set = MOI.get(model, MOI.ConstraintSet(), ci)
if !MOI.Utilities.supports_shift_constant(typeof(set))
error(
"Unable to add to function constant for constraint type " *
"$(typeof(ci))",
)
end
new_set = MOIU.shift_constant(set, -value)
return MOI.set(model, MOI.ConstraintSet(), ci, new_set)
end
function _moi_add_to_function_constant(
model::MOI.ModelLike,
ci::MOI.ConstraintIndex{
<:Union{MOI.VectorAffineFunction,MOI.VectorQuadraticFunction},
<:MOI.AbstractVectorSet,
},
value,
)
func = MOI.get(model, MOI.ConstraintFunction(), ci)
new_constant = value + MOI.constant(func)
return MOI.modify(model, ci, MOI.VectorConstantChange(new_constant))
end
"""
add_to_function_constant(constraint::ConstraintRef, value)
Add `value` to the function constant term of `constraint`.
Note that for scalar constraints, JuMP will aggregate all constant terms onto
the right-hand side of the constraint so instead of modifying the function, the
set will be translated by `-value`. For example, given a constraint `2x <=
3`, `add_to_function_constant(c, 4)` will modify it to `2x <= -1`.
## Example
For scalar constraints, the set is translated by `-value`:
```jldoctest; filter=r"≤|<="
julia> model = Model();
julia> @variable(model, x);
julia> @constraint(model, con, 0 <= 2x - 1 <= 2)
con : 2 x ∈ [1, 3]
julia> add_to_function_constant(con, 4)
julia> con
con : 2 x ∈ [-3, -1]
```
For vector constraints, the constant is added to the function:
```jldoctest; filter=r"≤|<="
julia> model = Model();
julia> @variable(model, x);
julia> @variable(model, y);
julia> @constraint(model, con, [x + y, x, y] in SecondOrderCone())
con : [x + y, x, y] ∈ MathOptInterface.SecondOrderCone(3)
julia> add_to_function_constant(con, [1, 2, 2])
julia> con
con : [x + y + 1, x + 2, y + 2] ∈ MathOptInterface.SecondOrderCone(3)
```
"""
function add_to_function_constant(
constraint::ConstraintRef{<:AbstractModel},
value,
)
model = owner_model(constraint)
# The type of `backend(model)` is not type-stable, so we use a function
# barrier (`_moi_add_to_function_constant`) to improve performance.
_moi_add_to_function_constant(backend(model), index(constraint), value)
model.is_model_dirty = true
return
end
"""
value(con_ref::ConstraintRef; result::Int = 1)
Return the primal value of constraint `con_ref` associated with result index
`result` of the most-recent solution returned by the solver.
That is, if `con_ref` is the reference of a constraint `func`-in-`set`, it
returns the value of `func` evaluated at the value of the variables (given by
[`value(::GenericVariableRef)`](@ref)).
Use [`has_values`](@ref) to check if a result exists before asking for values.
See also: [`result_count`](@ref).
## Note
For scalar constraints, the constant is moved to the `set` so it is not taken
into account in the primal value of the constraint. For instance, the constraint
`@constraint(model, 2x + 3y + 1 == 5)` is transformed into
`2x + 3y`-in-`MOI.EqualTo(4)` so the value returned by this function is the
evaluation of `2x + 3y`.
"""
function value(
con_ref::ConstraintRef{<:AbstractModel,<:MOI.ConstraintIndex};
result::Int = 1,
)
return reshape_vector(_constraint_primal(con_ref, result), con_ref.shape)
end
"""
value(var_value::Function, con_ref::ConstraintRef)
Evaluate the primal value of the constraint `con_ref` using `var_value(v)`
as the value for each variable `v`.
"""
function value(
var_value::Function,
con_ref::ConstraintRef{<:AbstractModel,<:MOI.ConstraintIndex},
)
f = jump_function(constraint_object(con_ref))
return reshape_vector(value.(var_value, f), con_ref.shape)
end
# Returns the value of MOI.ConstraintPrimal in a type-stable way
function _constraint_primal(
con_ref::ConstraintRef{M,MOI.ConstraintIndex{F,S}},
result::Int,
)::_value_type(M, F) where {M<:AbstractModel,F,S}
return MOI.get(con_ref.model, MOI.ConstraintPrimal(result), con_ref)
end
"""
has_duals(model::GenericModel; result::Int = 1)
Return `true` if the solver has a dual solution in result index `result`
available to query, otherwise return `false`.
See also [`dual`](@ref), [`shadow_price`](@ref), and [`result_count`](@ref).
"""
function has_duals(model::GenericModel; result::Int = 1)
return dual_status(model; result = result) != MOI.NO_SOLUTION
end
"""
dual(con_ref::ConstraintRef; result::Int = 1)
Return the dual value of constraint `con_ref` associated with result index
`result` of the most-recent solution returned by the solver.
Use `has_dual` to check if a result exists before asking for values.
See also: [`result_count`](@ref), [`shadow_price`](@ref).
"""
function dual(
con_ref::ConstraintRef{<:AbstractModel,<:MOI.ConstraintIndex};
result::Int = 1,
)
return reshape_vector(
_constraint_dual(con_ref, result),
dual_shape(con_ref.shape),
)
end
# Returns the value of MOI.ConstraintDual in a type-stable way
function _constraint_dual(
con_ref::ConstraintRef{M,MOI.ConstraintIndex{F,S}},
result::Int,
)::_value_type(M, F) where {M<:AbstractModel,F,S}
return MOI.get(con_ref.model, MOI.ConstraintDual(result), con_ref)
end
"""
shadow_price(con_ref::ConstraintRef)
Return the change in the objective from an infinitesimal relaxation of the
constraint.
This value is computed from [`dual`](@ref) and can be queried only when
`has_duals` is `true` and the objective sense is `MIN_SENSE` or `MAX_SENSE`
(not `FEASIBILITY_SENSE`). For linear constraints, the shadow prices differ at
most in sign from the `dual` value depending on the objective sense.
See also [`reduced_cost`](@ref JuMP.reduced_cost).