dict.go raw
1 package iskra
2
3 import "sort"
4
5 // Token classes, dict.mx.
6 const (
7 TokUnknown uint8 = 0
8 TokNoun uint8 = 1 // not followed by (
9 TokVerb uint8 = 2 // followed by ( - function or method call
10 TokModifier uint8 = 3 // operators, punctuation, whitespace, metadata
11 TokStructural uint8 = 4 // unused, kept for mesh compatibility
12 TokLiteral uint8 = 5 // numbers and string literals
13 )
14
15 // DictEntry points at one token in Dict.Pool.
16 type DictEntry struct {
17 Offset uint32
18 Len uint16
19 Class uint8
20 Count uint32
21 }
22
23 // NewWordDict returns a dictionary for whole-word tokenisation.
24 func NewWordDict() *Dict { return NewDict() }
25
26 // Dict is the token dictionary: interned strings plus a token id sequence.
27 //
28 // A dictionary is either a chunk dictionary, filled by the corpus loader with
29 // two-character chunks (the .meta layout this port wrote before Rechunk), or a
30 // word dictionary, filled by Rechunk with whole words. TokenPool holds the ids
31 // of the run(s) and belongs to one of them; Dict.Entries is whichever
32 // dictionary the ids index.
33 type Dict struct {
34 Pool []byte
35 Entries []DictEntry
36 Index map[string]uint32
37 }
38
39 // NewDict returns an empty dictionary.
40 func NewDict() *Dict {
41 return &Dict{Index: make(map[string]uint32)}
42 }
43
44 // Add interns one token, bumping its count if it is already present, and
45 // returns its id.
46 func (d *Dict) Add(token []byte, class uint8) uint32 {
47 s := string(token)
48 if idx, ok := d.Index[s]; ok {
49 d.Entries[idx].Count++
50 return idx
51 }
52 idx := uint32(len(d.Entries))
53 off := uint32(len(d.Pool))
54 d.Pool = append(d.Pool, token...)
55 d.Entries = append(d.Entries, DictEntry{Offset: off, Len: uint16(len(token)), Class: class, Count: 1})
56 d.Index[s] = idx
57 return idx
58 }
59
60 // Get returns the token bytes for an id.
61 func (d *Dict) Get(idx uint32) []byte {
62 e := &d.Entries[idx]
63 return d.Pool[e.Offset : e.Offset+uint32(e.Len)]
64 }
65
66 // Class returns the token class for an id.
67 func (d *Dict) Class(idx uint32) uint8 { return d.Entries[idx].Class }
68
69 // EntryCount is the number of distinct tokens.
70 func (d *Dict) EntryCount() int { return len(d.Entries) }
71
72 // PoolSize is the byte length of the token pool.
73 func (d *Dict) PoolSize() int { return len(d.Pool) }
74
75 // Tokenize splits content into tokens and returns their ids.
76 func (d *Dict) Tokenize(content []byte) []uint32 {
77 toks := Tokenize(content)
78 out := make([]uint32, 0, len(toks))
79 for _, t := range toks {
80 out = append(out, d.Add([]byte(t.Text), t.Class))
81 }
82 return out
83 }
84
85 // Decode concatenates a token-id sequence with no separator.
86 func (d *Dict) Decode(seq []uint32) []byte {
87 var out []byte
88 for _, idx := range seq {
89 if int(idx) >= len(d.Entries) {
90 continue
91 }
92 out = append(out, d.Get(idx)...)
93 }
94 return out
95 }
96
97 // SortByFrequency reorders entries by descending count and remaps a token
98 // sequence through the renumbering.
99 func (d *Dict) SortByFrequency(tokenPool []uint32) []uint32 {
100 n := len(d.Entries)
101 if n == 0 {
102 return tokenPool
103 }
104 order := make([]int, n)
105 for i := range order {
106 order[i] = i
107 }
108 sort.SliceStable(order, func(a, b int) bool {
109 ca, cb := d.Entries[order[a]].Count, d.Entries[order[b]].Count
110 if ca != cb {
111 return ca > cb
112 }
113 return order[a] < order[b]
114 })
115 oldToNew := make([]uint32, n)
116 newEntries := make([]DictEntry, n)
117 for newIdx, oldIdx := range order {
118 oldToNew[oldIdx] = uint32(newIdx)
119 newEntries[newIdx] = d.Entries[oldIdx]
120 }
121 d.Entries = newEntries
122 newIndex := make(map[string]uint32, len(d.Index))
123 for s, oldIdx := range d.Index {
124 newIndex[s] = oldToNew[oldIdx]
125 }
126 d.Index = newIndex
127 for i := range tokenPool {
128 tokenPool[i] = oldToNew[tokenPool[i]]
129 }
130 return tokenPool
131 }
132