Debian Codegraph @

dstream/lagchunk.go

raw symbols SCIP
1 package dstream
2
3 // TODO make type generic
4
5 import (
6 "fmt"
7 )
8
9 type lagChunk struct {
10 xform
11
12 SourceData Dstream
13
14 // Lags maps variable names to the number of lags to include
15 // for the variable. Variables not included in the map are
16 // retained with no lags.
17 Lags map[string]int
18
19 namespos map[string]int
20
21 nobs int // total sample size
22 nobsKnown bool // indicates whether the sample size is available
23 maxlag int // maximum of all requested lags
24 doneInit bool // init has run
25 }
26
27 // LagChunk returns a new Dstream in which specified variables are
28 // included with lagged values. Lagged values are only computed
29 // within a chunk, not across chunk boundaries, and the first m values
30 // of each chunk are omitted, where m is the maximum lag value.
31 func LagChunk(data Dstream, lags map[string]int) Dstream {
32 lc := &lagChunk{
33 SourceData: data,
34 Lags: lags,
35 }
36 lc.init()
37 return lc
38 }
39
40 func (lc *lagChunk) init() {
41 maxlag := 0
42 for _, v := range lc.Lags {
43 if v > maxlag {
44 maxlag = v
45 }
46 }
47 lc.maxlag = maxlag
48
49 // Create the names of the new variables
50 var names []string
51 for _, a := range lc.SourceData.Names() {
52 if lc.Lags[a] == 0 {
53 names = append(names, a)
54 } else {
55 for j := 0; j <= lc.Lags[a]; j++ {
56 b := fmt.Sprintf("%s[%d]", a, -j)
57 names = append(names, b)
58 }
59 }
60 }
61
62 lc.names = names
63
64 lc.namespos = make(map[string]int)
65 for pos, na := range lc.names {
66 lc.namespos[na] = pos
67 }
68
69 lc.doneInit = true
70 }
71
72 func (lc *lagChunk) NumObs() int {
73 if lc.nobsKnown {
74 return lc.nobs
75 }
76 return -1
77 }
78
79 func (lc *lagChunk) Reset() {
80 lc.SourceData.Reset()
81 lc.doneInit = false
82 }
83
84 func (lc *lagChunk) Next() bool {
85
86 if !lc.doneInit {
87 lc.init()
88 }
89
90 if !lc.SourceData.Next() {
91 lc.nobsKnown = true
92 return false
93 }
94
95 if lc.bdata == nil {
96 lc.bdata = make([]interface{}, len(lc.names))
97 }
98
99 // Loop over the original data columns
100 jj := 0
101 maxlag := lc.maxlag
102 for j, oname := range lc.SourceData.Names() {
103
104 v := lc.SourceData.GetPos(j)
105 if ilen(v) <= maxlag {
106 // Segment is too short to use
107 continue
108 }
109
110 q := lc.Lags[oname]
111 switch v := v.(type) {
112 case []float64:
113 n := len(v)
114 lc.nobs += n - maxlag
115 for k := 0; k <= q; k++ {
116 lc.bdata[jj] = v[(maxlag - k):(n - k)]
117 jj++
118 }
119 case []string:
120 n := len(v)
121 lc.nobs += n - maxlag
122 for k := 0; k <= q; k++ {
123 lc.bdata[jj] = v[(maxlag - k):(n - k)]
124 jj++
125 }
126 default:
127 panic("unknown data type")
128
129 }
130 }
131
132 return true
133 }