Debian Codegraph @

dstream/center.go

raw symbols SCIP
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 // Positions of variables to center
13 pos []int
14
15 // Map from variable name to variable position
16 vpos map[string]int
17
18 // Query if something is in pos
19 cenpos map[int]int
20
21 // Means of variables to center
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 // Center returns a new Dstream in which the given columns have been
34 // mean-centered. Currently only works with float64 type data.
35 func Center(source Dstream, names ...string) Dstream {
36
37 means := make([]float64, len(names))
38
39 // Map from variable names to position
40 vpos := make(map[string]int)
41 for k, na := range source.Names() {
42 vpos[na] = k
43 }
44
45 // Positions of variables to center. cenpos[j], if it exists,
46 // is the position within means where the mean of the variable
47 // j is found. If cenpos[j] does not exist, the variable
48 // should not be centered.
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 // Get the means of the variables to center
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 &center{
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 }