-
Notifications
You must be signed in to change notification settings - Fork 0
/
ngram.go
242 lines (205 loc) · 5.91 KB
/
ngram.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package ngram
import (
"math"
"sort"
"strings"
)
// Ngram is a struct for holding an ngram defined by the New() function below
type Ngram struct {
n int
sentence string
// grams count is a mapping of gram to occurences; counts the frequency of the ngram
gramsCount map[string]int
// a list of ngrams in the sentence. ordered if grams_ordered is true
grams []string
// a flag to identify if the grams slice is ordered
gramsOrdered bool
c4hash [32]byte
c4hashValid bool
c5hash [32]byte
c5hashValid bool
}
// New creates a new n, ngram over string s and fills in the appropriate data struct
func New(n int, s string) *Ngram {
grams := make([]string, 0)
gramsCount := make(map[string]int, 0)
var array4, array5 [32]byte
slice := make([]byte, 32)
copy(array4[:], slice)
copy(array5[:], slice)
return &Ngram{
n: n,
sentence: strings.ReplaceAll(s, " ", ""),
grams: grams,
gramsCount: gramsCount,
gramsOrdered: false,
c4hash: array4,
c4hashValid: false,
c5hash: array5,
c5hashValid: false,
}
}
// CalculateGrams will count and order the ngrams if they haven't been ordered
// yet, filling in the appropriate fields in the Ngram struct
func (n *Ngram) CalculateGrams() {
// if we've already calculated Ngrams, return without re-computing
if n.gramsOrdered {
return
}
// Count ngram occurence
for i := 0; i <= len(n.sentence)-n.n; i++ {
n.gramsCount[n.sentence[i:i+n.n]] += 1
}
// get all unique ngrams
keys := make([]string, 0)
for key := range n.gramsCount {
keys = append(keys, key)
}
// sort based on associated values in grams_count
sort.SliceStable(keys, func(i, j int) bool {
if n.gramsCount[keys[i]] == n.gramsCount[keys[j]] {
return keys[i] < keys[j]
}
return n.gramsCount[keys[i]] > n.gramsCount[keys[j]]
})
// transfer keys back into ngram struct
n.grams = append(n.grams, keys...)
// set ordered flag to prevent re-calculation accidentally
n.gramsOrdered = true
}
// NthFrequentGram will return the ith most frequent ngram. For instance if the most
// frequent ngrams were ['asdf', 'sdfg', 'dfgh', ...] then NthFrequentGram(0) == 'asdf'
func (n *Ngram) NthFrequentGram(i int) string {
// memoize the frequency calculations
if !n.gramsOrdered {
n.CalculateGrams()
}
return n.grams[i]
}
// NthFrequentGram will return the ith least frequent ngram. For instance if the most
// frequent ngrams were [..., 'asdf', 'sdfg', 'dfgh'] then NthRareGram(0) == 'dfgh'
func (n *Ngram) NthRareGram(i int) string {
// memoize the frequency calculations
if !n.gramsOrdered {
n.CalculateGrams()
}
return n.grams[len(n.grams)-1-i]
}
// NSpacedRareGrams will return the i rarest ngrams that are at least spacing
// edit distance apart from each other
func (n *Ngram) NSpacedRareGrams(spacing, i int) []string {
// memoize the frequency calculations
if !n.gramsOrdered {
n.CalculateGrams()
}
grams := make([]string, 0)
idx := 0
// iterate through our grams until we fill a list with sufficiently spaced ngrams
for len(grams) < i && idx < len(n.grams) {
nextGram := n.NthRareGram(idx)
goodGram := true
for _, gram := range grams {
if n.ngramDistance(nextGram, gram) < spacing {
goodGram = false
}
}
if goodGram {
grams = append(grams, nextGram)
}
idx++
}
return grams
}
// String will get a string representation of the ngram hash
func (n *Ngram) String() string {
s := ""
for i := 0; i < 8 && i < len(n.grams); i++ {
s += n.NthRareGram(i)
}
return s
}
// Bytes returns the byte represetation of the ngram hash
func (n *Ngram) Bytes() [32]byte {
var byteSlice [32]byte
copy(byteSlice[:], []byte(n.String()))
return byteSlice
}
func (n *Ngram) Sentence() string {
return n.sentence
}
// adapted for words and sentences from the code here:
// https://golangbyexample.com/edit-distance-two-strings-golang/
func ngramEditDistance(g1, g2 string) int {
lenGram1 := len(g1)
lenGram2 := len(g2)
editDistanceMatrix := make([][]int, lenGram1+1)
for i := range editDistanceMatrix {
editDistanceMatrix[i] = make([]int, lenGram2+1)
}
for i := 1; i <= lenGram2; i++ {
editDistanceMatrix[0][i] = i
}
for i := 1; i <= lenGram1; i++ {
editDistanceMatrix[i][0] = i
}
for i := 1; i <= lenGram1; i++ {
for j := 1; j <= lenGram2; j++ {
if g1[i-1] == g2[j-1] {
editDistanceMatrix[i][j] = editDistanceMatrix[i-1][j-1]
} else {
// modified here to not count a replace as a distance of 1
editDistanceMatrix[i][j] = 1 + int(math.Min(float64(editDistanceMatrix[i-1][j]), float64(editDistanceMatrix[i][j-1])))
}
}
}
return editDistanceMatrix[lenGram1][lenGram2]
}
// ngramDistance will calculate the distance between two ngrams
// returns -1 if one of the ngrams isn't found (we never expect
// this to happen with current use cases, so something must have gone wrong)
// returns 0 if there is an overlap
func (n *Ngram) ngramDistance(g1, g2 string) int {
g1Idx := strings.Index(n.sentence, g1)
g2Idx := strings.Index(n.sentence, g2)
if g1Idx == -1 || g2Idx == -1 {
return -1
}
dist := g1Idx - g2Idx
if int(math.Abs(float64(dist))) < len(g1) {
return 0
}
return int(math.Abs(float64(dist))) - len(g1)
}
func (n *Ngram) Campbell4Hash() [32]byte {
if n.c4hashValid {
return n.c4hash
}
var byteSlice []byte
grams := n.NSpacedRareGrams(3, 8)
for _, gram := range grams {
gramBytes := []byte(gram)
byteSlice = append(byteSlice, gramBytes...)
}
copy(n.c4hash[:], byteSlice)
n.c4hashValid = true
return n.c4hash
}
func (n *Ngram) Campbell5Hash() [32]byte {
if n.c5hashValid {
return n.c5hash
}
byteSlice := make([]byte, 0)
grams := n.NSpacedRareGrams(3, 8)
for _, gram := range grams {
gramBytes := []byte(gram)
byteSlice = append(byteSlice, gramBytes...)
}
idx := 0
for len(byteSlice) > 0 && byteSlice[len(byteSlice)-1] == 0 && idx < len(n.grams) {
byteSlice = append(byteSlice, []byte(n.NthFrequentGram(idx))...)
idx++
}
copy(n.c5hash[:], byteSlice)
n.c5hashValid = true
return n.c5hash
}