-
-
Notifications
You must be signed in to change notification settings - Fork 393
/
optimizer_interface.jl
1311 lines (1061 loc) · 37.6 KB
/
optimizer_interface.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/.
"""
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_attribute`](@ref).
See also: [`set_attribute`](@ref), [`get_attribute`](@ref).
## 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.
## Example
```jldoctest
julia> import HiGHS
julia> optimizer = optimizer_with_attributes(
HiGHS.Optimizer, "presolve" => "off", MOI.Silent() => true,
);
julia> model = Model(optimizer);
```
is equivalent to:
```jldoctest
julia> import HiGHS
julia> model = Model(HiGHS.Optimizer);
julia> set_attribute(model, "presolve", "off")
julia> set_attribute(model, MOI.Silent(), true)
```
"""
function optimizer_with_attributes(optimizer_constructor, args::Pair...)
return MOI.OptimizerWithAttributes(optimizer_constructor, args...)
end
"""
set_optimizer_attribute(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
attr::Union{AbstractString,MOI.AbstractOptimizerAttribute},
value,
)
Set the solver-specific attribute `attr` in `model` to `value`.
If `attr` is an `AbstractString`, this is equivalent to
`set_optimizer_attribute(model, MOI.RawOptimizerAttribute(name), value)`.
!!! compat
This method will remain in all v1.X releases of JuMP, but it may be removed
in a future v2.0 release. We recommend using [`set_attribute`](@ref) instead.
See also: [`set_optimizer_attributes`](@ref), [`get_optimizer_attribute`](@ref).
## Example
```jldoctest
julia> model = Model();
julia> set_optimizer_attribute(model, MOI.Silent(), true)
```
"""
set_optimizer_attribute(model, attr, value) = set_attribute(model, attr, value)
"""
set_optimizer_attributes(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
pairs::Pair...,
)
Given a list of `attribute => value` pairs, calls
`set_optimizer_attribute(model, attribute, value)` for each pair.
!!! compat
This method will remain in all v1.X releases of JuMP, but it may be removed
in a future v2.0 release. We recommend using [`set_attributes`](@ref) instead.
See also: [`set_optimizer_attribute`](@ref), [`get_optimizer_attribute`](@ref).
## Example
```jldoctest
julia> import Ipopt
julia> model = Model(Ipopt.Optimizer);
julia> set_optimizer_attributes(model, "tol" => 1e-4, "max_iter" => 100)
```
is equivalent to:
```jldoctest
julia> import Ipopt
julia> model = Model(Ipopt.Optimizer);
julia> set_optimizer_attribute(model, "tol", 1e-4)
julia> set_optimizer_attribute(model, "max_iter", 100)
```
"""
function set_optimizer_attributes(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
pairs::Pair...,
)
for (name, value) in pairs
set_attribute(model, name, value)
end
return
end
"""
get_optimizer_attribute(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
attr::Union{AbstractString,MOI.AbstractOptimizerAttribute},
)
Return the value associated with the solver-specific attribute `attr`.
If `attr` is an `AbstractString`, this is equivalent to
`get_optimizer_attribute(model, MOI.RawOptimizerAttribute(name))`.
!!! compat
This method will remain in all v1.X releases of JuMP, but it may be removed
in a future v2.0 release. We recommend using [`get_attribute`](@ref) instead.
See also: [`set_optimizer_attribute`](@ref), [`set_optimizer_attributes`](@ref).
## Example
```jldoctest
julia> import Ipopt
julia> model = Model(Ipopt.Optimizer);
julia> get_optimizer_attribute(model, MOI.Silent())
false
```
"""
get_optimizer_attribute(model, attr) = get_attribute(model, attr)
"""
set_silent(model::GenericModel)
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::GenericModel)
return MOI.set(model, MOI.Silent(), true)
end
"""
unset_silent(model::GenericModel)
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::GenericModel)
return MOI.set(model, MOI.Silent(), false)
end
"""
set_time_limit_sec(model::GenericModel, limit::Float64)
Set the time limit (in seconds) of the solver.
Can be unset using [`unset_time_limit_sec`](@ref) or with `limit` set to
`nothing`.
See also: [`unset_time_limit_sec`](@ref), [`time_limit_sec`](@ref).
"""
function set_time_limit_sec(model::GenericModel, limit::Real)
return MOI.set(model, MOI.TimeLimitSec(), convert(Float64, limit))
end
function set_time_limit_sec(model::GenericModel, ::Nothing)
return unset_time_limit_sec(model)
end
"""
unset_time_limit_sec(model::GenericModel)
Unset the time limit of the solver.
See also: [`set_time_limit_sec`](@ref), [`time_limit_sec`](@ref).
"""
function unset_time_limit_sec(model::GenericModel)
return MOI.set(model, MOI.TimeLimitSec(), nothing)
end
"""
time_limit_sec(model::GenericModel)
Return the time limit (in seconds) of the `model`.
Returns `nothing` if unset.
See also: [`set_time_limit_sec`](@ref), [`unset_time_limit_sec`](@ref).
"""
function time_limit_sec(model::GenericModel)
return MOI.get(model, MOI.TimeLimitSec())
end
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::GenericModel)
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::GenericModel)
if mode(model) != DIRECT && MOIU.state(backend(model)) == MOIU.NO_OPTIMIZER
return "No optimizer attached."
end
return _try_get_solver_name(backend(model))
end
"""
error_if_direct_mode(model::GenericModel, func::Symbol)
Errors if `model` is in direct mode during a call from the function named
`func`.
Used internally within JuMP, or by JuMP extensions who do not want to support
models in direct mode.
"""
function error_if_direct_mode(model::GenericModel, func::Symbol)
if mode(model) == DIRECT
error("The `$func` function is not supported in DIRECT mode.")
end
return
end
# These methods directly map to CachingOptimizer methods.
"""
MOIU.reset_optimizer(model::GenericModel, optimizer::MOI.AbstractOptimizer)
Call `MOIU.reset_optimizer` on the backend of `model`.
Cannot be called in direct mode.
"""
function MOIU.reset_optimizer(
model::GenericModel,
optimizer::MOI.AbstractOptimizer,
::Bool = true,
)
error_if_direct_mode(model, :reset_optimizer)
MOIU.reset_optimizer(backend(model), optimizer)
return
end
"""
MOIU.reset_optimizer(model::GenericModel)
Call `MOIU.reset_optimizer` on the backend of `model`.
Cannot be called in direct mode.
"""
function MOIU.reset_optimizer(model::GenericModel)
error_if_direct_mode(model, :reset_optimizer)
if MOI.Utilities.state(backend(model)) == MOI.Utilities.ATTACHED_OPTIMIZER
MOIU.reset_optimizer(backend(model))
end
return
end
"""
MOIU.drop_optimizer(model::GenericModel)
Call `MOIU.drop_optimizer` on the backend of `model`.
Cannot be called in direct mode.
"""
function MOIU.drop_optimizer(model::GenericModel)
error_if_direct_mode(model, :drop_optimizer)
MOIU.drop_optimizer(backend(model))
return
end
"""
MOIU.attach_optimizer(model::GenericModel)
Call `MOIU.attach_optimizer` on the backend of `model`.
Cannot be called in direct mode.
"""
function MOIU.attach_optimizer(model::GenericModel)
error_if_direct_mode(model, :attach_optimizer)
MOIU.attach_optimizer(backend(model))
return
end
"""
set_optimizer(
model::GenericModel,
optimizer_factory;
add_bridges::Bool = true,
)
Creates an empty `MathOptInterface.AbstractOptimizer` instance by calling
`optimizer_factory()` and sets it as the optimizer of `model`. Specifically,
`optimizer_factory` must be callable with zero arguments and return an empty
`MathOptInterface.AbstractOptimizer`.
If `add_bridges` is true, constraints and objectives that are not supported by
the optimizer are automatically bridged to equivalent supported formulation.
Passing `add_bridges = false` can improve performance if the solver natively
supports all of the elements in `model`.
See [`set_attribute`](@ref) for setting solver-specific parameters of the
optimizer.
## Example
```jldoctest
julia> import HiGHS
julia> model = Model();
julia> set_optimizer(model, () -> HiGHS.Optimizer())
julia> set_optimizer(model, HiGHS.Optimizer; add_bridges = false)
```
"""
function set_optimizer(
model::GenericModel{T},
@nospecialize(optimizer_constructor);
add_bridges::Bool = true,
) where {T}
error_if_direct_mode(model, :set_optimizer)
if add_bridges
optimizer = MOI.instantiate(optimizer_constructor; with_bridge_type = T)
for BT in model.bridge_types
_moi_call_bridge_function(MOI.Bridges.add_bridge, optimizer, BT)
end
else
optimizer = MOI.instantiate(optimizer_constructor)
end
# Update the backend to create a new, concretely typed CachingOptimizer
# using the existing `model_cache`.
model.moi_backend =
MOI.Utilities.CachingOptimizer(backend(model).model_cache, optimizer)
return
end
"""
optimize!(
model::GenericModel;
ignore_optimize_hook = (model.optimize_hook === nothing),
_differentiation_backend::MOI.Nonlinear.AbstractAutomaticDifferentiation =
MOI.Nonlinear.SparseReverseMode(),
kwargs...,
)
Optimize the model.
If an optimizer has not been set yet (see [`set_optimizer`](@ref)), a
[`NoOptimizer`](@ref) error is thrown.
If `ignore_optimize_hook == true`, the optimize hook is ignored and the model is
solved as if the hook was not set. Keyword arguments `kwargs` are passed to the
`optimize_hook`. An error is thrown if `optimize_hook` is `nothing` and keyword
arguments are provided.
## Experimental features
These features may change or be removed in any future version of JuMP.
Pass `_differentiation_backend` to set the
[`MOI.Nonlinear.AbstractAutomaticDifferentiation`](@ref) backend used to compute
derivatives of nonlinear programs.
If you require only `:ExprGraph`, it is more efficient to pass
`_differentiation_backend = MOI.Nonlinear.ExprGraphOnly()`.
"""
function optimize!(
model::GenericModel;
ignore_optimize_hook = (model.optimize_hook === nothing),
_differentiation_backend::MOI.Nonlinear.AbstractAutomaticDifferentiation = MOI.Nonlinear.SparseReverseMode(),
kwargs...,
)
# The nlp_model is not kept in sync, so re-set it here.
# TODO: Consider how to handle incremental solves.
nlp = nonlinear_model(model)
if nlp !== nothing
if _uses_new_nonlinear_interface(model)
error(
"Cannot optimize a model which contains the features from " *
"both the legacy (macros beginning with `@NL`) and new " *
"(`NonlinearExpr`) nonlinear interfaces. You must use one or " *
"the other.",
)
end
evaluator = MOI.Nonlinear.Evaluator(
nlp,
_differentiation_backend,
index.(all_variables(model)),
)
MOI.set(model, MOI.NLPBlock(), MOI.NLPBlockData(evaluator))
end
# If the user or an extension has provided an optimize hook, call
# that instead of solving the model ourselves
if !ignore_optimize_hook
return model.optimize_hook(model; kwargs...)
end
if !isempty(kwargs)
error(
"Unrecognized keyword arguments: $(join([k[1] for k in kwargs], ", "))",
)
end
if mode(model) != DIRECT && MOIU.state(backend(model)) == MOIU.NO_OPTIMIZER
throw(NoOptimizer())
end
optimizer = unsafe_backend(model)
if !(optimizer isa MOI.AbstractOptimizer)
error(
"Cannot call `optimize!` because the provided optimizer is not " *
"a subtype of `MOI.AbstractOptimizer`.\n\nThe optimizer is:\n\n" *
sprint(show, optimizer) *
"\n",
)
end
try
MOI.optimize!(backend(model))
catch err
# TODO: This error also be thrown also in MOI.set() if the solver is
# attached. Currently we catch only the more common case. More generally
# JuMP is missing a translation layer from MOI errors to JuMP errors.
if err isa MOI.UnsupportedAttribute{MOI.NLPBlock}
error(
"The solver does not support nonlinear problems " *
"(that is, NLobjective and NLconstraint).",
)
else
rethrow(err)
end
end
model.is_model_dirty = false
return
end
function _uses_new_nonlinear_interface(model)
if objective_function_type(model) <: GenericNonlinearExpr
return true
end
for (F, S) in list_of_constraint_types(model)
if F <: GenericNonlinearExpr
return true
end
end
return false
end
"""
compute_conflict!(model::GenericModel)
Compute a conflict if the model is infeasible. If an optimizer has not
been set yet (see [`set_optimizer`](@ref)), a [`NoOptimizer`](@ref)
error is thrown.
The status of the conflict can be checked with the `MOI.ConflictStatus`
model attribute. Then, the status for each constraint can be queried with
the `MOI.ConstraintConflictStatus` attribute.
"""
function compute_conflict!(model::GenericModel)
if mode(model) != DIRECT && MOIU.state(backend(model)) == MOIU.NO_OPTIMIZER
throw(NoOptimizer())
end
MOI.compute_conflict!(backend(model))
return
end
"""
termination_status(model::GenericModel)
Return a [`MOI.TerminationStatusCode`](@ref) describing why the solver stopped
(that is, the [`MOI.TerminationStatus`](@ref) attribute).
"""
function termination_status(model::GenericModel)
return MOI.get(model, MOI.TerminationStatus())::MOI.TerminationStatusCode
end
function MOI.get(model::GenericModel, attr::MOI.TerminationStatus)
if model.is_model_dirty && mode(model) != DIRECT
return MOI.OPTIMIZE_NOT_CALLED
end
return MOI.get(backend(model), attr)
end
"""
result_count(model::GenericModel)
Return the number of results available to query after a call to
[`optimize!`](@ref).
"""
function result_count(model::GenericModel)::Int
if termination_status(model) == MOI.OPTIMIZE_NOT_CALLED
return 0
end
return MOI.get(model, MOI.ResultCount())
end
"""
raw_status(model::GenericModel)
Return the reason why the solver stopped in its own words (that is, the
MathOptInterface model attribute `RawStatusString`).
"""
function raw_status(model::GenericModel)
if MOI.get(model, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED
return "optimize not called"
end
return MOI.get(model, MOI.RawStatusString())
end
function MOI.get(
model::GenericModel,
attr::Union{MOI.PrimalStatus,MOI.DualStatus},
)
if model.is_model_dirty && mode(model) != DIRECT
return MOI.NO_SOLUTION
end
return MOI.get(backend(model), attr)
end
"""
primal_status(model::GenericModel; result::Int = 1)
Return a [`MOI.ResultStatusCode`](@ref) describing the status of the most recent
primal solution of the solver (that is, the [`MOI.PrimalStatus`](@ref) attribute)
associated with the result index `result`.
See also: [`result_count`](@ref).
"""
function primal_status(model::GenericModel; result::Int = 1)
return MOI.get(model, MOI.PrimalStatus(result))::MOI.ResultStatusCode
end
"""
dual_status(model::GenericModel; result::Int = 1)
Return a [`MOI.ResultStatusCode`](@ref) describing the status of the most recent
dual solution of the solver (that is, the [`MOI.DualStatus`](@ref) attribute)
associated with the result index `result`.
See also: [`result_count`](@ref).
"""
function dual_status(model::GenericModel; result::Int = 1)
return MOI.get(model, MOI.DualStatus(result))::MOI.ResultStatusCode
end
"""
is_solved_and_feasible(
model::GenericModel;
allow_local::Bool = true,
allow_almost::Bool = false,
dual::Bool = false,
result::Int = 1,
)
Return `true` if the model has a feasible primal solution associated with result
index `result` and the [`termination_status`](@ref) is [`OPTIMAL`](@ref) (the
solver found a global optimum) or [`LOCALLY_SOLVED`](@ref) (the solver found a
local optimum, which may also be the global optimum, but the solver could not
prove so).
If `allow_local = false`, then this function returns `true` only if the
[`termination_status`](@ref) is [`OPTIMAL`](@ref).
If `allow_almost = true`, then the [`termination_status`](@ref) may additionally
be [`ALMOST_OPTIMAL`](@ref) or [`ALMOST_LOCALLY_SOLVED`](@ref) (if `allow_local`),
and the [`primal_status`](@ref) and [`dual_status`](@ref) may additionally be
[`NEARLY_FEASIBLE_POINT`](@ref).
If `dual`, additionally check that an optimal dual solution is available.
If this function returns `false`, use [`termination_status`](@ref),
[`result_count`](@ref), [`primal_status`](@ref) and [`dual_status`](@ref) to
understand what solutions are available (if any).
"""
function is_solved_and_feasible(
model::GenericModel;
dual::Bool = false,
allow_local::Bool = true,
allow_almost::Bool = false,
result::Int = 1,
)
status = termination_status(model)
ret =
(status == OPTIMAL) ||
(allow_local && (status == LOCALLY_SOLVED)) ||
(allow_almost && (status == ALMOST_OPTIMAL)) ||
(allow_almost && allow_local && (status == ALMOST_LOCALLY_SOLVED))
if ret
primal = primal_status(model; result)
ret &=
(primal == FEASIBLE_POINT) ||
(allow_almost && (primal == NEARLY_FEASIBLE_POINT))
end
if ret && dual
dual_stat = dual_status(model; result)
ret &=
(dual_stat == FEASIBLE_POINT) ||
(allow_almost && (dual_stat == NEARLY_FEASIBLE_POINT))
end
return ret
end
"""
solve_time(model::GenericModel)
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::GenericModel)
return MOI.get(model, MOI.SolveTimeSec())
end
"""
simplex_iterations(model::GenericModel)
Gets the cumulative number of simplex iterations during the most-recent
optimization.
Solvers must implement `MOI.SimplexIterations()` to use this function.
"""
function simplex_iterations(model::GenericModel)
return MOI.get(model, MOI.SimplexIterations())
end
"""
barrier_iterations(model::GenericModel)
Gets the cumulative number of barrier iterations during the most recent
optimization.
Solvers must implement `MOI.BarrierIterations()` to use this function.
"""
function barrier_iterations(model::GenericModel)
return MOI.get(model, MOI.BarrierIterations())
end
"""
node_count(model::GenericModel)
Gets the total number of branch-and-bound nodes explored during the most recent
optimization in a Mixed Integer Program.
Solvers must implement `MOI.NodeCount()` to use this function.
"""
function node_count(model::GenericModel)
return MOI.get(model, MOI.NodeCount())
end
"""
get(model::GenericModel, attr::MathOptInterface.AbstractOptimizerAttribute)
Return the value of the attribute `attr` from the model's MOI backend.
"""
function MOI.get(model::GenericModel, attr::MOI.AbstractOptimizerAttribute)
return MOI.get(backend(model), attr)
end
"""
struct OptimizeNotCalled <: Exception end
A result attribute cannot be queried before [`optimize!`](@ref) is called.
"""
struct OptimizeNotCalled <: Exception end
"""
struct NoOptimizer <: Exception end
No optimizer is set. The optimizer can be provided to the [`Model`](@ref)
constructor or by calling [`set_optimizer`](@ref).
"""
struct NoOptimizer <: Exception end
# Throws an error if `optimize!` has not been called, that is, if there is no
# optimizer attached or if the termination status is `MOI.OPTIMIZE_NOT_CALLED`.
function _moi_get_result(model::MOI.ModelLike, args...)
if MOI.get(model, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED
throw(OptimizeNotCalled())
end
return MOI.get(model, args...)
end
function _moi_get_result(model::MOIU.CachingOptimizer, args...)
if MOIU.state(model) == MOIU.NO_OPTIMIZER
throw(NoOptimizer())
elseif MOI.get(model, MOI.TerminationStatus()) == MOI.OPTIMIZE_NOT_CALLED
throw(OptimizeNotCalled())
end
return MOI.get(model, args...)
end
"""
get(model::GenericModel, attr::MathOptInterface.AbstractModelAttribute)
Return the value of the attribute `attr` from the model's MOI backend.
"""
function MOI.get(model::GenericModel, attr::MOI.AbstractModelAttribute)
if !MOI.is_set_by_optimize(attr)
return MOI.get(backend(model), attr)
elseif model.is_model_dirty && mode(model) != DIRECT
@warn(
"The model has been modified since the last call to `optimize!` (" *
"or `optimize!` has not been called yet). If you are iteratively " *
"querying solution information and modifying a model, query all " *
"the results first, then modify the model.",
)
throw(OptimizeNotCalled())
end
return _moi_get_result(backend(model), attr)
end
function MOI.get(
model::GenericModel,
attr::MOI.AbstractVariableAttribute,
v::GenericVariableRef,
)
check_belongs_to_model(v, model)
if !MOI.is_set_by_optimize(attr)
return MOI.get(backend(model), attr, index(v))
elseif model.is_model_dirty && mode(model) != DIRECT
@warn(
"The model has been modified since the last call to `optimize!` (" *
"or `optimize!` has not been called yet). If you are iteratively " *
"querying solution information and modifying a model, query all " *
"the results first, then modify the model.",
)
throw(OptimizeNotCalled())
end
return _moi_get_result(backend(model), attr, index(v))
end
function MOI.get(
model::GenericModel,
attr::MOI.AbstractConstraintAttribute,
cr::ConstraintRef,
)
check_belongs_to_model(cr, model)
if !MOI.is_set_by_optimize(attr)
return MOI.get(backend(model), attr, index(cr))
elseif model.is_model_dirty && mode(model) != DIRECT
@warn(
"The model has been modified since the last call to `optimize!` (" *
"or `optimize!` has not been called yet). If you are iteratively " *
"querying solution information and modifying a model, query all " *
"the results first, then modify the model.",
)
throw(OptimizeNotCalled())
end
return _moi_get_result(backend(model), attr, index(cr))
end
function MOI.set(m::GenericModel, attr::MOI.AbstractOptimizerAttribute, value)
m.is_model_dirty = true
MOI.set(backend(m), attr, value)
return
end
function MOI.set(m::GenericModel, attr::MOI.AbstractModelAttribute, value)
m.is_model_dirty = true
MOI.set(backend(m), attr, value)
return
end
function MOI.set(
model::GenericModel,
attr::MOI.AbstractVariableAttribute,
v::GenericVariableRef,
value,
)
check_belongs_to_model(v, model)
model.is_model_dirty = true
return MOI.set(backend(model), attr, index(v), value)
end
function MOI.set(
model::GenericModel,
attr::MOI.AbstractConstraintAttribute,
cr::ConstraintRef,
value,
)
check_belongs_to_model(cr, model)
model.is_model_dirty = true
return MOI.set(backend(model), attr, index(cr), value)
end
"""
get_attribute(model::GenericModel, attr::MOI.AbstractModelAttribute)
get_attribute(x::GenericVariableRef, attr::MOI.AbstractVariableAttribute)
get_attribute(cr::ConstraintRef, attr::MOI.AbstractConstraintAttribute)
Get the value of a solver-specifc attribute `attr`.
This is equivalent to calling [`MOI.get`](@ref) with the associated MOI model
and, for variables and constraints, with the associated [`MOI.VariableIndex`](@ref)
or [`MOI.ConstraintIndex`](@ref).
## Example
```jldoctest
julia> model = Model();
julia> @variable(model, x)
x
julia> @constraint(model, c, 2 * x <= 1)
c : 2 x ≤ 1
julia> get_attribute(model, MOI.Name())
""
julia> get_attribute(x, MOI.VariableName())
"x"
julia> get_attribute(c, MOI.ConstraintName())
"c"
```
"""
function get_attribute(model::GenericModel, attr::MOI.AbstractModelAttribute)
return MOI.get(model, attr)
end
function get_attribute(
x::GenericVariableRef,
attr::MOI.AbstractVariableAttribute,
)
return MOI.get(owner_model(x), attr, x)
end
function get_attribute(cr::ConstraintRef, attr::MOI.AbstractConstraintAttribute)
return MOI.get(owner_model(cr), attr, cr)
end
"""
get_attribute(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
attr::Union{AbstractString,MOI.AbstractOptimizerAttribute},
)
Get the value of a solver-specifc attribute `attr`.
This is equivalent to calling [`MOI.get`](@ref) with the associated MOI model.
If `attr` is an `AbstractString`, it is converted to
[`MOI.RawOptimizerAttribute`](@ref).
## Example
```jldoctest
julia> import HiGHS
julia> opt = optimizer_with_attributes(HiGHS.Optimizer, "output_flag" => true);
julia> model = Model(opt);
julia> get_attribute(model, "output_flag")
true
julia> get_attribute(model, MOI.RawOptimizerAttribute("output_flag"))
true
julia> get_attribute(opt, "output_flag")
true
julia> get_attribute(opt, MOI.RawOptimizerAttribute("output_flag"))
true
```
"""
function get_attribute(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
attr::MOI.AbstractOptimizerAttribute,
)
return MOI.get(model, attr)
end
function get_attribute(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
name::String,
)
return get_attribute(model, MOI.RawOptimizerAttribute(name))
end
# This method is needed for string types like String15 coming from a DataFrame.
function get_attribute(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
name::AbstractString,
)
return get_attribute(model, String(name))
end
"""
set_attribute(model::GenericModel, attr::MOI.AbstractModelAttribute, value)
set_attribute(x::GenericVariableRef, attr::MOI.AbstractVariableAttribute, value)
set_attribute(cr::ConstraintRef, attr::MOI.AbstractConstraintAttribute, value)
Set the value of a solver-specifc attribute `attr` to `value`.
This is equivalent to calling [`MOI.set`](@ref) with the associated MOI model
and, for variables and constraints, with the associated [`MOI.VariableIndex`](@ref)
or [`MOI.ConstraintIndex`](@ref).
## Example
```jldoctest
julia> model = Model();
julia> @variable(model, x)
x
julia> @constraint(model, c, 2 * x <= 1)
c : 2 x ≤ 1
julia> set_attribute(model, MOI.Name(), "model_new")
julia> set_attribute(x, MOI.VariableName(), "x_new")
julia> set_attribute(c, MOI.ConstraintName(), "c_new")
```
"""
function set_attribute(
model::GenericModel,
attr::MOI.AbstractModelAttribute,
value,
)
MOI.set(model, attr, value)
return
end
function set_attribute(
x::GenericVariableRef,
attr::MOI.AbstractVariableAttribute,
value,
)
MOI.set(owner_model(x), attr, x, value)
return
end
function set_attribute(
cr::ConstraintRef,
attr::MOI.AbstractConstraintAttribute,
value,
)
MOI.set(owner_model(cr), attr, cr, value)
return
end
"""
set_attribute(
model::Union{GenericModel,MOI.OptimizerWithAttributes},
attr::Union{AbstractString,MOI.AbstractOptimizerAttribute},
value,
)
Set the value of a solver-specifc attribute `attr` to `value`.
This is equivalent to calling [`MOI.set`](@ref) with the associated MOI model.
If `attr` is an `AbstractString`, it is converted to
[`MOI.RawOptimizerAttribute`](@ref).
## Example