aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/containers/comptrie/minimize.cpp
blob: 85260619bc8d296b2c51310cfc706633e0507fb0 (plain) (blame)
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#include "minimize.h" 
#include "node.h" 
#include "writeable_node.h" 
#include "write_trie_backwards.h" 
#include "comptrie_impl.h" 

#include <util/generic/hash.h>
#include <util/generic/algorithm.h> 

namespace NCompactTrie {
    // Minimize the trie. The result is equivalent to the original
    // trie, except that it takes less space (and has marginally lower
    // performance, because of eventual epsilon links).
    // The algorithm is as follows: starting from the largest pieces, we find
    // nodes that have identical continuations  (Daciuk's right language),
    // and repack the trie. Repacking is done in-place, so memory is less
    // of an issue; however, it may take considerable time.

    // IMPORTANT: never try to reminimize an already minimized trie or a trie with fast layout.
    // Because of non-local structure and epsilon links, it won't work
    // as you expect it to, and can destroy the trie in the making.

    namespace {
        using TOffsetList = TVector<size_t>;
        using TPieceIndex = THashMap<size_t, TOffsetList>;

        using TSizePair = std::pair<size_t, size_t>;
        using TSizePairVector = TVector<TSizePair>;
        using TSizePairVectorVector = TVector<TSizePairVector>;
 
        class TOffsetMap {
        protected:
            TSizePairVectorVector Data;

        public:
            TOffsetMap() {
                Data.reserve(0x10000);
            }

            void Add(size_t key, size_t value) {
                size_t hikey = key & 0xFFFF;

                if (Data.size() <= hikey)
                    Data.resize(hikey + 1);

                TSizePairVector& sublist = Data[hikey];

                for (auto& it : sublist) {
                    if (it.first == key) {
                        it.second = value;

                        return;
                    }
                }

                sublist.push_back(TSizePair(key, value));
            }

            bool Contains(size_t key) const {
                return (Get(key) != 0);
            }

            size_t Get(size_t key) const {
                size_t hikey = key & 0xFFFF;

                if (Data.size() <= hikey)
                    return 0;

                const TSizePairVector& sublist = Data[hikey];

                for (const auto& it : sublist) {
                    if (it.first == key)
                        return it.second;
                }

                return 0;
            }
        };

        class TOffsetDeltas {
        protected:
            TSizePairVector Data;

        public:
            void Add(size_t key, size_t value) {
                if (Data.empty()) {
                    if (key == value)
                        return; // no offset
                } else {
                    TSizePair last = Data.back();

                    if (key <= last.first) {
                        Cerr << "Trouble: elements to offset delta list added in wrong order" << Endl;

                        return;
                    }

                    if (last.first + value == last.second + key)
                        return; // same  offset
                }

                Data.push_back(TSizePair(key, value));
            }

            size_t Get(size_t key) const {
                if (Data.empty())
                    return key; // difference is zero;

                if (key < Data.front().first)
                    return key;

                // Binary search for the highest entry in the list that does not exceed the key
                size_t from = 0;
                size_t to = Data.size() - 1;

                while (from < to) {
                    size_t midpoint = (from + to + 1) / 2;

                    if (key < Data[midpoint].first)
                        to = midpoint - 1;
                    else
                        from = midpoint;
                }

                TSizePair entry = Data[from];

                return key - entry.first + entry.second;
            }
        };

        class TPieceComparer {
        private:
            const char* Data;
            const size_t Length;

        public:
            TPieceComparer(const char* buf, size_t len)
                : Data(buf)
                , Length(len)
            {
            }

            bool operator()(size_t p1, const size_t p2) {
                int res = memcmp(Data + p1, Data + p2, Length);

                if (res)
                    return (res > 0);

                return (p1 > p2); // the pieces are sorted in the reverse order of appearance
            }
        };

        struct TBranchPoint {
            TNode Node;
            int Selector;

        public:
            TBranchPoint()
                : Selector(0)
            {
            }

            TBranchPoint(const char* data, size_t offset, const ILeafSkipper& skipFunction)
                : Node(data, offset, skipFunction)
                , Selector(0)
            {
            }

            bool IsFinal() const {
                return Node.IsFinal();
            }

            // NextNode returns child nodes, starting from the last node: Right, then Left, then Forward
            size_t NextNode(const TOffsetMap& mergedNodes) {
                while (Selector < 3) {
                    size_t nextOffset = 0;

                    switch (++Selector) {
                        case 1:
                            if (Node.GetRightOffset())
                                nextOffset = Node.GetRightOffset();
                            break;
 
                        case 2:
                            if (Node.GetLeftOffset())
                                nextOffset = Node.GetLeftOffset();
                            break;

                        case 3:
                            if (Node.GetForwardOffset())
                                nextOffset = Node.GetForwardOffset();
                            break;

                        default:
                            break;
                    }

                    if (nextOffset && !mergedNodes.Contains(nextOffset))
                        return nextOffset;
                }
                return 0;
            }
        };

        class TMergingReverseNodeEnumerator: public TReverseNodeEnumerator {
        private:
            bool Fresh;
            TOpaqueTrie Trie;
            const TOffsetMap& MergeMap;
            TVector<TBranchPoint> Trace;
            TOffsetDeltas OffsetIndex;

        public:
            TMergingReverseNodeEnumerator(const TOpaqueTrie& trie, const TOffsetMap& mergers)
                : Fresh(true)
                , Trie(trie)
                , MergeMap(mergers)
            {
            }

            bool Move() override {
                if (Fresh) {
                    Trace.push_back(TBranchPoint(Trie.Data, 0, Trie.SkipFunction));
                    Fresh = false;
                } else {
                    if (Trace.empty())
                        return false;

                    Trace.pop_back();

                    if (Trace.empty())
                        return false;
                }

                size_t nextnode = Trace.back().NextNode(MergeMap);

                while (nextnode) {
                    Trace.push_back(TBranchPoint(Trie.Data, nextnode, Trie.SkipFunction));
                    nextnode = Trace.back().NextNode(MergeMap);
                }

                return (!Trace.empty());
            }

            const TNode& Get() const {
                return Trace.back().Node;
            }
            size_t GetLeafLength() const override {
                return Get().GetLeafLength();
            }

            // Returns recalculated offset from the end of the current node
            size_t PrepareOffset(size_t absoffset, size_t minilength) {
                if (!absoffset)
                    return NPOS;

                if (MergeMap.Contains(absoffset))
                    absoffset = MergeMap.Get(absoffset);
                return minilength - OffsetIndex.Get(Trie.Length - absoffset);
            }

            size_t RecreateNode(char* buffer, size_t resultLength) override {
                TWriteableNode newNode(Get(), Trie.Data);
                newNode.ForwardOffset = PrepareOffset(Get().GetForwardOffset(), resultLength);
                newNode.LeftOffset = PrepareOffset(Get().GetLeftOffset(), resultLength);
                newNode.RightOffset = PrepareOffset(Get().GetRightOffset(), resultLength);

                if (!buffer)
                    return newNode.Measure();

                const size_t len = newNode.Pack(buffer);
                OffsetIndex.Add(Trie.Length - Get().GetOffset(), resultLength + len);

                return len;
            }
        };

    }

    static void AddPiece(TPieceIndex& index, size_t offset, size_t len) {
        index[len].push_back(offset);
    }
 
    static TOffsetMap FindEquivalentSubtries(const TOpaqueTrie& trie, bool verbose, size_t minMergeSize) {
        // Tree nodes, arranged by span length.
        // When all nodes of a given size are considered, they pop off the queue.
        TPieceIndex subtries;
        TOffsetMap merger;
        // Start walking the trie from head.
        AddPiece(subtries, 0, trie.Length);

        size_t counter = 0;
        // Now consider all nodes with sizeable continuations
        for (size_t curlen = trie.Length; curlen >= minMergeSize && !subtries.empty(); curlen--) {
            TPieceIndex::iterator iit = subtries.find(curlen);

            if (iit == subtries.end())
                continue; // fast forward to the next available length value

            TOffsetList& batch = iit->second;
            TPieceComparer comparer(trie.Data, curlen);
            Sort(batch.begin(), batch.end(), comparer);

            TOffsetList::iterator it = batch.begin();
            while (it != batch.end()) {
                if (verbose)
                    ShowProgress(++counter);

                size_t offset = *it;

                // Fill the array with the subnodes of the element
                TNode node(trie.Data, offset, trie.SkipFunction);
                size_t end = offset + curlen;
                if (size_t rightOffset = node.GetRightOffset()) {
                    AddPiece(subtries, rightOffset, end - rightOffset);
                    end = rightOffset;
                }
                if (size_t leftOffset = node.GetLeftOffset()) {
                    AddPiece(subtries, leftOffset, end - leftOffset);
                    end = leftOffset;
                }
                if (size_t forwardOffset = node.GetForwardOffset()) {
                    AddPiece(subtries, forwardOffset, end - forwardOffset);
                }

                while (++it != batch.end()) {
                    // Find next different; until then, just add the offsets to the list of merged nodes.
                    size_t nextoffset = *it;

                    if (memcmp(trie.Data + offset, trie.Data + nextoffset, curlen))
                        break;

                    merger.Add(nextoffset, offset);
                }
            }

            subtries.erase(curlen);
        }
        if (verbose) {
            Cerr << counter << Endl;
        }
        return merger;
    }

    size_t RawCompactTrieMinimizeImpl(IOutputStream& os, TOpaqueTrie& trie, bool verbose, size_t minMergeSize, EMinimizeMode mode) {
        if (!trie.Data || !trie.Length) {
            return 0;
        }

        TOffsetMap merger = FindEquivalentSubtries(trie, verbose, minMergeSize);
        TMergingReverseNodeEnumerator enumerator(trie, merger);

        if (mode == MM_DEFAULT)
            return WriteTrieBackwards(os, enumerator, verbose);
        else
            return WriteTrieBackwardsNoAlloc(os, enumerator, trie, mode);
    } 
 
}