-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolver.go
667 lines (573 loc) · 17.1 KB
/
solver.go
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
// © 2019-present nextmv.io inc
// Package highs implements HiGHS solver bindings.
package highs
/*
#cgo darwin,arm64 LDFLAGS: ${SRCDIR}/external/darwin-arm64/lib/libhighs.a -lc++
#cgo darwin,arm64 CFLAGS: -I${SRCDIR}/external/darwin-arm64/include/highs -mmacosx-version-min=11.0
#cgo darwin,amd64 LDFLAGS: ${SRCDIR}/external/darwin-amd64/lib/libhighs.a -lc++
#cgo darwin,amd64 CFLAGS: -I${SRCDIR}/external/darwin-amd64/include/highs -mmacosx-version-min=11.0
#cgo linux,amd64 LDFLAGS: ${SRCDIR}/external/linux-amd64/lib/libhighs.a -lstdc++ -lm -ldl -lz
#cgo linux,amd64 CFLAGS: -I${SRCDIR}/external/linux-amd64/include/highs
#cgo linux,arm64 LDFLAGS: ${SRCDIR}/external/linux-arm64/lib/libhighs.a -lstdc++ -lm -ldl
#cgo linux,arm64 CFLAGS: -I${SRCDIR}/external/linux-arm64/include/highs
#cgo CXXFLAGS: -std=c++11
#include "interfaces/highs_c_api.h"
#include <stdlib.h>
*/
import "C"
import (
"errors"
"fmt"
"math"
"runtime"
"sort"
"time"
"unsafe"
"github.com/nextmv-io/go-mip"
)
// on Windows/WSL ubuntu amd64 we currently have to link against zlib
// dynamically. (this comment needs to come below the import "C" statement)
// NewSolver creates solver using Highs as back-end solver.
func NewSolver(model mip.Model) mip.Solver {
return &solverHighs{
model: model,
}
}
// Solve solves a given model with some options.
func (solver *solverHighs) Solve(options mip.SolveOptions) (mip.Solution, error) {
start := time.Now()
if len(solver.model.Vars()) == 0 {
return &highsSolution{
solutionStatus: optimal,
}, nil
}
highsPtr := C.Highs_create()
if highsPtr == nil {
return &highsSolution{
solutionStatus: statusUnknown,
}, nil
}
defer C.Highs_destroy(highsPtr)
input := solver.newHighsInput(highsPtr, start)
if err := handleOptions(highsPtr, *input, options); err != nil {
return nil, fmt.Errorf("error handling options in HiGHS solver: %w", err)
}
isMiqp := solver.model.Objective().IsQuadratic() &&
input.isIntegerProblem
if isMiqp {
return nil, errMiqpNotSupported
}
return solve(highsPtr, options, input)
}
type highsSolution struct {
values []float64
solutionStatus solutionStatus
objectiveValue float64
runtime time.Duration
}
func (l *highsSolution) ObjectiveValue() float64 {
return l.objectiveValue
}
func (l *highsSolution) Provider() mip.SolverProvider {
return "HiGHS"
}
func (l *highsSolution) RunTime() time.Duration {
return l.runtime
}
func (l *highsSolution) Value(variable mip.Var) float64 {
if variable.Index() >= len(l.values) {
return math.MaxFloat64
}
return l.values[variable.Index()]
}
func (l *highsSolution) IsNumericalFailure() bool {
return false
}
func (l *highsSolution) IsOptimal() bool {
return l.solutionStatus == optimal
}
func (l *highsSolution) HasValues() bool {
return hasValues(l.solutionStatus)
}
func (l *highsSolution) IsSubOptimal() bool {
return false
}
func (l *highsSolution) IsTimeOut() bool {
return l.solutionStatus == timeLimit
}
func (l *highsSolution) IsUnbounded() bool {
return l.solutionStatus == unbounded ||
l.solutionStatus == unboundedOrInfeasible
}
func (l *highsSolution) IsInfeasible() bool {
return l.solutionStatus == infeasible ||
l.solutionStatus == unboundedOrInfeasible
}
type solverHighs struct {
model mip.Model
}
type highsInput struct {
start time.Time
rowUpperBound []C.double
rowLowerBound []C.double
columnCosts []C.double
columnLowerBound []C.double
columnUpperBound []C.double
rowConstraintMatrixIndices []C.int
rowConstraintMatrixBegins []C.int
rowConstraintMatrixValues []C.double
hessianMatrixIndices []C.int
hessianMatrixBegins []C.int
hessianMatrixValues []C.double
columnIntegrality []C.int
numNonZeros int
numQuadraticNonZeros int
numColumns int
numRows int
sense C.int
isIntegerProblem bool
isQuadraticProblem bool
}
type solutionStatus int
// the values match HiGHS internal codes
const (
optimal solutionStatus = 7
infeasible solutionStatus = 8
unboundedOrInfeasible solutionStatus = 9
unbounded solutionStatus = 10
timeLimit solutionStatus = 13
statusUnknown solutionStatus = 15
)
func hasValues(solutionStatus solutionStatus) bool {
return solutionStatus == optimal
}
func (solver *solverHighs) newHighsInput(
highsPtr unsafe.Pointer,
start time.Time,
) *highsInput {
// infinity is defined as
// std::numeric_limits<double>::infinity()
// by HiGHS.
infinity := C.Highs_getInfinity(highsPtr)
input := new(highsInput)
input.start = start
input.numColumns = len(solver.model.Vars())
allConstraints := solver.model.Constraints()
constraintsWithTerms := make(mip.Constraints, 0, len(allConstraints))
for _, c := range allConstraints {
if len(c.Terms()) > 0 {
constraintsWithTerms = append(constraintsWithTerms, c)
}
}
input.numRows = len(constraintsWithTerms)
prepareColumns(input, solver, constraintsWithTerms, infinity)
prepareConstraintMatrix(input, solver, constraintsWithTerms, infinity)
prepareHessian(input, solver)
input.isQuadraticProblem = input.numQuadraticNonZeros > 0
input.sense = C.kHighsObjSenseMinimize
if solver.model.Objective().IsMaximize() {
input.sense = C.kHighsObjSenseMaximize
}
return input
}
func mapVarTypeToIntegrality(variable mip.Var) C.int {
if variable.IsBool() || variable.IsInt() {
return C.kHighsVarTypeInteger
}
return C.kHighsVarTypeContinuous
}
func handleOptions(highsPtr unsafe.Pointer, input highsInput, options mip.SolveOptions) error {
if err := setOutputFlag(highsPtr, options); err != nil {
return err
}
if err := setDoubleOption(
highsPtr,
"time_limit",
options.Duration.Seconds(),
); err != nil {
return err
}
if input.isIntegerProblem {
if err := setDoubleOption(
highsPtr,
"mip_abs_gap",
options.MIP.Gap.Absolute,
); err != nil {
return err
}
if err := setDoubleOption(
highsPtr,
"mip_rel_gap",
options.MIP.Gap.Relative,
); err != nil {
return err
}
}
controlOptions, err := options.Control.ToTyped()
if err != nil {
return err
}
for _, option := range controlOptions.Bool {
if err := setBoolOption(
highsPtr,
option.Name,
option.Value,
); err != nil {
return err
}
}
for _, option := range controlOptions.Float {
if err := setDoubleOption(
highsPtr,
option.Name,
option.Value,
); err != nil {
return err
}
}
for _, option := range controlOptions.Int {
if err := setIntOption(
highsPtr,
option.Name,
option.Value,
); err != nil {
return err
}
}
for _, option := range controlOptions.String {
if err := setStringOption(
highsPtr,
option.Name,
option.Value,
); err != nil {
return err
}
}
return nil
}
func setOutputFlag(ptr unsafe.Pointer, options mip.SolveOptions) error {
option := C.CString("output_flag")
defer C.free(unsafe.Pointer(option))
verbosityLevel := C.int(1)
if options.Verbosity == mip.Off {
verbosityLevel = C.int(0)
}
status := C.Highs_setBoolOptionValue(ptr, option, verbosityLevel)
if status != C.kHighsStatusOk {
return errors.New(
"highs failed setting verbosity level",
)
}
reportLevel := C.int(0)
switch options.Verbosity {
case mip.Low:
reportLevel = C.int(0)
case mip.Medium:
reportLevel = C.int(1)
case mip.High:
reportLevel = C.int(2)
}
option2 := C.CString("log_dev_level")
defer C.free(unsafe.Pointer(option2))
status = C.Highs_setIntOptionValue(
ptr,
option2,
reportLevel,
)
if status != C.kHighsStatusOk {
return errors.New(
"highs failed setting verbosity mip report level",
)
}
return nil
}
func setBoolOption(highsPtr unsafe.Pointer, option string, value bool) error {
optionName := C.CString(option)
defer C.free(unsafe.Pointer(optionName))
cBool := C.int(0)
if value {
cBool = C.int(1)
}
status := C.Highs_setBoolOptionValue(highsPtr, optionName, cBool)
if status != C.kHighsStatusOk {
return fmt.Errorf("HiGHS failed setting bool option %s to value %v", option, value)
}
return nil
}
func setDoubleOption(highsPtr unsafe.Pointer, option string, value float64) error {
optionName := C.CString(option)
defer C.free(unsafe.Pointer(optionName))
status := C.Highs_setDoubleOptionValue(highsPtr, optionName, C.double(value))
if status != C.kHighsStatusOk {
return fmt.Errorf("HiGHS failed setting float (double) option %s to value %v", option, value)
}
return nil
}
func setIntOption(highsPtr unsafe.Pointer, option string, value int) error {
optionName := C.CString(option)
defer C.free(unsafe.Pointer(optionName))
status := C.Highs_setIntOptionValue(highsPtr, optionName, C.int(value))
if status != C.kHighsStatusOk {
return fmt.Errorf("HiGHS failed setting int option %s to value %v", option, value)
}
return nil
}
func setStringOption(highsPtr unsafe.Pointer, option string, value string) error {
optionName := C.CString(option)
defer C.free(unsafe.Pointer(optionName))
optionValue := C.CString(value)
defer C.free(unsafe.Pointer(optionValue))
status := C.Highs_setStringOptionValue(highsPtr, optionName, optionValue)
if status != C.kHighsStatusOk {
return fmt.Errorf("HiGHS failed setting string option %s to value %v", option, value)
}
return nil
}
func solve(
highsPtr unsafe.Pointer, _ mip.SolveOptions, input *highsInput,
) (*highsSolution, error) {
pRowLowerBound := (*C.double)(unsafe.Pointer(nil))
pRowUpperBound := (*C.double)(unsafe.Pointer(nil))
pColumnIntegrality := (*C.int)(unsafe.Pointer(nil))
pRowConstraintMatrixBegins := (*C.int)(unsafe.Pointer(nil))
pRowConstraintMatrixIndices := (*C.int)(unsafe.Pointer(nil))
pRowConstraintMatrixValues := (*C.double)(unsafe.Pointer(nil))
pColumnCosts := (*C.double)(unsafe.Pointer(nil))
pColumnLowerBound := (*C.double)(unsafe.Pointer(nil))
pColumnUpperBound := (*C.double)(unsafe.Pointer(nil))
pHessianConstraintMatrixBegins := (*C.int)(unsafe.Pointer(nil))
pHessianConstraintMatrixIndices := (*C.int)(unsafe.Pointer(nil))
pHessianConstraintMatrixValues := (*C.double)(unsafe.Pointer(nil))
if input.numRows > 0 {
pRowLowerBound = (*C.double)(unsafe.Pointer(&input.rowLowerBound[0]))
pRowUpperBound = (*C.double)(unsafe.Pointer(&input.rowUpperBound[0]))
b := (*C.int)(unsafe.Pointer(&input.rowConstraintMatrixBegins[0]))
pRowConstraintMatrixBegins = b
i := (*C.int)(unsafe.Pointer(&input.rowConstraintMatrixIndices[0]))
pRowConstraintMatrixIndices = i
v := (*C.double)(unsafe.Pointer(&input.rowConstraintMatrixValues[0]))
pRowConstraintMatrixValues = v
}
if input.isQuadraticProblem {
pHessianConstraintMatrixBegins = (*C.int)(unsafe.Pointer(
&input.hessianMatrixBegins[0],
))
pHessianConstraintMatrixIndices = (*C.int)(unsafe.Pointer(
&input.hessianMatrixIndices[0],
))
pHessianConstraintMatrixValues = (*C.double)(unsafe.Pointer(
&input.hessianMatrixValues[0],
))
}
if input.numColumns > 0 {
pColumnCosts = (*C.double)(unsafe.Pointer(
&input.columnCosts[0],
))
pColumnLowerBound = (*C.double)(unsafe.Pointer(
&input.columnLowerBound[0],
))
pColumnUpperBound = (*C.double)(unsafe.Pointer(
&input.columnUpperBound[0],
))
}
if input.isIntegerProblem {
pColumnIntegrality = (*C.int)(unsafe.Pointer(
&input.columnIntegrality[0],
))
}
status := C.Highs_passModel(
highsPtr,
C.int(input.numColumns),
C.int(input.numRows),
C.int(input.numNonZeros),
C.int(input.numQuadraticNonZeros),
C.kHighsMatrixFormatRowwise,
C.kHighsHessianFormatTriangular,
input.sense,
C.double(0.0),
pColumnCosts,
pColumnLowerBound,
pColumnUpperBound,
pRowLowerBound,
pRowUpperBound,
pRowConstraintMatrixBegins,
pRowConstraintMatrixIndices,
pRowConstraintMatrixValues,
pHessianConstraintMatrixBegins,
pHessianConstraintMatrixIndices,
pHessianConstraintMatrixValues,
pColumnIntegrality,
)
if status != C.kHighsStatusOk {
return &highsSolution{
solutionStatus: statusUnknown,
}, errPassing
}
runStatus := C.Highs_run(highsPtr)
if !(runStatus == C.kHighsStatusOk || runStatus == C.kHighsStatusWarning) {
return &highsSolution{
solutionStatus: statusUnknown,
}, nil
}
modelStatus := C.Highs_getModelStatus(highsPtr)
columnValues := make([]float64, input.numColumns)
columnDuals := make([]C.double, input.numColumns)
rowValues := make([]float64, input.numRows)
rowDuals := make([]C.double, input.numRows)
pRowValues := (*C.double)(unsafe.Pointer(nil))
pRowDuals := (*C.double)(unsafe.Pointer(nil))
if input.numRows > 0 {
pRowValues = (*C.double)(unsafe.Pointer(&rowValues[0]))
pRowDuals = (*C.double)(unsafe.Pointer(&rowDuals[0]))
}
status = C.Highs_getSolution(
highsPtr,
(*C.double)(unsafe.Pointer(&columnValues[0])),
(*C.double)(unsafe.Pointer(&columnDuals[0])),
pRowValues,
pRowDuals,
)
if status != C.kHighsStatusOk {
return &highsSolution{
solutionStatus: statusUnknown,
}, errGetSolution
}
objectiveValue := float64(C.Highs_getObjectiveValue(highsPtr))
runtime.KeepAlive(input)
return &highsSolution{
objectiveValue: objectiveValue,
runtime: time.Since(input.start),
solutionStatus: solutionStatus(modelStatus),
values: columnValues,
}, nil
}
var (
errPassing = errors.New(
"highs failed passing the model",
)
errGetSolution = errors.New(
"highs failed getting the solution",
)
errMiqpNotSupported = errors.New(
"highs does not support mixed integer quadratic programs",
)
)
func prepareColumns(
input *highsInput,
solver *solverHighs,
constraintsWithTerms mip.Constraints,
_ C.double,
) {
input.numNonZeros = 0
for _, c := range constraintsWithTerms {
input.numNonZeros += len(c.Terms())
}
input.columnCosts = make([]C.double, input.numColumns)
input.columnLowerBound = make([]C.double, input.numColumns)
input.columnUpperBound = make([]C.double, input.numColumns)
input.columnIntegrality = make([]C.int, input.numColumns)
input.isIntegerProblem = false
for _, v := range solver.model.Vars() {
i := v.Index()
input.columnCosts[i] = C.double(0.0)
input.columnLowerBound[i] = C.double(v.LowerBound())
input.columnUpperBound[i] = C.double(v.UpperBound())
t := mapVarTypeToIntegrality(v)
input.columnIntegrality[i] = t
if t == C.kHighsVarTypeInteger {
input.isIntegerProblem = true
}
}
for _, term := range solver.model.Objective().Terms() {
input.columnCosts[term.Var().Index()] = C.double(term.Coefficient())
}
}
func prepareConstraintMatrix(
input *highsInput,
_ *solverHighs,
constraintsWithTerms mip.Constraints,
infinity C.double,
) {
input.rowConstraintMatrixBegins = make([]C.int, input.numRows)
input.rowLowerBound = make([]C.double, input.numRows)
input.rowUpperBound = make([]C.double, input.numRows)
input.rowConstraintMatrixIndices = make([]C.int, input.numNonZeros)
input.rowConstraintMatrixValues = make([]C.double, input.numNonZeros)
rowConstraintMatrixBegin := 0
for i, c := range constraintsWithTerms {
input.rowConstraintMatrixBegins[i] = C.int(
rowConstraintMatrixBegin,
)
rhs := C.double(c.RightHandSide())
switch c.Sense() {
case mip.LessThanOrEqual:
input.rowLowerBound[i] = -infinity
input.rowUpperBound[i] = rhs
case mip.Equal:
input.rowLowerBound[i] = rhs
input.rowUpperBound[i] = rhs
case mip.GreaterThanOrEqual:
input.rowLowerBound[i] = rhs
input.rowUpperBound[i] = infinity
}
for _, t := range c.Terms() {
i := C.int(t.Var().Index())
input.rowConstraintMatrixIndices[rowConstraintMatrixBegin] = i
c := C.double(t.Coefficient())
input.rowConstraintMatrixValues[rowConstraintMatrixBegin] = c
rowConstraintMatrixBegin++
}
}
}
func prepareHessian(input *highsInput, solver *solverHighs) {
qTerms := solver.model.Objective().QuadraticTerms()
qMat := make(map[int]map[int]mip.QuadraticTerm)
for _, v := range qTerms {
_, ok := qMat[v.Var1().Index()]
if !ok {
qMat[v.Var1().Index()] = make(map[int]mip.QuadraticTerm)
}
qMat[v.Var1().Index()][v.Var2().Index()] = v
}
input.numQuadraticNonZeros = len(qTerms)
input.hessianMatrixBegins = make([]C.int, 0, input.numColumns+1)
input.hessianMatrixIndices = make([]C.int, 0, input.numQuadraticNonZeros)
input.hessianMatrixValues = make([]C.double, 0, input.numQuadraticNonZeros)
nonZeros := 0
for i := 0; i < input.numColumns; i++ {
input.hessianMatrixBegins = append(input.hessianMatrixBegins, C.int(nonZeros))
row, ok := qMat[i]
if !ok {
continue
}
terms := make(mip.QuadraticTerms, 0, len(row))
for _, v := range row {
terms = append(terms, v)
}
sort.SliceStable(terms, func(i, j int) bool {
return terms[i].Var2().Index() < terms[j].Var2().Index()
})
for _, v := range terms {
input.hessianMatrixIndices = append(
input.hessianMatrixIndices,
C.int(v.Var2().Index()),
)
coef := v.Coefficient()
if v.Var1().Index() == v.Var2().Index() {
coef *= 2.0
}
// highs solves the problem of min/max c^tx * 1/2*x^tQx
// however it is more intuitive (we assume) when developers
// can expect min/max c^tx * x^tQx.
input.hessianMatrixValues = append(
input.hessianMatrixValues,
C.double(coef),
)
}
nonZeros += len(terms)
}
input.hessianMatrixBegins = append(
input.hessianMatrixBegins,
C.int(input.numQuadraticNonZeros),
)
}