-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathxpress_solver.cc
More file actions
2203 lines (2089 loc) · 90.2 KB
/
Copy pathxpress_solver.cc
File metadata and controls
2203 lines (2089 loc) · 90.2 KB
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 2010-2025 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ortools/math_opt/solvers/xpress_solver.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include "absl/container/linked_hash_map.h"
#include "absl/log/check.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "ortools/base/map_util.h"
#include "ortools/base/protoutil.h"
#include "ortools/base/status_macros.h"
#include "ortools/math_opt/core/empty_bounds.h"
#include "ortools/math_opt/core/inverted_bounds.h"
#include "ortools/math_opt/core/math_opt_proto_utils.h"
#include "ortools/math_opt/core/solver_interface.h"
#include "ortools/math_opt/core/sparse_vector_view.h"
#include "ortools/math_opt/cpp/math_opt.h"
#include "ortools/math_opt/cpp/streamable_solver_init_arguments.h"
#include "ortools/math_opt/solvers/xpress/g_xpress.h"
#include "ortools/math_opt/validators/callback_validator.h"
#include "ortools/port/proto_utils.h"
#include "ortools/third_party_solvers/xpress_environment.h"
#include "ortools/util/solve_interrupter.h"
namespace operations_research {
namespace math_opt {
namespace {
struct SharedSolveContext {
Xpress* xpress;
/** Mutex for accessing callbackException. */
absl::Mutex mutex;
/** Capturing of exceptions in callbacks.
* We cannot let exceptions escape from callbacks since that would just
* unroll the stack until some function that catches the exception.
* In particular, it would bypass any cleanup code implemented in the C code
* of the solver. So we must capture exceptions, interrupt the solve and
* handle the exception once the solver returned.
*/
std::exception_ptr callbackException;
};
/** Registered callback that is auto-removed in the destructor.
* Use Add() to add a callback to a solve context.
* The class also provides convenience functions SetCallbackException()
* and Interrupt() that are required in every callback implementation to
* capture exceptions from user code and reraise them appropriately.
*/
template <typename ProtoT, typename CbT>
class ScopedCallback {
using proto_type = typename ProtoT::proto_type;
SharedSolveContext* ctx;
ScopedCallback(ScopedCallback const&) = delete;
ScopedCallback(ScopedCallback&&) = delete;
ScopedCallback& operator=(ScopedCallback const&) = delete;
ScopedCallback& operator=(ScopedCallback&&) = delete;
// We intercept and store any exception throw by a callback defining a static
// wrapper function that invokes the callback within a try/carch block. For
// this to work, we need to deduce the callback return type and arguments.
template <typename FuncPtr>
struct ExWrapper;
// Specialization to deduce the callback return and arguments types
template <typename R, typename... Args>
struct ExWrapper<R (*)(XPRSprob, void*, Args...)> {
// The static function that will be directly invoked by Xpress
static auto low_level_cb(XPRSprob prob, void* cbdata, Args... args) try {
return ProtoT::glueFn(prob, cbdata, args...);
} catch (...) {
// Catch any exception and terminate Xpress gracefully
ScopedCallback* cb = reinterpret_cast<ScopedCallback*>(cbdata);
cb->Interrupt(XPRS_STOP_USER);
cb->SetCallbackException(std::current_exception());
if constexpr (std::is_convertible_v<R, int>) return static_cast<int>(1);
}
};
const proto_type low_level_cb = ExWrapper<proto_type>::low_level_cb;
public:
CbT or_tools_cb;
ScopedCallback() : ctx(nullptr) {}
inline absl::Status Add(SharedSolveContext* context, CbT cb) {
ctx = context;
RETURN_IF_ERROR(
ProtoT::Add(ctx->xpress, low_level_cb, reinterpret_cast<void*>(this)));
or_tools_cb = cb;
return absl::OkStatus();
}
inline void Interrupt(int reason) {
CHECK_OK(ctx->xpress->Interrupt(reason));
}
inline void SetCallbackException(std::exception_ptr ex) {
const absl::MutexLock lock(&ctx->mutex);
if (!ctx->callbackException) ctx->callbackException = ex;
}
~ScopedCallback() {
if (ctx)
ProtoT::Remove(ctx->xpress, low_level_cb, reinterpret_cast<void*>(this));
}
};
/** Define everything required for supporting a callback of type name.
* Use like so
* DEFINE_SCOPED_CB(CB_NAME, ORTOOLS_CB, CB_RET_TYPE, (...ARGS)) {
* <code>
* }
* where
* CB_NAME is the name of the callback (Message, Checktime, ...)
* ORTOOLS_CB the Or-Tools callbacks (function object) that get provided
* to the low-level static callback as user data, and then
* invoked.
* CB_RET_TYPE return type of the low-level Xpress callback.
* (...ARGS) arguments to the Xpress low-level callback.
* <code> code for the low-level Xpress callback
* The effect of the macro is an alias CB_NAME####ScopedCb =
* ScopedCallback<...>.
*/
#define DEFINE_SCOPED_CB(CB_NAME, ORTOOLS_CB, CB_RET_TYPE, ARGS) \
CB_RET_TYPE CB_NAME##GlueFn ARGS; \
struct CB_NAME##Traits { \
using proto_type = CB_RET_TYPE(XPRS_CC*) ARGS; \
static constexpr proto_type glueFn = CB_NAME##GlueFn; \
static absl::Status Add(Xpress* xpress, proto_type fn, void* data) { \
return xpress->AddCb##CB_NAME(fn, data, 0); \
} \
static void Remove(Xpress* xpress, proto_type fn, void* data) { \
CHECK_OK(xpress->RemoveCb##CB_NAME(fn, data)); \
} \
}; \
using CB_NAME##ScopedCb = ScopedCallback<CB_NAME##Traits, ORTOOLS_CB>; \
CB_RET_TYPE CB_NAME##GlueFn ARGS
/** Define the message callback.
* This forwards messages from Xpress to an ortools message callback.
*/
DEFINE_SCOPED_CB(Message, MessageCallback, void,
(XPRSprob prob, void* cbdata, char const* msg, int len,
int type)) {
auto cb = reinterpret_cast<MessageScopedCb*>(cbdata);
if (type != 1 && // info message
type != 3 && // warning message
type != 4) { // error message
// message type 2 is not used by Xpress, negative values mean "flush"
return;
}
if (len == 0) {
cb->or_tools_cb(std::vector<std::string>{""});
return;
}
std::vector<std::string> lines;
int start = 0;
// There are a few Xpress messages that span multiple lines.
// The MessageCallback contract says that messages must not contain
// newlines, so we have to split on newline.
while (start <= len) { // <= rather than < to catch message ending in '\n'
int end = start;
while (end < len && msg[end] != '\n') {
++end;
}
if (start < len) {
lines.emplace_back(msg, start, end - start);
} else {
lines.push_back("");
}
start = end + 1;
}
cb->or_tools_cb(lines);
}
/** Define the checktime callback.
* This callbacks checks an interrupter for whether the solve was interrupted.
*/
DEFINE_SCOPED_CB(Checktime, SolveInterrupter const*, int,
(XPRSprob prob, void* cbdata)) {
auto cb = reinterpret_cast<ChecktimeScopedCb*>(cbdata);
// Note: we do NOT return non-zero from the callback if the solve was
// interrupted. Returning non-zero from the callback is interpreted
// as hitting a time limit and we would therefore not map correctly
// the resulting stop status to ortools' termination status.
if (cb->or_tools_cb->IsInterrupted()) {
cb->Interrupt(XPRS_STOP_USER);
}
return 0;
}
/** An ortools message callback that prints everything to stdout. */
static void stdoutMessageCallback(std::vector<std::string> const& lines) {
for (auto& l : lines) std::cout << l << '\n';
}
inline BasisStatusProto XpressToMathOptBasisStatus(const int status,
bool isConstraint) {
// XPRESS row basis status is that of the slack variable
// For example, if the slack variable is at LB, the constraint is at UB
switch (status) {
case XPRS_BASIC:
return BASIS_STATUS_BASIC;
case XPRS_AT_LOWER:
return isConstraint ? BASIS_STATUS_AT_UPPER_BOUND
: BASIS_STATUS_AT_LOWER_BOUND;
case XPRS_AT_UPPER:
return isConstraint ? BASIS_STATUS_AT_LOWER_BOUND
: BASIS_STATUS_AT_UPPER_BOUND;
case XPRS_FREE_SUPER:
return BASIS_STATUS_FREE;
default:
return BASIS_STATUS_UNSPECIFIED;
}
}
inline int MathOptToXpressBasisStatus(const BasisStatusProto status,
bool isConstraint) {
// XPRESS row basis status is that of the slack variable
// For example, if the slack variable is at LB, the constraint is at UB
switch (status) {
case BASIS_STATUS_BASIC:
return XPRS_BASIC;
case BASIS_STATUS_AT_LOWER_BOUND:
return isConstraint ? XPRS_AT_UPPER : XPRS_AT_LOWER;
case BASIS_STATUS_AT_UPPER_BOUND:
return isConstraint ? XPRS_AT_LOWER : XPRS_AT_UPPER;
case BASIS_STATUS_FREE:
return XPRS_FREE_SUPER;
default:
return XPRS_FREE_SUPER;
}
}
/** Temporary settings for a solve.
* Instances of this class capture settings in the XPRSprob instance that are
* made only temporarily for a solve.
* This includes for example callbacks.
* This is a RAII class that will undo all settings when it goes out of scope.
*/
class ScopedSolverContext {
/** Solver context data shared by callbacks */
SharedSolveContext shared_ctx;
/** Installed message callback (if any). */
MessageScopedCb messageCallback;
/** Installed interrupter (if any). */
ChecktimeScopedCb checktimeCallback;
/** If we installed an interrupter callback then this removes it. */
std::function<void()> removeInterrupterCallback;
/** A single control that must be reset in the destructor. */
struct OneControl {
int id;
std::variant<int64_t, double, std::string> value;
enum {
INT_CONTROL,
DBL_CONTROL,
STR_CONTROL
}; // Matches std::variant<>::index;
};
/** Controls to be reset in the destructor. */
std::vector<OneControl> modifiedControls;
public:
ScopedSolverContext(Xpress* xpress) : removeInterrupterCallback(nullptr) {
shared_ctx.xpress = xpress;
}
absl::Status Set(int id, int32_t value) { return Set(id, int64_t(value)); }
absl::Status Set(int id, int64_t value) {
ASSIGN_OR_RETURN(int64_t old, shared_ctx.xpress->GetIntControl64(id));
modifiedControls.push_back({id, old});
RETURN_IF_ERROR(shared_ctx.xpress->SetIntControl64(id, value));
return absl::OkStatus();
}
absl::Status Set(int id, double value) {
ASSIGN_OR_RETURN(double old, shared_ctx.xpress->GetDblControl(id));
modifiedControls.push_back({id, old});
RETURN_IF_ERROR(shared_ctx.xpress->SetDblControl(id, value));
return absl::OkStatus();
}
absl::Status Set(int id, std::string const& value) {
ASSIGN_OR_RETURN(std::string old, shared_ctx.xpress->GetStrControl(id));
modifiedControls.push_back({id, old});
RETURN_IF_ERROR(shared_ctx.xpress->SetStrControl(id, value));
return absl::OkStatus();
}
absl::Status AddCallbacks(MessageCallback message_callback,
const SolveInterrupter* interrupter) {
if (message_callback)
RETURN_IF_ERROR(messageCallback.Add(&shared_ctx, message_callback));
if (interrupter) {
/* To be extra safe we add two ways to interrupt Xpress:
* 1. We register a checktime callback that polls the interrupter.
* 2. We register a callback with the interrupter that will call
* XPRSinterrupt().
* Eventually we should assess whether the first thing is a performance
* hit and if so, remove it.
*/
RETURN_IF_ERROR(checktimeCallback.Add(&shared_ctx, interrupter));
SolveInterrupter::CallbackId const id =
interrupter->AddInterruptionCallback(
[=] { CHECK_OK(shared_ctx.xpress->Interrupt(XPRS_STOP_USER)); });
removeInterrupterCallback = [=] {
interrupter->RemoveInterruptionCallback(id);
};
/** TODO: Support
* CallbackRegistrationProto and Callback and install the
* ortools callback as required.
* Note that this is only for Solve(), not for
* ComputeInfeasibleSubsystem()
*/
}
return absl::OkStatus();
}
/** Setup model specific parameters. */
absl::Status ApplyParameters(const SolveParametersProto& parameters,
MessageCallback message_callback,
std::string* export_model, bool* force_postsolve,
bool* stop_after_lp) {
std::vector<std::string> warnings;
ASSIGN_OR_RETURN(bool const isMIP, shared_ctx.xpress->IsMIP());
if (parameters.enable_output()) {
// This is considered only if no message callback is set, see the
// ortools specification of the enable_output parameter.
if (!message_callback) {
RETURN_IF_ERROR(
messageCallback.Add(&shared_ctx, stdoutMessageCallback));
}
}
absl::Duration time_limit = absl::InfiniteDuration();
if (parameters.has_time_limit()) {
ASSIGN_OR_RETURN(
time_limit, util_time::DecodeGoogleApiProto(parameters.time_limit()));
}
if (time_limit < absl::InfiniteDuration()) {
RETURN_IF_ERROR(Set(XPRS_TIMELIMIT, absl::ToDoubleSeconds(time_limit)));
}
if (parameters.has_iteration_limit()) {
if (parameters.lp_algorithm() == LP_ALGORITHM_FIRST_ORDER) {
// Iteration limit for PDHG is BARHGMAXRESTARTS
RETURN_IF_ERROR(
Set(XPRS_BARHGMAXRESTARTS, parameters.iteration_limit()));
} else {
RETURN_IF_ERROR(Set(XPRS_LPITERLIMIT, parameters.iteration_limit()));
RETURN_IF_ERROR(Set(XPRS_BARITERLIMIT, parameters.iteration_limit()));
}
}
if (parameters.has_node_limit()) {
RETURN_IF_ERROR(Set(XPRS_MAXNODE, parameters.node_limit()));
}
if (parameters.has_cutoff_limit()) {
RETURN_IF_ERROR(Set(XPRS_MIPABSCUTOFF, parameters.cutoff_limit()));
}
if (parameters.has_objective_limit()) {
// In Xpress you can apply MIPABSCUTOFF also to LPs.
// However, ortools applies both cutoff_limit and objective_limit
// to LPs and distinguishes the two, i.e., expect different return
// values depending on what is set. Since we cannot easily make this
// distinction, we do not support objective_limit. Users should just
// use cutoff_limit with LPs as well.
warnings.emplace_back(
"XpressSolver does not support objective_limit; use cutoff_limit "
"instead");
}
if (parameters.has_best_bound_limit()) {
warnings.emplace_back("XpressSolver does not support best_bound_limit");
}
if (parameters.has_solution_limit()) {
RETURN_IF_ERROR(Set(XPRS_MAXMIPSOL, parameters.solution_limit()));
}
if (parameters.has_threads() && parameters.threads() > 0)
RETURN_IF_ERROR(Set(XPRS_THREADS, parameters.threads()));
if (parameters.has_random_seed()) {
RETURN_IF_ERROR(Set(XPRS_RANDOMSEED, parameters.random_seed()));
}
if (parameters.has_absolute_gap_tolerance())
RETURN_IF_ERROR(
Set(XPRS_MIPABSSTOP, parameters.absolute_gap_tolerance()));
if (parameters.has_relative_gap_tolerance())
RETURN_IF_ERROR(
Set(XPRS_MIPRELSTOP, parameters.relative_gap_tolerance()));
if (parameters.has_solution_pool_size()) {
warnings.emplace_back("XpressSolver does not support solution_pool_size");
}
// According to the documentation, LP algorithm is only for LPs
if (!isMIP && parameters.lp_algorithm() != LP_ALGORITHM_UNSPECIFIED) {
switch (parameters.lp_algorithm()) {
case LP_ALGORITHM_PRIMAL_SIMPLEX:
RETURN_IF_ERROR(Set(XPRS_LPFLAGS, 1 << 1));
break;
case LP_ALGORITHM_DUAL_SIMPLEX:
RETURN_IF_ERROR(Set(XPRS_LPFLAGS, 1 << 0));
break;
case LP_ALGORITHM_BARRIER:
RETURN_IF_ERROR(Set(XPRS_LPFLAGS, 1 << 2));
break;
case LP_ALGORITHM_FIRST_ORDER:
RETURN_IF_ERROR(Set(XPRS_LPFLAGS, 1 << 2));
RETURN_IF_ERROR(Set(XPRS_BARALG, 4));
break;
// Note: Xpress also supports network simplex, but that is not
// supported by ortools.
}
}
if (parameters.presolve() != EMPHASIS_UNSPECIFIED) {
// default value for XPRS_PRESOLVEPASSES is 1
int presolvePasses = -1;
switch (parameters.presolve()) {
case EMPHASIS_OFF:
RETURN_IF_ERROR(Set(XPRS_PRESOLVE, 0)); // Turn presolve off
break;
case EMPHASIS_LOW:
presolvePasses = 2;
break;
case EMPHASIS_MEDIUM:
presolvePasses = 3;
break;
case EMPHASIS_HIGH:
presolvePasses = 4;
break;
case EMPHASIS_VERY_HIGH:
presolvePasses = 5;
break;
}
if (presolvePasses > 0)
RETURN_IF_ERROR(Set(XPRS_PRESOLVEPASSES, presolvePasses));
}
if (parameters.cuts() != EMPHASIS_UNSPECIFIED) {
switch (parameters.cuts()) {
case EMPHASIS_OFF:
RETURN_IF_ERROR(Set(XPRS_CUTSTRATEGY, 0));
break;
case EMPHASIS_LOW:
RETURN_IF_ERROR(Set(XPRS_CUTSTRATEGY, 1));
break;
case EMPHASIS_MEDIUM:
RETURN_IF_ERROR(Set(XPRS_CUTSTRATEGY, 2));
break;
case EMPHASIS_HIGH:
RETURN_IF_ERROR(Set(XPRS_CUTSTRATEGY, 3));
break;
case EMPHASIS_VERY_HIGH:
RETURN_IF_ERROR(Set(XPRS_CUTSTRATEGY, 3)); // Same as high
break;
}
}
if (parameters.heuristics() != EMPHASIS_UNSPECIFIED) {
switch (parameters.heuristics()) {
case EMPHASIS_OFF:
RETURN_IF_ERROR(Set(XPRS_HEUREMPHASIS, 0));
break;
case EMPHASIS_UNSPECIFIED:
break;
case EMPHASIS_LOW: // fallthrough
case EMPHASIS_MEDIUM:
RETURN_IF_ERROR(Set(XPRS_HEUREMPHASIS, 1));
break;
case EMPHASIS_HIGH: // fallthrough
case EMPHASIS_VERY_HIGH:
RETURN_IF_ERROR(Set(XPRS_HEUREMPHASIS, 2));
break;
}
}
for (const XpressParametersProto::Parameter& parameter :
parameters.xpress().parameters()) {
std::string const& name = parameter.name();
std::string const& value = parameter.value();
int id, type;
int64_t l;
double d;
if (name == "EXPORT_MODEL") {
if (export_model) *export_model = value;
continue;
} else if (name == "FORCE_POSTSOLVE") {
if (!absl::SimpleAtoi(value, &l))
return util::InvalidArgumentErrorBuilder()
<< "value " << value << " for FORCE_POSTSOLVE"
<< " is not an integer";
if (force_postsolve) *force_postsolve = l != 0;
continue;
} else if (name == "STOP_AFTER_LP") {
if (!absl::SimpleAtoi(value, &l))
return util::InvalidArgumentErrorBuilder()
<< "value " << value << " for STOP_AFTER_LP"
<< " is not an integer";
if (stop_after_lp) *stop_after_lp = l != 0;
continue;
}
RETURN_IF_ERROR(
shared_ctx.xpress->GetControlInfo(name.c_str(), &id, &type));
switch (type) {
case XPRS_TYPE_INT: // fallthrough
case XPRS_TYPE_INT64:
if (!absl::SimpleAtoi(value, &l))
return util::InvalidArgumentErrorBuilder()
<< "value " << value << " for " << name
<< " is not an integer";
if (type == XPRS_TYPE_INT && (l > std::numeric_limits<int>::max() ||
l < std::numeric_limits<int>::min()))
return util::InvalidArgumentErrorBuilder()
<< "value " << value << " for " << name
<< " is out of range";
RETURN_IF_ERROR(Set(id, l));
break;
case XPRS_TYPE_DOUBLE:
if (!absl::SimpleAtod(value, &d))
return util::InvalidArgumentErrorBuilder()
<< "value " << value << " for " << name
<< " is not a floating pointer number";
RETURN_IF_ERROR(Set(id, d));
break;
case XPRS_TYPE_STRING:
RETURN_IF_ERROR(Set(id, value));
break;
default:
return util::InvalidArgumentErrorBuilder()
<< "bad control type for " << name;
}
}
if (!warnings.empty()) {
return absl::InvalidArgumentError(absl::StrJoin(warnings, "; "));
}
return absl::OkStatus();
}
absl::Status ApplyModelParameters(
ModelSolveParametersProto const& model_parameters,
absl::linked_hash_map<XpressSolver::VarId,
XpressSolver::XpressVariableIndex> const&
variables_map,
absl::linked_hash_map<XpressSolver::LinearConstraintId,
XpressSolver::LinearConstraintData> const&
linear_constraints_map,
absl::linked_hash_map<XpressSolver::AuxiliaryObjectiveId,
XpressSolver::XpressMultiObjectiveIndex> const&
objectives_map) {
ASSIGN_OR_RETURN(int const cols,
shared_ctx.xpress->GetIntAttr(XPRS_ORIGINALCOLS));
ASSIGN_OR_RETURN(int const rows,
shared_ctx.xpress->GetIntAttr(XPRS_ORIGINALROWS));
// Set initial basis
if (model_parameters.has_initial_basis()) {
// XPRSloadbasis() will raise an error if called on a model in presolved
// state. We still trap this already here so that we can produce a more
// meaningful error message.
ASSIGN_OR_RETURN(int const state,
shared_ctx.xpress->GetIntAttr(XPRS_PRESOLVESTATE));
if (state & ((1 << 1) | (1 << 2))) {
return util::InvalidArgumentErrorBuilder()
<< "cannot set basis for model in presolved space (consider "
"FORCE_POSTSOLVE?)";
}
auto const& basis = model_parameters.initial_basis();
std::vector<int> xpress_var_basis_status(cols);
for (const auto [id, value] : MakeView(basis.variable_status())) {
xpress_var_basis_status[variables_map.at(id)] =
MathOptToXpressBasisStatus(static_cast<BasisStatusProto>(value),
false);
}
std::vector<int> xpress_constr_basis_status(rows);
for (const auto [id, value] : MakeView(basis.constraint_status())) {
xpress_constr_basis_status[linear_constraints_map.at(id)
.constraint_index] =
MathOptToXpressBasisStatus(static_cast<BasisStatusProto>(value),
true);
}
RETURN_IF_ERROR(shared_ctx.xpress->SetStartingBasis(
xpress_constr_basis_status, xpress_var_basis_status));
}
std::vector<int> colind;
// Install solution hints. Xpress does not explicitly have solution
// hints but it supports partial MIP starts. So we just add each solution
// hint as MIP start.
if (model_parameters.solution_hints_size() > 0) {
unsigned int cnt = 0;
std::vector<double> mipStart;
colind.reserve(cols);
mipStart.reserve(cols);
for (auto const& hint : model_parameters.solution_hints()) {
colind.clear();
mipStart.clear();
for (const auto [id, value] : MakeView(hint.variable_values())) {
colind.push_back(variables_map.at(id));
mipStart.push_back(value);
}
if (mipStart.size() > cols)
return util::InvalidArgumentErrorBuilder()
<< "more solution hints than columns";
// XPRSaddmipsol() expects a solution in the original space
RETURN_IF_ERROR(shared_ctx.xpress->AddMIPSol(
mipStart, colind, absl::StrCat("SolutionHint", cnt).c_str()));
++cnt;
}
}
// Install branching priorities.
if (model_parameters.has_branching_priorities()) {
auto const& prios = model_parameters.branching_priorities();
colind.clear();
colind.reserve(prios.ids_size());
std::vector<int> priority;
priority.reserve(prios.ids_size());
for (const auto [id, prio] : MakeView(prios)) {
colind.push_back(variables_map.at(id));
// Xpress only allows priorities in [0,1000].
// In ortools higher priority takes precedence while in Xpress
// lower priority takes precedence.
if (prio < 0 || prio > 1000)
return util::InvalidArgumentErrorBuilder()
<< "Xpress only allows branching priorities in [0,1000]";
priority.push_back(
1000 - prio); // Smaller prios have higher precedence in Xpress!
}
RETURN_IF_ERROR(shared_ctx.xpress->LoadDirs(
absl::MakeSpan(colind), absl::MakeSpan(priority), std::nullopt,
std::nullopt, std::nullopt));
}
// Objective parameters: primary/single objective
if (model_parameters.has_primary_objective_parameters()) {
auto const& p = model_parameters.primary_objective_parameters();
// Objective violation tolerances only need to be installed for
// multi-objective models. We just set them blindly here. They don't
// hurt for a single-objective model.
if (p.has_objective_degradation_absolute_tolerance()) {
RETURN_IF_ERROR(shared_ctx.xpress->SetObjectiveDoubleControl(
0, XPRS_OBJECTIVE_ABSTOL,
p.objective_degradation_absolute_tolerance()));
}
if (p.has_objective_degradation_relative_tolerance()) {
RETURN_IF_ERROR(shared_ctx.xpress->SetObjectiveDoubleControl(
0, XPRS_OBJECTIVE_RELTOL,
p.objective_degradation_relative_tolerance()));
}
if (p.has_time_limit()) {
// We support a time limit but only if there is one single objective.
if (objectives_map.size() > 0) {
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support per-objective time limits";
}
ASSIGN_OR_RETURN(auto l,
util_time::DecodeGoogleApiProto(p.time_limit()));
RETURN_IF_ERROR(shared_ctx.xpress->SetDblControl(
XPRS_TIMELIMIT, absl::ToDoubleSeconds(l)));
}
}
// Objective parameters: auxiliary objectives
for (auto const& [id, p] :
model_parameters.auxiliary_objective_parameters()) {
if (p.has_objective_degradation_absolute_tolerance()) {
RETURN_IF_ERROR(shared_ctx.xpress->SetObjectiveDoubleControl(
objectives_map.at(id), XPRS_OBJECTIVE_ABSTOL,
p.objective_degradation_absolute_tolerance()));
}
if (p.has_objective_degradation_relative_tolerance()) {
RETURN_IF_ERROR(shared_ctx.xpress->SetObjectiveDoubleControl(
objectives_map.at(id), XPRS_OBJECTIVE_RELTOL,
p.objective_degradation_relative_tolerance()));
}
if (p.has_time_limit()) {
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support per-objective time limits";
}
}
if (model_parameters.lazy_linear_constraint_ids_size() > 0) {
std::vector<int> delayedRows;
delayedRows.reserve(rows);
for (auto const& idx : model_parameters.lazy_linear_constraint_ids()) {
delayedRows.push_back(linear_constraints_map.at(idx).constraint_index);
}
if (delayedRows.size() > rows)
return util::InvalidArgumentErrorBuilder()
<< "more lazy constraints than rows";
RETURN_IF_ERROR(shared_ctx.xpress->LoadDelayedRows(delayedRows));
}
return absl::OkStatus();
}
/** Interrupt the current solve with the given reason. */
void Interrupt(int reason) { CHECK_OK(shared_ctx.xpress->Interrupt(reason)); }
void ReraiseException() {
if (shared_ctx.callbackException) {
std::exception_ptr ex = shared_ctx.callbackException;
shared_ctx.callbackException = nullptr;
std::rethrow_exception(ex);
}
}
~ScopedSolverContext() {
for (auto it = modifiedControls.rbegin(); it != modifiedControls.rend();
++it) {
switch (it->value.index()) {
case OneControl::INT_CONTROL:
CHECK_OK(shared_ctx.xpress->SetIntControl64(
it->id, std::get<int64_t>(it->value)));
break;
case OneControl::DBL_CONTROL:
CHECK_OK(shared_ctx.xpress->SetDblControl(
it->id, std::get<double>(it->value)));
break;
case OneControl::STR_CONTROL:
CHECK_OK(shared_ctx.xpress->SetStrControl(
it->id, std::get<std::string>(it->value).c_str()));
break;
}
}
if (removeInterrupterCallback) removeInterrupterCallback();
// If pending callback exception was not reraised yet then do it now
if (shared_ctx.callbackException)
std::rethrow_exception(shared_ctx.callbackException);
}
};
/** Different modes for ExtractSingleton(). */
enum class SingletonType {
SOS, /**< SOS constraint. */
SOCBound, /**< Second order cone constraint bound. */
SOCNorm /**< Second order cone constraint norm. */
};
// ortools supports SOS constraints and second order cone constraints on
// expressions. Xpress only supports these constructs on singleton variables.
// We could create auxiliary variables here, set each of them equal to one of
// the expressions and then formulate SOS/SOC on the auxiliary variables.
// This however seems a bit of overkill at the moment, so we just error out
// if elements are non-singleton.
// Returns the variable of the singleton as return value and its coefficient
// in *p_coef.
absl::StatusOr<std::optional<XpressSolver::VarId>> ExtractSingleton(
LinearExpressionProto const& expr, SingletonType type, double* p_coef) {
double const constant = expr.offset();
if (expr.ids_size() == 1 && constant == 0.0) {
// We have a single variable in the expression and no constant.
double const coef = expr.coefficients(0);
switch (type) {
case SingletonType::SOS:
// A non-zero coefficient does not change anything, so is allowed.
if (coef == 0.0) {
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support coefficient " << coef
<< " in SOS (consider using auxiliary variables?)";
}
break;
case SingletonType::SOCBound: // fallthrough
case SingletonType::SOCNorm:
// We are going to square the coefficient, so anything non-negative
// is allowed.
if (coef < 0) {
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support coefficient " << coef
<< " in a second order cone constraint "
<< (type == SingletonType::SOCBound ? "bound" : "norm")
<< " (consider using auxiliary variables?)";
}
break;
}
if (p_coef) *p_coef = coef;
return std::optional<XpressSolver::VarId>(expr.ids(0));
} else if (expr.ids_size() == 0) {
// The expression is constant.
switch (type) {
case SingletonType::SOS:
// Any non-zero constant would force all other variables to 0.
// Any zero constant would be redundant.
// Both are edge cases that we do not support at the moment.
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support constant expressions in SOS "
"(consider using auxiliary variables?)";
case SingletonType::SOCBound:
// We are going to square the bound, so it should not be negative.
if (constant < 0.0) {
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support constant " << constant
<< " in a second order cone constraint bound (consider using "
"auxiliary variables?)";
}
break;
case SingletonType::SOCNorm:
// Constant entries in the norm are not supported (we would have to
// move them to the right-hand side).
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support constants in a second order cone "
"constraint norm (consider using auxiliary variables?)";
}
if (p_coef) *p_coef = constant;
return std::nullopt;
} else {
// Multiple coefficients
static char const* const name[] = {"SOS",
"second order cone constraint bound",
"second order cone constraint norm"};
return util::InvalidArgumentErrorBuilder()
<< "Xpress does not support general linear expressions in "
<< name[static_cast<int>(type)]
<< " (consider using auxiliary variables?)";
}
}
/** Trait for AddNames() so that we can write it in a generic way.
* The default implementation works for columns and rows.
*/
template <typename T>
struct NameResolver {
static std::string const& GetName(T const& container, int i) {
return container.names(i);
}
};
/** Specialization for NameResolver for SOS. */
template <typename K, typename V>
struct NameResolver<google::protobuf::Map<K, V>> {
static std::string const& GetName(
google::protobuf::Map<K, V> const& container,
typename google::protobuf::Map<K, V>::const_iterator const& i) {
return i->second.name();
}
};
/** Add names to an Xpress object.
* Extracts the first count names from container.
* It is assumed that the names are for elements offset, offset+1, offset+2, ...
*/
template <typename T, typename I>
absl::Status AddNames(Xpress* xpress, int type, int offset, I begin, I end,
T const& container) {
std::vector<char> buffer;
int i = 0, start = 0;
while (begin != end) {
std::string const& name = NameResolver<T>::GetName(container, begin);
char const* c_name = name.c_str();
buffer.insert(buffer.end(), c_name, c_name + name.size() + 1);
// Add names in chunks of 1MB.
if (buffer.size() > 1024 * 1024) {
RETURN_IF_ERROR(
xpress->AddNames(type, buffer, offset + start, offset + i));
start = i + 1;
buffer.clear();
}
++i;
++begin;
}
if (buffer.size()) {
RETURN_IF_ERROR(
xpress->AddNames(type, buffer, offset + start, offset + i - 1));
}
return absl::OkStatus();
}
} // namespace
constexpr SupportedProblemStructures kXpressSupportedStructures = {
.integer_variables = SupportType::kSupported,
.multi_objectives = SupportType::kSupported,
.quadratic_objectives = SupportType::kSupported,
.quadratic_constraints = SupportType::kSupported,
// Limitation: We only implemented support for constraints of type
// norm(a1*x1,...,an*xn) <= a0*x0
// General linear expressions in the norm or in the bound are not
// supported at the moment. They must be emulated by the caller using
// auxiliary variables. The right-hand side may be a constant.
.second_order_cone_constraints = SupportType::kSupported,
// Limitation: We only implemented support for SOS constraints on singleton
// variables. General expressions in the SOS are not supported. They must
// be emulated by the caller using auxiliary variables.
.sos1_constraints = SupportType::kSupported,
.sos2_constraints = SupportType::kSupported,
.indicator_constraints = SupportType::kSupported};
absl::StatusOr<std::unique_ptr<XpressSolver>> XpressSolver::New(
const ModelProto& model, const InitArgs& init_args) {
if (!XpressIsCorrectlyInstalled()) {
return absl::InvalidArgumentError("Xpress is not correctly installed.");
}
RETURN_IF_ERROR(
ModelIsSupported(model, kXpressSupportedStructures, "XPRESS"));
// We can add here extra checks that are not made in ModelIsSupported
// (for example, if XPRESS does not support multi-objective with quad terms)
ASSIGN_OR_RETURN(auto xpr, Xpress::New(model.name()));
bool extract_names = init_args.streamable.has_xpress() &&
init_args.streamable.xpress().has_extract_names() &&
init_args.streamable.xpress().extract_names();
auto xpress_solver =
absl::WrapUnique(new XpressSolver(std::move(xpr), extract_names));
RETURN_IF_ERROR(xpress_solver->LoadModel(model));
return xpress_solver;
}
absl::Status XpressSolver::LoadModel(const ModelProto& input_model) {
CHECK(xpress_ != nullptr);
RETURN_IF_ERROR(xpress_->SetProbName(input_model.name()));
RETURN_IF_ERROR(AddNewVariables(input_model.variables()));
RETURN_IF_ERROR(AddNewLinearConstraints(input_model.linear_constraints()));
RETURN_IF_ERROR(ChangeCoefficients(input_model.linear_constraint_matrix()));
RETURN_IF_ERROR(AddObjective(input_model.objective(), std::nullopt,
!input_model.auxiliary_objectives().empty()));
// Tests expect an error on duplicate priorities, so raise one.
// Xpress would otherwise merge objectives with the same objective when it
// starts solving.
absl::flat_hash_set<AuxiliaryObjectiveId> prios = {
input_model.objective().priority()};
for (auto const& [id, obj] : input_model.auxiliary_objectives()) {
auto const prio = obj.priority();
if (!prios.insert(prio).second) {
return util::InvalidArgumentErrorBuilder()
<< "repeated objective priority: " << prio;
}
RETURN_IF_ERROR(AddObjective(obj, id, true));
}
RETURN_IF_ERROR(AddSOS(input_model.sos1_constraints(), true));
RETURN_IF_ERROR(AddSOS(input_model.sos2_constraints(), false));
RETURN_IF_ERROR(AddIndicators(input_model.indicator_constraints()));
RETURN_IF_ERROR(AddQuadraticConstraints(input_model.quadratic_constraints()));
RETURN_IF_ERROR(AddSecondOrderConeConstraints(
input_model.second_order_cone_constraints()));
return absl::OkStatus();
}
absl::Status XpressSolver::AddNewVariables(
const VariablesProto& new_variables) {
ASSIGN_OR_RETURN(const int num_old_variables,
xpress_->GetIntAttr(XPRS_ORIGINALCOLS));
const int num_new_variables = new_variables.lower_bounds().size();
std::vector<char> variable_type(num_new_variables);
ASSIGN_OR_RETURN(int const n_variables,
xpress_->GetIntAttr(XPRS_ORIGINALCOLS));
bool have_integers = false;
// Indices (within this batch) of integer variables whose unrounded bounds
// are non-empty but whose rounded integer bounds are empty. Xpress rounds
// bounds of integer variables on input and rejects creation of variables
// with crossed bounds, so we substitute safe bounds for these and remember
// them in empty_integer_bounds_vars_ to report infeasibility at solve time.
std::vector<int> empty_int_indices;
for (int j = 0; j < num_new_variables; ++j) {
const VarId id = new_variables.ids(j);
gtl::InsertOrDie(&variables_map_, id, j + n_variables);
if (new_variables.integers(j)) {
// Note: ortools does not distinguish between binary variables and
// integer variables in {0,1}
variable_type[j] = XPRS_INTEGER;
have_integers = true;
const double lb = new_variables.lower_bounds(j);
const double ub = new_variables.upper_bounds(j);
if (lb <= ub && std::ceil(lb) > std::floor(ub)) {
empty_integer_bounds_vars_.push_back({id, lb, ub});
empty_int_indices.push_back(j);
}
} else {
variable_type[j] = XPRS_CONTINUOUS;
}
}
if (!have_integers) {
// There are no integer variables, so we clear variable_type to
// save the call to XPRSchgcoltype() in AddVars()
variable_type.clear();
}
if (empty_int_indices.empty()) {
RETURN_IF_ERROR(