| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"io" |
| 5 |
"text/template" |
| 6 |
) |
| 7 |
|
| 8 |
const onesRaw = `// Ones creates a *Dense with the provided shape and type |
| 9 |
func Ones(dt Dtype, shape ...int) *Dense { |
| 10 |
d := recycledDense(dt, shape) |
| 11 |
switch d.t.Kind() { |
| 12 |
{{range .Kinds -}} |
| 13 |
{{if isNumber . -}} |
| 14 |
case reflect.{{reflectKind .}}: |
| 15 |
d.Memset({{asType .}}(1)) |
| 16 |
{{end -}} |
| 17 |
{{end -}} |
| 18 |
case reflect.Bool: |
| 19 |
d.Memset(true) |
| 20 |
default: |
| 21 |
// TODO: add a Oner interface |
| 22 |
} |
| 23 |
return d |
| 24 |
} |
| 25 |
` |
| 26 |
|
| 27 |
const Iraw = `// I creates the identity matrix (usually a square) matrix with 1s across the diagonals, and zeroes elsewhere, like so: |
| 28 |
// Matrix(4,4) |
| 29 |
// ⎡1 0 0 0⎤ |
| 30 |
// ⎢0 1 0 0⎥ |
| 31 |
// ⎢0 0 1 0⎥ |
| 32 |
// ⎣0 0 0 1⎦ |
| 33 |
// While technically an identity matrix is a square matrix, in attempt to keep feature parity with Numpy, |
| 34 |
// the I() function allows you to create non square matrices, as well as an index to start the diagonals. |
| 35 |
// |
| 36 |
// For example: |
| 37 |
// T = I(Float64, 4, 4, 1) |
| 38 |
// Yields: |
| 39 |
// ⎡0 1 0 0⎤ |
| 40 |
// ⎢0 0 1 0⎥ |
| 41 |
// ⎢0 0 0 1⎥ |
| 42 |
// ⎣0 0 0 0⎦ |
| 43 |
// |
| 44 |
// The index k can also be a negative number: |
| 45 |
// T = I(Float64, 4, 4, -1) |
| 46 |
// Yields: |
| 47 |
// ⎡0 0 0 0⎤ |
| 48 |
// ⎢1 0 0 0⎥ |
| 49 |
// ⎢0 1 0 0⎥ |
| 50 |
// ⎣0 0 1 0⎦ |
| 51 |
func I(dt Dtype, r, c, k int) *Dense{ |
| 52 |
ret := New(Of(dt), WithShape(r,c)) |
| 53 |
i := k |
| 54 |
if k < 0 { |
| 55 |
i = (-k) * c |
| 56 |
} |
| 57 |
|
| 58 |
var s *Dense |
| 59 |
var err error |
| 60 |
end := c - k |
| 61 |
if end > r { |
| 62 |
s, err = sliceDense(ret, nil) |
| 63 |
} else { |
| 64 |
s, err = sliceDense(ret, rs{0, end, 1}) |
| 65 |
} |
| 66 |
|
| 67 |
if err != nil { |
| 68 |
panic(err) |
| 69 |
} |
| 70 |
var nexts []int |
| 71 |
iter := newFlatIterator(&s.AP) |
| 72 |
nexts, err = iter.Slice(rs{i, s.Size(), c + 1}) |
| 73 |
|
| 74 |
switch s.t.Kind() { |
| 75 |
{{range .Kinds -}} |
| 76 |
{{if isNumber . -}} |
| 77 |
case reflect.{{reflectKind .}}: |
| 78 |
data := s.{{sliceOf .}} |
| 79 |
for _, v := range nexts { |
| 80 |
data[v] = 1 |
| 81 |
} |
| 82 |
{{end -}} |
| 83 |
{{end -}} |
| 84 |
} |
| 85 |
// TODO: create Oner interface for custom types |
| 86 |
return ret |
| 87 |
} |
| 88 |
` |
| 89 |
|
| 90 |
var ( |
| 91 |
ones *template.Template |
| 92 |
eye *template.Template |
| 93 |
) |
| 94 |
|
| 95 |
func init() { |
| 96 |
ones = template.Must(template.New("ones").Funcs(funcs).Parse(onesRaw)) |
| 97 |
eye = template.Must(template.New("eye").Funcs(funcs).Parse(Iraw)) |
| 98 |
} |
| 99 |
|
| 100 |
func generateDenseConstructionFns(f io.Writer, generic Kinds) { |
| 101 |
ones.Execute(f, generic) |
| 102 |
eye.Execute(f, generic) |
| 103 |
} |