forked from ryanbressler/CloudForest
-
Notifications
You must be signed in to change notification settings - Fork 3
/
forestreader.go
201 lines (182 loc) · 4.84 KB
/
forestreader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package CloudForest
import (
"bufio"
"errors"
"fmt"
"io"
"log"
"strconv"
"strings"
)
/*
ForestReader wraps an io.Reader to reads a forest. It includes ReadForest for reading an
entire forest or ReadTree for reading a forest tree by tree.
The forest should be in .sf format see the package doc's in doc.go for full format details.
It ignores fields that are not use by CloudForest.
*/
type ForestReader struct {
br *bufio.Reader
}
//NewForestReader wraps the supplied io.Reader as a ForestReader.
func NewForestReader(r io.Reader) *ForestReader {
return &ForestReader{bufio.NewReader(r)}
}
/*
ForestReader.ReadForest reads the next forest from the underlying reader.
If io.EOF or another error is encountered it returns that.
*/
func (fr *ForestReader) ReadForest() (forest *Forest, err error) {
peek := []byte(" ")
peek, err = fr.br.Peek(1)
if err != nil {
return
}
if peek[0] != 'F' && peek[0] != 'T' {
err = errors.New("Forest Header Not Found.")
return
}
for {
peek, err = fr.br.Peek(1)
if peek[0] == 'F' && forest != nil {
return
}
t, f, e := fr.ReadTree()
if forest != nil && f != nil {
return
}
if forest == nil && f != nil {
forest = f
}
if t != nil {
if forest == nil {
forest = new(Forest)
forest.Target = t.Target
}
forest.Trees = append(forest.Trees, t)
}
if e == io.EOF {
return forest, nil
}
if e != nil {
return
}
}
}
/*ForestReader.ReadTree reads the next tree from the underlying reader. If the next tree
is in a new forest it returns a forest object as well. If an io.EOF or other error is
encountered it returns that as well as any partially parsed structs.*/
func (fr *ForestReader) ReadTree() (tree *Tree, forest *Forest, err error) {
intree := false
line := ""
peek := []byte(" ")
for {
peek, err = fr.br.Peek(1)
//If their is no next line or it starts a new Tree or Forest return
if err != nil || (intree && (peek[0] == 'T' || peek[0] == 'F')) {
return
}
line, err = fr.br.ReadString('\n')
if err != nil {
return
}
parsed := fr.ParseRfAcePredictorLine(line)
switch {
case strings.HasPrefix(line, "FOREST"):
forest = new(Forest)
forest.Target = parsed["TARGET"]
i, ok := parsed["INTERCEPT"]
if ok {
intercept, err := strconv.ParseFloat(i, 64)
if err != nil {
log.Print("Error parsing forest intercept value ", err)
}
forest.Intercept = intercept
}
case strings.HasPrefix(line, "TREE"):
intree = true
tree = new(Tree)
tree.Target = parsed["TARGET"]
weights, ok := parsed["WEIGHT"]
if ok {
weight, err := strconv.ParseFloat(weights, 64)
if err != nil {
log.Print("Error parsing weight value ", err)
}
tree.Weight = weight
} else {
tree.Weight = -1.0
}
case strings.HasPrefix(line, "NODE"):
if intree == false {
err = errors.New("Poorly formed .sf file. Node found outside of tree.")
return
}
var splitter *Splitter
pred := ""
if filepred, ok := parsed["PRED"]; ok {
pred = filepred
}
if stype, ok := parsed["SPLITTERTYPE"]; ok {
splitter = new(Splitter)
splitter.Feature = parsed["SPLITTER"]
switch stype {
case "CATEGORICAL":
splitter.Numerical = false
splitter.Left = make(map[string]bool)
for _, f := range strings.Split(parsed["LVALUES"], ":") {
splitter.Left[f] = true
}
case "NUMERICAL":
splitter.Numerical = true
lvalue, err := strconv.ParseFloat(parsed["LVALUES"], 64)
if err != nil {
log.Print("Error parsing lvalues value ", err)
}
splitter.Value = float64(lvalue)
}
}
tree.AddNode(parsed["NODE"], pred, splitter)
}
}
}
/*
ParseRfAcePredictorLine parses a single line of an rf-ace sf "stochastic forest"
and returns a map[string]string of the key value pairs.
*/
func (fr *ForestReader) ParseRfAcePredictorLine(line string) map[string]string {
clauses := make([]string, 0)
insidequotes := make([]string, 0)
terms := strings.Split(strings.TrimSpace(line), ",")
for _, term := range terms {
term = strings.TrimSpace(term)
quotes := strings.Count(term, "\"")
//if quotes have been opend join terms
if quotes == 1 || len(insidequotes) > 0 {
insidequotes = append(insidequotes, term)
} else {
//If the term doesn't have an = in it join it to the last term
if strings.Count(term, "=") == 0 {
clauses[len(clauses)-1] += "," + term
} else {
clauses = append(clauses, term)
}
}
//quotes were closed
if quotes == 1 && len(insidequotes) > 1 {
clauses = append(clauses, strings.Join(insidequotes, ","))
insidequotes = make([]string, 0)
}
}
parsed := make(map[string]string, 0)
for _, clause := range clauses {
vs := strings.Split(clause, "=")
for i, v := range vs {
vs[i] = strings.Trim(strings.TrimSpace(v), "\"")
}
if len(vs) != 2 {
fmt.Println("Parser Choked on : \"", line, "\"")
}
parsed[vs[0]] = vs[1]
}
return parsed
}