Debian Codegraph @

dstream/streamcsv.go

raw symbols SCIP
1 package dstream
2
3 import (
4 "encoding/csv"
5 "errors"
6 "fmt"
7 "io"
8 "os"
9 "time"
10 )
11
12 // CSVReader supports reading a Dstream from an io.Reader.
13 type CSVReader struct {
14
15 // The reader for the file
16 rdr io.Reader
17
18 // The csv reader that parses the raw text
19 csvrdr *csv.Reader
20
21 // bdata holds the data
22 bdata []interface{}
23
24 // We need to read the first row to get the number of columns.
25 // or the header. We can then store it here so that it is
26 // included in the first data chunk.
27 firstrow []string
28
29 // If true, skip records with unparseable CSV data, otherwise
30 // panic on them.
31 skipErrors bool
32
33 // The record separator, passed to csv.Reader
34 comma rune
35
36 // The number of records to read at once
37 chunkSize int
38
39 // The number of variables
40 nvar int
41
42 // The number of observations, not known until reading is complete
43 nobs int
44
45 // If true, the first row of the data file is a header (contains column names)
46 hasheader bool
47
48 // doneInit becomes true after init is called
49 doneinit bool
50
51 // done becomes true after configuration is complete
52 done bool
53
54 // Index of current chunk
55 chunknum int
56
57 // If limitchunk > 0, read only this many chunks, otherwise read all chunks.
58 limitchunk int
59
60 // Map from variable names to column positions in the dstream
61 namepos map[string]int
62
63 // Map from variable names to column positions in the file
64 filenamepos map[string]int
65
66 // The positions in the file of the variables in the dstream, in dstream order
67 filepos []int
68
69 // The names of the dstream variables
70 names []string
71
72 // The variable name/type structs, provided by the caller
73 types []VarType
74
75 // The variable types
76 dtypes []Dtype
77
78 // A function for parsing time values
79 parseTime func(string) time.Time
80 }
81
82 // VarType defines the name and type of one column of the CSV file.
83 type VarType struct {
84
85 // The variable name
86 Name string
87
88 // The data type of the variable
89 Type Dtype
90 }
91
92 // FromCSV returns a Dstream that reads from a CSV source. Call at
93 // least one SetXX method to define variables to be retrieved. For
94 // further configuration, chain calls to other SetXXX methods, and
95 // finally call Done to produce the Dstream.
96 func FromCSV(r io.Reader) *CSVReader {
97
98 dr := &CSVReader{
99 rdr: r,
100 }
101
102 return dr
103 }
104
105 // ParseTime sets the time parsing function./
106 func (cs *CSVReader) ParseTime(f func(string) time.Time) *CSVReader {
107 cs.parseTime = f
108 return cs
109 }
110
111 // Done is called when all configuration is complete. After calling
112 // Done, the DStream can be used.
113 func (cs *CSVReader) Done() Dstream {
114 cs.init()
115 return cs
116 }
117
118 // SkipErrors results in lines with unpareable CSV content being
119 // skipped (the csv.ParseError is printed to stdio).
120 func (cs *CSVReader) SkipErrors() *CSVReader {
121 cs.skipErrors = true
122 return cs
123 }
124
125 // SetTypes species the types of the variables. If the CSV file has a header,
126 // these values may appear in any order, and variables not included in types
127 // are omitted. If the CSV file does not have a header, then
128 // types must match the columns in the file, in the correct order.
129 func (cs *CSVReader) SetTypes(types []VarType) *CSVReader {
130 cs.types = types
131 return cs
132 }
133
134 // LimitChunk sets the number of chunks to read.
135 func (cs *CSVReader) LimitChunk(n int) *CSVReader {
136 cs.limitchunk = n
137 return cs
138 }
139
140 // Close does nothing and is implemented to satisfy the Dstream interface.
141 // If any io.Reader values passed to FromCSV need closing, they should be
142 // closed by the caller.
143 func (cs *CSVReader) Close() {
144 }
145
146 // HasHeader indicates that the first row of the data file contains
147 // column names. The default behavior is that there is no header.
148 func (cs *CSVReader) HasHeader() *CSVReader {
149 if cs.doneinit {
150 msg := "FromCSV: can't call HasHeader after beginning data read"
151 panic(msg)
152 }
153 cs.hasheader = true
154 return cs
155 }
156
157 // Comma sets the delimiter (comma rune) for the CSVReader. By default,
158 // the comma rune is a comma.
159 func (cs *CSVReader) Comma(c rune) *CSVReader {
160 cs.comma = c
161 return cs
162 }
163
164 // Consistency checks for arguments.
165 func (cs *CSVReader) checkArgs() {
166
167 }
168
169 func (cs *CSVReader) init() {
170
171 cs.checkArgs()
172
173 if cs.chunkSize == 0 {
174 cs.chunkSize = 10000
175 }
176
177 cs.csvrdr = csv.NewReader(cs.rdr)
178 if cs.comma != 0 {
179 cs.csvrdr.Comma = cs.comma
180 }
181
182 // Read the first row (may or may not be column header)
183 var firstrow []string
184 var err error
185 firstrow, err = cs.csvrdr.Read()
186 if err != nil {
187 panic(err)
188 }
189
190 if len(cs.types) == 0 {
191 panic("SetTypes must be called.")
192 }
193 cs.nvar = len(cs.types)
194
195 cs.filenamepos = make(map[string]int)
196 if cs.hasheader {
197 for pos, na := range firstrow {
198 cs.filenamepos[na] = pos
199 }
200 } else {
201 // Save the first row since it contains data
202 cs.firstrow = firstrow
203
204 if len(firstrow) != len(cs.types) {
205 msg := fmt.Sprintf("File has %d columns and no header, but types has %d values.", len(firstrow), len(cs.types))
206 panic(msg)
207 }
208
209 // If no header, types contains the names in the proper order
210 for pos, vt := range cs.types {
211 cs.filenamepos[vt.Name] = pos
212 }
213 }
214
215 cs.setNames()
216 cs.setbdata()
217
218 cs.doneinit = true
219 }
220
221 func (cs *CSVReader) setNames() {
222
223 // By the time this is called, dtypes is guaranteed to exist.
224 cs.dtypes = make([]Dtype, len(cs.types))
225 cs.names = make([]string, len(cs.types))
226 cs.namepos = make(map[string]int)
227 cs.filepos = make([]int, len(cs.types))
228 for pos, vt := range cs.types {
229 cs.names[pos] = vt.Name
230 cs.dtypes[pos] = vt.Type
231 cs.namepos[vt.Name] = pos
232 cs.filepos[pos] = cs.filenamepos[vt.Name]
233 }
234 }
235
236 // ChunkSize sets the size of chunks for this Dstream, it can only
237 // be called before reading begins.
238 func (cs *CSVReader) ChunkSize(c int) *CSVReader {
239 cs.chunkSize = c
240 return cs
241 }
242
243 // Names returns the names of the variables in the dstream.
244 func (cs *CSVReader) Names() []string {
245 return cs.names
246 }
247
248 // NumVar returns the number of variables in the dstream.
249 func (cs *CSVReader) NumVar() int {
250 return cs.nvar
251 }
252
253 // NumObs returns the number of observations in the dstream. If the
254 // dstream has not been fully read, returns -1.
255 func (cs *CSVReader) NumObs() int {
256 if cs.done {
257 return cs.nobs
258 }
259 return -1
260 }
261
262 // GetPos returns a chunk of a data column by column position.
263 func (cs *CSVReader) GetPos(j int) interface{} {
264 return cs.bdata[j]
265 }
266
267 // Get returns a chunk of a data column by name.
268 func (cs *CSVReader) Get(na string) interface{} {
269 pos, ok := cs.namepos[na]
270 if !ok {
271 msg := fmt.Sprintf("Variable '%s' not found", na)
272 panic(msg)
273 }
274 return cs.bdata[pos]
275 }
276
277 // Reset attempts to reset the Dstream that is reading from an
278 // io.Reader. This is only possible if the underlying reader is
279 // seekable, so reset panics if the seek cannot be performed.
280 func (cs *CSVReader) Reset() {
281 if !cs.doneinit {
282 panic("cannot reset, Dstream has not been fully constructed")
283 }
284
285 if cs.nobs == 0 {
286 return
287 }
288
289 r, ok := cs.rdr.(io.ReadSeeker)
290 if !ok {
291 panic("cannot reset")
292 }
293 _, err := r.Seek(0, io.SeekStart)
294 if err != nil {
295 panic(err)
296 }
297 cs.nobs = 0
298 cs.done = false
299 cs.chunknum = 0
300 cs.rdr = r // is this needed?
301 cs.csvrdr = csv.NewReader(r) // is this needed?
302
303 // Skip over the header if needed.
304 if cs.hasheader {
305 _, err := cs.csvrdr.Read()
306 if err != nil {
307 panic(err)
308 }
309 }
310 }
311
312 // CSVWriter supports writing a Dstream to an io.Writer in csv format.
313 type CSVWriter struct {
314
315 // The Dstream to be written.
316 stream Dstream
317
318 // Format for float type value
319 floatFmt string
320
321 // A slice of format types, stored per-variable.
322 fmts []string
323
324 wtr io.Writer
325 }
326
327 // ToCSV writes a Dstream in CSV format. Call SetWriter or Filename
328 // to configure the underlying writer, then call additional methods
329 // for customization as desired, and finally call Done to complete the
330 // writing.
331 func ToCSV(d Dstream) *CSVWriter {
332 c := &CSVWriter{
333 stream: d,
334 }
335 return c
336 }
337
338 // FloatFmt sets the format string to be used when writing float
339 // values. This value is ignored for columns specified in a call to
340 // the Formats method.
341 func (dw *CSVWriter) FloatFmt(fmt string) *CSVWriter {
342
343 dw.floatFmt = fmt
344 return dw
345 }
346
347 // Formats sets format strings to be used when writing the Dstream.
348 // The provided argument is a map from variable names to variable
349 // formats.
350 func (dw *CSVWriter) Formats(fmts map[string]string) *CSVWriter {
351
352 vp := VarPos(dw.stream)
353
354 if dw.fmts == nil {
355 nvar := dw.stream.NumVar()
356 dw.fmts = make([]string, nvar)
357 }
358 for v, f := range fmts {
359 pos, ok := vp[v]
360 if !ok {
361 msg := fmt.Sprintf("ToCSV: column %s not found", v)
362 panic(msg)
363 }
364 dw.fmts[pos] = f
365 }
366
367 return dw
368 }
369
370 // Filename configures the CSVWriter to write to the given named file.
371 func (dw *CSVWriter) Filename(name string) *CSVWriter {
372
373 var err error
374 dw.wtr, err = os.Create(name)
375 if err != nil {
376 panic(err)
377 }
378
379 return dw
380 }
381
382 // SetWriter configures the CSVWriter to write to the given io stream.
383 func (dw *CSVWriter) SetWriter(w io.Writer) *CSVWriter {
384
385 dw.wtr = w
386 return dw
387 }
388
389 // getFmt is a utility for getting the format string for a given
390 // column.
391 func (dw *CSVWriter) getFmt(t string, col int) string {
392
393 if dw.fmts != nil && dw.fmts[col] != "" {
394 return dw.fmts[col]
395 }
396
397 switch t {
398 case "float":
399 if dw.floatFmt == "" {
400 return "%.8f"
401 }
402 return dw.floatFmt
403 case "int":
404 return "%d"
405 default:
406 panic("unknown type")
407 }
408 }
409
410 // Done completes writing a Dstream to a specified io.Writer in csv
411 // format.
412 func (dw *CSVWriter) Done() error {
413
414 if dw.wtr == nil {
415 return errors.New("ToCSV: writer must be set before calling Done")
416 }
417
418 csw := csv.NewWriter(dw.wtr)
419
420 err := csw.Write(dw.stream.Names())
421 if err != nil {
422 return err
423 }
424
425 nvar := dw.stream.NumVar()
426 rec := make([]string, nvar)
427 fmts := make([]string, nvar)
428
429 firstrow := true
430 for dw.stream.Next() {
431 n := ilen(dw.stream.GetPos(0))
432
433 for i := 0; i < n; i++ {
434 for j := 0; j < nvar; j++ {
435 // TODO: better support for types
436 switch x := dw.stream.GetPos(j).(type) {
437 case []float64:
438 if firstrow {
439 fmts[j] = dw.getFmt("float", j)
440 }
441 rec[j] = fmt.Sprintf(fmts[j], x[i])
442 case []string:
443 rec[j] = x[i]
444 default:
445 rec[j] = ""
446 }
447 }
448 if err := csw.Write(rec); err != nil {
449 return err
450 }
451 firstrow = false
452 }
453 }
454
455 csw.Flush()
456
457 return nil
458 }