FusionDictionary.java revision 6c721b5f68ee20e6d78ddd4f383fb8651827b726
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.inputmethod.latin.makedict;
18
19import com.android.inputmethod.latin.Constants;
20
21import java.util.ArrayList;
22import java.util.Arrays;
23import java.util.Collections;
24import java.util.HashMap;
25import java.util.Iterator;
26import java.util.LinkedList;
27
28/**
29 * A dictionary that can fusion heads and tails of words for more compression.
30 */
31public class FusionDictionary implements Iterable<Word> {
32
33    private static final boolean DBG = MakedictLog.DBG;
34
35    /**
36     * A node of the dictionary, containing several CharGroups.
37     *
38     * A node is but an ordered array of CharGroups, which essentially contain all the
39     * real information.
40     * This class also contains fields to cache size and address, to help with binary
41     * generation.
42     */
43    public static class Node {
44        ArrayList<CharGroup> mData;
45        // To help with binary generation
46        int mCachedSize = Integer.MIN_VALUE;
47        int mCachedAddress = Integer.MIN_VALUE;
48        int mCachedParentAddress = 0;
49
50        public Node() {
51            mData = new ArrayList<CharGroup>();
52        }
53        public Node(ArrayList<CharGroup> data) {
54            mData = data;
55        }
56    }
57
58    /**
59     * A string with a frequency.
60     *
61     * This represents an "attribute", that is either a bigram or a shortcut.
62     */
63    public static class WeightedString {
64        public final String mWord;
65        public int mFrequency;
66        public WeightedString(String word, int frequency) {
67            mWord = word;
68            mFrequency = frequency;
69        }
70
71        @Override
72        public int hashCode() {
73            return Arrays.hashCode(new Object[] { mWord, mFrequency });
74        }
75
76        @Override
77        public boolean equals(Object o) {
78            if (o == this) return true;
79            if (!(o instanceof WeightedString)) return false;
80            WeightedString w = (WeightedString)o;
81            return mWord.equals(w.mWord) && mFrequency == w.mFrequency;
82        }
83    }
84
85    /**
86     * A group of characters, with a frequency, shortcut targets, bigrams, and children.
87     *
88     * This is the central class of the in-memory representation. A CharGroup is what can
89     * be seen as a traditional "trie node", except it can hold several characters at the
90     * same time. A CharGroup essentially represents one or several characters in the middle
91     * of the trie trie; as such, it can be a terminal, and it can have children.
92     * In this in-memory representation, whether the CharGroup is a terminal or not is represented
93     * in the frequency, where NOT_A_TERMINAL (= -1) means this is not a terminal and any other
94     * value is the frequency of this terminal. A terminal may have non-null shortcuts and/or
95     * bigrams, but a non-terminal may not. Moreover, children, if present, are null.
96     */
97    public static class CharGroup {
98        public static final int NOT_A_TERMINAL = -1;
99        final int mChars[];
100        ArrayList<WeightedString> mShortcutTargets;
101        ArrayList<WeightedString> mBigrams;
102        int mFrequency; // NOT_A_TERMINAL == mFrequency indicates this is not a terminal.
103        Node mChildren;
104        boolean mIsNotAWord; // Only a shortcut
105        boolean mIsBlacklistEntry;
106        // The two following members to help with binary generation
107        int mCachedSize;
108        int mCachedAddress;
109
110        public CharGroup(final int[] chars, final ArrayList<WeightedString> shortcutTargets,
111                final ArrayList<WeightedString> bigrams, final int frequency,
112                final boolean isNotAWord, final boolean isBlacklistEntry) {
113            mChars = chars;
114            mFrequency = frequency;
115            mShortcutTargets = shortcutTargets;
116            mBigrams = bigrams;
117            mChildren = null;
118            mIsNotAWord = isNotAWord;
119            mIsBlacklistEntry = isBlacklistEntry;
120        }
121
122        public CharGroup(final int[] chars, final ArrayList<WeightedString> shortcutTargets,
123                final ArrayList<WeightedString> bigrams, final int frequency,
124                final boolean isNotAWord, final boolean isBlacklistEntry, final Node children) {
125            mChars = chars;
126            mFrequency = frequency;
127            mShortcutTargets = shortcutTargets;
128            mBigrams = bigrams;
129            mChildren = children;
130            mIsNotAWord = isNotAWord;
131            mIsBlacklistEntry = isBlacklistEntry;
132        }
133
134        public void addChild(CharGroup n) {
135            if (null == mChildren) {
136                mChildren = new Node();
137            }
138            mChildren.mData.add(n);
139        }
140
141        public boolean isTerminal() {
142            return NOT_A_TERMINAL != mFrequency;
143        }
144
145        public boolean hasSeveralChars() {
146            assert(mChars.length > 0);
147            return 1 < mChars.length;
148        }
149
150        /**
151         * Adds a word to the bigram list. Updates the frequency if the word already
152         * exists.
153         */
154        public void addBigram(final String word, final int frequency) {
155            if (mBigrams == null) {
156                mBigrams = new ArrayList<WeightedString>();
157            }
158            WeightedString bigram = getBigram(word);
159            if (bigram != null) {
160                bigram.mFrequency = frequency;
161            } else {
162                bigram = new WeightedString(word, frequency);
163                mBigrams.add(bigram);
164            }
165        }
166
167        /**
168         * Gets the shortcut target for the given word. Returns null if the word is not in the
169         * shortcut list.
170         */
171        public WeightedString getShortcut(final String word) {
172            // TODO: Don't do a linear search
173            if (mShortcutTargets != null) {
174                final int size = mShortcutTargets.size();
175                for (int i = 0; i < size; ++i) {
176                    WeightedString shortcut = mShortcutTargets.get(i);
177                    if (shortcut.mWord.equals(word)) {
178                        return shortcut;
179                    }
180                }
181            }
182            return null;
183        }
184
185        /**
186         * Gets the bigram for the given word.
187         * Returns null if the word is not in the bigrams list.
188         */
189        public WeightedString getBigram(final String word) {
190            // TODO: Don't do a linear search
191            if (mBigrams != null) {
192                final int size = mBigrams.size();
193                for (int i = 0; i < size; ++i) {
194                    WeightedString bigram = mBigrams.get(i);
195                    if (bigram.mWord.equals(word)) {
196                        return bigram;
197                    }
198                }
199            }
200            return null;
201        }
202
203        /**
204         * Updates the CharGroup with the given properties. Adds the shortcut and bigram lists to
205         * the existing ones if any. Note: unigram, bigram, and shortcut frequencies are only
206         * updated if they are higher than the existing ones.
207         */
208        public void update(final int frequency, final ArrayList<WeightedString> shortcutTargets,
209                final ArrayList<WeightedString> bigrams,
210                final boolean isNotAWord, final boolean isBlacklistEntry) {
211            if (frequency > mFrequency) {
212                mFrequency = frequency;
213            }
214            if (shortcutTargets != null) {
215                if (mShortcutTargets == null) {
216                    mShortcutTargets = shortcutTargets;
217                } else {
218                    final int size = shortcutTargets.size();
219                    for (int i = 0; i < size; ++i) {
220                        final WeightedString shortcut = shortcutTargets.get(i);
221                        final WeightedString existingShortcut = getShortcut(shortcut.mWord);
222                        if (existingShortcut == null) {
223                            mShortcutTargets.add(shortcut);
224                        } else if (existingShortcut.mFrequency < shortcut.mFrequency) {
225                            existingShortcut.mFrequency = shortcut.mFrequency;
226                        }
227                    }
228                }
229            }
230            if (bigrams != null) {
231                if (mBigrams == null) {
232                    mBigrams = bigrams;
233                } else {
234                    final int size = bigrams.size();
235                    for (int i = 0; i < size; ++i) {
236                        final WeightedString bigram = bigrams.get(i);
237                        final WeightedString existingBigram = getBigram(bigram.mWord);
238                        if (existingBigram == null) {
239                            mBigrams.add(bigram);
240                        } else if (existingBigram.mFrequency < bigram.mFrequency) {
241                            existingBigram.mFrequency = bigram.mFrequency;
242                        }
243                    }
244                }
245            }
246            mIsNotAWord = isNotAWord;
247            mIsBlacklistEntry = isBlacklistEntry;
248        }
249    }
250
251    /**
252     * Options global to the dictionary.
253     *
254     * There are no options at the moment, so this class is empty.
255     */
256    public static class DictionaryOptions {
257        public final boolean mGermanUmlautProcessing;
258        public final boolean mFrenchLigatureProcessing;
259        public final HashMap<String, String> mAttributes;
260        public DictionaryOptions(final HashMap<String, String> attributes,
261                final boolean germanUmlautProcessing, final boolean frenchLigatureProcessing) {
262            mAttributes = attributes;
263            mGermanUmlautProcessing = germanUmlautProcessing;
264            mFrenchLigatureProcessing = frenchLigatureProcessing;
265        }
266    }
267
268    public final DictionaryOptions mOptions;
269    public final Node mRoot;
270
271    public FusionDictionary(final Node root, final DictionaryOptions options) {
272        mRoot = root;
273        mOptions = options;
274    }
275
276    public void addOptionAttribute(final String key, final String value) {
277        mOptions.mAttributes.put(key, value);
278    }
279
280    /**
281     * Helper method to convert a String to an int array.
282     */
283    static private int[] getCodePoints(final String word) {
284        // TODO: this is a copy-paste of the contents of StringUtils.toCodePointArray,
285        // which is not visible from the makedict package. Factor this code.
286        final char[] characters = word.toCharArray();
287        final int length = characters.length;
288        final int[] codePoints = new int[Character.codePointCount(characters, 0, length)];
289        int codePoint = Character.codePointAt(characters, 0);
290        int dsti = 0;
291        for (int srci = Character.charCount(codePoint);
292                srci < length; srci += Character.charCount(codePoint), ++dsti) {
293            codePoints[dsti] = codePoint;
294            codePoint = Character.codePointAt(characters, srci);
295        }
296        codePoints[dsti] = codePoint;
297        return codePoints;
298    }
299
300    /**
301     * Helper method to add a word as a string.
302     *
303     * This method adds a word to the dictionary with the given frequency. Optional
304     * lists of bigrams and shortcuts can be passed here. For each word inside,
305     * they will be added to the dictionary as necessary.
306     *
307     * @param word the word to add.
308     * @param frequency the frequency of the word, in the range [0..255].
309     * @param shortcutTargets a list of shortcut targets for this word, or null.
310     * @param isNotAWord true if this should not be considered a word (e.g. shortcut only)
311     */
312    public void add(final String word, final int frequency,
313            final ArrayList<WeightedString> shortcutTargets, final boolean isNotAWord) {
314        add(getCodePoints(word), frequency, shortcutTargets, isNotAWord,
315                false /* isBlacklistEntry */);
316    }
317
318    /**
319     * Helper method to add a blacklist entry as a string.
320     *
321     * @param word the word to add as a blacklist entry.
322     * @param shortcutTargets a list of shortcut targets for this word, or null.
323     * @param isNotAWord true if this is not a word for spellcheking purposes (shortcut only or so)
324     */
325    public void addBlacklistEntry(final String word,
326            final ArrayList<WeightedString> shortcutTargets, final boolean isNotAWord) {
327        add(getCodePoints(word), 0, shortcutTargets, isNotAWord, true /* isBlacklistEntry */);
328    }
329
330    /**
331     * Sanity check for a node.
332     *
333     * This method checks that all CharGroups in a node are ordered as expected.
334     * If they are, nothing happens. If they aren't, an exception is thrown.
335     */
336    private void checkStack(Node node) {
337        ArrayList<CharGroup> stack = node.mData;
338        int lastValue = -1;
339        for (int i = 0; i < stack.size(); ++i) {
340            int currentValue = stack.get(i).mChars[0];
341            if (currentValue <= lastValue)
342                throw new RuntimeException("Invalid stack");
343            else
344                lastValue = currentValue;
345        }
346    }
347
348    /**
349     * Helper method to add a new bigram to the dictionary.
350     *
351     * @param word1 the previous word of the context
352     * @param word2 the next word of the context
353     * @param frequency the bigram frequency
354     */
355    public void setBigram(final String word1, final String word2, final int frequency) {
356        CharGroup charGroup = findWordInTree(mRoot, word1);
357        if (charGroup != null) {
358            final CharGroup charGroup2 = findWordInTree(mRoot, word2);
359            if (charGroup2 == null) {
360                add(getCodePoints(word2), 0, null, false /* isNotAWord */,
361                        false /* isBlacklistEntry */);
362            }
363            charGroup.addBigram(word2, frequency);
364        } else {
365            throw new RuntimeException("First word of bigram not found");
366        }
367    }
368
369    /**
370     * Add a word to this dictionary.
371     *
372     * The shortcuts, if any, have to be in the dictionary already. If they aren't,
373     * an exception is thrown.
374     *
375     * @param word the word, as an int array.
376     * @param frequency the frequency of the word, in the range [0..255].
377     * @param shortcutTargets an optional list of shortcut targets for this word (null if none).
378     * @param isNotAWord true if this is not a word for spellcheking purposes (shortcut only or so)
379     * @param isBlacklistEntry true if this is a blacklisted word, false otherwise
380     */
381    private void add(final int[] word, final int frequency,
382            final ArrayList<WeightedString> shortcutTargets,
383            final boolean isNotAWord, final boolean isBlacklistEntry) {
384        assert(frequency >= 0 && frequency <= 255);
385        if (word.length >= Constants.Dictionary.MAX_WORD_LENGTH) {
386            MakedictLog.w("Ignoring a word that is too long: word.length = " + word.length);
387            return;
388        }
389
390        Node currentNode = mRoot;
391        int charIndex = 0;
392
393        CharGroup currentGroup = null;
394        int differentCharIndex = 0; // Set by the loop to the index of the char that differs
395        int nodeIndex = findIndexOfChar(mRoot, word[charIndex]);
396        while (CHARACTER_NOT_FOUND != nodeIndex) {
397            currentGroup = currentNode.mData.get(nodeIndex);
398            differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex);
399            if (ARRAYS_ARE_EQUAL != differentCharIndex
400                    && differentCharIndex < currentGroup.mChars.length) break;
401            if (null == currentGroup.mChildren) break;
402            charIndex += currentGroup.mChars.length;
403            if (charIndex >= word.length) break;
404            currentNode = currentGroup.mChildren;
405            nodeIndex = findIndexOfChar(currentNode, word[charIndex]);
406        }
407
408        if (-1 == nodeIndex) {
409            // No node at this point to accept the word. Create one.
410            final int insertionIndex = findInsertionIndex(currentNode, word[charIndex]);
411            final CharGroup newGroup = new CharGroup(
412                    Arrays.copyOfRange(word, charIndex, word.length),
413                    shortcutTargets, null /* bigrams */, frequency, isNotAWord, isBlacklistEntry);
414            currentNode.mData.add(insertionIndex, newGroup);
415            if (DBG) checkStack(currentNode);
416        } else {
417            // There is a word with a common prefix.
418            if (differentCharIndex == currentGroup.mChars.length) {
419                if (charIndex + differentCharIndex >= word.length) {
420                    // The new word is a prefix of an existing word, but the node on which it
421                    // should end already exists as is. Since the old CharNode was not a terminal,
422                    // make it one by filling in its frequency and other attributes
423                    currentGroup.update(frequency, shortcutTargets, null, isNotAWord,
424                            isBlacklistEntry);
425                } else {
426                    // The new word matches the full old word and extends past it.
427                    // We only have to create a new node and add it to the end of this.
428                    final CharGroup newNode = new CharGroup(
429                            Arrays.copyOfRange(word, charIndex + differentCharIndex, word.length),
430                                    shortcutTargets, null /* bigrams */, frequency, isNotAWord,
431                                    isBlacklistEntry);
432                    currentGroup.mChildren = new Node();
433                    currentGroup.mChildren.mData.add(newNode);
434                }
435            } else {
436                if (0 == differentCharIndex) {
437                    // Exact same word. Update the frequency if higher. This will also add the
438                    // new shortcuts to the existing shortcut list if it already exists.
439                    currentGroup.update(frequency, shortcutTargets, null,
440                            currentGroup.mIsNotAWord && isNotAWord,
441                            currentGroup.mIsBlacklistEntry || isBlacklistEntry);
442                } else {
443                    // Partial prefix match only. We have to replace the current node with a node
444                    // containing the current prefix and create two new ones for the tails.
445                    Node newChildren = new Node();
446                    final CharGroup newOldWord = new CharGroup(
447                            Arrays.copyOfRange(currentGroup.mChars, differentCharIndex,
448                                    currentGroup.mChars.length), currentGroup.mShortcutTargets,
449                            currentGroup.mBigrams, currentGroup.mFrequency,
450                            currentGroup.mIsNotAWord, currentGroup.mIsBlacklistEntry,
451                            currentGroup.mChildren);
452                    newChildren.mData.add(newOldWord);
453
454                    final CharGroup newParent;
455                    if (charIndex + differentCharIndex >= word.length) {
456                        newParent = new CharGroup(
457                                Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
458                                shortcutTargets, null /* bigrams */, frequency,
459                                isNotAWord, isBlacklistEntry, newChildren);
460                    } else {
461                        newParent = new CharGroup(
462                                Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex),
463                                null /* shortcutTargets */, null /* bigrams */, -1,
464                                false /* isNotAWord */, false /* isBlacklistEntry */, newChildren);
465                        final CharGroup newWord = new CharGroup(Arrays.copyOfRange(word,
466                                charIndex + differentCharIndex, word.length),
467                                shortcutTargets, null /* bigrams */, frequency,
468                                isNotAWord, isBlacklistEntry);
469                        final int addIndex = word[charIndex + differentCharIndex]
470                                > currentGroup.mChars[differentCharIndex] ? 1 : 0;
471                        newChildren.mData.add(addIndex, newWord);
472                    }
473                    currentNode.mData.set(nodeIndex, newParent);
474                }
475                if (DBG) checkStack(currentNode);
476            }
477        }
478    }
479
480    private static int ARRAYS_ARE_EQUAL = 0;
481
482    /**
483     * Custom comparison of two int arrays taken to contain character codes.
484     *
485     * This method compares the two arrays passed as an argument in a lexicographic way,
486     * with an offset in the dst string.
487     * This method does NOT test for the first character. It is taken to be equal.
488     * I repeat: this method starts the comparison at 1 <> dstOffset + 1.
489     * The index where the strings differ is returned. ARRAYS_ARE_EQUAL = 0 is returned if the
490     * strings are equal. This works BECAUSE we don't look at the first character.
491     *
492     * @param src the left-hand side string of the comparison.
493     * @param dst the right-hand side string of the comparison.
494     * @param dstOffset the offset in the right-hand side string.
495     * @return the index at which the strings differ, or ARRAYS_ARE_EQUAL = 0 if they don't.
496     */
497    private static int compareArrays(final int[] src, final int[] dst, int dstOffset) {
498        // We do NOT test the first char, because we come from a method that already
499        // tested it.
500        for (int i = 1; i < src.length; ++i) {
501            if (dstOffset + i >= dst.length) return i;
502            if (src[i] != dst[dstOffset + i]) return i;
503        }
504        if (dst.length > src.length) return src.length;
505        return ARRAYS_ARE_EQUAL;
506    }
507
508    /**
509     * Helper class that compares and sorts two chargroups according to their
510     * first element only. I repeat: ONLY the first element is considered, the rest
511     * is ignored.
512     * This comparator imposes orderings that are inconsistent with equals.
513     */
514    static private class CharGroupComparator implements java.util.Comparator<CharGroup> {
515        @Override
516        public int compare(CharGroup c1, CharGroup c2) {
517            if (c1.mChars[0] == c2.mChars[0]) return 0;
518            return c1.mChars[0] < c2.mChars[0] ? -1 : 1;
519        }
520    }
521    final static private CharGroupComparator CHARGROUP_COMPARATOR = new CharGroupComparator();
522
523    /**
524     * Finds the insertion index of a character within a node.
525     */
526    private static int findInsertionIndex(final Node node, int character) {
527        final ArrayList<CharGroup> data = node.mData;
528        final CharGroup reference = new CharGroup(new int[] { character },
529                null /* shortcutTargets */, null /* bigrams */, 0, false /* isNotAWord */,
530                false /* isBlacklistEntry */);
531        int result = Collections.binarySearch(data, reference, CHARGROUP_COMPARATOR);
532        return result >= 0 ? result : -result - 1;
533    }
534
535    private static int CHARACTER_NOT_FOUND = -1;
536
537    /**
538     * Find the index of a char in a node, if it exists.
539     *
540     * @param node the node to search in.
541     * @param character the character to search for.
542     * @return the position of the character if it's there, or CHARACTER_NOT_FOUND = -1 else.
543     */
544    private static int findIndexOfChar(final Node node, int character) {
545        final int insertionIndex = findInsertionIndex(node, character);
546        if (node.mData.size() <= insertionIndex) return CHARACTER_NOT_FOUND;
547        return character == node.mData.get(insertionIndex).mChars[0] ? insertionIndex
548                : CHARACTER_NOT_FOUND;
549    }
550
551    /**
552     * Helper method to find a word in a given branch.
553     */
554    public static CharGroup findWordInTree(Node node, final String s) {
555        int index = 0;
556        final StringBuilder checker = DBG ? new StringBuilder() : null;
557
558        CharGroup currentGroup;
559        final int codePointCountInS = s.codePointCount(0, s.length());
560        do {
561            int indexOfGroup = findIndexOfChar(node, s.codePointAt(index));
562            if (CHARACTER_NOT_FOUND == indexOfGroup) return null;
563            currentGroup = node.mData.get(indexOfGroup);
564
565            if (s.length() - index < currentGroup.mChars.length) return null;
566            int newIndex = index;
567            while (newIndex < s.length() && newIndex - index < currentGroup.mChars.length) {
568                if (currentGroup.mChars[newIndex - index] != s.codePointAt(newIndex)) return null;
569                newIndex++;
570            }
571            index = newIndex;
572
573            if (DBG) checker.append(new String(currentGroup.mChars, 0, currentGroup.mChars.length));
574            if (index < codePointCountInS) {
575                node = currentGroup.mChildren;
576            }
577        } while (null != node && index < codePointCountInS);
578
579        if (index < codePointCountInS) return null;
580        if (!currentGroup.isTerminal()) return null;
581        if (DBG && !s.equals(checker.toString())) return null;
582        return currentGroup;
583    }
584
585    /**
586     * Helper method to find out whether a word is in the dict or not.
587     */
588    public boolean hasWord(final String s) {
589        if (null == s || "".equals(s)) {
590            throw new RuntimeException("Can't search for a null or empty string");
591        }
592        return null != findWordInTree(mRoot, s);
593    }
594
595    /**
596     * Recursively count the number of character groups in a given branch of the trie.
597     *
598     * @param node the parent node.
599     * @return the number of char groups in all the branch under this node.
600     */
601    public static int countCharGroups(final Node node) {
602        final int nodeSize = node.mData.size();
603        int size = nodeSize;
604        for (int i = nodeSize - 1; i >= 0; --i) {
605            CharGroup group = node.mData.get(i);
606            if (null != group.mChildren)
607                size += countCharGroups(group.mChildren);
608        }
609        return size;
610    }
611
612    /**
613     * Recursively count the number of nodes in a given branch of the trie.
614     *
615     * @param node the node to count.
616     * @return the number of nodes in this branch.
617     */
618    public static int countNodes(final Node node) {
619        int size = 1;
620        for (int i = node.mData.size() - 1; i >= 0; --i) {
621            CharGroup group = node.mData.get(i);
622            if (null != group.mChildren)
623                size += countNodes(group.mChildren);
624        }
625        return size;
626    }
627
628    // Recursively find out whether there are any bigrams.
629    // This can be pretty expensive especially if there aren't any (we return as soon
630    // as we find one, so it's much cheaper if there are bigrams)
631    private static boolean hasBigramsInternal(final Node node) {
632        if (null == node) return false;
633        for (int i = node.mData.size() - 1; i >= 0; --i) {
634            CharGroup group = node.mData.get(i);
635            if (null != group.mBigrams) return true;
636            if (hasBigramsInternal(group.mChildren)) return true;
637        }
638        return false;
639    }
640
641    /**
642     * Finds out whether there are any bigrams in this dictionary.
643     *
644     * @return true if there is any bigram, false otherwise.
645     */
646    // TODO: this is expensive especially for large dictionaries without any bigram.
647    // The up side is, this is always accurate and correct and uses no memory. We should
648    // find a more efficient way of doing this, without compromising too much on memory
649    // and ease of use.
650    public boolean hasBigrams() {
651        return hasBigramsInternal(mRoot);
652    }
653
654    // Historically, the tails of the words were going to be merged to save space.
655    // However, that would prevent the code to search for a specific address in log(n)
656    // time so this was abandoned.
657    // The code is still of interest as it does add some compression to any dictionary
658    // that has no need for attributes. Implementations that does not read attributes should be
659    // able to read a dictionary with merged tails.
660    // Also, the following code does support frequencies, as in, it will only merges
661    // tails that share the same frequency. Though it would result in the above loss of
662    // performance while searching by address, it is still technically possible to merge
663    // tails that contain attributes, but this code does not take that into account - it does
664    // not compare attributes and will merge terminals with different attributes regardless.
665    public void mergeTails() {
666        MakedictLog.i("Do not merge tails");
667        return;
668
669//        MakedictLog.i("Merging nodes. Number of nodes : " + countNodes(root));
670//        MakedictLog.i("Number of groups : " + countCharGroups(root));
671//
672//        final HashMap<String, ArrayList<Node>> repository =
673//                  new HashMap<String, ArrayList<Node>>();
674//        mergeTailsInner(repository, root);
675//
676//        MakedictLog.i("Number of different pseudohashes : " + repository.size());
677//        int size = 0;
678//        for (ArrayList<Node> a : repository.values()) {
679//            size += a.size();
680//        }
681//        MakedictLog.i("Number of nodes after merge : " + (1 + size));
682//        MakedictLog.i("Recursively seen nodes : " + countNodes(root));
683    }
684
685    // The following methods are used by the deactivated mergeTails()
686//   private static boolean isEqual(Node a, Node b) {
687//       if (null == a && null == b) return true;
688//       if (null == a || null == b) return false;
689//       if (a.data.size() != b.data.size()) return false;
690//       final int size = a.data.size();
691//       for (int i = size - 1; i >= 0; --i) {
692//           CharGroup aGroup = a.data.get(i);
693//           CharGroup bGroup = b.data.get(i);
694//           if (aGroup.frequency != bGroup.frequency) return false;
695//           if (aGroup.alternates == null && bGroup.alternates != null) return false;
696//           if (aGroup.alternates != null && !aGroup.equals(bGroup.alternates)) return false;
697//           if (!Arrays.equals(aGroup.chars, bGroup.chars)) return false;
698//           if (!isEqual(aGroup.children, bGroup.children)) return false;
699//       }
700//       return true;
701//   }
702
703//   static private HashMap<String, ArrayList<Node>> mergeTailsInner(
704//           final HashMap<String, ArrayList<Node>> map, final Node node) {
705//       final ArrayList<CharGroup> branches = node.data;
706//       final int nodeSize = branches.size();
707//       for (int i = 0; i < nodeSize; ++i) {
708//           CharGroup group = branches.get(i);
709//           if (null != group.children) {
710//               String pseudoHash = getPseudoHash(group.children);
711//               ArrayList<Node> similarList = map.get(pseudoHash);
712//               if (null == similarList) {
713//                   similarList = new ArrayList<Node>();
714//                   map.put(pseudoHash, similarList);
715//               }
716//               boolean merged = false;
717//               for (Node similar : similarList) {
718//                   if (isEqual(group.children, similar)) {
719//                       group.children = similar;
720//                       merged = true;
721//                       break;
722//                   }
723//               }
724//               if (!merged) {
725//                   similarList.add(group.children);
726//               }
727//               mergeTailsInner(map, group.children);
728//           }
729//       }
730//       return map;
731//   }
732
733//  private static String getPseudoHash(final Node node) {
734//      StringBuilder s = new StringBuilder();
735//      for (CharGroup g : node.data) {
736//          s.append(g.frequency);
737//          for (int ch : g.chars) {
738//              s.append(Character.toChars(ch));
739//          }
740//      }
741//      return s.toString();
742//  }
743
744    /**
745     * Iterator to walk through a dictionary.
746     *
747     * This is purely for convenience.
748     */
749    public static class DictionaryIterator implements Iterator<Word> {
750
751        private static class Position {
752            public Iterator<CharGroup> pos;
753            public int length;
754            public Position(ArrayList<CharGroup> groups) {
755                pos = groups.iterator();
756                length = 0;
757            }
758        }
759        final StringBuilder mCurrentString;
760        final LinkedList<Position> mPositions;
761
762        public DictionaryIterator(ArrayList<CharGroup> root) {
763            mCurrentString = new StringBuilder();
764            mPositions = new LinkedList<Position>();
765            final Position rootPos = new Position(root);
766            mPositions.add(rootPos);
767        }
768
769        @Override
770        public boolean hasNext() {
771            for (Position p : mPositions) {
772                if (p.pos.hasNext()) {
773                    return true;
774                }
775            }
776            return false;
777        }
778
779        @Override
780        public Word next() {
781            Position currentPos = mPositions.getLast();
782            mCurrentString.setLength(mCurrentString.length() - currentPos.length);
783
784            do {
785                if (currentPos.pos.hasNext()) {
786                    final CharGroup currentGroup = currentPos.pos.next();
787                    currentPos.length = currentGroup.mChars.length;
788                    for (int i : currentGroup.mChars)
789                        mCurrentString.append(Character.toChars(i));
790                    if (null != currentGroup.mChildren) {
791                        currentPos = new Position(currentGroup.mChildren.mData);
792                        mPositions.addLast(currentPos);
793                    }
794                    if (currentGroup.mFrequency >= 0)
795                        return new Word(mCurrentString.toString(), currentGroup.mFrequency,
796                                currentGroup.mShortcutTargets, currentGroup.mBigrams,
797                                currentGroup.mIsNotAWord, currentGroup.mIsBlacklistEntry);
798                } else {
799                    mPositions.removeLast();
800                    currentPos = mPositions.getLast();
801                    mCurrentString.setLength(mCurrentString.length() - mPositions.getLast().length);
802                }
803            } while (true);
804        }
805
806        @Override
807        public void remove() {
808            throw new UnsupportedOperationException("Unsupported yet");
809        }
810
811    }
812
813    /**
814     * Method to return an iterator.
815     *
816     * This method enables Java's enhanced for loop. With this you can have a FusionDictionary x
817     * and say : for (Word w : x) {}
818     */
819    @Override
820    public Iterator<Word> iterator() {
821        return new DictionaryIterator(mRoot.mData);
822    }
823}
824