forked from pa-m/mat32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dense.go
533 lines (487 loc) · 13.6 KB
/
dense.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
// Copyright ©2013 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package mat32
import (
"gonum.org/v1/gonum/blas"
"gonum.org/v1/gonum/blas/blas32"
)
var (
dense *Dense
_ Matrix = dense
_ Mutable = dense
_ Cloner = dense
_ RowViewer = dense
_ ColViewer = dense
_ RawRowViewer = dense
_ Grower = dense
_ RawMatrixSetter = dense
_ RawMatrixer = dense
_ Reseter = dense
)
// Dense is a dense matrix representation.
type Dense struct {
mat blas32.General
capRows, capCols int
}
// NewDense creates a new Dense matrix with r rows and c columns. If data == nil,
// a new slice is allocated for the backing slice. If len(data) == r*c, data is
// used as the backing slice, and changes to the elements of the returned Dense
// will be reflected in data. If neither of these is true, NewDense will panic.
//
// The data must be arranged in row-major order, i.e. the (i*c + j)-th
// element in the data slice is the {i, j}-th element in the matrix.
func NewDense(r, c int, data []float32) *Dense {
if r < 0 || c < 0 {
panic("mat: negative dimension")
}
if data != nil && r*c != len(data) {
panic(ErrShape)
}
if data == nil {
data = make([]float32, r*c)
}
return &Dense{
mat: blas32.General{
Rows: r,
Cols: c,
Stride: c,
Data: data,
},
capRows: r,
capCols: c,
}
}
// reuseAs resizes an empty matrix to a r×c matrix,
// or checks that a non-empty matrix is r×c.
//
// reuseAs must be kept in sync with reuseAsZeroed.
func (m *Dense) reuseAs(r, c int) {
if m.mat.Rows > m.capRows || m.mat.Cols > m.capCols {
// Panic as a string, not a mat.Error.
panic("mat: caps not correctly set")
}
if r == 0 || c == 0 {
panic(ErrZeroLength)
}
if m.IsZero() {
m.mat = blas32.General{
Rows: r,
Cols: c,
Stride: c,
Data: use(m.mat.Data, r*c),
}
m.capRows = r
m.capCols = c
return
}
if r != m.mat.Rows || c != m.mat.Cols {
panic(ErrShape)
}
}
// reuseAsZeroed resizes an empty matrix to a r×c matrix,
// or checks that a non-empty matrix is r×c. It zeroes
// all the elements of the matrix.
//
// reuseAsZeroed must be kept in sync with reuseAs.
func (m *Dense) reuseAsZeroed(r, c int) {
if m.mat.Rows > m.capRows || m.mat.Cols > m.capCols {
// Panic as a string, not a mat.Error.
panic("mat: caps not correctly set")
}
if r == 0 || c == 0 {
panic(ErrZeroLength)
}
if m.IsZero() {
m.mat = blas32.General{
Rows: r,
Cols: c,
Stride: c,
Data: useZeroed(m.mat.Data, r*c),
}
m.capRows = r
m.capCols = c
return
}
if r != m.mat.Rows || c != m.mat.Cols {
panic(ErrShape)
}
for i := 0; i < r; i++ {
zero(m.mat.Data[i*m.mat.Stride : i*m.mat.Stride+c])
}
}
// untranspose untransposes a matrix if applicable. If a is an Untransposer, then
// untranspose returns the underlying matrix and true. If it is not, then it returns
// the input matrix and false.
func untranspose(a Matrix) (Matrix, bool) {
if ut, ok := a.(Untransposer); ok {
return ut.Untranspose(), true
}
return a, false
}
// isolatedWorkspace returns a new dense matrix w with the size of a and
// returns a callback to defer which performs cleanup at the return of the call.
// This should be used when a method receiver is the same pointer as an input argument.
func (m *Dense) isolatedWorkspace(a Matrix) (w *Dense, restore func()) {
r, c := a.Dims()
if r == 0 || c == 0 {
panic(ErrZeroLength)
}
w = getWorkspace(r, c, false)
return w, func() {
m.Copy(w)
putWorkspace(w)
}
}
// Reset zeros the dimensions of the matrix so that it can be reused as the
// receiver of a dimensionally restricted operation.
//
// See the Reseter interface for more information.
func (m *Dense) Reset() {
// Row, Cols and Stride must be zeroed in unison.
m.mat.Rows, m.mat.Cols, m.mat.Stride = 0, 0, 0
m.capRows, m.capCols = 0, 0
m.mat.Data = m.mat.Data[:0]
}
// IsZero returns whether the receiver is zero-sized. Zero-sized matrices can be the
// receiver for size-restricted operations. Dense matrices can be zeroed using Reset.
func (m *Dense) IsZero() bool {
// It must be the case that m.Dims() returns
// zeros in this case. See comment in Reset().
return m.mat.Stride == 0
}
// asTriDense returns a TriDense with the given size and side. The backing data
// of the TriDense is the same as the receiver.
func (m *Dense) asTriDense(n int, diag blas.Diag, uplo blas.Uplo) *TriDense {
return &TriDense{
mat: blas32.Triangular{
N: n,
Stride: m.mat.Stride,
Data: m.mat.Data,
Uplo: uplo,
Diag: diag,
},
cap: n,
}
}
// DenseCopyOf returns a newly allocated copy of the elements of a.
func DenseCopyOf(a Matrix) *Dense {
d := &Dense{}
d.Clone(a)
return d
}
// SetRawMatrix sets the underlying blas32.General used by the receiver.
// Changes to elements in the receiver following the call will be reflected
// in b.
func (m *Dense) SetRawMatrix(b blas32.General) {
m.capRows, m.capCols = b.Rows, b.Cols
m.mat = b
}
// RawMatrix returns the underlying blas32.General used by the receiver.
// Changes to elements in the receiver following the call will be reflected
// in returned blas32.General.
func (m *Dense) RawMatrix() blas32.General { return m.mat }
// Dims returns the number of rows and columns in the matrix.
func (m *Dense) Dims() (r, c int) { return m.mat.Rows, m.mat.Cols }
// Caps returns the number of rows and columns in the backing matrix.
func (m *Dense) Caps() (r, c int) { return m.capRows, m.capCols }
// T performs an implicit transpose by returning the receiver inside a Transpose.
func (m *Dense) T() Matrix {
return Transpose{m}
}
// ColView returns a Vector reflecting the column j, backed by the matrix data.
//
// See ColViewer for more information.
func (m *Dense) ColView(j int) Vector {
var v VecDense
v.ColViewOf(m, j)
return &v
}
// SetCol sets the values in the specified column of the matrix to the values
// in src. len(src) must equal the number of rows in the receiver.
func (m *Dense) SetCol(j int, src []float32) {
if j >= m.mat.Cols || j < 0 {
panic(ErrColAccess)
}
if len(src) != m.mat.Rows {
panic(ErrColLength)
}
blas32.Copy(m.mat.Rows,
blas32.Vector{Inc: 1, Data: src},
blas32.Vector{Inc: m.mat.Stride, Data: m.mat.Data[j:]},
)
}
// SetRow sets the values in the specified rows of the matrix to the values
// in src. len(src) must equal the number of columns in the receiver.
func (m *Dense) SetRow(i int, src []float32) {
if i >= m.mat.Rows || i < 0 {
panic(ErrRowAccess)
}
if len(src) != m.mat.Cols {
panic(ErrRowLength)
}
copy(m.rawRowView(i), src)
}
// RowView returns row i of the matrix data represented as a column vector,
// backed by the matrix data.
//
// See RowViewer for more information.
func (m *Dense) RowView(i int) Vector {
var v VecDense
v.RowViewOf(m, i)
return &v
}
// RawRowView returns a slice backed by the same array as backing the
// receiver.
func (m *Dense) RawRowView(i int) []float32 {
if i >= m.mat.Rows || i < 0 {
panic(ErrRowAccess)
}
return m.rawRowView(i)
}
func (m *Dense) rawRowView(i int) []float32 {
return m.mat.Data[i*m.mat.Stride : i*m.mat.Stride+m.mat.Cols]
}
// Slice returns a new Matrix that shares backing data with the receiver.
// The returned matrix starts at {i,j} of the receiver and extends k-i rows
// and l-j columns. The final row in the resulting matrix is k-1 and the
// final column is l-1.
// Slice panics with ErrIndexOutOfRange if the slice is outside the capacity
// of the receiver.
func (m *Dense) Slice(i, k, j, l int) Matrix {
mr, mc := m.Caps()
if i < 0 || mr <= i || j < 0 || mc <= j || k <= i || mr < k || l <= j || mc < l {
panic(ErrIndexOutOfRange)
}
t := *m
t.mat.Data = t.mat.Data[i*t.mat.Stride+j : (k-1)*t.mat.Stride+l]
t.mat.Rows = k - i
t.mat.Cols = l - j
t.capRows -= i
t.capCols -= j
return &t
}
// Grow returns the receiver expanded by r rows and c columns. If the dimensions
// of the expanded matrix are outside the capacities of the receiver a new
// allocation is made, otherwise not. Note the receiver itself is not modified
// during the call to Grow.
func (m *Dense) Grow(r, c int) Matrix {
if r < 0 || c < 0 {
panic(ErrIndexOutOfRange)
}
if r == 0 && c == 0 {
return m
}
r += m.mat.Rows
c += m.mat.Cols
var t Dense
switch {
case m.mat.Rows == 0 || m.mat.Cols == 0:
t.mat = blas32.General{
Rows: r,
Cols: c,
Stride: c,
// We zero because we don't know how the matrix will be used.
// In other places, the mat is immediately filled with a result;
// this is not the case here.
Data: useZeroed(m.mat.Data, r*c),
}
case r > m.capRows || c > m.capCols:
cr := max(r, m.capRows)
cc := max(c, m.capCols)
t.mat = blas32.General{
Rows: r,
Cols: c,
Stride: cc,
Data: make([]float32, cr*cc),
}
t.capRows = cr
t.capCols = cc
// Copy the complete matrix over to the new matrix.
// Including elements not currently visible. Use a temporary structure
// to avoid modifying the receiver.
var tmp Dense
tmp.mat = blas32.General{
Rows: m.mat.Rows,
Cols: m.mat.Cols,
Stride: m.mat.Stride,
Data: m.mat.Data,
}
tmp.capRows = m.capRows
tmp.capCols = m.capCols
t.Copy(&tmp)
return &t
default:
t.mat = blas32.General{
Data: m.mat.Data[:(r-1)*m.mat.Stride+c],
Rows: r,
Cols: c,
Stride: m.mat.Stride,
}
}
t.capRows = r
t.capCols = c
return &t
}
// Clone makes a copy of a into the receiver, overwriting the previous value of
// the receiver. The clone operation does not make any restriction on shape and
// will not cause shadowing.
//
// See the Cloner interface for more information.
func (m *Dense) Clone(a Matrix) {
r, c := a.Dims()
mat := blas32.General{
Rows: r,
Cols: c,
Stride: c,
}
m.capRows, m.capCols = r, c
aU, trans := untranspose(a)
switch aU := aU.(type) {
case RawMatrixer:
amat := aU.RawMatrix()
mat.Data = make([]float32, r*c)
if trans {
for i := 0; i < r; i++ {
blas32.Copy(c,
blas32.Vector{Inc: amat.Stride, Data: amat.Data[i : i+(c-1)*amat.Stride+1]},
blas32.Vector{Inc: 1, Data: mat.Data[i*c : (i+1)*c]})
}
} else {
for i := 0; i < r; i++ {
copy(mat.Data[i*c:(i+1)*c], amat.Data[i*amat.Stride:i*amat.Stride+c])
}
}
case *VecDense:
amat := aU.mat
mat.Data = make([]float32, aU.n)
blas32.Copy(aU.n,
blas32.Vector{Inc: amat.Inc, Data: amat.Data},
blas32.Vector{Inc: 1, Data: mat.Data})
default:
mat.Data = make([]float32, r*c)
w := *m
w.mat = mat
for i := 0; i < r; i++ {
for j := 0; j < c; j++ {
w.set(i, j, a.At(i, j))
}
}
*m = w
return
}
m.mat = mat
}
// Copy makes a copy of elements of a into the receiver. It is similar to the
// built-in copy; it copies as much as the overlap between the two matrices and
// returns the number of rows and columns it copied. If a aliases the receiver
// and is a transposed Dense or VecDense, with a non-unitary increment, Copy will
// panic.
//
// See the Copier interface for more information.
func (m *Dense) Copy(a Matrix) (r, c int) {
r, c = a.Dims()
if a == m {
return r, c
}
r = min(r, m.mat.Rows)
c = min(c, m.mat.Cols)
if r == 0 || c == 0 {
return 0, 0
}
aU, trans := untranspose(a)
switch aU := aU.(type) {
case RawMatrixer:
amat := aU.RawMatrix()
if trans {
if amat.Stride != 1 {
m.checkOverlap(amat)
}
for i := 0; i < r; i++ {
blas32.Copy(c,
blas32.Vector{Inc: amat.Stride, Data: amat.Data[i : i+(c-1)*amat.Stride+1]},
blas32.Vector{Inc: 1, Data: m.mat.Data[i*m.mat.Stride : i*m.mat.Stride+c]})
}
} else {
switch o := offset(m.mat.Data, amat.Data); {
case o < 0:
for i := r - 1; i >= 0; i-- {
copy(m.mat.Data[i*m.mat.Stride:i*m.mat.Stride+c], amat.Data[i*amat.Stride:i*amat.Stride+c])
}
case o > 0:
for i := 0; i < r; i++ {
copy(m.mat.Data[i*m.mat.Stride:i*m.mat.Stride+c], amat.Data[i*amat.Stride:i*amat.Stride+c])
}
default:
// Nothing to do.
}
}
case *VecDense:
var n, stride int
amat := aU.mat
if trans {
if amat.Inc != 1 {
m.checkOverlap(aU.asGeneral())
}
n = c
stride = 1
} else {
n = r
stride = m.mat.Stride
}
if amat.Inc == 1 && stride == 1 {
copy(m.mat.Data, amat.Data[:n])
break
}
switch o := offset(m.mat.Data, amat.Data); {
case o < 0:
blas32.Copy(n,
blas32.Vector{Inc: -amat.Inc, Data: amat.Data},
blas32.Vector{Inc: -stride, Data: m.mat.Data})
case o > 0:
blas32.Copy(n,
blas32.Vector{Inc: amat.Inc, Data: amat.Data},
blas32.Vector{Inc: stride, Data: m.mat.Data})
default:
// Nothing to do.
}
default:
m.checkOverlapMatrix(aU)
for i := 0; i < r; i++ {
for j := 0; j < c; j++ {
m.set(i, j, a.At(i, j))
}
}
}
return r, c
}
// Stack appends the rows of b onto the rows of a, placing the result into the
// receiver with b placed in the greater indexed rows. Stack will panic if the
// two input matrices do not have the same number of columns or the constructed
// stacked matrix is not the same shape as the receiver.
func (m *Dense) Stack(a, b Matrix) {
ar, ac := a.Dims()
br, bc := b.Dims()
if ac != bc || m == a || m == b {
panic(ErrShape)
}
m.reuseAs(ar+br, ac)
m.Copy(a)
w := m.Slice(ar, ar+br, 0, bc).(*Dense)
w.Copy(b)
}
// Augment creates the augmented matrix of a and b, where b is placed in the
// greater indexed columns. Augment will panic if the two input matrices do
// not have the same number of rows or the constructed augmented matrix is
// not the same shape as the receiver.
func (m *Dense) Augment(a, b Matrix) {
ar, ac := a.Dims()
br, bc := b.Dims()
if ar != br || m == a || m == b {
panic(ErrShape)
}
m.reuseAs(ar, ac+bc)
m.Copy(a)
w := m.Slice(0, br, ac, ac+bc).(*Dense)
w.Copy(b)
}