forked from apremalal/go-chart
/
matrix.go
592 lines (513 loc) · 12.4 KB
/
matrix.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
package matrix
import (
"bytes"
"errors"
"fmt"
"math"
)
const (
// DefaultEpsilon represents the minimum precision for matrix math operations.
DefaultEpsilon = 0.000001
)
var (
// ErrDimensionMismatch is a typical error.
ErrDimensionMismatch = errors.New("dimension mismatch")
// ErrSingularValue is a typical error.
ErrSingularValue = errors.New("singular value")
)
// New returns a new matrix.
func New(rows, cols int, values ...float64) *Matrix {
if len(values) == 0 {
return &Matrix{
stride: cols,
epsilon: DefaultEpsilon,
elements: make([]float64, rows*cols),
}
}
elems := make([]float64, rows*cols)
copy(elems, values)
return &Matrix{
stride: cols,
epsilon: DefaultEpsilon,
elements: elems,
}
}
// Identity returns the identity matrix of a given order.
func Identity(order int) *Matrix {
m := New(order, order)
for i := 0; i < order; i++ {
m.Set(i, i, 1)
}
return m
}
// Zero returns a matrix of a given size zeroed.
func Zero(rows, cols int) *Matrix {
return New(rows, cols)
}
// Ones returns an matrix of ones.
func Ones(rows, cols int) *Matrix {
ones := make([]float64, rows*cols)
for i := 0; i < (rows * cols); i++ {
ones[i] = 1
}
return &Matrix{
stride: cols,
epsilon: DefaultEpsilon,
elements: ones,
}
}
// Eye returns the eye matrix.
func Eye(n int) *Matrix {
m := Zero(n, n)
for i := 0; i < len(m.elements); i += n + 1 {
m.elements[i] = 1
}
return m
}
// NewFromArrays creates a matrix from a jagged array set.
func NewFromArrays(a [][]float64) *Matrix {
rows := len(a)
if rows == 0 {
return nil
}
cols := len(a[0])
m := New(rows, cols)
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
m.Set(row, col, a[row][col])
}
}
return m
}
// Matrix represents a 2d dense array of floats.
type Matrix struct {
epsilon float64
elements []float64
stride int
}
// String returns a string representation of the matrix.
func (m *Matrix) String() string {
buffer := bytes.NewBuffer(nil)
rows, cols := m.Size()
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
buffer.WriteString(f64s(m.Get(row, col)))
buffer.WriteRune(' ')
}
buffer.WriteRune('\n')
}
return buffer.String()
}
// Epsilon returns the maximum precision for math operations.
func (m *Matrix) Epsilon() float64 {
return m.epsilon
}
// WithEpsilon sets the epsilon on the matrix and returns a reference to the matrix.
func (m *Matrix) WithEpsilon(epsilon float64) *Matrix {
m.epsilon = epsilon
return m
}
// Each applies the action to each element of the matrix in
// rows => cols order.
func (m *Matrix) Each(action func(row, col int, value float64)) {
rows, cols := m.Size()
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
action(row, col, m.Get(row, col))
}
}
}
// Round rounds all the values in a matrix to it epsilon,
// returning a reference to the original
func (m *Matrix) Round() *Matrix {
rows, cols := m.Size()
for row := 0; row < rows; row++ {
for col := 0; col < cols; col++ {
m.Set(row, col, roundToEpsilon(m.Get(row, col), m.epsilon))
}
}
return m
}
// Arrays returns the matrix as a two dimensional jagged array.
func (m *Matrix) Arrays() [][]float64 {
rows, cols := m.Size()
a := make([][]float64, rows)
for row := 0; row < rows; row++ {
a[row] = make([]float64, cols)
for col := 0; col < cols; col++ {
a[row][col] = m.Get(row, col)
}
}
return a
}
// Size returns the dimensions of the matrix.
func (m *Matrix) Size() (rows, cols int) {
rows = len(m.elements) / m.stride
cols = m.stride
return
}
// IsSquare returns if the row count is equal to the column count.
func (m *Matrix) IsSquare() bool {
return m.stride == (len(m.elements) / m.stride)
}
// IsSymmetric returns if the matrix is symmetric about its diagonal.
func (m *Matrix) IsSymmetric() bool {
rows, cols := m.Size()
if rows != cols {
return false
}
for i := 0; i < rows; i++ {
for j := 0; j < i; j++ {
if m.Get(i, j) != m.Get(j, i) {
return false
}
}
}
return true
}
// Get returns the element at the given row, col.
func (m *Matrix) Get(row, col int) float64 {
index := (m.stride * row) + col
return m.elements[index]
}
// Set sets a value.
func (m *Matrix) Set(row, col int, val float64) {
index := (m.stride * row) + col
m.elements[index] = val
}
// Col returns a column of the matrix as a vector.
func (m *Matrix) Col(col int) Vector {
rows, _ := m.Size()
values := make([]float64, rows)
for row := 0; row < rows; row++ {
values[row] = m.Get(row, col)
}
return Vector(values)
}
// Row returns a row of the matrix as a vector.
func (m *Matrix) Row(row int) Vector {
_, cols := m.Size()
values := make([]float64, cols)
for col := 0; col < cols; col++ {
values[col] = m.Get(row, col)
}
return Vector(values)
}
// SubMatrix returns a sub matrix from a given outer matrix.
func (m *Matrix) SubMatrix(i, j, rows, cols int) *Matrix {
return &Matrix{
elements: m.elements[i*m.stride+j : i*m.stride+j+(rows-1)*m.stride+cols],
stride: m.stride,
epsilon: m.epsilon,
}
}
// ScaleRow applies a scale to an entire row.
func (m *Matrix) ScaleRow(row int, scale float64) {
startIndex := row * m.stride
for i := startIndex; i < m.stride; i++ {
m.elements[i] = m.elements[i] * scale
}
}
func (m *Matrix) scaleAddRow(rd int, rs int, f float64) {
indexd := rd * m.stride
indexs := rs * m.stride
for col := 0; col < m.stride; col++ {
m.elements[indexd] += f * m.elements[indexs]
indexd++
indexs++
}
}
// SwapRows swaps a row in the matrix in place.
func (m *Matrix) SwapRows(i, j int) {
var vi, vj float64
for col := 0; col < m.stride; col++ {
vi = m.Get(i, col)
vj = m.Get(j, col)
m.Set(i, col, vj)
m.Set(j, col, vi)
}
}
// Augment concatenates two matrices about the horizontal.
func (m *Matrix) Augment(m2 *Matrix) (*Matrix, error) {
mr, mc := m.Size()
m2r, m2c := m2.Size()
if mr != m2r {
return nil, ErrDimensionMismatch
}
m3 := Zero(mr, mc+m2c)
for row := 0; row < mr; row++ {
for col := 0; col < mc; col++ {
m3.Set(row, col, m.Get(row, col))
}
for col := 0; col < m2c; col++ {
m3.Set(row, mc+col, m2.Get(row, col))
}
}
return m3, nil
}
// Copy returns a duplicate of a given matrix.
func (m *Matrix) Copy() *Matrix {
m2 := &Matrix{stride: m.stride, epsilon: m.epsilon, elements: make([]float64, len(m.elements))}
copy(m2.elements, m.elements)
return m2
}
// DiagonalVector returns a vector from the diagonal of a matrix.
func (m *Matrix) DiagonalVector() Vector {
rows, cols := m.Size()
rank := minInt(rows, cols)
values := make([]float64, rank)
for index := 0; index < rank; index++ {
values[index] = m.Get(index, index)
}
return Vector(values)
}
// Diagonal returns a matrix from the diagonal of a matrix.
func (m *Matrix) Diagonal() *Matrix {
rows, cols := m.Size()
rank := minInt(rows, cols)
m2 := New(rank, rank)
for index := 0; index < rank; index++ {
m2.Set(index, index, m.Get(index, index))
}
return m2
}
// Equals returns if a matrix equals another matrix.
func (m *Matrix) Equals(other *Matrix) bool {
if other == nil && m != nil {
return false
} else if other == nil {
return true
}
if m.stride != other.stride {
return false
}
msize := len(m.elements)
m2size := len(other.elements)
if msize != m2size {
return false
}
for i := 0; i < msize; i++ {
if m.elements[i] != other.elements[i] {
return false
}
}
return true
}
// L returns the matrix with zeros below the diagonal.
func (m *Matrix) L() *Matrix {
rows, cols := m.Size()
m2 := New(rows, cols)
for row := 0; row < rows; row++ {
for col := row; col < cols; col++ {
m2.Set(row, col, m.Get(row, col))
}
}
return m2
}
// U returns the matrix with zeros above the diagonal.
// Does not include the diagonal.
func (m *Matrix) U() *Matrix {
rows, cols := m.Size()
m2 := New(rows, cols)
for row := 0; row < rows; row++ {
for col := 0; col < row && col < cols; col++ {
m2.Set(row, col, m.Get(row, col))
}
}
return m2
}
// math operations
// Multiply multiplies two matrices.
func (m *Matrix) Multiply(m2 *Matrix) (m3 *Matrix, err error) {
if m.stride*m2.stride != len(m2.elements) {
return nil, ErrDimensionMismatch
}
m3 = &Matrix{epsilon: m.epsilon, stride: m2.stride, elements: make([]float64, (len(m.elements)/m.stride)*m2.stride)}
for m1c0, m3x := 0, 0; m1c0 < len(m.elements); m1c0 += m.stride {
for m2r0 := 0; m2r0 < m2.stride; m2r0++ {
for m1x, m2x := m1c0, m2r0; m2x < len(m2.elements); m2x += m2.stride {
m3.elements[m3x] += m.elements[m1x] * m2.elements[m2x]
m1x++
}
m3x++
}
}
return
}
// Pivotize does something i'm not sure what.
func (m *Matrix) Pivotize() *Matrix {
pv := make([]int, m.stride)
for i := range pv {
pv[i] = i
}
for j, dx := 0, 0; j < m.stride; j++ {
row := j
max := m.elements[dx]
for i, ixcj := j, dx; i < m.stride; i++ {
if m.elements[ixcj] > max {
max = m.elements[ixcj]
row = i
}
ixcj += m.stride
}
if j != row {
pv[row], pv[j] = pv[j], pv[row]
}
dx += m.stride + 1
}
p := Zero(m.stride, m.stride)
for r, c := range pv {
p.elements[r*m.stride+c] = 1
}
return p
}
// Times returns the product of a matrix and another.
func (m *Matrix) Times(m2 *Matrix) (*Matrix, error) {
mr, mc := m.Size()
m2r, m2c := m2.Size()
if mc != m2r {
return nil, fmt.Errorf("cannot multiply (%dx%d) and (%dx%d)", mr, mc, m2r, m2c)
//return nil, ErrDimensionMismatch
}
c := Zero(mr, m2c)
for i := 0; i < mr; i++ {
sums := c.elements[i*c.stride : (i+1)*c.stride]
for k, a := range m.elements[i*m.stride : i*m.stride+m.stride] {
for j, b := range m2.elements[k*m2.stride : k*m2.stride+m2.stride] {
sums[j] += a * b
}
}
}
return c, nil
}
// Decompositions
// LU performs the LU decomposition.
func (m *Matrix) LU() (l, u, p *Matrix) {
l = Zero(m.stride, m.stride)
u = Zero(m.stride, m.stride)
p = m.Pivotize()
m, _ = p.Multiply(m)
for j, jxc0 := 0, 0; j < m.stride; j++ {
l.elements[jxc0+j] = 1
for i, ixc0 := 0, 0; ixc0 <= jxc0; i++ {
sum := 0.
for k, kxcj := 0, j; k < i; k++ {
sum += u.elements[kxcj] * l.elements[ixc0+k]
kxcj += m.stride
}
u.elements[ixc0+j] = m.elements[ixc0+j] - sum
ixc0 += m.stride
}
for ixc0 := jxc0; ixc0 < len(m.elements); ixc0 += m.stride {
sum := 0.
for k, kxcj := 0, j; k < j; k++ {
sum += u.elements[kxcj] * l.elements[ixc0+k]
kxcj += m.stride
}
l.elements[ixc0+j] = (m.elements[ixc0+j] - sum) / u.elements[jxc0+j]
}
jxc0 += m.stride
}
return
}
// QR performs the qr decomposition.
func (m *Matrix) QR() (q, r *Matrix) {
defer func() {
q = q.Round()
r = r.Round()
}()
rows, cols := m.Size()
qr := m.Copy()
q = New(rows, cols)
r = New(rows, cols)
var i, j, k int
var norm, s float64
for k = 0; k < cols; k++ {
norm = 0
for i = k; i < rows; i++ {
norm = math.Hypot(norm, qr.Get(i, k))
}
if norm != 0 {
if qr.Get(k, k) < 0 {
norm = -norm
}
for i = k; i < rows; i++ {
qr.Set(i, k, qr.Get(i, k)/norm)
}
qr.Set(k, k, qr.Get(k, k)+1.0)
for j = k + 1; j < cols; j++ {
s = 0
for i = k; i < rows; i++ {
s += qr.Get(i, k) * qr.Get(i, j)
}
s = -s / qr.Get(k, k)
for i = k; i < rows; i++ {
qr.Set(i, j, qr.Get(i, j)+s*qr.Get(i, k))
if i < j {
r.Set(i, j, qr.Get(i, j))
}
}
}
}
r.Set(k, k, -norm)
}
//Q Matrix:
i, j, k = 0, 0, 0
for k = cols - 1; k >= 0; k-- {
q.Set(k, k, 1.0)
for j = k; j < cols; j++ {
if qr.Get(k, k) != 0 {
s = 0
for i = k; i < rows; i++ {
s += qr.Get(i, k) * q.Get(i, j)
}
s = -s / qr.Get(k, k)
for i = k; i < rows; i++ {
q.Set(i, j, q.Get(i, j)+s*qr.Get(i, k))
}
}
}
}
return
}
// Transpose flips a matrix about its diagonal, returning a new copy.
func (m *Matrix) Transpose() *Matrix {
rows, cols := m.Size()
m2 := Zero(cols, rows)
for i := 0; i < rows; i++ {
for j := 0; j < cols; j++ {
m2.Set(j, i, m.Get(i, j))
}
}
return m2
}
// Inverse returns a matrix such that M*I==1.
func (m *Matrix) Inverse() (*Matrix, error) {
if !m.IsSymmetric() {
return nil, ErrDimensionMismatch
}
rows, cols := m.Size()
aug, _ := m.Augment(Eye(rows))
for i := 0; i < rows; i++ {
j := i
for k := i; k < rows; k++ {
if math.Abs(aug.Get(k, i)) > math.Abs(aug.Get(j, i)) {
j = k
}
}
if j != i {
aug.SwapRows(i, j)
}
if aug.Get(i, i) == 0 {
return nil, ErrSingularValue
}
aug.ScaleRow(i, 1.0/aug.Get(i, i))
for k := 0; k < rows; k++ {
if k == i {
continue
}
aug.scaleAddRow(k, i, -aug.Get(k, i))
}
}
return aug.SubMatrix(0, cols, rows, cols), nil
}