FusionDictionary.java revision 72b1c9394105b6fbc0d8c6ff00f3574ee37a9aaa
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 java.util.ArrayList; 20import java.util.Arrays; 21import java.util.Collections; 22import java.util.HashMap; 23import java.util.Iterator; 24import java.util.LinkedList; 25 26/** 27 * A dictionary that can fusion heads and tails of words for more compression. 28 */ 29public class FusionDictionary implements Iterable<Word> { 30 31 private static final boolean DBG = MakedictLog.DBG; 32 33 /** 34 * A node of the dictionary, containing several CharGroups. 35 * 36 * A node is but an ordered array of CharGroups, which essentially contain all the 37 * real information. 38 * This class also contains fields to cache size and address, to help with binary 39 * generation. 40 */ 41 public static class Node { 42 ArrayList<CharGroup> mData; 43 // To help with binary generation 44 int mCachedSize; 45 int mCachedAddress; 46 public Node() { 47 mData = new ArrayList<CharGroup>(); 48 mCachedSize = Integer.MIN_VALUE; 49 mCachedAddress = Integer.MIN_VALUE; 50 } 51 public Node(ArrayList<CharGroup> data) { 52 mData = data; 53 mCachedSize = Integer.MIN_VALUE; 54 mCachedAddress = Integer.MIN_VALUE; 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 Node currentNode = mRoot; 386 int charIndex = 0; 387 388 CharGroup currentGroup = null; 389 int differentCharIndex = 0; // Set by the loop to the index of the char that differs 390 int nodeIndex = findIndexOfChar(mRoot, word[charIndex]); 391 while (CHARACTER_NOT_FOUND != nodeIndex) { 392 currentGroup = currentNode.mData.get(nodeIndex); 393 differentCharIndex = compareArrays(currentGroup.mChars, word, charIndex); 394 if (ARRAYS_ARE_EQUAL != differentCharIndex 395 && differentCharIndex < currentGroup.mChars.length) break; 396 if (null == currentGroup.mChildren) break; 397 charIndex += currentGroup.mChars.length; 398 if (charIndex >= word.length) break; 399 currentNode = currentGroup.mChildren; 400 nodeIndex = findIndexOfChar(currentNode, word[charIndex]); 401 } 402 403 if (-1 == nodeIndex) { 404 // No node at this point to accept the word. Create one. 405 final int insertionIndex = findInsertionIndex(currentNode, word[charIndex]); 406 final CharGroup newGroup = new CharGroup( 407 Arrays.copyOfRange(word, charIndex, word.length), 408 shortcutTargets, null /* bigrams */, frequency, isNotAWord, isBlacklistEntry); 409 currentNode.mData.add(insertionIndex, newGroup); 410 if (DBG) checkStack(currentNode); 411 } else { 412 // There is a word with a common prefix. 413 if (differentCharIndex == currentGroup.mChars.length) { 414 if (charIndex + differentCharIndex >= word.length) { 415 // The new word is a prefix of an existing word, but the node on which it 416 // should end already exists as is. Since the old CharNode was not a terminal, 417 // make it one by filling in its frequency and other attributes 418 currentGroup.update(frequency, shortcutTargets, null, isNotAWord, 419 isBlacklistEntry); 420 } else { 421 // The new word matches the full old word and extends past it. 422 // We only have to create a new node and add it to the end of this. 423 final CharGroup newNode = new CharGroup( 424 Arrays.copyOfRange(word, charIndex + differentCharIndex, word.length), 425 shortcutTargets, null /* bigrams */, frequency, isNotAWord, 426 isBlacklistEntry); 427 currentGroup.mChildren = new Node(); 428 currentGroup.mChildren.mData.add(newNode); 429 } 430 } else { 431 if (0 == differentCharIndex) { 432 // Exact same word. Update the frequency if higher. This will also add the 433 // new shortcuts to the existing shortcut list if it already exists. 434 currentGroup.update(frequency, shortcutTargets, null, 435 currentGroup.mIsNotAWord && isNotAWord, 436 currentGroup.mIsBlacklistEntry || isBlacklistEntry); 437 } else { 438 // Partial prefix match only. We have to replace the current node with a node 439 // containing the current prefix and create two new ones for the tails. 440 Node newChildren = new Node(); 441 final CharGroup newOldWord = new CharGroup( 442 Arrays.copyOfRange(currentGroup.mChars, differentCharIndex, 443 currentGroup.mChars.length), currentGroup.mShortcutTargets, 444 currentGroup.mBigrams, currentGroup.mFrequency, 445 currentGroup.mIsNotAWord, currentGroup.mIsBlacklistEntry, 446 currentGroup.mChildren); 447 newChildren.mData.add(newOldWord); 448 449 final CharGroup newParent; 450 if (charIndex + differentCharIndex >= word.length) { 451 newParent = new CharGroup( 452 Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex), 453 shortcutTargets, null /* bigrams */, frequency, 454 isNotAWord, isBlacklistEntry, newChildren); 455 } else { 456 newParent = new CharGroup( 457 Arrays.copyOfRange(currentGroup.mChars, 0, differentCharIndex), 458 null /* shortcutTargets */, null /* bigrams */, -1, 459 false /* isNotAWord */, false /* isBlacklistEntry */, newChildren); 460 final CharGroup newWord = new CharGroup(Arrays.copyOfRange(word, 461 charIndex + differentCharIndex, word.length), 462 shortcutTargets, null /* bigrams */, frequency, 463 isNotAWord, isBlacklistEntry); 464 final int addIndex = word[charIndex + differentCharIndex] 465 > currentGroup.mChars[differentCharIndex] ? 1 : 0; 466 newChildren.mData.add(addIndex, newWord); 467 } 468 currentNode.mData.set(nodeIndex, newParent); 469 } 470 if (DBG) checkStack(currentNode); 471 } 472 } 473 } 474 475 private static int ARRAYS_ARE_EQUAL = 0; 476 477 /** 478 * Custom comparison of two int arrays taken to contain character codes. 479 * 480 * This method compares the two arrays passed as an argument in a lexicographic way, 481 * with an offset in the dst string. 482 * This method does NOT test for the first character. It is taken to be equal. 483 * I repeat: this method starts the comparison at 1 <> dstOffset + 1. 484 * The index where the strings differ is returned. ARRAYS_ARE_EQUAL = 0 is returned if the 485 * strings are equal. This works BECAUSE we don't look at the first character. 486 * 487 * @param src the left-hand side string of the comparison. 488 * @param dst the right-hand side string of the comparison. 489 * @param dstOffset the offset in the right-hand side string. 490 * @return the index at which the strings differ, or ARRAYS_ARE_EQUAL = 0 if they don't. 491 */ 492 private static int compareArrays(final int[] src, final int[] dst, int dstOffset) { 493 // We do NOT test the first char, because we come from a method that already 494 // tested it. 495 for (int i = 1; i < src.length; ++i) { 496 if (dstOffset + i >= dst.length) return i; 497 if (src[i] != dst[dstOffset + i]) return i; 498 } 499 if (dst.length > src.length) return src.length; 500 return ARRAYS_ARE_EQUAL; 501 } 502 503 /** 504 * Helper class that compares and sorts two chargroups according to their 505 * first element only. I repeat: ONLY the first element is considered, the rest 506 * is ignored. 507 * This comparator imposes orderings that are inconsistent with equals. 508 */ 509 static private class CharGroupComparator implements java.util.Comparator<CharGroup> { 510 @Override 511 public int compare(CharGroup c1, CharGroup c2) { 512 if (c1.mChars[0] == c2.mChars[0]) return 0; 513 return c1.mChars[0] < c2.mChars[0] ? -1 : 1; 514 } 515 } 516 final static private CharGroupComparator CHARGROUP_COMPARATOR = new CharGroupComparator(); 517 518 /** 519 * Finds the insertion index of a character within a node. 520 */ 521 private static int findInsertionIndex(final Node node, int character) { 522 final ArrayList<CharGroup> data = node.mData; 523 final CharGroup reference = new CharGroup(new int[] { character }, 524 null /* shortcutTargets */, null /* bigrams */, 0, false /* isNotAWord */, 525 false /* isBlacklistEntry */); 526 int result = Collections.binarySearch(data, reference, CHARGROUP_COMPARATOR); 527 return result >= 0 ? result : -result - 1; 528 } 529 530 private static int CHARACTER_NOT_FOUND = -1; 531 532 /** 533 * Find the index of a char in a node, if it exists. 534 * 535 * @param node the node to search in. 536 * @param character the character to search for. 537 * @return the position of the character if it's there, or CHARACTER_NOT_FOUND = -1 else. 538 */ 539 private static int findIndexOfChar(final Node node, int character) { 540 final int insertionIndex = findInsertionIndex(node, character); 541 if (node.mData.size() <= insertionIndex) return CHARACTER_NOT_FOUND; 542 return character == node.mData.get(insertionIndex).mChars[0] ? insertionIndex 543 : CHARACTER_NOT_FOUND; 544 } 545 546 /** 547 * Helper method to find a word in a given branch. 548 */ 549 public static CharGroup findWordInTree(Node node, final String s) { 550 int index = 0; 551 final StringBuilder checker = DBG ? new StringBuilder() : null; 552 553 CharGroup currentGroup; 554 do { 555 int indexOfGroup = findIndexOfChar(node, s.codePointAt(index)); 556 if (CHARACTER_NOT_FOUND == indexOfGroup) return null; 557 currentGroup = node.mData.get(indexOfGroup); 558 559 if (s.length() - index < currentGroup.mChars.length) return null; 560 int newIndex = index; 561 while (newIndex < s.length() && newIndex - index < currentGroup.mChars.length) { 562 if (currentGroup.mChars[newIndex - index] != s.codePointAt(newIndex)) return null; 563 newIndex++; 564 } 565 index = newIndex; 566 567 if (DBG) checker.append(new String(currentGroup.mChars, 0, currentGroup.mChars.length)); 568 if (index < s.length()) { 569 node = currentGroup.mChildren; 570 } 571 } while (null != node && index < s.length()); 572 573 if (index < s.length()) return null; 574 if (!currentGroup.isTerminal()) return null; 575 if (DBG && !s.equals(checker.toString())) return null; 576 return currentGroup; 577 } 578 579 /** 580 * Helper method to find out whether a word is in the dict or not. 581 */ 582 public boolean hasWord(final String s) { 583 if (null == s || "".equals(s)) { 584 throw new RuntimeException("Can't search for a null or empty string"); 585 } 586 return null != findWordInTree(mRoot, s); 587 } 588 589 /** 590 * Recursively count the number of character groups in a given branch of the trie. 591 * 592 * @param node the parent node. 593 * @return the number of char groups in all the branch under this node. 594 */ 595 public static int countCharGroups(final Node node) { 596 final int nodeSize = node.mData.size(); 597 int size = nodeSize; 598 for (int i = nodeSize - 1; i >= 0; --i) { 599 CharGroup group = node.mData.get(i); 600 if (null != group.mChildren) 601 size += countCharGroups(group.mChildren); 602 } 603 return size; 604 } 605 606 /** 607 * Recursively count the number of nodes in a given branch of the trie. 608 * 609 * @param node the node to count. 610 * @return the number of nodes in this branch. 611 */ 612 public static int countNodes(final Node node) { 613 int size = 1; 614 for (int i = node.mData.size() - 1; i >= 0; --i) { 615 CharGroup group = node.mData.get(i); 616 if (null != group.mChildren) 617 size += countNodes(group.mChildren); 618 } 619 return size; 620 } 621 622 // Recursively find out whether there are any bigrams. 623 // This can be pretty expensive especially if there aren't any (we return as soon 624 // as we find one, so it's much cheaper if there are bigrams) 625 private static boolean hasBigramsInternal(final Node node) { 626 if (null == node) return false; 627 for (int i = node.mData.size() - 1; i >= 0; --i) { 628 CharGroup group = node.mData.get(i); 629 if (null != group.mBigrams) return true; 630 if (hasBigramsInternal(group.mChildren)) return true; 631 } 632 return false; 633 } 634 635 /** 636 * Finds out whether there are any bigrams in this dictionary. 637 * 638 * @return true if there is any bigram, false otherwise. 639 */ 640 // TODO: this is expensive especially for large dictionaries without any bigram. 641 // The up side is, this is always accurate and correct and uses no memory. We should 642 // find a more efficient way of doing this, without compromising too much on memory 643 // and ease of use. 644 public boolean hasBigrams() { 645 return hasBigramsInternal(mRoot); 646 } 647 648 // Historically, the tails of the words were going to be merged to save space. 649 // However, that would prevent the code to search for a specific address in log(n) 650 // time so this was abandoned. 651 // The code is still of interest as it does add some compression to any dictionary 652 // that has no need for attributes. Implementations that does not read attributes should be 653 // able to read a dictionary with merged tails. 654 // Also, the following code does support frequencies, as in, it will only merges 655 // tails that share the same frequency. Though it would result in the above loss of 656 // performance while searching by address, it is still technically possible to merge 657 // tails that contain attributes, but this code does not take that into account - it does 658 // not compare attributes and will merge terminals with different attributes regardless. 659 public void mergeTails() { 660 MakedictLog.i("Do not merge tails"); 661 return; 662 663// MakedictLog.i("Merging nodes. Number of nodes : " + countNodes(root)); 664// MakedictLog.i("Number of groups : " + countCharGroups(root)); 665// 666// final HashMap<String, ArrayList<Node>> repository = 667// new HashMap<String, ArrayList<Node>>(); 668// mergeTailsInner(repository, root); 669// 670// MakedictLog.i("Number of different pseudohashes : " + repository.size()); 671// int size = 0; 672// for (ArrayList<Node> a : repository.values()) { 673// size += a.size(); 674// } 675// MakedictLog.i("Number of nodes after merge : " + (1 + size)); 676// MakedictLog.i("Recursively seen nodes : " + countNodes(root)); 677 } 678 679 // The following methods are used by the deactivated mergeTails() 680// private static boolean isEqual(Node a, Node b) { 681// if (null == a && null == b) return true; 682// if (null == a || null == b) return false; 683// if (a.data.size() != b.data.size()) return false; 684// final int size = a.data.size(); 685// for (int i = size - 1; i >= 0; --i) { 686// CharGroup aGroup = a.data.get(i); 687// CharGroup bGroup = b.data.get(i); 688// if (aGroup.frequency != bGroup.frequency) return false; 689// if (aGroup.alternates == null && bGroup.alternates != null) return false; 690// if (aGroup.alternates != null && !aGroup.equals(bGroup.alternates)) return false; 691// if (!Arrays.equals(aGroup.chars, bGroup.chars)) return false; 692// if (!isEqual(aGroup.children, bGroup.children)) return false; 693// } 694// return true; 695// } 696 697// static private HashMap<String, ArrayList<Node>> mergeTailsInner( 698// final HashMap<String, ArrayList<Node>> map, final Node node) { 699// final ArrayList<CharGroup> branches = node.data; 700// final int nodeSize = branches.size(); 701// for (int i = 0; i < nodeSize; ++i) { 702// CharGroup group = branches.get(i); 703// if (null != group.children) { 704// String pseudoHash = getPseudoHash(group.children); 705// ArrayList<Node> similarList = map.get(pseudoHash); 706// if (null == similarList) { 707// similarList = new ArrayList<Node>(); 708// map.put(pseudoHash, similarList); 709// } 710// boolean merged = false; 711// for (Node similar : similarList) { 712// if (isEqual(group.children, similar)) { 713// group.children = similar; 714// merged = true; 715// break; 716// } 717// } 718// if (!merged) { 719// similarList.add(group.children); 720// } 721// mergeTailsInner(map, group.children); 722// } 723// } 724// return map; 725// } 726 727// private static String getPseudoHash(final Node node) { 728// StringBuilder s = new StringBuilder(); 729// for (CharGroup g : node.data) { 730// s.append(g.frequency); 731// for (int ch : g.chars){ 732// s.append(Character.toChars(ch)); 733// } 734// } 735// return s.toString(); 736// } 737 738 /** 739 * Iterator to walk through a dictionary. 740 * 741 * This is purely for convenience. 742 */ 743 public static class DictionaryIterator implements Iterator<Word> { 744 745 private static class Position { 746 public Iterator<CharGroup> pos; 747 public int length; 748 public Position(ArrayList<CharGroup> groups) { 749 pos = groups.iterator(); 750 length = 0; 751 } 752 } 753 final StringBuilder mCurrentString; 754 final LinkedList<Position> mPositions; 755 756 public DictionaryIterator(ArrayList<CharGroup> root) { 757 mCurrentString = new StringBuilder(); 758 mPositions = new LinkedList<Position>(); 759 final Position rootPos = new Position(root); 760 mPositions.add(rootPos); 761 } 762 763 @Override 764 public boolean hasNext() { 765 for (Position p : mPositions) { 766 if (p.pos.hasNext()) { 767 return true; 768 } 769 } 770 return false; 771 } 772 773 @Override 774 public Word next() { 775 Position currentPos = mPositions.getLast(); 776 mCurrentString.setLength(mCurrentString.length() - currentPos.length); 777 778 do { 779 if (currentPos.pos.hasNext()) { 780 final CharGroup currentGroup = currentPos.pos.next(); 781 currentPos.length = currentGroup.mChars.length; 782 for (int i : currentGroup.mChars) 783 mCurrentString.append(Character.toChars(i)); 784 if (null != currentGroup.mChildren) { 785 currentPos = new Position(currentGroup.mChildren.mData); 786 mPositions.addLast(currentPos); 787 } 788 if (currentGroup.mFrequency >= 0) 789 return new Word(mCurrentString.toString(), currentGroup.mFrequency, 790 currentGroup.mShortcutTargets, currentGroup.mBigrams, 791 currentGroup.mIsNotAWord, currentGroup.mIsBlacklistEntry); 792 } else { 793 mPositions.removeLast(); 794 currentPos = mPositions.getLast(); 795 mCurrentString.setLength(mCurrentString.length() - mPositions.getLast().length); 796 } 797 } while(true); 798 } 799 800 @Override 801 public void remove() { 802 throw new UnsupportedOperationException("Unsupported yet"); 803 } 804 805 } 806 807 /** 808 * Method to return an iterator. 809 * 810 * This method enables Java's enhanced for loop. With this you can have a FusionDictionary x 811 * and say : for (Word w : x) {} 812 */ 813 @Override 814 public Iterator<Word> iterator() { 815 return new DictionaryIterator(mRoot.mData); 816 } 817} 818