-
Notifications
You must be signed in to change notification settings - Fork 2
/
dmatrix.go
120 lines (105 loc) · 2.22 KB
/
dmatrix.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
package treelite
// #cgo LDFLAGS: -ltreelite -ltreelite_runtime
// #include <stdlib.h>
// #include "treelite/c_api.h"
// #include "treelite/c_api_common.h"
// #include "treelite/c_api_runtime.h"
import "C"
import (
"errors"
"unsafe"
)
var (
errCreateDMatrixHandle = errors.New("create dmatrix failed")
errFreeDMatrix = errors.New("free dmatrix failed")
)
// DMatrix is treelite DMatrix
type DMatrix struct {
pointer C.DMatrixHandle
row int
col int
element int
}
// CreateFromMat creates a dense DMatrix from the given data
func CreateFromMat(
data []float32,
nrow, ncol int,
missing float32,
) (*DMatrix, error) {
var handle C.DMatrixHandle
ret := C.TreeliteDMatrixCreateFromMat(
unsafe.Pointer(&data[0]),
C.CString("float32"),
C.ulong(nrow),
C.ulong(ncol),
unsafe.Pointer(&missing),
&handle,
)
if C.int(ret) == -1 {
return nil, errCreateDMatrixHandle
}
return &DMatrix{
pointer: handle,
row: nrow,
col: ncol,
element: len(data),
}, nil
}
// CreateFromCSR creates a sparse DMatrix from the given data
func CreateFromCSR(
header []uint64,
indices []uint32,
data []float32,
nrow, ncol int,
) (*DMatrix, error) {
var handle C.DMatrixHandle
ret := C.TreeliteDMatrixCreateFromCSR(
unsafe.Pointer(&data[0]),
C.CString("float32"),
(*C.uint)(&indices[0]),
(*C.ulong)(&header[0]),
C.ulong(nrow),
C.ulong(ncol),
&handle,
)
if C.int(ret) == -1 {
return nil, errCreateDMatrixHandle
}
var row, col, element uint64
// CSR format removes zero element
ret = C.TreeliteDMatrixGetDimension(
handle,
(*C.ulong)(&row),
(*C.ulong)(&col),
(*C.ulong)(&element),
)
if C.int(ret) == -1 {
return nil, errCreateDMatrixHandle
}
return &DMatrix{
pointer: handle,
row: nrow,
col: ncol,
element: int(element),
}, nil
}
// Close frees internally allocated memory
func (d *DMatrix) Close() error {
ret := C.TreeliteDMatrixFree(d.pointer)
if C.int(ret) == -1 {
return errFreeDMatrix
}
return nil
}
// Col returns the number of columns
func (d DMatrix) Col() int {
return d.col
}
// Row returns the number of rows
func (d DMatrix) Row() int {
return d.row
}
// Element returns the number of internal elements
func (d DMatrix) Element() int {
return d.element
}