/
JuMP.jl
745 lines (623 loc) · 25.5 KB
/
JuMP.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
# 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
#############################################################################
VERSION < v"0.7.0-beta2.199" && __precompile__()
module JuMP
using Compat
using Compat.LinearAlgebra
using Compat.SparseArrays
import MathOptInterface
const MOI = MathOptInterface
const MOIU = MOI.Utilities
import Calculus
import DataStructures.OrderedDict
import ForwardDiff
include("Derivatives/Derivatives.jl")
using .Derivatives
export
Model, VariableRef, AffExpr, QuadExpr,
with_optimizer,
NonlinearConstraint,
ConstraintRef,
SecondOrderCone, RotatedSecondOrderCone, PSDCone,
optimize,
setname,
setlowerbound, setupperbound,
setstartvalue,
linearterms,
# Macros and support functions
@LinearConstraint, @LinearConstraints, @QuadConstraint, @QuadConstraints,
@SOCConstraint, @SOCConstraints,
@expression, @expressions, @NLexpression, @NLexpressions,
@variable, @variables, @constraint, @constraints,
@NLconstraint, @NLconstraints,
@SDconstraint, @SDconstraints,
@objective, @NLobjective,
@NLparameter, @constraintref
include("utils.jl")
const MOIVAR = MOI.VariableIndex
const MOICON{F,S} = MOI.ConstraintIndex{F,S}
const MOILB = MOICON{MOI.SingleVariable,MOI.GreaterThan{Float64}}
const MOIUB = MOICON{MOI.SingleVariable,MOI.LessThan{Float64}}
const MOIFIX = MOICON{MOI.SingleVariable,MOI.EqualTo{Float64}}
const MOIINT = MOICON{MOI.SingleVariable,MOI.Integer}
const MOIBIN = MOICON{MOI.SingleVariable,MOI.ZeroOne}
@MOIU.model JuMPMOIModel (ZeroOne, Integer) (EqualTo, GreaterThan, LessThan, Interval) (Zeros, Nonnegatives, Nonpositives, SecondOrderCone, RotatedSecondOrderCone, GeometricMeanCone, PositiveSemidefiniteConeTriangle, PositiveSemidefiniteConeSquare, RootDetConeTriangle, RootDetConeSquare, LogDetConeTriangle, LogDetConeSquare) () (SingleVariable,) (ScalarAffineFunction,ScalarQuadraticFunction) (VectorOfVariables,) (VectorAffineFunction,)
"""
OptimizerFactory
User-friendly closure that creates new MOI models. New `OptimizerFactory`s are
created with [`with_optimizer`](@ref) and new models are created from the
optimizer factory `optimizer_factory` with `optimizer_factory()`.
## Examples
The following construct an optimizer factory and then use it to create two
independent `IpoptOptimizer`s:
```julia
optimizer_factory = with_optimizer(IpoptOptimizer, print_level=0)
optimizer1 = optimizer_factory()
optimizer2 = optimizer_factory()
```
"""
struct OptimizerFactory
# The constructor can be
# * `Function`: a function, or
# * `DataType`: a type, or
# * `UnionAll`: a type with missing parameters.
constructor
args::Tuple
kwargs # type changes from Julia v0.6 to v0.7 so we leave it untyped for now
end
"""
with_optimizer(constructor, args...; kwargs...)
Return an `OptimizerFactory` that creates optimizers using the constructor
`constructor` with positional arguments `args` and keyword arguments `kwargs`.
## Examples
The following returns an optimizer factory that creates `IpoptOptimizer`s using
the constructor call `IpoptOptimizer(print_level=0)`:
```julia
with_optimizer(IpoptOptimizer, print_level=0)
```
"""
function with_optimizer(constructor,
args...; kwargs...)
if !applicable(constructor, args...)
error("$constructor is does not have any method with arguments $args.",
"The first argument of `with_optimizer` should be callable with",
" the other argument of `with_optimizer`.")
end
return OptimizerFactory(constructor, args, kwargs)
end
function (optimizer_factory::OptimizerFactory)()
return optimizer_factory.constructor(optimizer_factory.args...;
optimizer_factory.kwargs...)
end
###############################################################################
# Model
# Model has three modes:
# 1) Automatic: moi_backend field holds a LazyBridgeOptimizer{CachingOptimizer} in Automatic mode.
# 2) Manual: moi_backend field holds a LazyBridgeOptimizer{CachingOptimizer} in Manual mode.
# 3) Direct: moi_backend field holds an AbstractOptimizer. No extra copy of the model is stored. The moi_backend must support addconstraint! etc.
# Methods to interact with the CachingOptimizer are defined in solverinterface.jl.
@enum ModelMode Automatic Manual Direct
abstract type AbstractModel end
# All `AbstractModel`s must define methods for these functions:
# num_variables, object_dictionary
"""
Model
A mathematical model of an optimization problem.
"""
mutable struct Model <: AbstractModel
# Special variablewise properties that we keep track of:
# lower bound, upper bound, fixed, integrality, binary
variable_to_lower_bound::Dict{MOIVAR, MOILB}
variable_to_upper_bound::Dict{MOIVAR, MOIUB}
variable_to_fix::Dict{MOIVAR, MOIFIX}
variable_to_integrality::Dict{MOIVAR, MOIINT}
variable_to_zero_one::Dict{MOIVAR, MOIBIN}
# In Manual and Automatic modes, LazyBridgeOptimizer{CachingOptimizer}.
# In Direct mode, will hold an AbstractOptimizer.
moi_backend::MOI.AbstractOptimizer
# Hook into a solve call...function of the form f(m::Model; kwargs...),
# where kwargs get passed along to subsequent solve calls.
optimize_hook
# TODO: Document.
nlp_data
# Dictionary from variable and constraint names to objects.
obj_dict::Dict{Symbol, Any}
# Number of times we add large expressions. Incremented and checked by
# the `operator_warn` method.
operator_counter::Int
# Enable extensions to attach arbitrary information to a JuMP model by
# using an extension-specific symbol as a key.
ext::Dict{Symbol, Any}
end
"""
Model(; caching_mode::MOIU.CachingOptimizerMode=MOIU.Automatic,
bridge_constraints::Bool=true)
Return a new JuMP model without any optimizer; the model is stored the model in
a cache. The mode of the `CachingOptimizer` storing this cache is
`caching_mode`. The optimizer can be set later in the [`JuMP.optimize`](@ref)
call. If `bridge_constraints` is true, constraints that are not supported by the
optimizer are automatically bridged to equivalent supported constraints when
an appropriate is defined in the `MathOptInterface.Bridges` module or is
defined in another module and is explicitely added.
"""
function Model(; caching_mode::MOIU.CachingOptimizerMode=MOIU.Automatic,
bridge_constraints::Bool=true)
universal_fallback = MOIU.UniversalFallback(JuMPMOIModel{Float64}())
caching_opt = MOIU.CachingOptimizer(universal_fallback,
caching_mode)
if bridge_constraints
backend = MOI.Bridges.fullbridgeoptimizer(caching_opt,
Float64)
else
backend = caching_opt
end
return direct_model(backend)
end
"""
Model(optimizer_factory::OptimizerFactory;
caching_mode::MOIU.CachingOptimizerMode=MOIU.Automatic,
bridge_constraints::Bool=true)
Return a new JuMP model using the optimizer factory `optimizer_factory` to
create the optimizer. The optimizer factory can be created by the
[`with_optimizer`](@ref) function.
## Examples
The following creates a model using the optimizer
`IpoptOptimizer(print_level=0)`:
```julia
model = JuMP.Model(with_optimizer(IpoptOptimizer, print_level=0))
```
"""
function Model(optimizer_factory::OptimizerFactory; kwargs...)
model = Model(; kwargs...)
optimizer = optimizer_factory()
MOIU.resetoptimizer!(model, optimizer)
return model
end
"""
direct_model(backend::MOI.ModelLike)
Return a new JuMP model using `backend` to store the model and solve it. As
opposed to the [`Model`](@ref) constructor, no cache of the model is stored
outside of `backend` and no bridges are automatically applied to `backend`.
The absence of cache reduces the memory footprint but it is important to bear
in mind the following implications of creating models using this *direct* mode:
* When `backend` does not support an operation such as adding
variables/constraints after solver or modifying constraints, an error is
thrown. With models created using the [`Model`](@ref) constructor, such
situations can be dealt with by storing the modifications in a cache and
loading them into the optimizer when `JuMP.optimize` is called.
* No constraint bridging is supported by default.
* The optimizer used cannot be changed the model is constructed.
* The model created cannot be copied.
"""
function direct_model(backend::MOI.ModelLike)
@assert MOI.isempty(backend)
return Model(Dict{MOIVAR, MOILB}(),
Dict{MOIVAR, MOIUB}(),
Dict{MOIVAR, MOIFIX}(),
Dict{MOIVAR, MOIINT}(),
Dict{MOIVAR, MOIBIN}(),
backend,
nothing,
nothing,
Dict{Symbol, Any}(),
0,
Dict{Symbol, Any}())
end
if VERSION >= v"0.7-"
Base.broadcastable(model::Model) = Ref(model)
end
# In Automatic and Manual mode, `model.moi_backend` is either directly the
# `CachingOptimizer` if `bridge_constraints=false` was passed in the constructor
# or it is a `LazyBridgeOptimizer` and the `CachingOptimizer` is stored in the
# `model` field
function caching_optimizer(model::Model)
if model.moi_backend isa MOIU.CachingOptimizer
return model.moi_backend
elseif (model.moi_backend isa
MOI.Bridges.LazyBridgeOptimizer{<:MOIU.CachingOptimizer})
return model.moi_backend.model
else
error("The function `caching_optimizer` cannot be called on a model " *
"in `Direct` mode.")
end
end
"""
mode(model::Model)
Return mode (Direct, Automatic, Manual) of model.
"""
function mode(model::Model)
if !(model.moi_backend isa MOI.Bridges.LazyBridgeOptimizer{<:MOIU.CachingOptimizer} ||
model.moi_backend isa MOIU.CachingOptimizer)
return Direct
elseif caching_optimizer(model).mode == MOIU.Automatic
return Automatic
else
return Manual
end
end
"""
num_variables(model::Model)
Returns number of variables in `model`.
"""
num_variables(model::Model) = MOI.get(model, MOI.NumberOfVariables())
"""
numnlconstr(model::Model)
Returns the number of nonlinear constraints associated with the `model`.
"""
function numnlconstr(model::Model)
return model.nlp_data !== nothing ? length(model.nlp_data.nlconstr) : 0
end
"""
objectivebound(model::Model)
Return the best known bound on the optimal objective value after a call to
`optimize(model)`.
"""
objectivebound(model::Model) = MOI.get(model, MOI.ObjectiveBound())
"""
objectivevalue(model::Model)
Return the objective value after a call to `optimize(model)`.
"""
objectivevalue(model::Model) = MOI.get(model, MOI.ObjectiveValue())
"""
objectivesense(model::Model)
Return the objective sense, `:Min`, `:Max`, or `:Feasibility`.
"""
function objectivesense(model::Model)
moisense = MOI.get(model, MOI.ObjectiveSense())
if moisense == MOI.MinSense
return :Min
elseif moisense == MOI.MaxSense
return :Max
else
@assert moisense == MOI.FeasibilitySense
return :Feasibility
end
end
# TODO(IainNZ): Document these too.
# TODO(#1381): Implement Base.copy for Model.
object_dictionary(model::Model) = model.obj_dict
terminationstatus(m::Model) = MOI.get(m, MOI.TerminationStatus())
primalstatus(m::Model) = MOI.get(m, MOI.PrimalStatus())
dualstatus(m::Model) = MOI.get(m, MOI.DualStatus())
set_optimize_hook(m::Model, f) = (m.optimize_hook = f)
#############################################################################
# AbstractConstraint
# Abstract base type for all constraint types
abstract type AbstractConstraint end
# Abstract base type for all scalar types
abstract type AbstractJuMPScalar end
@static if VERSION >= v"0.7-"
# These are required to create symmetric containers of AbstractJuMPScalars.
Compat.LinearAlgebra.symmetric_type(::Type{T}) where T <: AbstractJuMPScalar = T
Compat.LinearAlgebra.symmetric(scalar::AbstractJuMPScalar, ::Symbol) = scalar
# This is required for linear algebra operations involving transposes.
Compat.LinearAlgebra.adjoint(scalar::AbstractJuMPScalar) = scalar
end
"""
owner_model(s::AbstractJuMPScalar)
Return the model owning the scalar `s`.
"""
function owner_model end
if VERSION < v"0.7-"
Base.start(::AbstractJuMPScalar) = false
Base.next(x::AbstractJuMPScalar, state) = (x, true)
Base.done(::AbstractJuMPScalar, state) = state
else
Base.iterate(x::AbstractJuMPScalar) = (x, true)
Base.iterate(::AbstractJuMPScalar, state) = nothing
end
Base.isempty(::AbstractJuMPScalar) = false
# Check if two arrays of AbstractJuMPScalars are equal. Useful for testing.
function isequal_canonical(x::AbstractArray{<:JuMP.AbstractJuMPScalar},
y::AbstractArray{<:JuMP.AbstractJuMPScalar})
return size(x) == size(y) && all(JuMP.isequal_canonical.(x, y))
end
"""
AbstractShape
Abstract vectorizable shape. Given a flat vector form of an object of shape
`shape`, the original object can be obtained by [`reshape`](@ref).
"""
abstract type AbstractShape end
"""
dual_shape(shape::AbstractShape)::AbstractShape
Returns the shape of the dual space of the space of objects of shape `shape`. By
default, the `dual_shape` of a shape is itself. See the examples section below
for an example for which this is not the case.
## Examples
Consider polynomial constraints for which the dual is moment constraints and
moment constraints for which the dual is polynomial constraints. Shapes for
polynomials can be defined as follows:
```julia
struct Polynomial
coefficients::Vector{Float64}
monomials::Vector{Monomial}
end
struct PolynomialShape <: JuMP.AbstractShape
monomials::Vector{Monomial}
end
JuMP.reshape(x::Vector, shape::PolynomialShape) = Polynomial(x, shape.monomials)
```
and a shape for moments can be defined as follows:
```julia
struct Moments
coefficients::Vector{Float64}
monomials::Vector{Monomial}
end
struct MomentsShape <: JuMP.AbstractShape
monomials::Vector{Monomial}
end
JuMP.reshape(x::Vector, shape::MomentsShape) = Moments(x, shape.monomials)
```
The `dual_shape` allows to define the shape of the dual of polynomial and moment
constraints:
```julia
dual_shape(shape::PolynomialShape) = MomentsShape(shape.monomials)
dual_shape(shape::MomentsShape) = PolynomialShape(shape.monomials)
```
"""
dual_shape(shape::AbstractShape) = shape
"""
reshape(vectorized_form::Vector, shape::AbstractShape)
Return an object in it original shape `shape` given its vectorized form
`vectorized_form`.
## Examples
Given a [`SymmetricMatrixShape`](@ref) of vectorized form `[1, 2, 3]`, the
following code retrieve the matrix `Symmetric(Matrix[1 2; 2 3])`:
```julia
reshape([1, 2, 3], SymmetricMatrixShape(2))
```
"""
function reshape end
"""
shape(c::AbstractConstraint)::AbstractShape
Return the shape of the constraint `c`.
"""
function shape end
"""
ScalarShape
Shape of scalar constraints.
"""
struct ScalarShape <: AbstractShape end
reshape(α, ::ScalarShape) = α
"""
VectorShape
Vector for which the vectorized form corresponds exactly to the vector given.
"""
struct VectorShape <: AbstractShape end
reshape(vectorized_form, ::VectorShape) = vectorized_form
##########################################################################
# Constraint
# Holds the index of a constraint in a Model.
# TODO: Rename "m" field (breaks style guidelines).
struct ConstraintRef{M <: AbstractModel, C, Shape <: AbstractShape}
m::M
index::C
shape::Shape
end
if VERSION >= v"0.7-"
Base.broadcastable(cref::ConstraintRef) = Ref(cref)
end
# TODO: should model be a parameter here?
function MOI.delete!(m::Model, cr::ConstraintRef{Model})
@assert m === cr.m
MOI.delete!(m.moi_backend, index(cr))
end
MOI.isvalid(m::Model, cr::ConstraintRef{Model}) = cr.m === m && MOI.isvalid(m.moi_backend, cr.index)
"""
addconstraint(m::Model, c::AbstractConstraint, name::String="")
Add a constraint `c` to `Model m` and sets its name.
"""
function addconstraint(m::Model, c::AbstractConstraint, name::String="")
f, s = moi_function_and_set(c)
if !MOI.supportsconstraint(m.moi_backend, typeof(f), typeof(s))
if m.moi_backend isa MOI.Bridges.LazyBridgeOptimizer
bridge_message = " and there are no bridges that can reformulate it into supported constraints."
else
bridge_message = ", try using `bridge_constraints=true` in the `JuMP.Model` constructor if you believe the constraint can be reformulated to constraints supported by the solver."
end
error("Constraints of type $(typeof(f))-in-$(typeof(s)) are not supported by the solver" * bridge_message)
end
cindex = MOI.addconstraint!(m.moi_backend, f, s)
cref = ConstraintRef(m, cindex, shape(c))
if !isempty(name)
setname(cref, name)
end
return cref
end
include("variables.jl")
Base.zero(::Type{V}) where V<:AbstractVariableRef = zero(GenericAffExpr{Float64, V})
Base.zero(v::AbstractVariableRef) = zero(typeof(v))
Base.one(::Type{V}) where V<:AbstractVariableRef = one(GenericAffExpr{Float64, V})
Base.one(v::AbstractVariableRef) = one(typeof(v))
mutable struct VariableNotOwnedError <: Exception
context::String
end
function Base.showerror(io::IO, ex::VariableNotOwnedError)
print(io, "VariableNotOwnedError: Variable not owned by model present in $(ex.context)")
end
function verify_ownership(m::Model, vec::Vector{VariableRef})
n = length(vec)
@inbounds for i in 1:n
vec[i].m !== m && return false
end
return true
end
Base.copy(v::VariableRef, new_model::Model) = VariableRef(new_model, v.index)
Base.copy(x::Nothing, new_model::Model) = nothing
# TODO: Replace with vectorized copy?
Base.copy(v::AbstractArray{VariableRef}, new_model::Model) = (var -> VariableRef(new_model, var.index)).(v)
function optimizerindex(v::VariableRef)
if mode(v.m) == Direct
return index(v)
else
@assert caching_optimizer(v.m).state == MOIU.AttachedOptimizer
return caching_optimizer(v.m).model_to_optimizer_map[index(v)]
end
end
function optimizerindex(cr::ConstraintRef{Model})
if mode(cr.m) == Direct
return index(cr)
else
@assert caching_optimizer(cr.m).state == MOIU.AttachedOptimizer
return caching_optimizer(cr.m).model_to_optimizer_map[index(cr)]
end
end
index(cr::ConstraintRef) = cr.index
function hasresultdual(m::Model, REF::Type{<:ConstraintRef{Model, T}}) where {T <: MOICON}
MOI.canget(m, MOI.ConstraintDual(), REF)
end
"""
resultdual(cr::ConstraintRef)
Get the dual value of this constraint in the result returned by a solver.
Use `hasresultdual` to check if a result exists before asking for values.
Replaces `getdual` for most use cases.
"""
function resultdual(cr::ConstraintRef{Model, <:MOICON})
reshape(MOI.get(cr.m, MOI.ConstraintDual(), cr), dual_shape(cr.shape))
end
"""
name(v::ConstraintRef)
Get a constraint's name.
"""
name(cr::ConstraintRef{Model,<:MOICON}) = MOI.get(cr.m, MOI.ConstraintName(), cr)
setname(cr::ConstraintRef{Model,<:MOICON}, s::String) = MOI.set!(cr.m, MOI.ConstraintName(), cr, s)
"""
canget(m::JuMP.Model, attr::MathOptInterface.AbstractModelAttribute)::Bool
Return `true` if one may query the attribute `attr` from the model's MOI backend.
false if not.
"""
MOI.canget(m::Model, attr::MOI.AbstractModelAttribute) = MOI.canget(m.moi_backend, attr)
MOI.canget(m::Model, attr::MOI.AbstractVariableAttribute, ::Type{VariableRef}) = MOI.canget(m.moi_backend, attr, MOIVAR)
function MOI.canget(model::Model, attr::MOI.AbstractConstraintAttribute,
::Type{<:ConstraintRef{Model, T}}) where {T <: MOICON}
return MOI.canget(model.moi_backend, attr, T)
end
"""
get(m::JuMP.Model, attr::MathOptInterface.AbstractModelAttribute)
Return the value of the attribute `attr` from model's MOI backend.
"""
MOI.get(m::Model, attr::MOI.AbstractModelAttribute) = MOI.get(m.moi_backend, attr)
function MOI.get(m::Model, attr::MOI.AbstractVariableAttribute, v::VariableRef)
@assert m === v.m
MOI.get(m.moi_backend, attr, index(v))
end
function MOI.get(m::Model, attr::MOI.AbstractConstraintAttribute, cr::ConstraintRef)
@assert m === cr.m
MOI.get(m.moi_backend, attr, index(cr))
end
MOI.set!(m::Model, attr::MOI.AbstractModelAttribute, value) = MOI.set!(m.moi_backend, attr, value)
function MOI.set!(m::Model, attr::MOI.AbstractVariableAttribute, v::VariableRef, value)
@assert m === v.m
MOI.set!(m.moi_backend, attr, index(v), value)
end
function MOI.set!(m::Model, attr::MOI.AbstractConstraintAttribute, cr::ConstraintRef, value)
@assert m === cr.m
MOI.set!(m.moi_backend, attr, index(cr), value)
end
###############################################################################
# GenericAffineExpression, AffExpr, AffExprConstraint
include("affexpr.jl")
###############################################################################
# GenericQuadExpr, QuadExpr
# GenericQuadConstraint, QuadConstraint
include("quadexpr.jl")
##########################################################################
# SOSConstraint (special ordered set constraints)
# include("sos.jl")
include("sets.jl")
##########################################################################
# SDConstraint
include("sd.jl")
# handle dictionary of variables
function registervar(m::AbstractModel, varname::Symbol, value)
registerobject(m, varname, value, "A variable or constraint named $varname is already attached to this model. If creating variables programmatically, use the anonymous variable syntax x = @variable(m, [1:N], ...).")
end
registervar(m::AbstractModel, varname, value) = error("Invalid variable name $varname")
function registercon(m::AbstractModel, conname::Symbol, value)
registerobject(m, conname, value, "A variable or constraint named $conname is already attached to this model. If creating constraints programmatically, use the anonymous constraint syntax con = @constraint(m, ...).")
end
registercon(m::AbstractModel, conname, value) = error("Invalid constraint name $conname")
function registerobject(m::AbstractModel, name::Symbol, value, errorstring::String)
obj_dict = object_dictionary(m)
if haskey(obj_dict, name)
error(errorstring)
obj_dict[name] = nothing
else
obj_dict[name] = value
end
return value
end
"""
Base.getindex(m::JuMP.AbstractModel, name::Symbol)
To allow easy accessing of JuMP tVariables and Constraints via `[]` syntax.
Returns the variable, or group of variables, or constraint, or group of constraints, of the given name which were added to the model. This errors if multiple variables or constraints share the same name.
"""
function Base.getindex(m::JuMP.AbstractModel, name::Symbol)
obj_dict = object_dictionary(m)
if !haskey(obj_dict, name)
throw(KeyError("No object with name $name"))
elseif obj_dict[name] === nothing
error("There are multiple variables and/or constraints named $name that are already attached to this model. If creating variables programmatically, use the anonymous variable syntax x = @variable(m, [1:N], ...). If creating constraints programmatically, use the anonymous constraint syntax con = @constraint(m, ...).")
else
return obj_dict[name]
end
end
"""
Base.setindex!(m::JuMP.Model, value, name::Symbol)
stores the object `value` in the model `m` using so that it can be accessed via `getindex`. Can be called with `[]` syntax.
"""
function Base.setindex!(m::JuMP.Model, value, name::Symbol)
# if haskey(m.obj_dict, name)
# warn("Overwriting the object $name stored in the model. Consider using anonymous variables and constraints instead")
# end
m.obj_dict[name] = value
end
"""
operator_warn(model::AbstractModel)
operator_warn(model::Model)
This function is called on the model whenever two affine expressions are added
together without using `destructive_add!`, and at least one of the two
expressions has more than 50 terms.
For the case of `Model`, if this function is called more than 20,000 times then
a warning is generated once.
"""
function operator_warn(::AbstractModel) end
function operator_warn(model::Model)
model.operator_counter += 1
if model.operator_counter > 20000
Base.warn_once(
"The addition operator has been used on JuMP expressions a large " *
"number of times. This warning is safe to ignore but may " *
"indicate that model generation is slower than necessary. For " *
"performance reasons, you should not add expressions in a loop. " *
"Instead of x += y, use add_to_expression!(x,y) to modify x in " *
"place. If y is a single variable, you may also use " *
"add_to_expression!(x, coef, y) for x += coef*y.")
end
end
##########################################################################
# Types used in the nonlinear code
struct NonlinearExpression
m::Model
index::Int
end
struct NonlinearParameter <: AbstractJuMPScalar
m::Model
index::Int
end
##########################################################################
include("containers.jl")
include("operators.jl")
include("macros.jl")
include("optimizerinterface.jl")
include("nlp.jl")
include("print.jl")
##########################################################################
end