forked from ardanlabs/python-go
-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
252 lines (216 loc) · 6.77 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/christian-korneck/go-python3"
)
//detect wraps around the detect() function from the given Python module. Borrows the PyObject reference.
func detect(module *python3.PyObject, data []float64) ([]int, error) {
pylist := python3.PyList_New(len(data)) //retval: New reference, gets stolen later
for i := 0; i < len(data); i++ {
item := python3.PyFloat_FromDouble(data[i]) //retval: New reference, gets stolen later
ret := python3.PyList_SetItem(pylist, i, item)
if ret != 0 {
if python3.PyErr_Occurred() != nil {
python3.PyErr_Print()
}
item.DecRef()
pylist.DecRef()
return nil, fmt.Errorf("error setting list item")
}
}
args := python3.PyTuple_New(1) //retval: New reference
if args == nil {
pylist.DecRef()
return nil, fmt.Errorf("error creating args tuple")
}
defer args.DecRef()
ret := python3.PyTuple_SetItem(args, 0, pylist) //steals ref to pylist
pylist = nil
if ret != 0 {
if python3.PyErr_Occurred() != nil {
python3.PyErr_Print()
}
pylist.DecRef()
pylist = nil
return nil, fmt.Errorf("error setting args tuple item")
}
oDict := python3.PyModule_GetDict(module) //retval: Borrowed
if !(oDict != nil && python3.PyErr_Occurred() == nil) {
python3.PyErr_Print()
return nil, fmt.Errorf("could not get dict for module")
}
detect := python3.PyDict_GetItemString(oDict, "detect")
if !(detect != nil && python3.PyCallable_Check(detect)) { //retval: Borrowed
return nil, fmt.Errorf("could not find function 'detect'")
}
detectdataPy := detect.CallObject(args)
if !(detectdataPy != nil && python3.PyErr_Occurred() == nil) { //retval: New reference
python3.PyErr_Print()
return nil, fmt.Errorf("error calling function detect")
}
defer detectdataPy.DecRef()
outliers, err := goSliceFromPylist(detectdataPy, "int", false)
if err != nil {
return nil, fmt.Errorf("error converting pylist to go list: %s", err)
}
return outliers.([]int), nil
}
//goSliceFromPylist converts a []float64 pylist to a go list. Borrows the PyObject reference.
func goSliceFromPylist(pylist *python3.PyObject, itemtype string, strictfail bool) (interface{}, error) {
seq := pylist.GetIter() //ret val: New reference
if !(seq != nil && python3.PyErr_Occurred() == nil) {
python3.PyErr_Print()
return nil, fmt.Errorf("error creating iterator for list")
}
defer seq.DecRef()
tNext := seq.GetAttrString("__next__") //ret val: new ref
if !(tNext != nil && python3.PyCallable_Check(tNext)) {
return nil, fmt.Errorf("iterator has no __next__ function")
}
defer tNext.DecRef()
var golist interface{}
var compare *python3.PyObject
switch itemtype {
case "float64":
golist = []float64{}
compare = python3.PyFloat_FromDouble(0)
case "int":
golist = []int{}
compare = python3.PyLong_FromGoInt(0)
}
if compare == nil {
return nil, fmt.Errorf("error creating compare var")
}
defer compare.DecRef()
pytype := compare.Type() //ret val: new ref
if pytype == nil && python3.PyErr_Occurred() != nil {
python3.PyErr_Print()
return nil, fmt.Errorf("error getting type of compare var")
}
defer pytype.DecRef()
errcnt := 0
pylistLen := pylist.Length()
if pylistLen == -1 {
return nil, fmt.Errorf("error getting list length")
}
for i := 1; i <= pylistLen; i++ {
item := tNext.CallObject(nil) //ret val: new ref
if item == nil && python3.PyErr_Occurred() != nil {
python3.PyErr_Print()
return nil, fmt.Errorf("error getting next item in sequence")
}
itemType := item.Type()
if itemType == nil && python3.PyErr_Occurred() != nil {
python3.PyErr_Print()
return nil, fmt.Errorf("error getting item type")
}
defer itemType.DecRef()
if itemType != pytype {
//item has wrong type, skip it
if item != nil {
item.DecRef()
}
errcnt++
continue
}
switch itemtype {
case "float64":
itemGo := python3.PyFloat_AsDouble(item)
if itemGo != -1 && python3.PyErr_Occurred() == nil {
golist = append(golist.([]float64), itemGo)
} else {
if item != nil {
item.DecRef()
}
errcnt++
}
case "int":
itemGo := python3.PyLong_AsLong(item)
if itemGo != -1 && python3.PyErr_Occurred() == nil {
golist = append(golist.([]int), itemGo)
} else {
if item != nil {
item.DecRef()
}
errcnt++
}
}
if item != nil {
item.DecRef()
item = nil
}
}
if errcnt > 0 {
if strictfail {
return nil, fmt.Errorf("could not add %d values (wrong type?)", errcnt)
}
}
return golist, nil
}
//genTestdata wraps around the gen_testdata() function from the given Python module. Borrows the PyObject reference.
func genTestdata(module *python3.PyObject) ([]float64, error) {
oDict := python3.PyModule_GetDict(module) //ret val: Borrowed
if !(oDict != nil && python3.PyErr_Occurred() == nil) {
python3.PyErr_Print()
return nil, fmt.Errorf("could not get dict for module")
}
genTestdata := python3.PyDict_GetItemString(oDict, "gen_testdata") //retval: Borrowed
if !(genTestdata != nil && python3.PyCallable_Check(genTestdata)) {
return nil, fmt.Errorf("could not find function 'gen_testdata'")
}
testdataPy := genTestdata.CallObject(nil) //retval: New reference
if !(testdataPy != nil && python3.PyErr_Occurred() == nil) {
python3.PyErr_Print()
return nil, fmt.Errorf("error calling function gen_testdata")
}
defer testdataPy.DecRef()
testdataGo, err := goSliceFromPylist(testdataPy, "float64", false)
if err != nil {
return nil, fmt.Errorf("error converting pylist to go list: %s", err)
}
return testdataGo.([]float64), nil
}
func demo(module *python3.PyObject) {
testdata, err := genTestdata(module)
if err != nil {
log.Fatalf("Error getting testdata: %s", err)
}
outliers, err := detect(module, testdata)
if err != nil {
log.Fatalf("Error detecting outliers: %s", err)
}
fmt.Println(outliers)
}
func main() {
defer python3.Py_Finalize()
python3.Py_Initialize()
if !python3.Py_IsInitialized() {
fmt.Println("Error initializing the python interpreter")
os.Exit(1)
}
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
// we could also use PySys_GetObject("path") + PySys_SetPath,
//but this is easier (at the cost of less flexible error handling)
ret := python3.PyRun_SimpleString("import sys\nsys.path.append(\"" + dir + "\")")
if ret != 0 {
log.Fatalf("error appending '%s' to python sys.path", dir)
}
oImport := python3.PyImport_ImportModule("pyoutliers") //ret val: new ref
if !(oImport != nil && python3.PyErr_Occurred() == nil) {
python3.PyErr_Print()
log.Fatal("failed to import module 'pyoutliers'")
}
defer oImport.DecRef()
oModule := python3.PyImport_AddModule("pyoutliers") //ret val: borrowed ref (from oImport)
if !(oModule != nil && python3.PyErr_Occurred() == nil) {
python3.PyErr_Print()
log.Fatal("failed to add module 'pyoutliers'")
}
demo(oModule)
}