-
-
Notifications
You must be signed in to change notification settings - Fork 390
/
variables.jl
588 lines (489 loc) · 17.9 KB
/
variables.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
# 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 http://mozilla.org/MPL/2.0/.
abstract type AbstractVariable end
# Any fields can usually be either a number or an expression
mutable struct VariableInfoExpr
has_lb::Bool
lower_bound::Any
has_ub::Bool
upper_bound::Any
has_fix::Bool
fixed_value::Any
has_start::Bool
start::Any
binary::Any
integer::Any
end
function set_lower_bound_or_error(_error::Function, info::VariableInfoExpr, lower)
info.has_lb && _error("Cannot specify variable lower_bound twice")
info.has_lb = true
info.lower_bound = lower
end
function set_upper_bound_or_error(_error::Function, info::VariableInfoExpr, upper)
info.has_ub && _error("Cannot specify variable upper_bound twice")
info.has_ub = true
info.upper_bound = upper
end
function fix_or_error(_error::Function, info::VariableInfoExpr, value)
info.has_fix && _error("Cannot specify variable fixed value twice")
info.has_fix = true
info.fixed_value = value
end
function set_binary_or_error(_error::Function, info::VariableInfoExpr)
info.binary === false || _error("'Bin' and 'binary' keyword argument cannot both be specified.")
info.binary = true
end
function set_integer_or_error(_error::Function, info::VariableInfoExpr)
info.integer === false || _error("'Int' and 'integer' keyword argument cannot both be specified.")
info.integer = true
end
function is_info_keyword(kw::Expr)
kw.args[1] in [:lower_bound, :upper_bound, :start, :binary, :integer]
end
# :(start = 0) -> (:start, 0)
# :(start = i + 1) -> (:start, :($(Expr(:escape, :(i + 1)))))
function keywordify(kw::Expr)
(kw.args[1], esc_nonconstant(kw.args[2]))
end
function VariableInfoExpr(; lower_bound=NaN, upper_bound=NaN, start=NaN, binary=false, integer=false)
# isnan(::Expr) is not defined so we need to do !== NaN
VariableInfoExpr(lower_bound !== NaN, lower_bound, upper_bound !== NaN, upper_bound, false, NaN, start !== NaN, start, binary, integer)
end
struct VariableInfo{S, T, U, V}
has_lb::Bool
lower_bound::S
has_ub::Bool
upper_bound::T
has_fix::Bool
fixed_value::U
has_start::Bool
start::V
binary::Bool
integer::Bool
end
function constructor_expr(info::VariableInfoExpr)
return :(VariableInfo($(info.has_lb), $(info.lower_bound), $(info.has_ub),
$(info.upper_bound), $(info.has_fix), $(info.fixed_value),
$(info.has_start), $(info.start), $(info.binary), $(info.integer)))
end
struct ScalarVariable{S, T, U, V} <: AbstractVariable
info::VariableInfo{S, T, U, V}
end
"""
AbstractVariableRef
Variable returned by [`add_variable`](@ref). Affine (resp. quadratic) operations
with variables of type `V<:AbstractVariableRef` and coefficients of type `T`
create a `GenericAffExpr{T,V}` (resp. `GenericQuadExpr{T,V}`).
"""
abstract type AbstractVariableRef <: AbstractJuMPScalar end
variable_ref_type(v::AbstractVariableRef) = typeof(v)
"""
VariableRef <: AbstractVariableRef
Holds a reference to the model and the corresponding MOI.VariableIndex.
"""
struct VariableRef <: AbstractVariableRef
model::Model
index::MOI.VariableIndex
end
# `AbstractVariableRef` types must override the default `owner_model` if the field
# name is not `model`.
"""
owner_model(v::AbstractVariableRef)
Returns the model to which `v` belongs.
# Example
```jldoctest
julia> model = Model()
julia> x = @variable(model)
julia> JuMP.owner_model(x) === model
true
"""
owner_model(v::AbstractVariableRef) = v.model
Base.iszero(::VariableRef) = false
Base.copy(v::VariableRef) = VariableRef(v.model, v.index)
if VERSION >= v"0.7-"
Base.broadcastable(v::VariableRef) = Ref(v)
end
isequal_canonical(v::VariableRef, other::VariableRef) = isequal(v, other)
"""
delete(model::Model, variable_ref::VariableRef)
Delete the variable associated with `variable_ref` from the model `model`.
"""
function delete(model::Model, variable_ref::VariableRef)
if model !== owner_model(variable_ref)
error("The variable reference you are trying to delete does not " *
"belong to the model.")
end
MOI.delete(model.moi_backend, variable_ref.index)
end
"""
is_valid(model::Model, variable_ref::VariableRef)
Return `true` if `variable` refers to a valid variable in `model`.
"""
function is_valid(model::Model, variable_ref::VariableRef)
return (model === owner_model(variable_ref) &&
MOI.is_valid(model.moi_backend, variable_ref.index))
end
# The default hash is slow. It's important for the performance of AffExpr to
# define our own.
# https://github.com/JuliaOpt/MathOptInterface.jl/issues/234#issuecomment-366868878
function Base.hash(v::VariableRef, h::UInt)
return hash(objectid(owner_model(v)), hash(v.index.value, h))
end
function Base.isequal(v1::VariableRef, v2::VariableRef)
return owner_model(v1) === owner_model(v2) && v1.index == v2.index
end
"""
VariableToValueMap{T}
An object for storing a mapping from variables to a value of type `T`.
"""
struct VariableToValueMap{T}
model::Model
d::Dict{MOIVAR,T}
end
function VariableToValueMap{T}(m::Model) where T
return VariableToValueMap{T}(m, Dict{MOIVAR,T}())
end
function Base.getindex(vm::VariableToValueMap, v::VariableRef)
@assert owner_model(v) === vm.model # TODO: better error message
return vm.d[index(v)]
end
function Base.setindex!(vm::VariableToValueMap{T}, value::T, v::VariableRef) where T
@assert owner_model(v) === vm.model # TODO: better error message
vm.d[index(v)] = value
end
Base.setindex!(vm::VariableToValueMap{T}, value, v::VariableRef) where T = setindex!(vm, convert(T, value), v)
function Base.delete!(vm::VariableToValueMap,v::VariableRef)
delete!(vm.d, index(v))
vm
end
Base.empty!(vm::VariableToValueMap) = empty!(vm.d)
Base.isempty(vm::VariableToValueMap) = isempty(vm.d)
function Base.haskey(vm::VariableToValueMap, v::VariableRef)
return (vm.model === owner_model(v)) && haskey(vm.d, index(v))
end
index(v::VariableRef) = v.index
function VariableRef(m::Model)
index = MOI.add_variable(m.moi_backend)
return VariableRef(m, index)
end
# Name setter/getters
# These functions need to be implemented for all `AbstractVariableRef`s
"""
name(v::VariableRef)::String
Get a variable's name.
"""
name(v::VariableRef) = MOI.get(owner_model(v), MOI.VariableName(), v)
"""
set_name(v::VariableRef,s::AbstractString)
Set a variable's name.
"""
function set_name(v::VariableRef, s::String)
return MOI.set(owner_model(v), MOI.VariableName(), v, s)
end
MOI.SingleVariable(v::VariableRef) = MOI.SingleVariable(index(v))
function moi_function(variable::AbstractVariableRef)
return MOI.SingleVariable(variable)
end
# Note: No validation is performed that the variables belong to the same model.
MOI.VectorOfVariables(vars::Vector{VariableRef}) = MOI.VectorOfVariables(index.(vars))
function moi_function(variables::Vector{<:AbstractVariableRef})
return MOI.VectorOfVariables(variables)
end
function jump_function(model::AbstractModel, variables::MOI.VectorOfVariables)
return map(v -> VariableRef(model, v), variables.variables)
end
VariableRef(m::Model, f::MOI.SingleVariable) = VariableRef(m, f.variable)
function jump_function(model::AbstractModel, variable::MOI.SingleVariable)
return VariableRef(model, variable)
end
"""
objective_function(m::Model, ::Type{VariableRef})
Return a `VariableRef` object representing the objective function.
Error if the objective is not a `SingleVariable`.
"""
function objective_function(m::Model, ::Type{VariableRef})
f = MOI.get(m.moi_backend, MOI.ObjectiveFunction{MOI.SingleVariable}())::MOI.SingleVariable
return VariableRef(m, f)
end
## Bound setter/getters
# lower bounds
function has_lower_bound(v::VariableRef)
return haskey(owner_model(v).variable_to_lower_bound, index(v))
end
function lower_bound_index(v::VariableRef)
@assert has_lower_bound(v) # TODO error message
return owner_model(v).variable_to_lower_bound[index(v)]
end
function set_lower_bound_index(v::VariableRef, cindex::MOILB)
owner_model(v).variable_to_lower_bound[index(v)] = cindex
end
"""
set_lower_bound(v::VariableRef,lower::Number)
Set the lower bound of a variable. If one does not exist, create a new lower bound constraint.
"""
function set_lower_bound(v::VariableRef,lower::Number)
newset = MOI.GreaterThan(convert(Float64,lower))
# do we have a lower bound already?
if has_lower_bound(v)
cindex = lower_bound_index(v)
MOI.set(owner_model(v).moi_backend, MOI.ConstraintSet(), cindex, newset)
else
@assert !is_fixed(v)
cindex = MOI.add_constraint(owner_model(v).moi_backend,
MOI.SingleVariable(index(v)), newset)
set_lower_bound_index(v, cindex)
end
nothing
end
function LowerBoundRef(v::VariableRef)
return ConstraintRef{Model, MOILB, ScalarShape}(owner_model(v),
lower_bound_index(v),
ScalarShape())
end
"""
delete_lower_bound(v::VariableRef)
Delete the lower bound constraint of a variable.
"""
function delete_lower_bound(variable_ref::VariableRef)
JuMP.delete(owner_model(variable_ref), LowerBoundRef(variable_ref))
delete!(owner_model(variable_ref).variable_to_lower_bound,
index(variable_ref))
return
end
"""
lower_bound(v::VariableRef)
Return the lower bound of a variable. Error if one does not exist.
"""
function lower_bound(v::VariableRef)
cset = MOI.get(owner_model(v), MOI.ConstraintSet(),
LowerBoundRef(v))::MOI.GreaterThan
return cset.lower
end
# upper bounds
function has_upper_bound(v::VariableRef)
return haskey(owner_model(v).variable_to_upper_bound, index(v))
end
function upper_bound_index(v::VariableRef)
@assert has_upper_bound(v) # TODO error message
return owner_model(v).variable_to_upper_bound[index(v)]
end
function set_upper_bound_index(v::VariableRef, cindex::MOIUB)
owner_model(v).variable_to_upper_bound[index(v)] = cindex
end
"""
set_upper_bound(v::VariableRef,upper::Number)
Set the upper bound of a variable. If one does not exist, create an upper bound constraint.
"""
function set_upper_bound(v::VariableRef,upper::Number)
newset = MOI.LessThan(convert(Float64,upper))
# do we have an upper bound already?
if has_upper_bound(v)
cindex = upper_bound_index(v)
MOI.set(owner_model(v).moi_backend, MOI.ConstraintSet(), cindex, newset)
else
@assert !is_fixed(v)
cindex = MOI.add_constraint(owner_model(v).moi_backend,
MOI.SingleVariable(index(v)), newset)
set_upper_bound_index(v, cindex)
end
nothing
end
function UpperBoundRef(v::VariableRef)
return ConstraintRef{Model, MOIUB, ScalarShape}(owner_model(v),
upper_bound_index(v),
ScalarShape())
end
"""
delete_upper_bound(v::VariableRef)
Delete the upper bound constraint of a variable.
"""
function delete_upper_bound(variable_ref::VariableRef)
JuMP.delete(owner_model(variable_ref), UpperBoundRef(variable_ref))
delete!(owner_model(variable_ref).variable_to_upper_bound,
index(variable_ref))
return
end
"""
upper_bound(v::VariableRef)
Return the upper bound of a variable. Error if one does not exist.
"""
function upper_bound(v::VariableRef)
cset = MOI.get(owner_model(v), MOI.ConstraintSet(),
UpperBoundRef(v))::MOI.LessThan
return cset.upper
end
# fixed value
is_fixed(v::VariableRef) = haskey(owner_model(v).variable_to_fix, index(v))
function fix_index(v::VariableRef)
@assert is_fixed(v) # TODO error message
return owner_model(v).variable_to_fix[index(v)]
end
function set_fix_index(v::VariableRef, cindex::MOIFIX)
owner_model(v).variable_to_fix[index(v)] = cindex
end
"""
fix(v::VariableRef,upper::Number)
Fix a variable to a value. Update the fixing constraint if one exists, otherwise create a new one.
"""
function fix(v::VariableRef,upper::Number)
newset = MOI.EqualTo(convert(Float64,upper))
# are we already fixed?
if is_fixed(v)
cindex = fix_index(v)
MOI.set(owner_model(v).moi_backend, MOI.ConstraintSet(), cindex, newset)
else
@assert !has_upper_bound(v) && !has_lower_bound(v) # Do we want to remove these instead of throwing an error?
cindex = MOI.add_constraint(owner_model(v).moi_backend,
MOI.SingleVariable(index(v)), newset)
set_fix_index(v, cindex)
end
nothing
end
"""
unfix(v::VariableRef)
Delete the fixing constraint of a variable.
"""
function unfix(variable_ref::VariableRef)
JuMP.delete(owner_model(variable_ref), FixRef(variable_ref))
delete!(owner_model(variable_ref).variable_to_fix, index(variable_ref))
return
end
"""
fix_value(v::VariableRef)
Return the value to which a variable is fixed. Error if one does not exist.
"""
function fix_value(v::VariableRef)
cset = MOI.get(owner_model(v), MOI.ConstraintSet(), FixRef(v))::MOI.EqualTo
return cset.value
end
function FixRef(v::VariableRef)
return ConstraintRef{Model, MOIFIX, ScalarShape}(owner_model(v),
fix_index(v),
ScalarShape())
end
# integer and binary constraints
function is_integer(v::VariableRef)
return haskey(owner_model(v).variable_to_integrality,index(v))
end
function integer_index(v::VariableRef)
@assert is_integer(v) # TODO error message
return owner_model(v).variable_to_integrality[index(v)]
end
function set_integer_index(v::VariableRef, cindex::MOIINT)
owner_model(v).variable_to_integrality[index(v)] = cindex
end
"""
set_integer(variable_ref::VariableRef)
Add an integrality constraint on the variable `variable_ref`.
"""
function set_integer(variable_ref::VariableRef)
if is_integer(variable_ref)
return
elseif is_binary(variable_ref)
error("Cannot set the variable_ref $(variable_ref) to integer as it " *
"is already binary.")
end
constraint_ref = MOI.add_constraint(owner_model(variable_ref).moi_backend,
MOI.SingleVariable(index(variable_ref)),
MOI.Integer())
set_integer_index(variable_ref, constraint_ref)
return
end
function unset_integer(variable_ref::VariableRef)
JuMP.delete(owner_model(variable_ref), IntegerRef(variable_ref))
delete!(owner_model(variable_ref).variable_to_integrality,
index(variable_ref))
return
end
function IntegerRef(v::VariableRef)
return ConstraintRef{Model, MOIINT, ScalarShape}(owner_model(v),
integer_index(v),
ScalarShape())
end
function is_binary(v::VariableRef)
return haskey(owner_model(v).variable_to_zero_one,index(v))
end
function binary_index(v::VariableRef)
@assert is_binary(v) # TODO error message
return owner_model(v).variable_to_zero_one[index(v)]
end
function set_binary_index(v::VariableRef, cindex::MOIBIN)
owner_model(v).variable_to_zero_one[index(v)] = cindex
end
"""
set_binary(v::VariableRef)
Add a constraint on the variable `v` that it must take values in the set ``\\{0,1\\}``.
"""
function set_binary(variable_ref::VariableRef)
if is_binary(variable_ref)
return
elseif is_integer(variable_ref)
error("Cannot set the variable_ref $(variable_ref) to binary as it " *
"is already integer.")
end
constraint_ref = MOI.add_constraint(owner_model(variable_ref).moi_backend,
MOI.SingleVariable(index(variable_ref)),
MOI.ZeroOne())
set_binary_index(variable_ref, constraint_ref)
return
end
function unset_binary(variable_ref::VariableRef)
JuMP.delete(owner_model(variable_ref), BinaryRef(variable_ref))
delete!(owner_model(variable_ref).variable_to_zero_one, index(variable_ref))
return
end
function BinaryRef(v::VariableRef)
return ConstraintRef{Model, MOIBIN, ScalarShape}(owner_model(v),
binary_index(v),
ScalarShape())
end
function start_value(v::VariableRef)
return MOI.get(owner_model(v), MOI.VariablePrimalStart(), v)
end
function set_start_value(v::VariableRef, val::Number)
return MOI.set(owner_model(v), MOI.VariablePrimalStart(), v, val)
end
"""
result_value(v::VariableRef)
Get the value of this variable in the result returned by a solver.
Use `has_result_values` to check if a result exists before asking for values.
Replaces `getvalue` for most use cases.
"""
result_value(v::VariableRef) = MOI.get(owner_model(v), MOI.VariablePrimal(), v)
function has_result_values(model::Model)
return MOI.get(model, MOI.PrimalStatus()) != MOI.NoSolution
end
@Base.deprecate setvalue(v::VariableRef, val::Number) set_start_value(v, val)
"""
add_variable(m::Model, v::AbstractVariable, name::String="")
Add a variable `v` to `Model m` and sets its name.
"""
function add_variable end
function add_variable(m::Model, v::ScalarVariable, name::String="")
info = v.info
vref = VariableRef(m)
if info.has_lb
set_lower_bound(vref, info.lower_bound)
end
if info.has_ub
set_upper_bound(vref, info.upper_bound)
end
if info.has_fix
fix(vref, info.fixed_value)
end
if info.binary
set_binary(vref)
end
if info.integer
set_integer(vref)
end
if info.has_start
set_start_value(vref, info.start)
end
if !isempty(name)
set_name(vref, name)
end
return vref
end