/
vars.go
441 lines (368 loc) · 9.81 KB
/
vars.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
package optim
import (
"fmt"
"github.com/MatProGo-dev/SymbolicMath.go/symbolic"
"gonum.org/v1/gonum/mat"
)
// Var represnts a variable in a optimization problem. The variable is
// identified with an uint64.
type Variable struct {
ID uint64
Lower float64
Upper float64
Vtype VarType
}
/*
Variables
Description:
This function returns a slice containing all unique variables in the variable expression v.
*/
func (v Variable) Variables() []Variable {
return []Variable{v}
}
// NumVars returns the number of variables in the expression. For a variable, it
// always returns one.
func (v Variable) NumVars() int {
return 1
}
// Vars returns a slice of the Var ids in the expression. For a variable, it
// always returns a singleton slice with the given variable ID.
func (v Variable) IDs() []uint64 {
return []uint64{v.ID}
}
// Coeffs returns a slice of the coefficients in the expression. For a variable,
// it always returns a singleton slice containing the value one.
func (v Variable) Coeffs() []float64 {
return []float64{1}
}
// Constant returns the constant additive value in the expression. For a
// variable, it always returns zero.
func (v Variable) Constant() float64 {
return 0
}
// Plus adds the current expression to another and returns the resulting
// expression.
func (v Variable) Plus(e interface{}, errors ...error) (Expression, error) {
// Input Processing
err := v.Check()
if err != nil {
return v, err
}
err = CheckErrors(errors)
if err != nil {
return v, err
}
// Algorithm
switch e.(type) {
case K:
eAsK := e.(K)
// Organize vector variables
vv := VarVector{
UniqueVars(append([]Variable{v}, eAsK.Variables()...)),
}
// Return
return ScalarLinearExpr{
L: OnesVector(1),
X: vv,
C: float64(eAsK),
}, nil
case Variable:
// Convert
eAsV := e.(Variable)
vv := VarVector{
UniqueVars(append([]Variable{v}, eAsV.Variables()...)),
}
// Check to see if this is the same Variable or a different one
if eAsV.ID == v.ID {
return ScalarLinearExpr{
X: vv,
L: *mat.NewVecDense(1, []float64{2.0}),
C: 0.0,
}, nil
} else {
return ScalarLinearExpr{
X: vv,
L: OnesVector(2),
C: 0.0,
}, nil
}
case ScalarLinearExpr:
// Convert
eAsSLE := e.(ScalarLinearExpr)
vv := VarVector{
UniqueVars(append([]Variable{v}, eAsSLE.Variables()...)),
}
// Convert SLE to new form
e2, _ := eAsSLE.RewriteInTermsOf(vv)
vIndex, _ := FindInSlice(v, vv.Elements)
e2.L.SetVec(vIndex, e2.L.AtVec(vIndex)+1.0)
return e2, nil
case ScalarQuadraticExpression:
// Convert
eAsQE := e.(ScalarQuadraticExpression)
vv := VarVector{
UniqueVars(append([]Variable{v}, eAsQE.Variables()...)),
}
// Convert QE to new form
e2, _ := eAsQE.RewriteInTermsOf(vv)
vIndex, _ := FindInSlice(v, vv.Elements)
e2.L.SetVec(vIndex, e2.L.AtVec(vIndex)+1.0)
return e2, nil
default:
return v, fmt.Errorf("There was an unexpected type (%T) given to Variable.Plus()!", e)
}
}
//// Mult multiplies the current expression to another and returns the
//// resulting expression
//func (v Variable) Mult(m float64) (ScalarExpression, error) {
// // Constants
// // switch m.(type) {
// // case float64:
//
// vars := []Variable{v}
// coeffs := []float64{m * v.Coeffs()[0]}
//
// // Algorithm
// newExpr := ScalarLinearExpr{
// X: VarVector{vars},
// L: *mat.NewVecDense(1, coeffs),
// C: 0,
// }
// return newExpr, nil
// // case *Variable:
// // return nil
// // }
//}
// LessEq returns a less than or equal to (<=) constraint between the
// current expression and another
func (v Variable) LessEq(rhsIn interface{}, errors ...error) (Constraint, error) {
return v.Comparison(rhsIn, SenseLessThanEqual, errors...)
}
// GreaterEq returns a greater than or equal to (>=) constraint between the
// current expression and another
func (v Variable) GreaterEq(rhsIn interface{}, errors ...error) (Constraint, error) {
return v.Comparison(rhsIn, SenseGreaterThanEqual, errors...)
}
// Eq returns an equality (==) constraint between the current expression
// and another
func (v Variable) Eq(rhsIn interface{}, errors ...error) (Constraint, error) {
return v.Comparison(rhsIn, SenseEqual, errors...)
}
/*
Comparison
Description:
This method compares the receiver with expression rhs in the sense provided by sense.
Usage:
constr, err := v.Comparison(expr1,SenseGreaterThanEqual)
*/
func (v Variable) Comparison(rhsIn interface{}, sense ConstrSense, errors ...error) (Constraint, error) {
// Input Processing
err := CheckErrors(errors)
if err != nil {
return ScalarConstraint{}, err
}
rhs, err := ToScalarExpression(rhsIn)
if err != nil {
return ScalarConstraint{}, err
}
// Constants
// Algorithm
return ScalarConstraint{v, rhs, sense}, nil
}
/*
// ID returns the ID of the variable
func (v *Variable) ID() uint64 {
return v.ID
}
// Lower returns the lower value limit of the variable
func (v *Variable) Lower() float64 {
return v.Lower
}
// Upper returns the upper value limit of the variable
func (v *Variable) Upper() float64 {
return v.Upper
}
// Type returns the type of variable (continuous, binary, integer, etc)
func (v *Variable) Type() VarType {
return v.Vtype
}
*/
// VarType represents the type of the variable (continuous, binary,
// integer, etc) and uses Gurobi's encoding.
type VarType byte
// Multiple common variable types have been included as constants that conform
// to Gurobi's encoding.
const (
Continuous VarType = 'C'
Binary = 'B'
Integer = 'I'
)
/*
UniqueVars
Description:
This function creates a slice of unique variables from the slice given in
varsIn
*/
func UniqueVars(varsIn []Variable) []Variable {
// Constants
// Algorithm
var varsOut []Variable
for _, v := range varsIn {
if vIndex, _ := FindInSlice(v, varsOut); vIndex == -1 { // If v is not yet in varsOut, then add it
varsOut = append(varsOut, v)
}
}
return varsOut
}
/*
Multiply
Description:
multiplies the current expression to another and returns the resulting expression
*/
func (v Variable) Multiply(val interface{}, errors ...error) (Expression, error) {
// Input Processing
err := v.Check()
if err != nil {
return v, err
}
err = CheckErrors(errors)
if err != nil {
return v, err
}
if IsExpression(val) {
rightAsE, _ := ToExpression(val)
err = CheckDimensionsInMultiplication(v, rightAsE)
if err != nil {
return v, err
}
}
// Constants
switch e := val.(type) {
case float64:
return v.Multiply(K(e))
case K:
// Algorithm
return e.Multiply(v)
case Variable:
sqeOut := ScalarQuadraticExpression{
X: VarVector{
UniqueVars([]Variable{e, v}),
},
C: 0.0,
}
sqeOut.L = ZerosVector(sqeOut.X.Len())
if e.ID == v.ID {
sqeOut.Q = *mat.NewDense(1, 1, []float64{1.0})
} else {
sqeOut.Q = ZerosMatrix(2, 2)
sqeOut.Q.Set(0, 1, 0.5)
sqeOut.Q.Set(1, 0, 0.5)
}
return sqeOut, nil
case ScalarLinearExpr:
// Algorithm
sqeOut := ScalarQuadraticExpression{
X: VarVector{
UniqueVars(append(e.X.Elements, v)),
},
C: 0.0,
}
sqeOut.Q = ZerosMatrix(sqeOut.X.Len(), sqeOut.X.Len())
sqeOut.L = ZerosVector(sqeOut.X.Len())
// Update Q
vIndex, _ := FindInSlice(v, e.X.Elements) // err should be nil
vIndexInSQE, _ := FindInSlice(v, sqeOut.X.Elements) // err should be nil
for xIndex := 0; xIndex < e.L.Len(); xIndex++ {
// Check to make sure index is not the vIndex
if vIndex == xIndex {
// If v is in the original slice (i.e., we now need to represent v^2)
sqeOut.Q.Set(vIndexInSQE, vIndexInSQE, e.L.AtVec(vIndex))
} else {
// If xIndex is not for v, then create off-diagonal elements
xIndexInSQE, _ := FindInSlice(e.X.AtVec(xIndex), sqeOut.X.Elements)
// Create a pair of off-diagonal elements
sqeOut.Q.Set(vIndexInSQE, xIndexInSQE, e.L.AtVec(xIndex)*0.5)
sqeOut.Q.Set(xIndexInSQE, vIndexInSQE, e.L.AtVec(xIndex)*0.5)
}
}
// Update L
sqeOut.L.SetVec(vIndexInSQE, e.C)
return sqeOut, nil
case ScalarQuadraticExpression:
// Return error
return ScalarQuadraticExpression{}, fmt.Errorf("Can not multiply Variable with ScalarQuadraticExpression. MatProInterface can not represent polynomials higher than degree 2.")
case VectorLinearExpressionTranspose:
return ScalarQuadraticExpression{}, fmt.Errorf(
"cannot currently multiply a variable with a vector to create a quadratic expression; file an issue if you are interested in seeing a feature like this.",
)
default:
return v, fmt.Errorf("Unexpected input to v.Multiply(): %T", val)
}
}
/*
ToScalarLinearExpression
Description:
Converting the variable into a scalar linear Expression.
*/
func (v Variable) ToScalarLinearExpression() ScalarLinearExpr {
// Constants
// Create components
vars := []Variable{v}
coeffs := []float64{v.Coeffs()[0]}
// Create sle
return ScalarLinearExpr{
X: VarVector{vars},
L: *mat.NewVecDense(1, coeffs),
C: 0,
}
}
/*
Dims
Description:
Returns the dimension of the Variable object (should be scalar).
*/
func (v Variable) Dims() []int {
return []int{1, 1}
}
/*
Check
Description:
Checks whether or not the Variable has a sensible initialization.
*/
func (v Variable) Check() error {
// Check that the lower bound is below is the upper bound
if v.Lower > v.Upper {
return fmt.Errorf(
"lower bound (%v) of variable is above upper bound (%v).",
v.Lower, v.Upper,
)
}
// If nothing was thrown, then return nil!
return nil
}
func (v Variable) Transpose() Expression {
return v
}
/*
ToSymbolic
Description:
Converts the variable into a symbolic variable
(from the symbolic math toolbox).
*/
func (v Variable) ToSymbolic() (symbolic.Expression, error) {
// Input Checking
err := v.Check()
if err != nil {
return nil, err
}
// Create base variable and fill its elements
symVar := symbolic.Variable{
ID: v.ID,
Lower: v.Lower,
Upper: v.Upper,
Type: symbolic.VarType(v.Vtype),
Name: fmt.Sprintf("x_{%v}", v.ID),
}
// Algorithm
return symVar, nil
}