-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstate.go
71 lines (62 loc) · 1.64 KB
/
state.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
package main
import (
"math"
"reflect"
"runtime"
"strconv"
)
type FvCache map[string][]int
type State struct {
pending []*Word
arcs map[int]int
fvCache FvCache
}
func (state *State) cacheKeyStr(pair ActionIndexPair) string {
funcName := runtime.FuncForPC(reflect.ValueOf(pair.action).Pointer()).Name()
left := state.pending[pair.index]
right := state.pending[pair.index+1]
return funcName + ":" + strconv.Itoa(left.idx) + "-" + strconv.Itoa(right.idx)
}
func (state *State) InitFvCache() {
for _, f := range StateActions {
for idx := 0; idx < len(state.pending)-1; idx++ {
pair := ActionIndexPair{f, idx}
fv := ExtractFeatures(state, pair)
state.fvCache[state.cacheKeyStr(pair)] = fv
}
}
}
func NewState(pending []*Word) *State {
for _, w := range pending {
w.children = make([]Word, 0)
}
p := make([]*Word, len(pending))
copy(p, pending)
state := State{p, make(map[int]int), FvCache{}}
state.InitFvCache()
return &state
}
func (state *State) deletePending(idx int) []*Word {
state.pending = append(state.pending[:idx], state.pending[idx+1:]...)
return state.pending
}
func (state *State) ResetFvCache(index int) {
for _, f := range StateActions {
min := int(math.Max(0, float64(index-3)))
max := int(math.Min(float64(len(state.pending)-1), float64(index+3)))
for idx := min; idx < max; idx++ {
pair := ActionIndexPair{f, idx}
delete(state.fvCache, state.cacheKeyStr(pair))
}
}
}
func (state *State) GetFvCache(pair ActionIndexPair) []int {
key := state.cacheKeyStr(pair)
if fv, ok := state.fvCache[key]; ok {
return fv
} else {
fv = ExtractFeatures(state, pair)
state.fvCache[key] = fv
return fv
}
}