forked from draffensperger/golp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlp_test.go
64 lines (51 loc) · 1.91 KB
/
lp_test.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
// Package golp gives Go bindings for LPSolve.
package golp
import (
"github.com/stretchr/testify/assert"
"testing"
)
// TestLP tests a real-valued linear programming example
func TestLP(t *testing.T) {
lp := NewLP(0, 2)
lp.SetVerboseLevel(NEUTRAL)
lp.SetColName(0, "x")
lp.SetColName(1, "y")
assert.Equal(t, "x", lp.ColName(0))
assert.Equal(t, "y", lp.ColName(1))
lp.AddConstraint([]float64{120.0, 210.0}, LE, 15000)
lp.AddConstraintSparse([]Entry{Entry{Col: 0, Val: 110.0}, Entry{Col: 1, Val: 30.0}}, LE, 4000)
lp.AddConstraintSparse([]Entry{Entry{Col: 1, Val: 1.0}, Entry{Col: 0, Val: 1.0}}, LE, 75)
lp.SetObjFn([]float64{143, 60})
lp.SetMaximize()
lpString := "/* Objective function */\nmax: +143 x +60 y;\n\n/* Constraints */\n+120 x +210 y <= 15000;\n+110 x +30 y <= 4000;\n+x +y <= 75;\n"
assert.Equal(t, lpString, lp.WriteToString())
lp.Solve()
delta := 0.000001
assert.InDelta(t, 6315.625, lp.Objective(), delta)
vars := lp.Variables()
assert.Equal(t, len(vars), 2)
assert.InDelta(t, 21.875, vars[0], delta)
assert.InDelta(t, 53.125, vars[1], delta)
}
// TestMIP tests a mixed-integer programming example
func TestMIP(t *testing.T) {
lp := NewLP(0, 4)
lp.AddConstraintSparse([]Entry{{0, 1.0}, {1, 1.0}}, LE, 5.0)
lp.AddConstraintSparse([]Entry{{0, 2.0}, {1, -1.0}}, GE, 0.0)
lp.AddConstraintSparse([]Entry{{0, 1.0}, {1, 3.0}}, GE, 0.0)
lp.AddConstraintSparse([]Entry{{2, 1.0}, {3, 1.0}}, GE, 0.5)
lp.AddConstraintSparse([]Entry{{2, 1.0}}, GE, 1.1)
lp.SetObjFn([]float64{-1.0, -2.0, 0.1, 3.0})
lp.SetInt(2, true)
assert.Equal(t, lp.IsInt(2), true)
lp.Solve()
delta := 0.000001
assert.InDelta(t, -8.133333333, lp.Objective(), delta)
vars := lp.Variables()
assert.Equal(t, lp.NumCols(), 4)
assert.Equal(t, len(vars), 4)
assert.InDelta(t, 1.6666666666, vars[0], delta)
assert.InDelta(t, 3.3333333333, vars[1], delta)
assert.InDelta(t, 2.0, vars[2], delta)
assert.InDelta(t, 0.0, vars[3], delta)
}