forked from jump-dev/JuMP.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquad_expr.jl
473 lines (406 loc) · 16.3 KB
/
quad_expr.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
# 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/.
#############################################################################
# JuMP
# An algebraic modeling language for Julia
# See http://github.com/JuliaOpt/JuMP.jl
#############################################################################
# src/quad_expr.jl
# Defines all types relating to expressions with a quadratic and affine part
# - GenericQuadExpr ∑qᵢⱼ xᵢⱼ + ∑ aᵢ xᵢ + c
# - QuadExpr Alias for (Float64, VariableRef)
# - QuadExprConstraint ∑qᵢⱼ xᵢⱼ + ∑ aᵢ xᵢ + c in set
# Operator overloads in src/operators.jl
#############################################################################
struct UnorderedPair{T}
a::T
b::T
end
Base.hash(p::UnorderedPair, h::UInt) = hash(hash(p.a) + hash(p.b), h)
function Base.isequal(p1::UnorderedPair, p2::UnorderedPair)
return (p1.a == p2.a && p1.b == p2.b) || (p1.a == p2.b && p1.b == p2.a)
end
# GenericQuadExpr
# ∑qᵢⱼ xᵢⱼ + ∑ aᵢ xᵢ + c
mutable struct GenericQuadExpr{CoefType,VarType} <: AbstractJuMPScalar
aff::GenericAffExpr{CoefType,VarType}
terms::OrderedDict{UnorderedPair{VarType}, CoefType}
end
function GenericQuadExpr(aff::GenericAffExpr{V,K}, kv::AbstractArray{Pair{UnorderedPair{K},V}}) where {K,V}
return GenericQuadExpr{V,K}(aff, _new_ordered_dict(UnorderedPair{K}, V, kv))
end
function GenericQuadExpr(aff::GenericAffExpr{V,K}, kv::Pair{UnorderedPair{K},V}...) where {K,V}
return GenericQuadExpr{V,K}(aff, _new_ordered_dict(UnorderedPair{K}, V, kv...))
end
function GenericAffExpr{V,K}(aff::GenericAffExpr{V,K}, kv::AbstractArray{<:Pair}) where {K,V}
return GenericQuadExpr{V,K}(aff, _new_ordered_dict(UnorderedPair{K}, V, kv))
end
function GenericQuadExpr{V,K}(aff::GenericAffExpr{V,K}, kv::Pair...) where {K,V}
return GenericQuadExpr{V,K}(aff, _new_ordered_dict(UnorderedPair{K}, V, kv...))
end
function Base.iszero(expr::GenericQuadExpr)
return iszero(expr.aff) && all(iszero, values(expr.terms))
end
function Base.zero(::Type{GenericQuadExpr{C,V}}) where {C,V}
return GenericQuadExpr(zero(GenericAffExpr{C,V}), OrderedDict{UnorderedPair{V}, C}())
end
function Base.one(::Type{GenericQuadExpr{C,V}}) where {C,V}
return GenericQuadExpr(one(GenericAffExpr{C,V}), OrderedDict{UnorderedPair{V}, C}())
end
Base.zero(q::GenericQuadExpr) = zero(typeof(q))
Base.one(q::GenericQuadExpr) = one(typeof(q))
Base.copy(q::GenericQuadExpr) = GenericQuadExpr(copy(q.aff), copy(q.terms))
Base.broadcastable(q::GenericQuadExpr) = Ref(q)
"""
drop_zeros!(expr::GenericQuadExpr)
Remove terms in the quadratic expression with `0` coefficients.
"""
function drop_zeros!(expr::GenericQuadExpr)
drop_zeros!(expr.aff)
for (key, coef) in expr.terms
if iszero(coef)
delete!(expr.terms, key)
end
end
return
end
function map_coefficients_inplace!(f::Function, q::GenericQuadExpr)
# The iterator remains valid if existing elements are updated.
for (key, value) in q.terms
q.terms[key] = f(value)
end
map_coefficients_inplace!(f, q.aff)
return q
end
function map_coefficients(f::Function, q::GenericQuadExpr)
return map_coefficients_inplace!(f, copy(q))
end
function _affine_coefficient(f::GenericQuadExpr{C, V}, variable::V) where {C, V}
return _affine_coefficient(f.aff, variable)
end
"""
constant(aff::GenericQuadExpr{C, V})::C
Return the constant of the quadratic expression.
"""
constant(quad::GenericQuadExpr) = constant(quad.aff)
"""
linear_terms(quad::GenericQuadExpr{C, V})
Provides an iterator over tuples `(coefficient::C, variable::V)` in the
linear part of the quadratic expression.
"""
linear_terms(quad::GenericQuadExpr) = LinearTermIterator(quad.aff)
struct QuadTermIterator{GQE<:GenericQuadExpr}
quad::GQE
end
"""
quad_terms(quad::GenericQuadExpr{C, V})
Provides an iterator over tuples `(coefficient::C, var_1::V, var_2::V)` in the
quadratic part of the quadratic expression.
"""
quad_terms(quad::GenericQuadExpr) = QuadTermIterator(quad)
function _reorder_and_flatten(p::Pair{<:UnorderedPair})
return (p.second, p.first.a, p.first.b)
end
function Base.iterate(qti::QuadTermIterator)
ret = iterate(qti.quad.terms)
if ret === nothing
return nothing
else
return _reorder_and_flatten(ret[1]), ret[2]
end
end
function Base.iterate(qti::QuadTermIterator, state)
ret = iterate(qti.quad.terms, state)
if ret === nothing
return nothing
else
return _reorder_and_flatten(ret[1]), ret[2]
end
end
Base.length(qti::QuadTermIterator) = length(qti.quad.terms)
function Base.eltype(qti::QuadTermIterator{GenericQuadExpr{C, V}}
) where {C, V}
return Tuple{C, V, V}
end
# With one factor.
function add_to_expression!(quad::GenericQuadExpr, other::_Constant)
add_to_expression!(quad.aff, other)
return quad
end
function add_to_expression!(quad::GenericQuadExpr{C, V}, other::V) where {C, V}
add_to_expression!(quad.aff, other)
return quad
end
function add_to_expression!(q::GenericQuadExpr{T,S},
other::GenericAffExpr{T,S}) where {T,S}
add_to_expression!(q.aff, other)
return q
end
function add_to_expression!(q::GenericQuadExpr{T,S},
other::GenericQuadExpr{T,S}) where {T,S}
merge!(+, q.terms, other.terms)
add_to_expression!(q.aff, other.aff)
return q
end
# With two factors.
function add_to_expression!(quad::GenericQuadExpr{C, V},
new_coef::_Constant,
new_var::V) where {C,V}
add_to_expression!(quad.aff, new_coef, new_var)
return quad
end
function add_to_expression!(quad::GenericQuadExpr{C, V},
new_var::Union{V, GenericAffExpr{C, V}},
new_coef::_Constant) where {C,V}
return add_to_expression!(quad, new_coef, new_var)
end
function add_to_expression!(quad::GenericQuadExpr{C},
new_coef::_Constant,
new_aff::GenericAffExpr{C}) where {C}
add_to_expression!(quad.aff, new_coef, new_aff)
return quad
end
function add_to_expression!(quad::GenericQuadExpr{C, V}, coef::_Constant,
other::GenericQuadExpr{C, V}) where {C, V}
for (key, term_coef) in other.terms
_add_or_set!(quad.terms, key, coef * term_coef)
end
return add_to_expression!(quad, coef, other.aff)
end
function add_to_expression!(quad::GenericQuadExpr{C, V},
other::GenericQuadExpr{C, V},
coef::_Constant) where {C, V}
return add_to_expression!(quad, coef, other)
end
function add_to_expression!(quad::GenericQuadExpr{C},
var_1::AbstractVariableRef,
var_2::AbstractVariableRef) where {C}
return add_to_expression!(quad, one(C), var_1, var_2)
end
function add_to_expression!(quad::GenericQuadExpr{C,V},
var::V,
aff::GenericAffExpr{C,V}) where {C,V}
for (coef, term_var) in linear_terms(aff)
key = UnorderedPair(var, term_var)
_add_or_set!(quad.terms, key, coef)
end
return add_to_expression!(quad, var, aff.constant)
end
function add_to_expression!(quad::GenericQuadExpr{C,V},
aff::GenericAffExpr{C,V},
var::V) where {C,V}
return add_to_expression!(quad, var, aff)
end
function add_to_expression!(quad::GenericQuadExpr{C,V},
lhs::GenericAffExpr{C,V},
rhs::GenericAffExpr{C,V}) where {C,V}
lhs_length = length(linear_terms(lhs))
rhs_length = length(linear_terms(rhs))
# Quadratic terms
for (lhscoef, lhsvar) in linear_terms(lhs)
for (rhscoef, rhsvar) in linear_terms(rhs)
add_to_expression!(quad, lhscoef*rhscoef, lhsvar, rhsvar)
end
end
# Try to preallocate space for aff
cur = length(linear_terms(quad))
if !iszero(lhs.constant) && !iszero(rhs.constant)
sizehint!(quad.aff, cur + lhs_length + rhs_length)
elseif !iszero(lhs.constant)
sizehint!(quad.aff, cur + rhs_length)
elseif !iszero(rhs.constant)
sizehint!(quad.aff, cur + lhs_length)
end
# [LHS constant] * [RHS linear terms]
if !iszero(lhs.constant)
c = lhs.constant
for (rhscoef, rhsvar) in linear_terms(rhs)
add_to_expression!(quad.aff, c*rhscoef, rhsvar)
end
end
# [RHS constant] * [LHS linear terms]
if !iszero(rhs.constant)
c = rhs.constant
for (lhscoef, lhsvar) in linear_terms(lhs)
add_to_expression!(quad.aff, c*lhscoef, lhsvar)
end
end
quad.aff.constant += lhs.constant * rhs.constant
return quad
end
# With three factors.
function add_to_expression!(quad::GenericQuadExpr{C,V}, new_coef::C,
new_var1::V, new_var2::V) where {C,V}
# Node: OrderedDict updates the *key* as well. That is, if there was a
# previous value for UnorderedPair(new_var2, new_var1), it's key will now be
# UnorderedPair(new_var1, new_var2) (because these are defined as equal).
key = UnorderedPair(new_var1, new_var2)
_add_or_set!(quad.terms, key, new_coef)
return quad
end
function _assert_isfinite(q::GenericQuadExpr)
_assert_isfinite(q.aff)
for (coef, var1, var2) in quad_terms(q)
isfinite(coef) || error("Invalid coefficient $coef on quadratic term $var1*$var2.")
end
end
function Base.isequal(q::GenericQuadExpr{T,S}, other::GenericQuadExpr{T,S}) where {T,S}
return isequal(q.aff,other.aff) && isequal(q.terms, other.terms)
end
Base.hash(quad::GenericQuadExpr, h::UInt) = hash(quad.aff, hash(quad.terms, h))
function SparseArrays.dropzeros(quad::GenericQuadExpr)
quad_terms = copy(quad.terms)
for (key, value) in quad.terms
if iszero(value)
delete!(quad_terms, key)
end
end
return GenericQuadExpr(dropzeros(quad.aff), quad_terms)
end
# Check if two QuadExprs are equal regardless of the order, and after dropping zeros.
# Mostly useful for testing.
function isequal_canonical(quad::GenericQuadExpr{CoefType,VarType}, other::GenericQuadExpr{CoefType,VarType}) where {CoefType,VarType}
quad_nozeros = dropzeros(quad)
other_nozeros = dropzeros(other)
return isequal(quad_nozeros, other_nozeros)
end
# Alias for (Float64, VariableRef)
const QuadExpr = GenericQuadExpr{Float64,VariableRef}
function Base.convert(::Type{GenericQuadExpr{C, V}}, v::Union{_Constant,AbstractVariableRef,GenericAffExpr}) where {C, V}
return GenericQuadExpr(convert(GenericAffExpr{C, V}, v))
end
GenericQuadExpr{C, V}() where {C, V} = zero(GenericQuadExpr{C, V})
# Used in `JuMP._mul!`.
function Base.convert(::Type{T}, quad::GenericQuadExpr{T}) where T
if !isempty(quad.terms)
throw(InexactError(:convert, T, quad))
end
return convert(T, quad.aff)
end
function check_belongs_to_model(q::GenericQuadExpr, model::AbstractModel)
check_belongs_to_model(q.aff, model)
for variable_pair in keys(q.terms)
check_belongs_to_model(variable_pair.a, model)
check_belongs_to_model(variable_pair.b, model)
end
end
"""
_moi_quadratic_term(t::Tuple)
Return the MOI.ScalarQuadraticTerm for the quadratic term `t`, element of the
[`quad_terms`](@ref) iterator. Note that the `VariableRef`s are transformed
into `MOI.VariableIndex`s hence the owner model information is lost.
"""
function _moi_quadratic_term(t::Tuple)
return MOI.ScalarQuadraticTerm(t[2] == t[3] ? 2t[1] : t[1], index(t[2]),
index(t[3]))
end
function MOI.ScalarQuadraticFunction(q::QuadExpr)
_assert_isfinite(q)
qterms = MOI.ScalarQuadraticTerm{Float64}[_moi_quadratic_term(t)
for t in quad_terms(q)]
moi_aff = MOI.ScalarAffineFunction(q.aff)
return MOI.ScalarQuadraticFunction(moi_aff.terms,
qterms, moi_aff.constant)
end
function moi_function(aff::GenericQuadExpr)
return MOI.ScalarQuadraticFunction(aff)
end
function moi_function_type(::Type{<:GenericQuadExpr{T}}) where T
return MOI.ScalarQuadraticFunction{T}
end
function QuadExpr(m::Model, f::MOI.ScalarQuadraticFunction)
quad = QuadExpr(AffExpr(m, MOI.ScalarAffineFunction(f.affine_terms,
f.constant)))
for t in f.quadratic_terms
v1 = t.variable_index_1
v2 = t.variable_index_2
coef = t.coefficient
if v1 == v2
coef /= 2
end
add_to_expression!(quad, coef, VariableRef(m, v1), VariableRef(m, v2))
end
return quad
end
function jump_function_type(::Model,
::Type{MOI.ScalarQuadraticFunction{T}}) where T
return GenericQuadExpr{T, VariableRef}
end
function jump_function(model::Model, f::MOI.ScalarQuadraticFunction{T}) where T
return GenericQuadExpr{T, VariableRef}(model, f)
end
function jump_function_type(::Model,
::Type{MOI.VectorQuadraticFunction{T}}) where T
return Vector{GenericQuadExpr{T, VariableRef}}
end
function jump_function(model::Model, f::MOI.VectorQuadraticFunction{T}) where T
return GenericQuadExpr{T, VariableRef}[
GenericQuadExpr{T, VariableRef}(model, f) for f in MOIU.eachscalar(f)]
end
"""
_fill_vqf!(terms::Vector{<:MOI.VectorQuadraticTerm}, offset::Int, oi::Int,
quad::AbstractJuMPScalar)
Fills the vectors terms at indices starting at `offset+1` with the quadratic
terms of `quad`. The output index for all terms is `oi`. Return the index of the
last term added.
"""
function _fill_vqf!(terms::Vector{<:MOI.VectorQuadraticTerm}, offset::Int,
oi::Int, aff::AbstractJuMPScalar)
i = 1
for term in quad_terms(aff)
terms[offset + i] = MOI.VectorQuadraticTerm(Int64(oi),
_moi_quadratic_term(term))
i += 1
end
return offset + length(quad_terms(aff))
end
function MOI.VectorQuadraticFunction(quads::Vector{QuadExpr})
num_quadratic_terms = sum(quad -> length(quad_terms(quad)), quads)
quadratic_terms = Vector{MOI.VectorQuadraticTerm{Float64}}(undef,
num_quadratic_terms)
num_lin_terms = sum(quad -> length(linear_terms(quad)), quads)
lin_terms = Vector{MOI.VectorAffineTerm{Float64}}(undef, num_lin_terms)
constants = Vector{Float64}(undef, length(quads))
quad_offset = 0
lin_offset = 0
for (i, quad) in enumerate(quads)
quad_offset = _fill_vqf!(quadratic_terms, quad_offset, i, quad)
lin_offset = _fill_vaf!(lin_terms, lin_offset, i, quad)
constants[i] = constant(quad)
end
MOI.VectorQuadraticFunction(lin_terms, quadratic_terms, constants)
end
moi_function(a::Vector{<:GenericQuadExpr}) = MOI.VectorQuadraticFunction(a)
function moi_function_type(::Type{<:Vector{<:GenericQuadExpr{T}}}) where {T}
return MOI.VectorQuadraticFunction{T}
end
# Copy a quadratic expression to a new model by converting all the
# variables to the new model's variables
function Base.copy(q::GenericQuadExpr, new_model::Model)
GenericQuadExpr(copy(q.qvars1, new_model), copy(q.qvars2, new_model),
copy(q.qcoeffs), copy(q.aff, new_model))
end
# Requires that value_func(::VarType) is defined.
function value(ex::GenericQuadExpr{CoefType, VarType},
value_func::Function) where {CoefType, VarType}
RetType = Base.promote_op(
(ctype, vtype) -> ctype * value_func(vtype) * value_func(vtype),
CoefType, VarType)
ret = convert(RetType, value(ex.aff, value_func))
for (vars, coef) in ex.terms
ret += coef * value_func(vars.a) * value_func(vars.b)
end
return ret
end
"""
value(v::GenericQuadExpr; result::Int = 1)
Return the value of the `GenericQuadExpr` `v` associated with result index
`result` of the most-recent solution returned by the solver.
Replaces `getvalue` for most use cases.
See also: [`result_count`](@ref).
"""
function value(ex::GenericQuadExpr; result::Int = 1)
return value(ex, (x) -> value(x; result = result))
end