/
main.go
306 lines (278 loc) · 8.63 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
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
// Copyright 2017 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// root2npy converts the content of a ROOT TTree to a NumPy data file.
//
// Usage of root2npy:
// -f string
// path to input ROOT file name
// -o string
// path to output npz file name (default "output.npz")
// -t string
// name of the tree to convert (default "tree")
//
// The NumPy data file format is described here:
//
// https://numpy.org/neps/nep-0001-npy-format.html
//
// Example:
//
// $> root2npy -f $GOPATH/src/go-hep.org/x/hep/groot/testdata/simple.root -t tree -o output.npz
// $> python2 -c 'import sys, numpy as np; print(dict(np.load(sys.argv[1])))' ./output.npz
// {'one': array([1, 2, 3, 4], dtype=int32),
// 'two': array([ 1.10000002, 2.20000005, 3.29999995, 4.4000001 ], dtype=float32),
// 'three': array([u'uno', u'dos', u'tres', u'quatro'], dtype='<U6')}
//
// $> python3 -c 'import sys, numpy as np; print(dict(np.load(sys.argv[1])))' ./output.npz
// {'one': array([1, 2, 3, 4], dtype=int32),
// 'two': array([ 1.10000002, 2.20000005, 3.29999995, 4.4000001 ], dtype=float32),
// 'three': array(['uno', 'dos', 'tres', 'quatro'], dtype='<U6')}
//
// $> go get github.com/sbinet/npyio/cmd/npyio-ls
// $> npyio-ls ./output.npz
// ================================================================================
// file: ./output.npz
// entry: one
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<i4, Fortran:false, Shape:[4]}}
// data = [1 2 3 4]
//
// entry: two
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<f4, Fortran:false, Shape:[4]}}
// data = [1.1 2.2 3.3 4.4]
//
// entry: three
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<U6, Fortran:false, Shape:[4]}}
// data = [uno dos tres quatro]
//
// $> root-ls -t $GOPATH/src/go-hep.org/x/hep/groot/testdata/simple.root
// === [$GOPATH/src/go-hep.org/x/hep/groot/testdata/simple.root] ===
// version: 60600
// TTree tree fake data (entries=4)
// one "one/I" TBranch
// two "two/F" TBranch
// three "three/C" TBranch
//
// If you have a 10-events tree with a branch "doubles" containing an array of 3 float64,
// root2npy will convert it to a NumPy data file containing a NumPy array with a shape (10,3).
//
// Example:
//
// $> root-ls -t $GOPATH/src/go-hep.org/x/hep/groot/testdata/small-flat-tree.root
// === [$GOPATH/src/go-hep.org/x/hep/groot/testdata/small-flat-tree.root] ===
// version: 60806
// TTree tree my tree title (entries=100)
// Int32 "Int32/I" TBranch
// Int64 "Int64/L" TBranch
// UInt32 "UInt32/i" TBranch
// UInt64 "UInt64/l" TBranch
// Float32 "Float32/F" TBranch
// Float64 "Float64/D" TBranch
// Str "Str/C" TBranch
// ArrayInt32 "ArrayInt32[10]/I" TBranch
// ArrayInt64 "ArrayInt64[10]/L" TBranch
// ArrayUInt32 "ArrayInt32[10]/i" TBranch
// ArrayUInt64 "ArrayInt64[10]/l" TBranch
// ArrayFloat32 "ArrayFloat32[10]/F" TBranch
// ArrayFloat64 "ArrayFloat64[10]/D" TBranch
// N "N/I" TBranch
// SliceInt32 "SliceInt32[N]/I" TBranch
// SliceInt64 "SliceInt64[N]/L" TBranch
// SliceUInt32 "SliceInt32[N]/i" TBranch
// SliceUInt64 "SliceInt64[N]/l" TBranch
// SliceFloat32 "SliceFloat32[N]/F" TBranch
// SliceFloat64 "SliceFloat64[N]/D" TBranch
//
// $> root2npy $GOPATH/src/go-hep.org/x/hep/groot/testdata/small-flat-tree.root
// root2npy: scanning leaves...
// root2npy: >>> "SliceInt32" []int32 not supported
// root2npy: >>> "SliceInt64" []int64 not supported
// root2npy: >>> "SliceInt32" []int32 not supported
// root2npy: >>> "SliceInt64" []int64 not supported
// root2npy: >>> "SliceFloat32" []float32 not supported
// root2npy: >>> "SliceFloat64" []float64 not supported
// root2npy: scanning leaves... [done]
//
// $> npyio-ls ./output.npz
// ================================================================================
// file: ./output.npz
// entry: Int32
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<i4, Fortran:false, Shape:[100]}}
// data = [0 1 2 3 4 5 6 7 8 9 10 11 ... 90 91 92 93 94 95 96 97 98 99]
//
// entry: Int64
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<i8, Fortran:false, Shape:[100]}}
// data = [0 1 2 3 4 5 6 7 8 9 10 11 ... 90 91 92 93 94 95 96 97 98 99]
//
// [...]
//
// entry: Float64
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<f8, Fortran:false, Shape:[100]}}
// data = [0 1 2 3 4 5 6 7 8 9 10 11 ... 90 91 92 93 94 95 96 97 98 99]
//
// entry: Str
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<U7, Fortran:false, Shape:[100]}}
// data = [evt-000 evt-001 evt-002 evt-003 evt-004 evt-005 evt-006 evt-007 ...
// evt-092 evt-093 evt-094 evt-095 evt-096 evt-097 evt-098 evt-099]
//
// entry: ArrayInt32
// npy-header: Header{Major:2, Minor:0, Descr:{Type:<i4, Fortran:false, Shape:[100 10]}}
// data = [0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 ...
// ... 97 98 98 98 98 98 98 98 98 98 98 99 99 99 99 99 99 99 99 99 99]
//
// [...]
//
package main
import (
"archive/zip"
"bytes"
"flag"
"io"
"log"
"os"
"reflect"
"github.com/sbinet/npyio"
"go-hep.org/x/hep/groot"
_ "go-hep.org/x/hep/groot/riofs/plugin/http"
_ "go-hep.org/x/hep/groot/riofs/plugin/xrootd"
"go-hep.org/x/hep/groot/rtree"
)
func main() {
log.SetPrefix("root2npy: ")
log.SetFlags(0)
fname := flag.String("f", "", "path to input ROOT file name")
oname := flag.String("o", "output.npz", "path to output npz file name")
tname := flag.String("t", "tree", "name of the tree to convert")
flag.Parse()
if *fname == "" {
flag.Usage()
log.Fatalf("missing input ROOT filename argument")
}
f, err := groot.Open(*fname)
if err != nil {
log.Fatal(err)
}
defer f.Close()
obj, err := f.Get(*tname)
if err != nil {
log.Fatal(err)
}
tree, ok := obj.(rtree.Tree)
if !ok {
log.Fatalf("object %q in file %q is not a rtree.Tree", *tname, *fname)
}
var nt = ntuple{n: tree.Entries()}
log.Printf("scanning leaves...")
for _, leaf := range tree.Leaves() {
if leaf.Kind() == reflect.String {
nt.add(leaf.Name(), leaf)
continue
}
if leaf.Class() == "TLeafElement" { // FIXME(sbinet): find a better, type-safe way
log.Printf(">>> %q %v not supported", leaf.Name(), leaf.Class())
continue
}
if leaf.LeafCount() != nil {
log.Printf(">>> %q []%v not supported", leaf.Name(), leaf.TypeName())
continue
}
nt.add(leaf.Name(), leaf)
}
log.Printf("scanning leaves... [done]")
sc, err := rtree.NewTreeScannerVars(tree, nt.args...)
if err != nil {
log.Fatal(err)
}
defer sc.Close()
for sc.Next() {
err = sc.Scan(nt.vars...)
if err != nil {
log.Fatal(err)
}
nt.fill()
}
out, err := os.Create(*oname)
if err != nil {
log.Fatal(err)
}
defer out.Close()
npz := zip.NewWriter(out)
defer npz.Close()
work := make([]byte, 1*1024*1024)
for _, col := range nt.cols {
buf := new(bytes.Buffer)
err = npyio.Write(buf, col.slice.Interface())
if err != nil {
log.Fatalf("error writing %q: %v\n", col.name, err)
}
wz, err := npz.Create(col.name)
if err != nil {
log.Fatalf("error creating %q: %v\n", col.name, err)
}
_, err = io.CopyBuffer(wz, buf, work)
if err != nil {
log.Fatal(err)
}
}
err = npz.Flush()
if err != nil {
log.Fatal(err)
}
err = npz.Close()
if err != nil {
log.Fatal(err)
}
err = out.Close()
if err != nil {
log.Fatal(err)
}
}
type ntuple struct {
n int64
cols []column
args []rtree.ScanVar
vars []interface{}
}
func (nt *ntuple) add(name string, leaf rtree.Leaf) {
n := len(nt.cols)
nt.cols = append(nt.cols, newColumn(name, leaf, nt.n))
col := &nt.cols[n]
nt.args = append(nt.args, rtree.ScanVar{Name: name, Leaf: leaf.Name()})
nt.vars = append(nt.vars, col.data.Addr().Interface())
}
func (nt *ntuple) fill() {
for i := range nt.cols {
col := &nt.cols[i]
col.fill()
}
}
type column struct {
name string
i int64
leaf rtree.Leaf
etype reflect.Type
shape []int
data reflect.Value
slice reflect.Value
}
func newColumn(name string, leaf rtree.Leaf, n int64) column {
etype := leaf.Type()
shape := []int{int(n)}
if leaf.Len() > 1 && leaf.Kind() != reflect.String {
etype = reflect.ArrayOf(leaf.Len(), etype)
shape = append(shape, leaf.Len())
}
rtype := reflect.SliceOf(etype)
return column{
name: name,
i: 0,
leaf: leaf,
etype: etype,
shape: shape,
data: reflect.New(etype).Elem(),
slice: reflect.MakeSlice(rtype, int(n), int(n)),
}
}
func (col *column) fill() {
col.slice.Index(int(col.i)).Set(col.data)
col.i++
}