| 1 |
package dstream |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
|
| 6 |
"gonum.org/v1/gonum/floats" |
| 7 |
) |
| 8 |
|
| 9 |
type center struct { |
| 10 |
source Dstream |
| 11 |
|
| 12 |
|
| 13 |
pos []int |
| 14 |
|
| 15 |
|
| 16 |
vpos map[string]int |
| 17 |
|
| 18 |
|
| 19 |
cenpos map[int]int |
| 20 |
|
| 21 |
|
| 22 |
means []float64 |
| 23 |
} |
| 24 |
|
| 25 |
func (c *center) Close() { |
| 26 |
c.source.Close() |
| 27 |
} |
| 28 |
|
| 29 |
func (c *center) Reset() { |
| 30 |
c.source.Reset() |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
func Center(source Dstream, names ...string) Dstream { |
| 36 |
|
| 37 |
means := make([]float64, len(names)) |
| 38 |
|
| 39 |
|
| 40 |
vpos := make(map[string]int) |
| 41 |
for k, na := range source.Names() { |
| 42 |
vpos[na] = k |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
var pos []int |
| 50 |
cenpos := make(map[int]int) |
| 51 |
for j, na := range names { |
| 52 |
q, ok := vpos[na] |
| 53 |
if !ok { |
| 54 |
msg := fmt.Sprintf("Center: variable '%s' not found.\n", na) |
| 55 |
panic(msg) |
| 56 |
} |
| 57 |
pos = append(pos, q) |
| 58 |
cenpos[q] = j |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
source.Reset() |
| 63 |
n := 0 |
| 64 |
for source.Next() { |
| 65 |
for i, j := range pos { |
| 66 |
v := source.GetPos(j).([]float64) |
| 67 |
if i == 0 { |
| 68 |
n += len(v) |
| 69 |
} |
| 70 |
means[i] += floats.Sum(v) |
| 71 |
} |
| 72 |
} |
| 73 |
floats.Scale(1/float64(n), means) |
| 74 |
|
| 75 |
return ¢er{ |
| 76 |
source: source, |
| 77 |
pos: pos, |
| 78 |
means: means, |
| 79 |
cenpos: cenpos, |
| 80 |
vpos: vpos, |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
func (c *center) GetPos(j int) interface{} { |
| 85 |
|
| 86 |
x := c.source.GetPos(j).([]float64) |
| 87 |
|
| 88 |
q, ok := c.cenpos[j] |
| 89 |
if !ok { |
| 90 |
return x |
| 91 |
} |
| 92 |
|
| 93 |
m := c.means[q] |
| 94 |
|
| 95 |
z := make([]float64, len(x)) |
| 96 |
for i := range x { |
| 97 |
z[i] = x[i] - m |
| 98 |
} |
| 99 |
|
| 100 |
return z |
| 101 |
} |
| 102 |
|
| 103 |
func (c *center) Names() []string { |
| 104 |
return c.source.Names() |
| 105 |
} |
| 106 |
|
| 107 |
func (c *center) Next() bool { |
| 108 |
return c.source.Next() |
| 109 |
} |
| 110 |
|
| 111 |
func (c *center) NumObs() int { |
| 112 |
return c.source.NumObs() |
| 113 |
} |
| 114 |
|
| 115 |
func (c *center) NumVar() int { |
| 116 |
return c.source.NumVar() |
| 117 |
} |
| 118 |
|
| 119 |
func (c *center) Get(na string) interface{} { |
| 120 |
return c.GetPos(c.vpos[na]) |
| 121 |
} |