File: bcols.tmpl

package info (click to toggle)
golang-github-kshedden-dstream 0.0~git20190512.c4c4106-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 596 kB
  • sloc: makefile: 30
file content (279 lines) | stat: -rw-r--r-- 6,883 bytes parent folder | download
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
package dstream

import (
    "encoding/json"
    "encoding/binary"
    "compress/gzip"
    "bufio"
    "strings"
    "io"
    "io/ioutil"
    "fmt"
    "os"
    "path"
    "time"
    "github.com/golang/snappy"
)

func (b *bcols) init() {

    // Prepare to read the dtypes structure
	fname := path.Join(b.bpath, "dtypes.json")
	fid, err := os.Open(fname)
	if err != nil {
		panic(err)
	}
    defer fid.Close()
    dec := json.NewDecoder(fid)

    // Dtypes for all variables
	b.dtypesAll = make(map[string]string)
	err = dec.Decode(&b.dtypesAll)
	if err != nil {
		panic(err)
	}

    // Names of variables to be used
    usenames := b.usenames()
    b.names = usenames

    // Dtypes for variables to be used
    dtypes := make(map[string]string)
    for _, na := range usenames {
    	dtypes[na] = b.dtypesAll[na]
    }
	b.dtypes = dtypes

	// Map from variable names to file names
	fi, err := ioutil.ReadDir(b.bpath)
	if err != nil {
		panic(err)
	}
	vf := make(map[string]string)
	for _, v := range fi {
		na := strings.Split(v.Name(), ".")[0]
		vf[na] = v.Name()
	}

	b.namepos = make(map[string]int)
	for k, na := range b.names {
        b.namepos[na] = k
    }

	b.bdata = b.bdata[0:0]

	for _, na := range b.names {

        // Create concrete types to hold the data
        switch b.dtypes[na] {

            // Standard dtypes
            {{- range . }}
                case "{{ .Type }}":
	                var x []{{ .Type }}
		            b.bdata = append(b.bdata, x)
            {{- end }}

            // Additional dtypes
	        case "uvarint":
	            var x []uint64
		        b.bdata = append(b.bdata, x)
	        case "varint":
	            var x []int64
		        b.bdata = append(b.bdata, x)
            case "default":
	            panic("bcols.init: unknown type")
        }

		fn, ok := vf[na]
		if !ok {
			msg := fmt.Sprintf("bcols.init: can't find variable %s in %s\n", na, b.bpath)
			os.Stderr.Write([]byte(msg))
			os.Exit(1)
		}

		if strings.HasSuffix(fn, ".bin.gz") {
			// gzip compression
			s := path.Join(b.bpath, fn)
			fid, err := os.Open(s)
			if err != nil {
				panic(err)
			}
			b.toclose = append(b.toclose, fid)
			gid, err := gzip.NewReader(fid)
			if err != nil {
				panic(err)
			}
			b.toclose = append(b.toclose, gid)
            bid := bufio.NewReader(gid) // adds ReadByte
			b.toclose = append(b.toclose, gid)
	        b.rdrs = append(b.rdrs, bid)
		} else if strings.HasSuffix(fn, ".bin.sz") {
			// Snappy compression
			s := path.Join(b.bpath, fn)
			fid, err := os.Open(s)
			if err != nil {
				panic(err)
			}
			b.toclose = append(b.toclose, fid)
			gid := snappy.NewReader(fid)
			bid := bufio.NewReader(gid) // adds ReadByte
	        b.rdrs = append(b.rdrs, bid)
		} else {
			panic("compression type not recognized")
		}
	}

    b.doneInit = true
}

func (b *bcols) Next() bool {

    if !b.doneInit {
        panic("Call Done before using stream")
    }

    if b.done {
        return false
    }

   	truncate(b.bdata)

    for j, na := range b.names {
        rdr := b.rdrs[j]

    	// Handle variable-width data
        if b.dtypes[na] == "varint" {
	        var v []int64
            for k := 0; k < b.chunksize; k++ {
		        var x int64
			    x, err := binary.ReadVarint(rdr)
			    if err == io.EOF {
                    b.done = true
				    break
                } else if err != nil {
			        msg := fmt.Sprintf("Error reading variable '%s' at position %d\n", na, b.nobs)
				    print(msg)
                       panic(err)
                }
			    v = append(v, x)
			    if j == 0 {
			        b.nobs++
			    }
            }
		    b.bdata[j] = v
            continue
        } else if b.dtypes[na] == "uvarint" {
	        var v []uint64
            for k := 0; k<b.chunksize; k++ {
		        var x uint64
			    x, err := binary.ReadUvarint(rdr)
			    if err == io.EOF {
			        b.done = true
				    break
			    } else if err != nil {
			        msg := fmt.Sprintf("Error reading variable '%s' at position %d\n", na, b.nobs)
				    print(msg)
                    panic(err)
                }
			    v = append(v, x)
			    if j == 0 {
			        b.nobs++
			    }
            }
		    b.bdata[j] = v
               continue
        }

        // Handle fixed-width data
        switch v := b.bdata[j].(type) {
            {{- range . }}
		        case []{{ .Type }}:
                    for k := 0; k<b.chunksize; k++ {
                        var x {{ .Type }}
                        {{- if eq .Type "string"}}
                            y, isprefix, err := rdr.ReadLine()
                            if isprefix {
                            	panic("buffer overflow")
                            }
                            x = string(y)
                        {{- else }}
			                err := binary.Read(rdr, binary.LittleEndian, &x)
			            {{- end }}
			            if err == io.EOF {
                            b.done = true
			                break
                        } else if err != nil {
          				    msg := fmt.Sprintf("Error reading variable '%s' at position %d\n", na, b.nobs)
	         				print(msg)
                            panic(err)
                        }
			            v = append(v, x)
					    if j == 0 {
					        b.nobs++
                        }
                    }
				    b.bdata[j] = v
            {{- end }}
        }
    }

    return true
}

func (bw *BColsWriter) writeDtypes() {

    dtypes := make(map[string]string)

    bw.stream.Reset()
    names := bw.stream.Names()
    bw.stream.Next()
    for j, na := range names {
        u := bw.stream.GetPos(j)
        switch u.(type) {
            {{- range . }}
	           case []{{ .Type }}:
               dtypes[na] = "{{ .Type }}"
            {{- end }}
        }
    }

    f, err := os.Create(path.Join(bw.path, "dtypes.json"))
    if err != nil {
        panic(err)
    }
    defer f.Close()
    enc := json.NewEncoder(f)
    enc.Encode(dtypes)
}

func (bw *BColsWriter) write() {

	bw.stream.Reset()
	names := bw.stream.Names()

	for bw.stream.Next() {
	    for j := range names {
	        u := bw.stream.GetPos(j)
            switch u.(type) {
                {{- range . }}
                    case []{{ .Type }}:
                    v := u.([]{{ .Type }})
                    {{- if eq .Type "string" }}
                        for _, x := range v {
                            _, err := bw.wtrs[j].Write([]byte(x + "\n"))
						    if err != nil {
                                panic(err)
                            }
                        }
                    {{- else }}
                        err := binary.Write(bw.wtrs[j], binary.LittleEndian, &v)
                        if err != nil {
                            panic(err)
                        }
                    {{- end }}
                {{- end }}
            }
	    }
	}
}