/
cpl.go
1464 lines (1298 loc) · 50.7 KB
/
cpl.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
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 (c) Harri Rautila, 2012
// This file is part of github.com/hrautila/cvx package.
// It is free software, distributed under the terms of GNU Lesser General Public
// License Version 3, or any later version. See the COPYING tile included in this archive.
package cvx
import (
"errors"
"fmt"
"github.com/hrautila/cvx/checkpnt"
"github.com/hrautila/cvx/sets"
la "github.com/hrautila/linalg"
"github.com/hrautila/linalg/blas"
"github.com/hrautila/matrix"
"math"
)
// Solves a convex optimization problem with a linear objective
//
// minimize c'*x
// subject to f(x) <= 0
// G*x <= h
// A*x = b.
//
// f is vector valued, convex and twice differentiable. The linear
// inequalities are with respect to a cone C defined as the Cartesian
// product of N + M + 1 cones:
//
// C = C_0 x C_1 x .... x C_N x C_{N+1} x ... x C_{N+M}.
//
// The first cone C_0 is the nonnegative orthant of dimension ml. The
// next N cones are second order cones of dimension r[0], ..., r[N-1].
// The second order cone of dimension m is defined as
//
// { (u0, u1) in R x R^{m-1} | u0 >= ||u1||_2 }.
//
// The next M cones are positive semidefinite cones of order t[0], ..., t[M-1] >= 0.
//
// The structure of C is specified by DimensionSet dims which holds following sets
//
// dims.At("l") l, the dimension of the nonnegative orthant (array of length 1)
// dims.At("q") r[0], ... r[N-1], list with the dimesions of the second-order cones
// dims.At("s") t[0], ... t[M-1], array with the dimensions of the positive
// semidefinite cones
//
// The default value for dims is l: []int{h.Rows()}, q: []int{}, s: []int{}.
//
// On exit Solution contains the result and information about the accurancy of the
// solution. if SolutionStatus is Optimal then Solution.Result contains solutions
// for the problems.
//
// Result.At("x")[0] primal solution
// Result.At("snl")[0] non-linear constraint slacks
// Result.At("sl")[0] linear constraint slacks
// Result.At("y")[0] values for linear equality constraints y
// Result.At("znl")[0] values of dual variables for nonlinear inequalities
// Result.At("zl")[0] values of dual variables for linear inequalities
//
// If err is non-nil then sol is nil and err contains information about the argument or
// computation error.
//
func Cpl(F ConvexProg, c, G, h, A, b *matrix.FloatMatrix, dims *sets.DimensionSet, solopts *SolverOptions) (sol *Solution, err error) {
var mnl int
var x0 *matrix.FloatMatrix
mnl, x0, err = F.F0()
if err != nil {
return
}
if x0.Cols() != 1 {
err = errors.New("'x0' must be matrix with one column")
return
}
if c == nil {
err = errors.New("'c' must be non nil matrix")
return
}
if !c.SizeMatch(x0.Size()) {
err = errors.New(fmt.Sprintf("'c' must be matrix of size (%d,1)", x0.Rows()))
return
}
if h == nil {
h = matrix.FloatZeros(0, 1)
}
if h.Cols() > 1 {
err = errors.New("'h' must be matrix with 1 column")
return
}
if dims == nil {
dims = sets.NewDimensionSet("l", "q", "s")
dims.Set("l", []int{h.Rows()})
}
cdim := dims.Sum("l", "q") + dims.SumSquared("s")
//cdim_pckd := dims.Sum("l", "q") + dims.SumPacked("s")
//cdim_diag := dims.Sum("l", "q", "s")
if h.Rows() != cdim {
err = errors.New(fmt.Sprintf("'h' must be float matrix of size (%d,1)", cdim))
return
}
if G == nil {
G = matrix.FloatZeros(0, c.Rows())
}
if !G.SizeMatch(cdim, c.Rows()) {
estr := fmt.Sprintf("'G' must be of size (%d,%d)", cdim, c.Rows())
err = errors.New(estr)
return
}
// Check A and set defaults if it is nil
if A == nil {
// zeros rows reduces Gemv to vector products
A = matrix.FloatZeros(0, c.Rows())
}
if A.Cols() != c.Rows() {
estr := fmt.Sprintf("'A' must have %d columns", c.Rows())
err = errors.New(estr)
return
}
// Check b and set defaults if it is nil
if b == nil {
b = matrix.FloatZeros(0, 1)
}
if b.Cols() != 1 {
estr := fmt.Sprintf("'b' must be a matrix with 1 column")
err = errors.New(estr)
return
}
if b.Rows() != A.Rows() {
estr := fmt.Sprintf("'b' must have length %d", A.Rows())
err = errors.New(estr)
return
}
var mc = matrixVar{c}
var mb = matrixVar{b}
var mA = matrixVarA{A}
var mG = matrixVarG{G, dims}
solvername := solopts.KKTSolverName
if len(solvername) == 0 {
if len(dims.At("q")) > 0 || len(dims.At("s")) > 0 {
solvername = "chol"
} else {
solvername = "chol2"
}
}
var factor kktFactor
var kktsolver KKTCpSolver = nil
if kktfunc, ok := solvers[solvername]; ok {
// kkt function returns us problem spesific factor function.
factor, err = kktfunc(G, dims, A, mnl)
// solver is
kktsolver = func(W *sets.FloatMatrixSet, x, z *matrix.FloatMatrix) (KKTFunc, error) {
_, Df, H, err := F.F2(x, z)
if err != nil {
return nil, err
}
return factor(W, H, Df)
}
} else {
err = errors.New(fmt.Sprintf("solver '%s' not known", solvername))
return
}
//return CplCustom(F, c, &mG, h, &mA, b, dims, kktsolver, solopts)
return cpl_problem(F, &mc, &mG, h, &mA, &mb, dims, kktsolver, solopts, x0, mnl)
}
// Solves a convex optimization problem with a linear objective
//
// minimize c'*x
// subject to f(x) <= 0
// G*x <= h
// A*x = b.
//
// using custom KTT equation solver.
//
func CplCustomKKT(F ConvexProg, c *matrix.FloatMatrix, G, h, A, b *matrix.FloatMatrix,
dims *sets.DimensionSet, kktsolver KKTCpSolver,
solopts *SolverOptions) (sol *Solution, err error) {
var mnl int
var x0 *matrix.FloatMatrix
mnl, x0, err = F.F0()
if err != nil {
return
}
if x0.Cols() != 1 {
err = errors.New("'x0' must be matrix with one column")
return
}
if c == nil {
err = errors.New("'c' must be non nil matrix")
return
}
if !c.SizeMatch(x0.Size()) {
err = errors.New(fmt.Sprintf("'c' must be matrix of size (%d,1)", x0.Rows()))
return
}
if h == nil {
h = matrix.FloatZeros(0, 1)
}
if h.Cols() > 1 {
err = errors.New("'h' must be matrix with 1 column")
return
}
if dims == nil {
dims = sets.NewDimensionSet("l", "q", "s")
dims.Set("l", []int{h.Rows()})
}
cdim := dims.Sum("l", "q") + dims.SumSquared("s")
if h.Rows() != cdim {
err = errors.New(fmt.Sprintf("'h' must be float matrix of size (%d,1)", cdim))
return
}
if G == nil {
G = matrix.FloatZeros(0, c.Rows())
}
if !G.SizeMatch(cdim, c.Rows()) {
estr := fmt.Sprintf("'G' must be of size (%d,%d)", cdim, c.Rows())
err = errors.New(estr)
return
}
// Check A and set defaults if it is nil
if A == nil {
// zeros rows reduces Gemv to vector products
A = matrix.FloatZeros(0, c.Rows())
}
if A.Cols() != c.Rows() {
estr := fmt.Sprintf("'A' must have %d columns", c.Rows())
err = errors.New(estr)
return
}
// Check b and set defaults if it is nil
if b == nil {
b = matrix.FloatZeros(0, 1)
}
if b.Cols() != 1 {
estr := fmt.Sprintf("'b' must be a matrix with 1 column")
err = errors.New(estr)
return
}
if b.Rows() != A.Rows() {
estr := fmt.Sprintf("'b' must have length %d", A.Rows())
err = errors.New(estr)
return
}
var mc = matrixVar{c}
var mb = matrixVar{b}
var mA = matrixVarA{A}
var mG = matrixVarG{G, dims}
return cpl_problem(F, &mc, &mG, h, &mA, &mb, dims, kktsolver, solopts, x0, mnl)
}
// Solves a convex optimization problem with a linear objective
//
// minimize c'*x
// subject to f(x) <= 0
// G*x <= h
// A*x = b.
//
// using custom KTT equation solver and custom constraints G and A.
//
func CplCustomMatrix(F ConvexProg, c *matrix.FloatMatrix, G MatrixG, h *matrix.FloatMatrix,
A MatrixA, b *matrix.FloatMatrix, dims *sets.DimensionSet, kktsolver KKTCpSolver,
solopts *SolverOptions) (sol *Solution, err error) {
var mnl int
var x0 *matrix.FloatMatrix
mnl, x0, err = F.F0()
if err != nil {
return
}
if x0.Cols() != 1 {
err = errors.New("'x0' must be matrix with one column")
return
}
if c == nil {
err = errors.New("'c' must be non nil matrix")
return
}
if !c.SizeMatch(x0.Size()) {
err = errors.New(fmt.Sprintf("'c' must be matrix of size (%d,1)", x0.Rows()))
return
}
if h == nil {
h = matrix.FloatZeros(0, 1)
}
if h.Cols() > 1 {
err = errors.New("'h' must be matrix with 1 column")
return
}
if dims == nil {
dims = sets.NewDimensionSet("l", "q", "s")
dims.Set("l", []int{h.Rows()})
}
cdim := dims.Sum("l", "q") + dims.SumSquared("s")
if h.Rows() != cdim {
err = errors.New(fmt.Sprintf("'h' must be float matrix of size (%d,1)", cdim))
return
}
// Check b and set defaults if it is nil
if b == nil {
b = matrix.FloatZeros(0, 1)
}
if b.Cols() != 1 {
estr := fmt.Sprintf("'b' must be a matrix with 1 column")
err = errors.New(estr)
return
}
mc := matrixVar{c}
mb := matrixVar{b}
var mG MatrixVarG
var mA MatrixVarA
if G == nil {
mG = &matrixVarG{matrix.FloatZeros(0, c.Rows()), dims}
} else {
mG = &matrixIfG{G}
}
if A == nil {
mA = &matrixVarA{matrix.FloatZeros(0, c.Rows())}
} else {
mA = &matrixIfA{A}
}
return cpl_problem(F, &mc, mG, h, mA, &mb, dims, kktsolver, solopts, x0, mnl)
}
func cpl_problem(F ConvexProg, c MatrixVariable, G MatrixVarG, h *matrix.FloatMatrix, A MatrixVarA,
b MatrixVariable, dims *sets.DimensionSet, kktsolver KKTCpSolver,
solopts *SolverOptions, x0 *matrix.FloatMatrix, mnl int) (sol *Solution, err error) {
err = nil
F_e := &convexVarProg{F}
mx0 := &matrixVar{x0.Copy()}
kktsolver_u := func(W *sets.FloatMatrixSet, x MatrixVariable, z *matrix.FloatMatrix) (KKTFuncVar, error) {
g, err := kktsolver(W, x.Matrix(), z)
solver := func(x, y MatrixVariable, z *matrix.FloatMatrix) error {
return g(x.Matrix(), y.Matrix(), z)
}
return solver, err
}
return cpl_solver(F_e, c, G, h, A, b, dims, kktsolver_u, solopts, mx0, mnl)
}
// Internal CPL solver for CP and CLP problems. Everything is wrapped to proper interfaces
func cpl_solver(F ConvexVarProg, c MatrixVariable, G MatrixVarG, h *matrix.FloatMatrix,
A MatrixVarA, b MatrixVariable, dims *sets.DimensionSet, kktsolver KKTCpSolverVar,
solopts *SolverOptions, x0 MatrixVariable, mnl int) (sol *Solution, err error) {
const (
STEP = 0.99
BETA = 0.5
ALPHA = 0.01
EXPON = 3
MAX_RELAXED_ITERS = 8
)
var refinement int
sol = &Solution{Unknown,
nil,
0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0, 0}
feasTolerance := FEASTOL
absTolerance := ABSTOL
relTolerance := RELTOL
maxIter := MAXITERS
if solopts.FeasTol > 0.0 {
feasTolerance = solopts.FeasTol
}
if solopts.AbsTol > 0.0 {
absTolerance = solopts.AbsTol
}
if solopts.RelTol > 0.0 {
relTolerance = solopts.RelTol
}
if solopts.Refinement > 0 {
refinement = solopts.Refinement
} else {
refinement = 1
}
if solopts.MaxIter > 0 {
maxIter = solopts.MaxIter
}
if x0 == nil {
mnl, x0, err = F.F0()
if err != nil {
return
}
}
if c == nil {
err = errors.New("Must define objective.")
return
}
if h == nil {
h = matrix.FloatZeros(0, 1)
}
if dims == nil {
err = errors.New("Problem dimensions not defined.")
return
}
if err = checkConeLpDimensions(dims); err != nil {
return
}
cdim := dims.Sum("l", "q") + dims.SumSquared("s")
cdim_diag := dims.Sum("l", "q", "s")
if h.Rows() != cdim {
err = errors.New(fmt.Sprintf("'h' must be float matrix of size (%d,1)", cdim))
return
}
if G == nil {
err = errors.New("'G' must be non-nil MatrixG interface.")
return
}
fG := func(x, y MatrixVariable, alpha, beta float64, trans la.Option) error {
return G.Gf(x, y, alpha, beta, trans)
}
// Check A and set defaults if it is nil
if A == nil {
err = errors.New("'A' must be non-nil MatrixA interface.")
return
}
fA := func(x, y MatrixVariable, alpha, beta float64, trans la.Option) error {
return A.Af(x, y, alpha, beta, trans)
}
if b == nil {
err = errors.New("'b' must be non-nil MatrixVariable interface.")
return
}
if kktsolver == nil {
err = errors.New("nil kktsolver not allowed.")
return
}
x := x0.Copy()
y := b.Copy()
y.Scal(0.0)
z := matrix.FloatZeros(mnl+cdim, 1)
s := matrix.FloatZeros(mnl+cdim, 1)
ind := mnl + dims.At("l")[0]
z.SetIndexes(1.0, matrix.MakeIndexSet(0, ind, 1)...)
s.SetIndexes(1.0, matrix.MakeIndexSet(0, ind, 1)...)
for _, m := range dims.At("q") {
z.SetIndexes(1.0, ind)
s.SetIndexes(1.0, ind)
ind += m
}
for _, m := range dims.At("s") {
iset := matrix.MakeIndexSet(ind, ind+m*m, m+1)
z.SetIndexes(1.0, iset...)
s.SetIndexes(1.0, iset...)
ind += m * m
}
rx := x0.Copy()
ry := b.Copy()
dx := x.Copy()
dy := y.Copy()
rznl := matrix.FloatZeros(mnl, 1)
rzl := matrix.FloatZeros(cdim, 1)
dz := matrix.FloatZeros(mnl+cdim, 1)
ds := matrix.FloatZeros(mnl+cdim, 1)
lmbda := matrix.FloatZeros(mnl+cdim_diag, 1)
lmbdasq := matrix.FloatZeros(mnl+cdim_diag, 1)
sigs := matrix.FloatZeros(dims.Sum("s"), 1)
sigz := matrix.FloatZeros(dims.Sum("s"), 1)
dz2 := matrix.FloatZeros(mnl+cdim, 1)
ds2 := matrix.FloatZeros(mnl+cdim, 1)
newx := x.Copy()
newy := y.Copy()
newrx := x0.Copy()
newz := matrix.FloatZeros(mnl+cdim, 1)
news := matrix.FloatZeros(mnl+cdim, 1)
newrznl := matrix.FloatZeros(mnl, 1)
rx0 := rx.Copy()
ry0 := ry.Copy()
rznl0 := matrix.FloatZeros(mnl, 1)
rzl0 := matrix.FloatZeros(cdim, 1)
x0, dx0 := x.Copy(), dx.Copy()
y0, dy0 := y.Copy(), dy.Copy()
z0 := matrix.FloatZeros(mnl+cdim, 1)
dz0 := matrix.FloatZeros(mnl+cdim, 1)
dz20 := matrix.FloatZeros(mnl+cdim, 1)
s0 := matrix.FloatZeros(mnl+cdim, 1)
ds0 := matrix.FloatZeros(mnl+cdim, 1)
ds20 := matrix.FloatZeros(mnl+cdim, 1)
checkpnt.AddMatrixVar("z", z)
checkpnt.AddMatrixVar("s", s)
checkpnt.AddMatrixVar("dz", dz)
checkpnt.AddMatrixVar("ds", ds)
checkpnt.AddMatrixVar("rznl", rznl)
checkpnt.AddMatrixVar("rzl", rzl)
checkpnt.AddMatrixVar("lmbda", lmbda)
checkpnt.AddMatrixVar("lmbdasq", lmbdasq)
checkpnt.AddMatrixVar("z0", z0)
checkpnt.AddMatrixVar("dz0", dz0)
checkpnt.AddVerifiable("c", c)
checkpnt.AddVerifiable("x", x)
checkpnt.AddVerifiable("rx", rx)
checkpnt.AddVerifiable("dx", dx)
checkpnt.AddVerifiable("newrx", newrx)
checkpnt.AddVerifiable("newx", newx)
checkpnt.AddVerifiable("x0", x0)
checkpnt.AddVerifiable("dx0", dx0)
checkpnt.AddVerifiable("rx0", rx0)
checkpnt.AddVerifiable("y", y)
checkpnt.AddVerifiable("dy", dy)
W0 := sets.NewFloatSet("d", "di", "dnl", "dnli", "v", "r", "rti", "beta")
W0.Set("dnl", matrix.FloatZeros(mnl, 1))
W0.Set("dnli", matrix.FloatZeros(mnl, 1))
W0.Set("d", matrix.FloatZeros(dims.At("l")[0], 1))
W0.Set("di", matrix.FloatZeros(dims.At("l")[0], 1))
W0.Set("beta", matrix.FloatZeros(len(dims.At("q")), 1))
for _, n := range dims.At("q") {
W0.Append("v", matrix.FloatZeros(n, 1))
}
for _, n := range dims.At("s") {
W0.Append("r", matrix.FloatZeros(n, n))
W0.Append("rti", matrix.FloatZeros(n, n))
}
lmbda0 := matrix.FloatZeros(mnl+dims.Sum("l", "q", "s"), 1)
lmbdasq0 := matrix.FloatZeros(mnl+dims.Sum("l", "q", "s"), 1)
var f MatrixVariable = nil
var Df MatrixVarDf = nil
var H MatrixVarH = nil
var ws3, wz3, wz2l, wz2nl *matrix.FloatMatrix
var ws, wz, wz2, ws2 *matrix.FloatMatrix
var wx, wx2, wy, wy2 MatrixVariable
var gap, gap0, theta1, theta2, theta3, ts, tz, phi, phi0, mu, sigma, eta float64
var resx, resy, reszl, resznl, pcost, dcost, dres, pres, relgap float64
var resx0, resznl0, dres0, pres0 float64
var dsdz, dsdz0, step, step0, dphi, dphi0, sigma0, eta0 float64
var newresx, newresznl, newgap, newphi float64
var W *sets.FloatMatrixSet
var f3 KKTFuncVar
checkpnt.AddFloatVar("gap", &gap)
checkpnt.AddFloatVar("pcost", &pcost)
checkpnt.AddFloatVar("dcost", &dcost)
checkpnt.AddFloatVar("pres", &pres)
checkpnt.AddFloatVar("dres", &dres)
checkpnt.AddFloatVar("relgap", &relgap)
checkpnt.AddFloatVar("step", &step)
checkpnt.AddFloatVar("dsdz", &dsdz)
checkpnt.AddFloatVar("resx", &resx)
checkpnt.AddFloatVar("resy", &resy)
checkpnt.AddFloatVar("reszl", &reszl)
checkpnt.AddFloatVar("resznl", &resznl)
// Declare fDf and fH here, they bind to Df and H as they are already declared.
// ??really??
var fDf func(u, v MatrixVariable, alpha, beta float64, trans la.Option) error = nil
var fH func(u, v MatrixVariable, alpha, beta float64) error = nil
relaxed_iters := 0
for iters := 0; iters <= maxIter+1; iters++ {
checkpnt.MajorNext()
checkpnt.Check("loopstart", 10)
checkpnt.MinorPush(10)
if refinement != 0 || solopts.Debug {
f, Df, H, err = F.F2(x, matrix.FloatVector(z.FloatArray()[:mnl]))
fDf = func(u, v MatrixVariable, alpha, beta float64, trans la.Option) error {
return Df.Df(u, v, alpha, beta, trans)
}
fH = func(u, v MatrixVariable, alpha, beta float64) error {
return H.Hf(u, v, alpha, beta)
}
} else {
f, Df, err = F.F1(x)
fDf = func(u, v MatrixVariable, alpha, beta float64, trans la.Option) error {
return Df.Df(u, v, alpha, beta, trans)
}
}
checkpnt.MinorPop()
gap = sdot(s, z, dims, mnl)
// these are helpers, copies of parts of z,s
z_mnl := matrix.FloatVector(z.FloatArray()[:mnl])
z_mnl2 := matrix.FloatVector(z.FloatArray()[mnl:])
s_mnl := matrix.FloatVector(s.FloatArray()[:mnl])
s_mnl2 := matrix.FloatVector(s.FloatArray()[mnl:])
// rx = c + A'*y + Df'*z[:mnl] + G'*z[mnl:]
// -- y, rx MatrixArg
mCopy(c, rx)
fA(y, rx, 1.0, 1.0, la.OptTrans)
fDf(&matrixVar{z_mnl}, rx, 1.0, 1.0, la.OptTrans)
fG(&matrixVar{z_mnl2}, rx, 1.0, 1.0, la.OptTrans)
resx = math.Sqrt(rx.Dot(rx))
// rznl = s[:mnl] + f
blas.Copy(s_mnl, rznl)
blas.AxpyFloat(f.Matrix(), rznl, 1.0)
resznl = blas.Nrm2Float(rznl)
// rzl = s[mnl:] + G*x - h
blas.Copy(s_mnl2, rzl)
blas.AxpyFloat(h, rzl, -1.0)
fG(x, &matrixVar{rzl}, 1.0, 1.0, la.OptNoTrans)
reszl = snrm2(rzl, dims, 0)
// Statistics for stopping criteria
// pcost = c'*x
// dcost = c'*x + y'*(A*x-b) + znl'*f(x) + zl'*(G*x-h)
// = c'*x + y'*(A*x-b) + znl'*(f(x)+snl) + zl'*(G*x-h+sl)
// - z'*s
// = c'*x + y'*ry + znl'*rznl + zl'*rzl - gap
//pcost = blas.DotFloat(c, x)
pcost = c.Dot(x)
dcost = pcost + blas.DotFloat(y.Matrix(), ry.Matrix()) + blas.DotFloat(z_mnl, rznl)
dcost += sdot(z_mnl2, rzl, dims, 0) - gap
if pcost < 0.0 {
relgap = gap / -pcost
} else if dcost > 0.0 {
relgap = gap / dcost
} else {
relgap = math.NaN()
}
pres = math.Sqrt(resy*resy + resznl*resznl + reszl*reszl)
dres = resx
if iters == 0 {
resx0 = math.Max(1.0, resx)
resznl0 = math.Max(1.0, resznl)
pres0 = math.Max(1.0, pres)
dres0 = math.Max(1.0, dres)
gap0 = gap
theta1 = 1.0 / gap0
theta2 = 1.0 / resx0
theta3 = 1.0 / resznl0
}
phi = theta1*gap + theta2*resx + theta3*resznl
pres = pres / pres0
dres = dres / dres0
if solopts.ShowProgress {
if iters == 0 {
// some headers
fmt.Printf("% 10s% 12s% 10s% 8s% 7s\n",
"pcost", "dcost", "gap", "pres", "dres")
}
fmt.Printf("%2d: % 8.4e % 8.4e % 4.0e% 7.0e% 7.0e\n",
iters, pcost, dcost, gap, pres, dres)
}
checkpnt.Check("checkgap", 50)
// Stopping criteria
if (pres <= feasTolerance && dres <= feasTolerance &&
(gap <= absTolerance || (!math.IsNaN(relgap) && relgap <= relTolerance))) ||
iters == maxIter {
if iters == maxIter {
s := "Terminated (maximum number of iterations reached)"
if solopts.ShowProgress {
fmt.Printf(s + "\n")
}
err = errors.New(s)
sol.Status = Unknown
} else {
err = nil
sol.Status = Optimal
}
sol.Result = sets.NewFloatSet("x", "y", "znl", "zl", "snl", "sl")
sol.Result.Set("x", x.Matrix())
sol.Result.Set("y", y.Matrix())
sol.Result.Set("znl", matrix.FloatVector(z.FloatArray()[:mnl]))
sol.Result.Set("zl", matrix.FloatVector(z.FloatArray()[mnl:]))
sol.Result.Set("sl", matrix.FloatVector(s.FloatArray()[mnl:]))
sol.Result.Set("snl", matrix.FloatVector(s.FloatArray()[:mnl]))
sol.Gap = gap
sol.RelativeGap = relgap
sol.PrimalObjective = pcost
sol.DualObjective = dcost
sol.PrimalInfeasibility = pres
sol.DualInfeasibility = dres
sol.PrimalSlack = -ts
sol.DualSlack = -tz
return
}
// Compute initial scaling W:
//
// W * z = W^{-T} * s = lambda.
//
// lmbdasq = lambda o lambda
if iters == 0 {
W, _ = computeScaling(s, z, lmbda, dims, mnl)
checkpnt.AddScaleVar(W)
}
ssqr(lmbdasq, lmbda, dims, mnl)
checkpnt.Check("lmbdasq", 90)
// f3(x, y, z) solves
//
// [ H A' GG'*W^{-1} ] [ ux ] [ bx ]
// [ A 0 0 ] [ uy ] = [ by ].
// [ GG 0 -W' ] [ uz ] [ bz ]
//
// On entry, x, y, z contain bx, by, bz.
// On exit, they contain ux, uy, uz.
checkpnt.MinorPush(95)
f3, err = kktsolver(W, x, z_mnl)
checkpnt.MinorPop()
checkpnt.Check("f3", 100)
if err != nil {
// ?? z_mnl is really copy of z[:mnl] ... should we copy here back to z??
singular_kkt_matrix := false
if iters == 0 {
err = errors.New("Rank(A) < p or Rank([H(x); A; Df(x); G] < n")
return
} else if relaxed_iters > 0 && relaxed_iters < MAX_RELAXED_ITERS {
// The arithmetic error may be caused by a relaxed line
// search in the previous iteration. Therefore we restore
// the last saved state and require a standard line search.
phi, gap = phi0, gap0
mu = gap / float64(mnl+dims.Sum("l", "s")+len(dims.At("q")))
blas.Copy(W0.At("dnl")[0], W.At("dnl")[0])
blas.Copy(W0.At("dnli")[0], W.At("dnli")[0])
blas.Copy(W0.At("d")[0], W.At("d")[0])
blas.Copy(W0.At("di")[0], W.At("di")[0])
blas.Copy(W0.At("beta")[0], W.At("beta")[0])
for k, _ := range dims.At("q") {
blas.Copy(W0.At("v")[k], W.At("v")[k])
}
for k, _ := range dims.At("s") {
blas.Copy(W0.At("r")[k], W.At("r")[k])
blas.Copy(W0.At("rti")[k], W.At("rti")[k])
}
//blas.Copy(x0, x)
//x0.CopyTo(x)
mCopy(x0, x)
//blas.Copy(y0, y)
mCopy(y0, y)
blas.Copy(s0, s)
blas.Copy(z0, z)
blas.Copy(lmbda0, lmbda)
blas.Copy(lmbdasq0, lmbdasq) // ???
//blas.Copy(rx0, rx)
//rx0.CopyTo(rx)
mCopy(rx0, rx)
//blas.Copy(ry0, ry)
mCopy(ry0, ry)
//resx = math.Sqrt(blas.DotFloat(rx, rx))
resx = math.Sqrt(rx.Dot(rx))
blas.Copy(rznl0, rznl)
blas.Copy(rzl0, rzl)
resznl = blas.Nrm2Float(rznl)
relaxed_iters = -1
// How about z_mnl here???
checkpnt.MinorPush(120)
f3, err = kktsolver(W, x, z_mnl)
checkpnt.MinorPop()
if err != nil {
singular_kkt_matrix = true
}
} else {
singular_kkt_matrix = true
}
if singular_kkt_matrix {
msg := "Terminated (singular KKT matrix)."
if solopts.ShowProgress {
fmt.Printf(msg + "\n")
}
zl := matrix.FloatVector(z.FloatArray()[mnl:])
sl := matrix.FloatVector(s.FloatArray()[mnl:])
ind := dims.Sum("l", "q")
for _, m := range dims.At("s") {
symm(sl, m, ind)
symm(zl, m, ind)
ind += m * m
}
ts, _ = maxStep(s, dims, mnl, nil)
tz, _ = maxStep(z, dims, mnl, nil)
err = errors.New(msg)
sol.Status = Unknown
sol.Result = sets.NewFloatSet("x", "y", "znl", "zl", "snl", "sl")
sol.Result.Set("x", x.Matrix())
sol.Result.Set("y", y.Matrix())
sol.Result.Set("znl", matrix.FloatVector(z.FloatArray()[:mnl]))
sol.Result.Set("zl", zl)
sol.Result.Set("sl", sl)
sol.Result.Set("snl", matrix.FloatVector(s.FloatArray()[:mnl]))
sol.Gap = gap
sol.RelativeGap = relgap
sol.PrimalObjective = pcost
sol.DualObjective = dcost
sol.PrimalInfeasibility = pres
sol.DualInfeasibility = dres
sol.PrimalSlack = -ts
sol.DualSlack = -tz
return
}
}
// f4_no_ir(x, y, z, s) solves
//
// [ 0 ] [ H A' GG' ] [ ux ] [ bx ]
// [ 0 ] + [ A 0 0 ] [ uy ] = [ by ]
// [ W'*us ] [ GG 0 0 ] [ W^{-1}*uz ] [ bz ]
//
// lmbda o (uz + us) = bs.
//
// On entry, x, y, z, x, contain bx, by, bz, bs.
// On exit, they contain ux, uy, uz, us.
if iters == 0 {
ws3 = matrix.FloatZeros(mnl+cdim, 1)
wz3 = matrix.FloatZeros(mnl+cdim, 1)
checkpnt.AddMatrixVar("ws3", ws3)
checkpnt.AddMatrixVar("wz3", wz3)
}
f4_no_ir := func(x, y MatrixVariable, z, s *matrix.FloatMatrix) (err error) {
// Solve
//
// [ H A' GG' ] [ ux ] [ bx ]
// [ A 0 0 ] [ uy ] = [ by ]
// [ GG 0 -W'*W ] [ W^{-1}*uz ] [ bz - W'*(lmbda o\ bs) ]
//
// us = lmbda o\ bs - uz.
err = nil
// s := lmbda o\ s
// = lmbda o\ bs
sinv(s, lmbda, dims, mnl)
// z := z - W'*s
// = bz - W' * (lambda o\ bs)
blas.Copy(s, ws3)
scale(ws3, W, true, false)
blas.AxpyFloat(ws3, z, -1.0)
// Solve for ux, uy, uz
err = f3(x, y, z)
// s := s - z
// = lambda o\ bs - z.
blas.AxpyFloat(z, s, -1.0)
return
}
if iters == 0 {
wz2nl = matrix.FloatZeros(mnl, 1)
wz2l = matrix.FloatZeros(cdim, 1)
checkpnt.AddMatrixVar("wz2nl", wz2nl)
checkpnt.AddMatrixVar("wz2l", wz2l)
}
res := func(ux, uy MatrixVariable, uz, us *matrix.FloatMatrix, vx, vy MatrixVariable, vz, vs *matrix.FloatMatrix) (err error) {
// Evaluates residuals in Newton equations:
//
// [ vx ] [ 0 ] [ H A' GG' ] [ ux ]
// [ vy ] -= [ 0 ] + [ A 0 0 ] [ uy ]
// [ vz ] [ W'*us ] [ GG 0 0 ] [ W^{-1}*uz ]
//
// vs -= lmbda o (uz + us).
err = nil
minor := checkpnt.MinorTop()
// vx := vx - H*ux - A'*uy - GG'*W^{-1}*uz
fH(ux, vx, -1.0, 1.0)
fA(uy, vx, -1.0, 1.0, la.OptTrans)
blas.Copy(uz, wz3)
scale(wz3, W, false, true)
wz3_nl := matrix.FloatVector(wz3.FloatArray()[:mnl])
wz3_l := matrix.FloatVector(wz3.FloatArray()[mnl:])
fDf(&matrixVar{wz3_nl}, vx, -1.0, 1.0, la.OptTrans)
fG(&matrixVar{wz3_l}, vx, -1.0, 1.0, la.OptTrans)
checkpnt.Check("10res", minor+10)
// vy := vy - A*ux
fA(ux, vy, -1.0, 1.0, la.OptNoTrans)
// vz := vz - W'*us - GG*ux
err = fDf(ux, &matrixVar{wz2nl}, 1.0, 0.0, la.OptNoTrans)
checkpnt.Check("15res", minor+10)
blas.AxpyFloat(wz2nl, vz, -1.0)
fG(ux, &matrixVar{wz2l}, 1.0, 0.0, la.OptNoTrans)
checkpnt.Check("20res", minor+10)
blas.AxpyFloat(wz2l, vz, -1.0, &la.IOpt{"offsety", mnl})
blas.Copy(us, ws3)
scale(ws3, W, true, false)
blas.AxpyFloat(ws3, vz, -1.0)
checkpnt.Check("30res", minor+10)
// vs -= lmbda o (uz + us)
blas.Copy(us, ws3)
blas.AxpyFloat(uz, ws3, 1.0)
sprod(ws3, lmbda, dims, mnl, &la.SOpt{"diag", "D"})
blas.AxpyFloat(ws3, vs, -1.0)
checkpnt.Check("90res", minor+10)
return
}
// f4(x, y, z, s) solves the same system as f4_no_ir, but applies
// iterative refinement.
if iters == 0 {
if refinement > 0 || solopts.Debug {
wx = c.Copy()
wy = b.Copy()
wz = z.Copy()
ws = s.Copy()
checkpnt.AddVerifiable("wx", wx)
checkpnt.AddMatrixVar("ws", ws)
checkpnt.AddMatrixVar("wz", wz)
}
if refinement > 0 {
wx2 = c.Copy()
wy2 = b.Copy()
wz2 = matrix.FloatZeros(mnl+cdim, 1)
ws2 = matrix.FloatZeros(mnl+cdim, 1)
checkpnt.AddVerifiable("wx2", wx2)
checkpnt.AddMatrixVar("ws2", ws2)
checkpnt.AddMatrixVar("wz2", wz2)
}
}
f4 := func(x, y MatrixVariable, z, s *matrix.FloatMatrix) (err error) {
if refinement > 0 || solopts.Debug {
mCopy(x, wx)
mCopy(y, wy)
blas.Copy(z, wz)
blas.Copy(s, ws)
}
minor := checkpnt.MinorTop()
checkpnt.Check("0_f4", minor+100)
checkpnt.MinorPush(minor + 100)
err = f4_no_ir(x, y, z, s)
checkpnt.MinorPop()
checkpnt.Check("1_f4", minor+200)
for i := 0; i < refinement; i++ {