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
|
// 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 mat
import (
"fmt"
"strconv"
"strings"
)
// Formatted returns a fmt.Formatter for the matrix m using the given options.
func Formatted(m Matrix, options ...FormatOption) fmt.Formatter {
f := formatter{
matrix: m,
dot: '.',
}
for _, o := range options {
o(&f)
}
return f
}
type formatter struct {
matrix Matrix
prefix string
margin int
dot byte
squeeze bool
format func(m Matrix, prefix string, margin int, dot byte, squeeze bool, fs fmt.State, c rune)
}
// FormatOption is a functional option for matrix formatting.
type FormatOption func(*formatter)
// Prefix sets the formatted prefix to the string p. Prefix is a string that is prepended to
// each line of output after the first line.
func Prefix(p string) FormatOption {
return func(f *formatter) { f.prefix = p }
}
// Excerpt sets the maximum number of rows and columns to print at the margins of the matrix
// to m. If m is zero or less all elements are printed.
func Excerpt(m int) FormatOption {
return func(f *formatter) { f.margin = m }
}
// DotByte sets the dot character to b. The dot character is used to replace zero elements
// if the result is printed with the fmt ' ' verb flag. Without a DotByte option, the default
// dot character is '.'.
func DotByte(b byte) FormatOption {
return func(f *formatter) { f.dot = b }
}
// Squeeze sets the printing behavior to minimise column width for each individual column.
func Squeeze() FormatOption {
return func(f *formatter) { f.squeeze = true }
}
// FormatMATLAB sets the printing behavior to output MATLAB syntax. If MATLAB syntax is
// specified, the ' ' verb flag and Excerpt option are ignored. If the alternative syntax
// verb flag, '#' is used the matrix is formatted in rows and columns.
func FormatMATLAB() FormatOption {
return func(f *formatter) { f.format = formatMATLAB }
}
// FormatPython sets the printing behavior to output Python syntax. If Python syntax is
// specified, the ' ' verb flag and Excerpt option are ignored. If the alternative syntax
// verb flag, '#' is used the matrix is formatted in rows and columns.
func FormatPython() FormatOption {
return func(f *formatter) { f.format = formatPython }
}
// Format satisfies the fmt.Formatter interface.
func (f formatter) Format(fs fmt.State, c rune) {
if c == 'v' && fs.Flag('#') && f.format == nil {
fmt.Fprintf(fs, "%#v", f.matrix)
return
}
if f.format == nil {
f.format = format
}
f.format(f.matrix, f.prefix, f.margin, f.dot, f.squeeze, fs, c)
}
// format prints a pretty representation of m to the fs io.Writer. The format character c
// specifies the numerical representation of elements; valid values are those for float64
// specified in the fmt package, with their associated flags. In addition to this, a space
// preceding a verb indicates that zero values should be represented by the dot character.
// The printed range of the matrix can be limited by specifying a positive value for margin;
// If margin is greater than zero, only the first and last margin rows/columns of the matrix
// are output. If squeeze is true, column widths are determined on a per-column basis.
//
// format will not provide Go syntax output.
func format(m Matrix, prefix string, margin int, dot byte, squeeze bool, fs fmt.State, c rune) {
rows, cols := m.Dims()
var printed int
if margin <= 0 {
printed = rows
if cols > printed {
printed = cols
}
} else {
printed = margin
}
prec, pOk := fs.Precision()
if !pOk {
prec = -1
}
var (
maxWidth int
widths widther
buf, pad []byte
)
if squeeze {
widths = make(columnWidth, cols)
} else {
widths = new(uniformWidth)
}
switch c {
case 'v', 'e', 'E', 'f', 'F', 'g', 'G':
if c == 'v' {
buf, maxWidth = maxCellWidth(m, 'g', printed, prec, widths)
} else {
buf, maxWidth = maxCellWidth(m, c, printed, prec, widths)
}
default:
fmt.Fprintf(fs, "%%!%c(%T=Dims(%d, %d))", c, m, rows, cols)
return
}
width, _ := fs.Width()
width = max(width, maxWidth)
pad = make([]byte, max(width, 2))
for i := range pad {
pad[i] = ' '
}
first := true
if rows > 2*printed || cols > 2*printed {
first = false
fmt.Fprintf(fs, "Dims(%d, %d)\n", rows, cols)
}
skipZero := fs.Flag(' ')
for i := 0; i < rows; i++ {
if !first {
fmt.Fprint(fs, prefix)
}
first = false
var el string
switch {
case rows == 1:
fmt.Fprint(fs, "[")
el = "]"
case i == 0:
fmt.Fprint(fs, "⎡")
el = "⎤\n"
case i < rows-1:
fmt.Fprint(fs, "⎢")
el = "⎥\n"
default:
fmt.Fprint(fs, "⎣")
el = "⎦"
}
for j := 0; j < cols; j++ {
if j >= printed && j < cols-printed {
j = cols - printed - 1
if i == 0 || i == rows-1 {
fmt.Fprint(fs, "... ... ")
} else {
fmt.Fprint(fs, " ")
}
continue
}
v := m.At(i, j)
if v == 0 && skipZero {
buf = buf[:1]
buf[0] = dot
} else {
if c == 'v' {
buf = strconv.AppendFloat(buf[:0], v, 'g', prec, 64)
} else {
buf = strconv.AppendFloat(buf[:0], v, byte(c), prec, 64)
}
}
if fs.Flag('-') {
fs.Write(buf)
fs.Write(pad[:widths.width(j)-len(buf)])
} else {
fs.Write(pad[:widths.width(j)-len(buf)])
fs.Write(buf)
}
if j < cols-1 {
fs.Write(pad[:2])
}
}
fmt.Fprint(fs, el)
if i >= printed-1 && i < rows-printed && 2*printed < rows {
i = rows - printed - 1
fmt.Fprintf(fs, "%s .\n%[1]s .\n%[1]s .\n", prefix)
continue
}
}
}
// formatMATLAB prints a MATLAB representation of m to the fs io.Writer. The format character c
// specifies the numerical representation of elements; valid values are those for float64
// specified in the fmt package, with their associated flags.
// The printed range of the matrix can be limited by specifying a positive value for margin;
// If squeeze is true, column widths are determined on a per-column basis.
//
// formatMATLAB will not provide Go syntax output.
func formatMATLAB(m Matrix, prefix string, _ int, _ byte, squeeze bool, fs fmt.State, c rune) {
rows, cols := m.Dims()
prec, pOk := fs.Precision()
width, _ := fs.Width()
if !fs.Flag('#') {
switch c {
case 'v', 'e', 'E', 'f', 'F', 'g', 'G':
default:
fmt.Fprintf(fs, "%%!%c(%T=Dims(%d, %d))", c, m, rows, cols)
return
}
format := fmtString(fs, c, prec, width)
fs.Write([]byte{'['})
for i := 0; i < rows; i++ {
if i != 0 {
fs.Write([]byte("; "))
}
for j := 0; j < cols; j++ {
if j != 0 {
fs.Write([]byte{' '})
}
fmt.Fprintf(fs, format, m.At(i, j))
}
}
fs.Write([]byte{']'})
return
}
if !pOk {
prec = -1
}
printed := rows
if cols > printed {
printed = cols
}
var (
maxWidth int
widths widther
buf, pad []byte
)
if squeeze {
widths = make(columnWidth, cols)
} else {
widths = new(uniformWidth)
}
switch c {
case 'v', 'e', 'E', 'f', 'F', 'g', 'G':
if c == 'v' {
buf, maxWidth = maxCellWidth(m, 'g', printed, prec, widths)
} else {
buf, maxWidth = maxCellWidth(m, c, printed, prec, widths)
}
default:
fmt.Fprintf(fs, "%%!%c(%T=Dims(%d, %d))", c, m, rows, cols)
return
}
width = max(width, maxWidth)
pad = make([]byte, max(width, 1))
for i := range pad {
pad[i] = ' '
}
for i := 0; i < rows; i++ {
var el string
switch {
case rows == 1:
fmt.Fprint(fs, "[")
el = "]"
case i == 0:
fmt.Fprint(fs, "[\n"+prefix+" ")
el = "\n"
case i < rows-1:
fmt.Fprint(fs, prefix+" ")
el = "\n"
default:
fmt.Fprint(fs, prefix+" ")
el = "\n" + prefix + "]"
}
for j := 0; j < cols; j++ {
v := m.At(i, j)
if c == 'v' {
buf = strconv.AppendFloat(buf[:0], v, 'g', prec, 64)
} else {
buf = strconv.AppendFloat(buf[:0], v, byte(c), prec, 64)
}
if fs.Flag('-') {
fs.Write(buf)
fs.Write(pad[:widths.width(j)-len(buf)])
} else {
fs.Write(pad[:widths.width(j)-len(buf)])
fs.Write(buf)
}
if j < cols-1 {
fs.Write(pad[:1])
}
}
fmt.Fprint(fs, el)
}
}
// formatPython prints a Python representation of m to the fs io.Writer. The format character c
// specifies the numerical representation of elements; valid values are those for float64
// specified in the fmt package, with their associated flags.
// The printed range of the matrix can be limited by specifying a positive value for margin;
// If squeeze is true, column widths are determined on a per-column basis.
//
// formatPython will not provide Go syntax output.
func formatPython(m Matrix, prefix string, _ int, _ byte, squeeze bool, fs fmt.State, c rune) {
rows, cols := m.Dims()
prec, pOk := fs.Precision()
width, _ := fs.Width()
if !fs.Flag('#') {
switch c {
case 'v', 'e', 'E', 'f', 'F', 'g', 'G':
default:
fmt.Fprintf(fs, "%%!%c(%T=Dims(%d, %d))", c, m, rows, cols)
return
}
format := fmtString(fs, c, prec, width)
fs.Write([]byte{'['})
if rows > 1 {
fs.Write([]byte{'['})
}
for i := 0; i < rows; i++ {
if i != 0 {
fs.Write([]byte("], ["))
}
for j := 0; j < cols; j++ {
if j != 0 {
fs.Write([]byte(", "))
}
fmt.Fprintf(fs, format, m.At(i, j))
}
}
if rows > 1 {
fs.Write([]byte{']'})
}
fs.Write([]byte{']'})
return
}
if !pOk {
prec = -1
}
printed := rows
if cols > printed {
printed = cols
}
var (
maxWidth int
widths widther
buf, pad []byte
)
if squeeze {
widths = make(columnWidth, cols)
} else {
widths = new(uniformWidth)
}
switch c {
case 'v', 'e', 'E', 'f', 'F', 'g', 'G':
if c == 'v' {
buf, maxWidth = maxCellWidth(m, 'g', printed, prec, widths)
} else {
buf, maxWidth = maxCellWidth(m, c, printed, prec, widths)
}
default:
fmt.Fprintf(fs, "%%!%c(%T=Dims(%d, %d))", c, m, rows, cols)
return
}
width = max(width, maxWidth)
pad = make([]byte, max(width, 1))
for i := range pad {
pad[i] = ' '
}
for i := 0; i < rows; i++ {
if i != 0 {
fmt.Fprint(fs, prefix)
}
var el string
switch {
case rows == 1:
fmt.Fprint(fs, "[")
el = "]"
case i == 0:
fmt.Fprint(fs, "[[")
el = "],\n"
case i < rows-1:
fmt.Fprint(fs, " [")
el = "],\n"
default:
fmt.Fprint(fs, " [")
el = "]]"
}
for j := 0; j < cols; j++ {
v := m.At(i, j)
if c == 'v' {
buf = strconv.AppendFloat(buf[:0], v, 'g', prec, 64)
} else {
buf = strconv.AppendFloat(buf[:0], v, byte(c), prec, 64)
}
if fs.Flag('-') {
fs.Write(buf)
fs.Write(pad[:widths.width(j)-len(buf)])
} else {
fs.Write(pad[:widths.width(j)-len(buf)])
fs.Write(buf)
}
if j < cols-1 {
fs.Write([]byte{','})
fs.Write(pad[:1])
}
}
fmt.Fprint(fs, el)
}
}
// This is horrible, but it's what we have.
func fmtString(fs fmt.State, c rune, prec, width int) string {
var b strings.Builder
b.WriteByte('%')
for _, f := range "0+- " {
if fs.Flag(int(f)) {
b.WriteByte(byte(f))
}
}
if width >= 0 {
fmt.Fprint(&b, width)
}
if prec >= 0 {
b.WriteByte('.')
if prec > 0 {
fmt.Fprint(&b, prec)
}
}
b.WriteRune(c)
return b.String()
}
func maxCellWidth(m Matrix, c rune, printed, prec int, w widther) ([]byte, int) {
var (
buf = make([]byte, 0, 64)
rows, cols = m.Dims()
max int
)
for i := 0; i < rows; i++ {
if i >= printed-1 && i < rows-printed && 2*printed < rows {
i = rows - printed - 1
continue
}
for j := 0; j < cols; j++ {
if j >= printed && j < cols-printed {
continue
}
buf = strconv.AppendFloat(buf, m.At(i, j), byte(c), prec, 64)
if len(buf) > max {
max = len(buf)
}
if len(buf) > w.width(j) {
w.setWidth(j, len(buf))
}
buf = buf[:0]
}
}
return buf, max
}
type widther interface {
width(i int) int
setWidth(i, w int)
}
type uniformWidth int
func (u *uniformWidth) width(_ int) int { return int(*u) }
func (u *uniformWidth) setWidth(_, w int) { *u = uniformWidth(w) }
type columnWidth []int
func (c columnWidth) width(i int) int { return c[i] }
func (c columnWidth) setWidth(i, w int) { c[i] = w }
|