Debian Codegraph @

dstream/diffchunk.go

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