/
JuMP.jl
1500 lines (1234 loc) · 44.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
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
#############################################################################
"""
JuMP
An algebraic modeling language for Julia.
For more information, go to https://jump.dev.
"""
module JuMP
using LinearAlgebra
using SparseArrays
import MutableArithmetics
const _MA = MutableArithmetics
import MathOptInterface
"""
MOI
Shorthand for the MathOptInterface package.
"""
const MOI = MathOptInterface
"""
MOIU
Shorthand for the MathOptInterface.Utilities package.
"""
const MOIU = MOI.Utilities
"""
MOIB
Shorthand for the MathOptInterface.Bridges package.
"""
const MOIB = MOI.Bridges
import Calculus
import DataStructures.OrderedDict
import ForwardDiff
include("_Derivatives/_Derivatives.jl")
using ._Derivatives
include("Containers/Containers.jl")
# Exports are at the end of the file.
# Deprecations for JuMP v0.18 -> JuMP v0.19 transition
Base.@deprecate(getobjectivevalue, JuMP.objective_value)
Base.@deprecate(getobjectivebound, JuMP.objective_bound)
Base.@deprecate(getvalue, JuMP.value)
Base.@deprecate(getdual, JuMP.dual)
Base.@deprecate(numvar, JuMP.num_variables)
Base.@deprecate(numnlconstr, JuMP.num_nl_constraints)
Base.@deprecate(setlowerbound, JuMP.set_lower_bound)
Base.@deprecate(setupperbound, JuMP.set_upper_bound)
Base.@deprecate(linearterms, JuMP.linear_terms)
function writeLP(args...; kargs...)
return error(
"writeLP has been removed from JuMP. Use `write_to_file` instead.",
)
end
function writeMPS(args...; kargs...)
return error(
"writeMPS has been removed from JuMP. Use `write_to_file` instead.",
)
end
include("utils.jl")
const _MOIVAR = MOI.VariableIndex
const _MOICON{F,S} = MOI.ConstraintIndex{F,S}
"""
optimizer_with_attributes(optimizer_constructor, attrs::Pair...)
Groups an optimizer constructor with the list of attributes `attrs`. Note that
it is equivalent to `MOI.OptimizerWithAttributes`.
When provided to the `Model` constructor or to [`set_optimizer`](@ref), it
creates an optimizer by calling `optimizer_constructor()`, and then sets the
attributes using [`set_optimizer_attribute`](@ref).
## Example
```julia
model = Model(
optimizer_with_attributes(
Gurobi.Optimizer, "Presolve" => 0, "OutputFlag" => 1
)
)
```
is equivalent to:
```julia
model = Model(Gurobi.Optimizer)
set_optimizer_attribute(model, "Presolve", 0)
set_optimizer_attribute(model, "OutputFlag", 1)
```
## Note
The string names of the attributes are specific to each solver. One should
consult the solver's documentation to find the attributes of interest.
See also: [`set_optimizer_attribute`](@ref), [`set_optimizer_attributes`](@ref),
[`get_optimizer_attribute`](@ref).
"""
function optimizer_with_attributes(optimizer_constructor, args::Pair...)
return MOI.OptimizerWithAttributes(optimizer_constructor, args...)
end
function with_optimizer(constructor; kwargs...)
if isempty(kwargs)
deprecation_message = """
`with_optimizer` is deprecated. Adapt the following example to update your code:
`with_optimizer(Ipopt.Optimizer)` becomes `Ipopt.Optimizer`.
"""
Base.depwarn(deprecation_message, :with_optimizer)
return constructor
else
deprecation_message = """
`with_optimizer` is deprecated. Adapt the following example to update your code:
`with_optimizer(Ipopt.Optimizer, max_cpu_time=60.0)` becomes `optimizer_with_attributes(Ipopt.Optimizer, "max_cpu_time" => 60.0)`.
"""
Base.depwarn(deprecation_message, :with_optimizer_kw)
params = [MOI.RawOptimizerAttribute(string(kw.first)) => kw.second for
kw in kwargs]
return MOI.OptimizerWithAttributes(constructor, params)
end
end
function with_optimizer(constructor, args...; kwargs...)
if isempty(kwargs)
deprecation_message = """
`with_optimizer` is deprecated. Adapt the following example to update your code:
`with_optimizer(Gurobi.Optimizer, env)` becomes `() -> Gurobi.Optimizer(env)`.
"""
Base.depwarn(deprecation_message, :with_optimizer_args)
if !applicable(constructor, args...)
error(
"$constructor 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 with_optimizer(() -> constructor(args...); kwargs...)
else
deprecation_message = """
`with_optimizer` is deprecated. Adapt the following example to update your code:
`with_optimizer(Gurobi.Optimizer, env, Presolve=0)` becomes `optimizer_with_attributes(() -> Gurobi.Optimizer(env), "Presolve" => 0)`.
"""
Base.depwarn(deprecation_message, :with_optimizer_args_kw)
if !applicable(constructor, args...)
error(
"$constructor 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
params = [MOI.RawOptimizerAttribute(string(kw.first)) => kw.second for
kw in kwargs]
return MOI.OptimizerWithAttributes(() -> constructor(args...), params)
end
end
include("shapes.jl")
# Model
"""
ModelMode
An enum to describe the state of the CachingOptimizer inside a JuMP model.
"""
@enum(ModelMode, AUTOMATIC, MANUAL, DIRECT)
@doc(
"`moi_backend` field holds a CachingOptimizer in AUTOMATIC mode.",
AUTOMATIC
)
@doc("`moi_backend` field holds a CachingOptimizer in MANUAL mode.", MANUAL)
@doc(
"`moi_backend` field holds an AbstractOptimizer. No extra copy of the " *
"model is stored. The `moi_backend` must support `add_constraint` etc.",
DIRECT,
)
"""
AbstractModel
An abstract type that should be subtyped for users creating JuMP extensions.
"""
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
# In MANUAL and AUTOMATIC modes, CachingOptimizer.
# In DIRECT mode, will hold an AbstractOptimizer.
moi_backend::MOI.AbstractOptimizer
# List of shapes of constraints that are not `ScalarShape` or `VectorShape`.
shapes::Dict{_MOICON,AbstractShape}
# List of bridges to add in addition to the ones added in
# `MOI.Bridges.full_bridge_optimizer`. With `BridgeableConstraint`, the
# same bridge may be added many times so we store them in a `Set` instead
# of, e.g., a `Vector`.
bridge_types::Set{Any}
# Hook into a solve call...function of the form f(m::Model; kwargs...),
# where kwargs get passed along to subsequent solve calls.
optimize_hook::Any
# TODO: Document.
nlp_data::Any
# 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
# A flag to track whether we have modified the model after calling
# optimize!.
is_model_dirty::Bool
# 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()
Return a new JuMP model without any optimizer; the model is stored in
a cache.
Use [`set_optimizer`](@ref) to set the optimizer before calling
[`optimize!`](@ref).
"""
function Model(; caching_mode = nothing, solver = nothing)
if caching_mode !== nothing
@warn("Ignoring `caching_mode` keyword because it has been removed.")
end
if solver !== nothing
error(
"The solver= keyword is no longer available in JuMP 0.19 and " *
"later. See the JuMP documentation " *
"(https://jump.dev/JuMP.jl/latest/) for latest syntax.",
)
end
caching_opt = MOIU.CachingOptimizer(
MOIU.UniversalFallback(MOIU.Model{Float64}()),
MOIU.AUTOMATIC,
)
return direct_model(caching_opt)
end
"""
Model(optimizer_factory; add_bridges::Bool = true)
Return a new JuMP model with the provided optimizer and bridge settings.
See [`set_optimizer`](@ref) for the description of the `optimizer_factory` and
`add_bridges` arguments.
## Examples
Create a model with the optimizer set to `Ipopt`:
```julia
model = Model(Ipopt.Optimizer)
```
Pass an anonymous function which creates a `Gurobi.Optimizer`, and disable
bridges:
```julia
env = Gurobi.Env()
model = Model(() -> Gurobi.Optimizer(env); add_bridges = false)
```
"""
function Model(
optimizer_factory;
add_bridges::Bool = true,
bridge_constraints::Union{Nothing,Bool} = nothing,
kwargs...,
)
if bridge_constraints !== nothing
@warn(
"`bridge_constraints` argument is deprecated. Use `add_bridges` " *
"instead.",
)
add_bridges = bridge_constraints
end
model = Model(; kwargs...)
set_optimizer(model, optimizer_factory, add_bridges = add_bridges)
return model
end
"""
direct_model(backend::MOI.ModelLike)
Return a new JuMP model using [`backend`](@ref) to store the model and solve it.
As opposed to the [`Model`](@ref) constructor, no cache of the model is stored
outside of [`backend`](@ref) and no bridges are automatically applied to
[`backend`](@ref).
## Notes
The absence of a 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`](@ref) does not support an operation, such as modifying
constraints or adding variables/constraints after solving, an error is
thrown. For 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 `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.is_empty(backend)
return Model(
backend,
Dict{_MOICON,AbstractShape}(),
Set{Any}(),
nothing,
nothing,
Dict{Symbol,Any}(),
0,
false,
Dict{Symbol,Any}(),
)
end
"""
direct_model(factory::MOI.OptimizerWithAttributes)
Create a [`direct_model`](@ref) using `factory`, a `MOI.OptimizerWithAttributes`
object created by [`optimizer_with_attributes`](@ref).
## Example
```julia
model = direct_model(
optimizer_with_attributes(
Gurobi.Optimizer,
"Presolve" => 0,
"OutputFlag" => 1,
)
)
```
is equivalent to:
```julia
model = direct_model(Gurobi.Optimizer())
set_optimizer_attribute(model, "Presolve", 0)
set_optimizer_attribute(model, "OutputFlag", 1)
```
"""
function direct_model(factory::MOI.OptimizerWithAttributes)
optimizer = MOI.instantiate(factory)
return direct_model(optimizer)
end
Base.broadcastable(model::Model) = Ref(model)
"""
backend(model::Model)
Return the lower-level MathOptInterface model that sits underneath JuMP. This
model depends on which operating mode JuMP is in (see [`mode`](@ref)).
* If JuMP is in `DIRECT` mode (i.e., the model was created using
[`direct_model`](@ref)), the backend will be the optimizer passed to
[`direct_model`](@ref).
* If JuMP is in `MANUAL` or `AUTOMATIC` mode, the backend is a
`MOI.Utilities.CachingOptimizer`.
**This function should only be used by advanced users looking to access
low-level MathOptInterface or solver-specific functionality.**
## Notes
If JuMP is not in `DIRECT` mode, the type returned by `backend` may change
between any JuMP releases. Therefore, only use the public API exposed by
MathOptInterface, and do not access internal fields. If you require access to
the innermost optimizer, see [`unsafe_backend`](@ref). Alternatively, use
[`direct_model`](@ref) to create a JuMP model in `DIRECT` mode.
See also: [`unsafe_backend`](@ref).
"""
backend(model::Model) = model.moi_backend
"""
unsafe_backend(model::Model)
Return the innermost optimizer associated with the JuMP model `model`.
**This function should only be used by advanced users looking to access
low-level solver-specific functionality. It has a high-risk of incorrect usage.
We strongly suggest you use the alternative suggested below.**
See also: [`backend`](@ref).
## Unsafe behavior
This function is unsafe for two main reasons.
First, the formulation and order of variables and constraints in the unsafe
backend may be different to the variables and constraints in `model`. This
can happen because of bridges, or because the solver requires the variables or
constraints in a specific order. In addition, the variable or constraint index
returned by [`index`](@ref) at the JuMP level may be different to the index of
the corresponding variable or constraint in the `unsafe_backend`. There is no
solution to this. Use the alternative suggested below instead.
Second, the `unsafe_backend` may be empty, or lack some modifications made to
the JuMP model. Thus, before calling `unsafe_backend` you should first call
[`MOI.Utilities.attach_optimizer`](@ref) to ensure that the backend is
synchronized with the JuMP model.
```julia
MOI.Utilities.attach_optimizer(model)
inner = unsafe_backend(model)
```
Moreover, if you modify the JuMP model, the reference you have to the backend
(i.e., `inner` in the example above) may be out-dated, and you should call
[`MOI.Utilities.attach_optimizer`](@ref) again.
This function is also unsafe in the reverse direction: if you modify the unsafe
backend, e.g., by adding a new constraint to `inner`, the changes may be
silently discarded by JuMP when the JuMP `model` is modified or solved.
## Alternative
Instead of `unsafe_backend`, create a model using [`direct_model`](@ref) and
call [`backend`](@ref) instead.
For example, instead of:
```julia
model = Model(GLPK.Optimizer)
@variable(model, x >= 0)
MOI.Utilities.attach_optimizer(model)
glpk = unsafe_backend(model)
```
Use:
```julia
model = direct_model(GLPK.Optimizer())
@variable(model, x >= 0)
glpk = backend(model) # No need to call `attach_optimizer`.
```
"""
unsafe_backend(model::Model) = unsafe_backend(backend(model))
function unsafe_backend(model::MOIU.CachingOptimizer)
if MOIU.state(model) == MOIU.NO_OPTIMIZER
error(
"Unable to get backend optimizer because CachingOptimizer is " *
"in state `NO_OPTIMIZER`. Call [`set_optimizer`](@ref) first.",
)
end
return unsafe_backend(model.optimizer)
end
unsafe_backend(model::MOIB.LazyBridgeOptimizer) = unsafe_backend(model.model)
unsafe_backend(model::MOI.ModelLike) = model
_moi_mode(::MOI.ModelLike) = DIRECT
function _moi_mode(model::MOIU.CachingOptimizer)
return model.mode == MOIU.AUTOMATIC ? AUTOMATIC : MANUAL
end
"""
mode(model::Model)
Return the [`ModelMode`](@ref) ([`DIRECT`](@ref), [`AUTOMATIC`](@ref), or
[`MANUAL`](@ref)) of `model`.
"""
function mode(model::Model)
# The type of `backend(model)` is not type-stable, so we use a function
# barrier (`_moi_mode`) to improve performance.
return _moi_mode(backend(model))
end
# Internal function.
function _try_get_solver_name(model_like)
try
return MOI.get(model_like, MOI.SolverName())::String
catch ex
if isa(ex, ArgumentError)
return "SolverName() attribute not implemented by the optimizer."
else
rethrow(ex)
end
end
end
"""
solver_name(model::Model)
If available, returns the `SolverName` property of the underlying optimizer.
Returns `"No optimizer attached"` in `AUTOMATIC` or `MANUAL` modes when no
optimizer is attached.
Returns `"SolverName() attribute not implemented by the optimizer."` if the
attribute is not implemented.
"""
function solver_name(model::Model)
if mode(model) != DIRECT && MOIU.state(backend(model)) == MOIU.NO_OPTIMIZER
return "No optimizer attached."
else
return _try_get_solver_name(backend(model))
end
end
_moi_bridge_constraints(::MOI.ModelLike) = false
function _moi_bridge_constraints(model::MOIU.CachingOptimizer)
return model.optimizer isa MOI.Bridges.LazyBridgeOptimizer
end
"""
bridge_constraints(model::Model)
When in direct mode, return `false`.
When in manual or automatic mode, return a `Bool` indicating whether the
optimizer is set and unsupported constraints are automatically bridged
to equivalent supported constraints when an appropriate transformation is
available.
"""
function bridge_constraints(model::Model)
# The type of `backend(model)` is not type-stable, so we use a function
# barrier (`_moi_bridge_constraints`) to improve performance.
return _moi_bridge_constraints(backend(model))
end
function _moi_add_bridge(
model::Nothing,
BridgeType::Type{<:MOI.Bridges.AbstractBridge},
)
# No optimizer is attached, the bridge will be added when one is attached
return
end
function _moi_add_bridge(
model::MOI.ModelLike,
BridgeType::Type{<:MOI.Bridges.AbstractBridge},
)
return error(
"Cannot add bridge if `bridge_constraints` was set to `false` in the",
" `Model` constructor.",
)
end
function _moi_add_bridge(
bridge_opt::MOI.Bridges.LazyBridgeOptimizer,
BridgeType::Type{<:MOI.Bridges.AbstractBridge},
)
MOI.Bridges.add_bridge(bridge_opt, BridgeType{Float64})
return
end
function _moi_add_bridge(
caching_opt::MOIU.CachingOptimizer,
BridgeType::Type{<:MOI.Bridges.AbstractBridge},
)
_moi_add_bridge(caching_opt.optimizer, BridgeType)
return
end
"""
add_bridge(model::Model,
BridgeType::Type{<:MOI.Bridges.AbstractBridge})
Add `BridgeType` to the list of bridges that can be used to transform
unsupported constraints into an equivalent formulation using only constraints
supported by the optimizer.
"""
function add_bridge(
model::Model,
BridgeType::Type{<:MOI.Bridges.AbstractBridge},
)
push!(model.bridge_types, BridgeType)
# The type of `backend(model)` is not type-stable, so we use a function
# barrier (`_moi_add_bridge`) to improve performance.
_moi_add_bridge(JuMP.backend(model), BridgeType)
return
end
"""
print_bridge_graph([io::IO,] model::Model)
Print the hyper-graph containing all variable, constraint, and objective types
that could be obtained by bridging the variables, constraints, and objectives
that are present in the model.
Each node in the hyper-graph corresponds to a variable, constraint, or objective
type.
* Variable nodes are indicated by `[ ]`
* Constraint nodes are indicated by `( )`
* Objective nodes are indicated by `| |`
The number inside each pair of brackets is an index of the node in the
hyper-graph.
Note that this hyper-graph is the full list of possible transformations. When
the bridged model is created, we select the shortest hyper-path(s) from this
graph, so many nodes may be un-used.
For more information, see Legat, B., Dowson, O., Garcia, J., and Lubin, M.
(2020). "MathOptInterface: a data structure for mathematical optimization
problems." URL: [https://arxiv.org/abs/2002.03447](https://arxiv.org/abs/2002.03447)
"""
print_bridge_graph(model::Model) = print_bridge_graph(Base.stdout, model)
function print_bridge_graph(io::IO, model::Model)
# The type of `backend(model)` is not type-stable, so we use a function
# barrier (`_moi_print_bridge_graph`) to improve performance.
return _moi_print_bridge_graph(io, backend(model))
end
function _moi_print_bridge_graph(io::IO, model::MOI.Bridges.LazyBridgeOptimizer)
return MOI.Bridges.print_graph(io, model)
end
function _moi_print_bridge_graph(io::IO, model::MOIU.CachingOptimizer)
return _moi_print_bridge_graph(io, model.optimizer)
end
function _moi_print_bridge_graph(::IO, ::MOI.ModelLike)
return error(
"Cannot print bridge graph if `bridge_constraints` was set to " *
"`false` in the `Model` constructor.",
)
end
"""
empty!(model::Model)::Model
Empty the model, that is, remove all variables, constraints and model
attributes but not optimizer attributes. Always return the argument.
Note: removes extensions data.
"""
function Base.empty!(model::Model)::Model
# The method changes the Model object to, basically, the state it was when
# created (if the optimizer was already pre-configured). The exceptions
# are:
# * optimize_hook: it is basically an optimizer attribute and we promise
# to leave them alone (as do MOI.empty!).
# * bridge_types: for consistency with MOI.empty! for
# MOI.Bridges.LazyBridgeOptimizer.
# * operator_counter: it is just a counter for a single-time warning
# message (so keeping it helps to discover inefficiencies).
MOI.empty!(model.moi_backend)
empty!(model.shapes)
model.nlp_data = nothing
empty!(model.obj_dict)
empty!(model.ext)
model.is_model_dirty = false
return model
end
"""
isempty(model::Model)
Verifies whether the model is empty, that is, whether the MOI backend
is empty and whether the model is in the same state as at its creation
apart from optimizer attributes.
"""
function Base.isempty(model::Model)
MOI.is_empty(model.moi_backend) || return false
isempty(model.shapes) || return false
model.nlp_data === nothing || return false
isempty(model.obj_dict) && isempty(model.ext) || return false
return !model.is_model_dirty
end
"""
num_variables(model::Model)::Int64
Returns number of variables in `model`.
"""
num_variables(model::Model)::Int64 = MOI.get(model, MOI.NumberOfVariables())
"""
num_nl_constraints(model::Model)
Returns the number of nonlinear constraints associated with the `model`.
"""
function num_nl_constraints(model::Model)
return model.nlp_data !== nothing ? length(model.nlp_data.nlconstr) : 0
end
"""
object_dictionary(model::Model)
Return the dictionary that maps the symbol name of a variable, constraint, or
expression to the corresponding object.
Objects are registered to a specific symbol in the macros.
For example, `@variable(model, x[1:2, 1:2])` registers the array of variables
`x` to the symbol `:x`.
This method should be defined for any subtype of `AbstractModel`.
"""
object_dictionary(model::Model) = model.obj_dict
"""
unregister(model::Model, key::Symbol)
Unregister the name `key` from `model` so that a new variable, constraint, or
expression can be created with the same key.
Note that this will not delete the object `model[key]`; it will just remove the
reference at `model[key]`. To delete the object, use
```julia
delete(model, model[key])
unregister(model, key)
```
See also: [`object_dictionary`](@ref).
## Examples
```jldoctest; setup=:(model = Model())
julia> @variable(model, x)
x
julia> @variable(model, x)
ERROR: An object of name x is already attached to this model. If
this is intended, consider using the anonymous construction syntax,
e.g., `x = @variable(model, [1:N], ...)` where the name of the object
does not appear inside the macro.
Alternatively, use `unregister(model, :x)` to first unregister the
existing name from the model. Note that this will not delete the object;
it will just remove the reference at `model[:x]`.
[...]
julia> num_variables(model)
1
julia> unregister(model, :x)
julia> @variable(model, x)
x
julia> num_variables(model)
2
```
"""
function unregister(model::AbstractModel, key::Symbol)
delete!(object_dictionary(model), key)
return
end
"""
termination_status(model::Model)
Return a [`MOI.TerminationStatusCode`](@ref) describing why the solver stopped
(i.e., the [`MOI.TerminationStatus`](@ref) attribute).
"""
function termination_status(model::Model)
return MOI.get(model, MOI.TerminationStatus())::MOI.TerminationStatusCode
end
"""
raw_status(model::Model)
Return the reason why the solver stopped in its own words (i.e., the
MathOptInterface model attribute `RawStatusString`).
"""
function raw_status(model::Model)
return MOI.get(model, MOI.RawStatusString())
end
"""
primal_status(model::Model; result::Int = 1)
Return a [`MOI.ResultStatusCode`](@ref) describing the status of the most recent
primal solution of the solver (i.e., the [`MOI.PrimalStatus`](@ref) attribute)
associated with the result index `result`.
See also: [`result_count`](@ref).
"""
function primal_status(model::Model; result::Int = 1)
return MOI.get(model, MOI.PrimalStatus(result))::MOI.ResultStatusCode
end
"""
dual_status(model::Model; result::Int = 1)
Return a [`MOI.ResultStatusCode`](@ref) describing the status of the most recent
dual solution of the solver (i.e., the [`MOI.DualStatus`](@ref) attribute)
associated with the result index `result`.
See also: [`result_count`](@ref).
"""
function dual_status(model::Model; result::Int = 1)
return MOI.get(model, MOI.DualStatus(result))::MOI.ResultStatusCode
end
"""
set_optimize_hook(model::Model, f::Union{Function,Nothing})
Set the function `f` as the optimize hook for `model`.
`f` should have a signature `f(model::Model; kwargs...)`, where the `kwargs` are
those passed to [`optimize!`](@ref).
## Notes
* The optimize hook should generally modify the model, or some external state
in some way, and then call `optimize!(model; ignore_optimize_hook = true)` to
optimize the problem, bypassing the hook.
* Use `set_optimize_hook(model, nothing)` to unset an optimize hook.
## Examples
```julia
model = Model()
function my_hook(model::Model; kwargs...)
print(kwargs)
return optimize!(model; ignore_optimize_hook = true)
end
set_optimize_hook(model, my_hook)
optimize!(model; test_arg = true)
```
"""
set_optimize_hook(model::Model, f) = (model.optimize_hook = f)
"""
solve_time(model::Model)
If available, returns the solve time reported by the solver.
Returns "ArgumentError: ModelLike of type `Solver.Optimizer` does not support
accessing the attribute MathOptInterface.SolveTimeSec()" if the attribute is
not implemented.
"""
function solve_time(model::Model)
return MOI.get(model, MOI.SolveTimeSec())
end
"""
set_optimizer_attribute(model::Model, name::String, value)
Sets solver-specific attribute identified by `name` to `value`.
Note that this is equivalent to
`set_optimizer_attribute(model, MOI.RawOptimizerAttribute(name), value)`.
## Example
```julia
set_optimizer_attribute(model, "SolverSpecificAttributeName", true)
```
See also: [`set_optimizer_attributes`](@ref), [`get_optimizer_attribute`](@ref).
"""
function set_optimizer_attribute(model::Model, name::String, value)
set_optimizer_attribute(model, MOI.RawOptimizerAttribute(name), value)
return
end
"""
set_optimizer_attribute(
model::Model,
attr::MOI.AbstractOptimizerAttribute,
value,
)
Set the solver-specific attribute `attr` in `model` to `value`.
## Example
```julia
set_optimizer_attribute(model, MOI.Silent(), true)
```
See also: [`set_optimizer_attributes`](@ref), [`get_optimizer_attribute`](@ref).
"""
function set_optimizer_attribute(
model::Model,
attr::MOI.AbstractOptimizerAttribute,
value,
)
MOI.set(model, attr, value)
return
end
@deprecate set_parameter set_optimizer_attribute
"""
set_optimizer_attributes(model::Model, pairs::Pair...)
Given a list of `attribute => value` pairs, calls
`set_optimizer_attribute(model, attribute, value)` for each pair.
## Example
```julia
model = Model(Ipopt.Optimizer)
set_optimizer_attributes(model, "tol" => 1e-4, "max_iter" => 100)
```
is equivalent to:
```julia
model = Model(Ipopt.Optimizer)
set_optimizer_attribute(model, "tol", 1e-4)
set_optimizer_attribute(model, "max_iter", 100)
```
See also: [`set_optimizer_attribute`](@ref), [`get_optimizer_attribute`](@ref).
"""
function set_optimizer_attributes(model::Model, pairs::Pair...)
for (name, value) in pairs
set_optimizer_attribute(model, name, value)
end
return
end
@deprecate set_parameters set_optimizer_attributes
"""
get_optimizer_attribute(model, name::String)
Return the value associated with the solver-specific attribute named `name`.
Note that this is equivalent to
`get_optimizer_attribute(model, MOI.RawOptimizerAttribute(name))`.
## Example
```julia
get_optimizer_attribute(model, "SolverSpecificAttributeName")
```
See also: [`set_optimizer_attribute`](@ref), [`set_optimizer_attributes`](@ref).
"""
function get_optimizer_attribute(model::Model, name::String)
return get_optimizer_attribute(model, MOI.RawOptimizerAttribute(name))
end
"""
get_optimizer_attribute(
model::Model, attr::MOI.AbstractOptimizerAttribute
)
Return the value of the solver-specific attribute `attr` in `model`.
## Example
```julia
get_optimizer_attribute(model, MOI.Silent())
```
See also: [`set_optimizer_attribute`](@ref), [`set_optimizer_attributes`](@ref).
"""
function get_optimizer_attribute(
model::Model,
attr::MOI.AbstractOptimizerAttribute,
)
return MOI.get(model, attr)
end
"""
set_silent(model::Model)
Takes precedence over any other attribute controlling verbosity and requires the
solver to produce no output.
See also: [`unset_silent`](@ref).
"""
function set_silent(model::Model)
return MOI.set(model, MOI.Silent(), true)
end
"""
unset_silent(model::Model)
Neutralize the effect of the `set_silent` function and let the solver attributes
control the verbosity.
See also: [`set_silent`](@ref).
"""
function unset_silent(model::Model)
return MOI.set(model, MOI.Silent(), false)
end
"""
set_time_limit_sec(model::Model, limit::Float64)