blob: d4c51df63564087e71bc12e22a3cace1e692317d [file] [log] [blame]
satok30088252010-12-01 21:22:15 +09001/*
Ken Wakasa5460ea32012-07-30 16:27:44 +09002 * Copyright (C) 2010, The Android Open Source Project
Ken Wakasa0bbb9172012-07-25 17:51:43 +09003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
satok30088252010-12-01 21:22:15 +090016
Ken Wakasaf1008c52012-07-31 17:56:40 +090017#include <cassert>
18#include <cstring>
satok30088252010-12-01 21:22:15 +090019
satoke808e432010-12-02 14:53:24 +090020#define LOG_TAG "LatinIME: unigram_dictionary.cpp"
satok30088252010-12-01 21:22:15 +090021
Ken Wakasa77e8e812012-08-02 19:48:08 +090022#include "binary_format.h"
satok30088252010-12-01 21:22:15 +090023#include "char_utils.h"
Ken Wakasa3b088a22012-05-16 23:05:32 +090024#include "defines.h"
satoke808e432010-12-02 14:53:24 +090025#include "dictionary.h"
Ken Wakasa77e8e812012-08-02 19:48:08 +090026#include "proximity_info.h"
Jean Chalardcf9dbbd2011-12-26 15:16:59 +090027#include "terminal_attributes.h"
Ken Wakasa77e8e812012-08-02 19:48:08 +090028#include "unigram_dictionary.h"
29#include "words_priority_queue.h"
30#include "words_priority_queue_pool.h"
Jean Chalard1059f272011-06-28 20:45:05 +090031
satok30088252010-12-01 21:22:15 +090032namespace latinime {
33
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090034const UnigramDictionary::digraph_t UnigramDictionary::GERMAN_UMLAUT_DIGRAPHS[] =
Jean Chalardd3043382012-03-21 18:38:25 +090035 { { 'a', 'e', 0x00E4 }, // U+00E4 : LATIN SMALL LETTER A WITH DIAERESIS
36 { 'o', 'e', 0x00F6 }, // U+00F6 : LATIN SMALL LETTER O WITH DIAERESIS
37 { 'u', 'e', 0x00FC } }; // U+00FC : LATIN SMALL LETTER U WITH DIAERESIS
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090038
Jean Chalardcc78d032012-03-23 16:48:49 +090039const UnigramDictionary::digraph_t UnigramDictionary::FRENCH_LIGATURES_DIGRAPHS[] =
40 { { 'a', 'e', 0x00E6 }, // U+00E6 : LATIN SMALL LETTER AE
41 { 'o', 'e', 0x0153 } }; // U+0153 : LATIN SMALL LIGATURE OE
42
Jean Chalard293ece02011-06-16 20:55:16 +090043// TODO: check the header
Ken Wakasa0bbb9172012-07-25 17:51:43 +090044UnigramDictionary::UnigramDictionary(const uint8_t *const streamStart, int typedLetterMultiplier,
Jean Chalardcd274b12012-04-06 18:26:00 +090045 int fullWordMultiplier, int maxWordLength, int maxWords, const unsigned int flags)
Jean Chalard46a1eec2012-02-27 19:48:47 +090046 : DICT_ROOT(streamStart), MAX_WORD_LENGTH(maxWordLength), MAX_WORDS(maxWords),
satok662fe692010-12-08 17:05:39 +090047 TYPED_LETTER_MULTIPLIER(typedLetterMultiplier), FULL_WORD_MULTIPLIER(fullWordMultiplier),
Jean Chalard1059f272011-06-28 20:45:05 +090048 // TODO : remove this variable.
49 ROOT_POS(0),
satok9df4a452012-03-23 16:05:18 +090050 BYTES_IN_ONE_CHAR(sizeof(int)),
Jean Chalardcd274b12012-04-06 18:26:00 +090051 MAX_DIGRAPH_SEARCH_DEPTH(DEFAULT_MAX_DIGRAPH_SEARCH_DEPTH), FLAGS(flags) {
Ken Wakasade3070a2011-03-19 09:16:42 +090052 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +090053 AKLOGI("UnigramDictionary - constructor");
Ken Wakasade3070a2011-03-19 09:16:42 +090054 }
satok30088252010-12-01 21:22:15 +090055}
56
satok2df30602011-07-15 13:49:00 +090057UnigramDictionary::~UnigramDictionary() {
satok2df30602011-07-15 13:49:00 +090058}
satok30088252010-12-01 21:22:15 +090059
satok9df4a452012-03-23 16:05:18 +090060static inline unsigned int getCodesBufferSize(const int *codes, const int codesSize) {
61 return sizeof(*codes) * codesSize;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090062}
63
Ken Wakasa951ab9d2012-03-09 19:18:59 +090064// TODO: This needs to take a const unsigned short* and not tinker with its contents
satok1147c7b2011-12-14 15:04:58 +090065static inline void addWord(
Jean Chalard926ef062012-08-10 13:14:45 +090066 unsigned short *word, int length, int frequency, WordsPriorityQueue *queue, int type) {
67 queue->push(frequency, word, length, type);
satok1147c7b2011-12-14 15:04:58 +090068}
69
Jean Chalardd3043382012-03-21 18:38:25 +090070// Return the replacement code point for a digraph, or 0 if none.
71int UnigramDictionary::getDigraphReplacement(const int *codes, const int i, const int codesSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +090072 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090073
74 // There can't be a digraph if we don't have at least 2 characters to examine
75 if (i + 2 > codesSize) return false;
76
77 // Search for the first char of some digraph
78 int lastDigraphIndex = -1;
satok9df4a452012-03-23 16:05:18 +090079 const int thisChar = codes[i];
Jean Chalard6c300612012-03-06 19:54:03 +090080 for (lastDigraphIndex = digraphsSize - 1; lastDigraphIndex >= 0; --lastDigraphIndex) {
81 if (thisChar == digraphs[lastDigraphIndex].first) break;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090082 }
83 // No match: return early
Jean Chalardd3043382012-03-21 18:38:25 +090084 if (lastDigraphIndex < 0) return 0;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090085
86 // It's an interesting digraph if the second char matches too.
satok9df4a452012-03-23 16:05:18 +090087 if (digraphs[lastDigraphIndex].second == codes[i + 1]) {
Jean Chalardd3043382012-03-21 18:38:25 +090088 return digraphs[lastDigraphIndex].replacement;
89 } else {
90 return 0;
91 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090092}
93
94// Mostly the same arguments as the non-recursive version, except:
95// codes is the original value. It points to the start of the work buffer, and gets passed as is.
96// codesSize is the size of the user input (thus, it is the size of codesSrc).
97// codesDest is the current point in the work buffer.
98// codesSrc is the current point in the user-input, original, content-unmodified buffer.
99// codesRemain is the remaining size in codesSrc.
satok1d7eaf82011-07-13 10:32:02 +0900100void UnigramDictionary::getWordWithDigraphSuggestionsRec(ProximityInfo *proximityInfo,
satok1147c7b2011-12-14 15:04:58 +0900101 const int *xcoordinates, const int *ycoordinates, const int *codesBuffer,
satok219a5142012-03-08 11:53:18 +0900102 int *xCoordinatesBuffer, int *yCoordinatesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900103 const int codesBufferSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900104 const bool useFullEditDistance, const int *codesSrc,
satok1147c7b2011-12-14 15:04:58 +0900105 const int codesRemain, const int currentDepth, int *codesDest, Correction *correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900106 WordsPriorityQueuePool *queuePool,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900107 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900108
satok9df4a452012-03-23 16:05:18 +0900109 const int startIndex = codesDest - codesBuffer;
Jean Chalard6c300612012-03-06 19:54:03 +0900110 if (currentDepth < MAX_DIGRAPH_SEARCH_DEPTH) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900111 for (int i = 0; i < codesRemain; ++i) {
satok219a5142012-03-08 11:53:18 +0900112 xCoordinatesBuffer[startIndex + i] = xcoordinates[codesBufferSize - codesRemain + i];
113 yCoordinatesBuffer[startIndex + i] = ycoordinates[codesBufferSize - codesRemain + i];
Jean Chalardd3043382012-03-21 18:38:25 +0900114 const int replacementCodePoint =
115 getDigraphReplacement(codesSrc, i, codesRemain, digraphs, digraphsSize);
116 if (0 != replacementCodePoint) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900117 // Found a digraph. We will try both spellings. eg. the word is "pruefen"
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900118
Jean Chalardd3043382012-03-21 18:38:25 +0900119 // Copy the word up to the first char of the digraph, including proximity chars,
120 // and overwrite the primary code with the replacement code point. Then, continue
121 // processing on the remaining part of the word, skipping the second char of the
122 // digraph.
123 // In our example, copy "pru", replace "u" with the version with the diaeresis and
124 // continue running on "fen".
Jean Chalarda787dba2011-03-04 12:17:48 +0900125 // Make i the index of the second char of the digraph for simplicity. Forgetting
126 // to do that results in an infinite recursion so take care!
127 ++i;
128 memcpy(codesDest, codesSrc, i * BYTES_IN_ONE_CHAR);
Jean Chalardd3043382012-03-21 18:38:25 +0900129 codesDest[(i - 1) * (BYTES_IN_ONE_CHAR / sizeof(codesDest[0]))] =
130 replacementCodePoint;
Jean Chalarda787dba2011-03-04 12:17:48 +0900131 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900132 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900133 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i + 1,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900134 codesRemain - i - 1, currentDepth + 1, codesDest + i, correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900135 queuePool, digraphs, digraphsSize);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900136
Jean Chalarda787dba2011-03-04 12:17:48 +0900137 // Copy the second char of the digraph in place, then continue processing on
138 // the remaining part of the word.
139 // In our example, after "pru" in the buffer copy the "e", and continue on "fen"
satok9df4a452012-03-23 16:05:18 +0900140 memcpy(codesDest + i, codesSrc + i, BYTES_IN_ONE_CHAR);
Jean Chalarda787dba2011-03-04 12:17:48 +0900141 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900142 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900143 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i, codesRemain - i,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900144 currentDepth + 1, codesDest + i, correction, queuePool, digraphs,
145 digraphsSize);
Jean Chalarda787dba2011-03-04 12:17:48 +0900146 return;
147 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900148 }
149 }
150
151 // If we come here, we hit the end of the word: let's check it against the dictionary.
152 // In our example, we'll come here once for "prufen" and then once for "pruefen".
153 // If the word contains several digraphs, we'll come it for the product of them.
154 // eg. if the word is "ueberpruefen" we'll test, in order, against
155 // "uberprufen", "uberpruefen", "ueberprufen", "ueberpruefen".
156 const unsigned int remainingBytes = BYTES_IN_ONE_CHAR * codesRemain;
satok219a5142012-03-08 11:53:18 +0900157 if (0 != remainingBytes) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900158 memcpy(codesDest, codesSrc, remainingBytes);
satok219a5142012-03-08 11:53:18 +0900159 memcpy(&xCoordinatesBuffer[startIndex], &xcoordinates[codesBufferSize - codesRemain],
160 sizeof(int) * codesRemain);
161 memcpy(&yCoordinatesBuffer[startIndex], &ycoordinates[codesBufferSize - codesRemain],
162 sizeof(int) * codesRemain);
163 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900164
satok219a5142012-03-08 11:53:18 +0900165 getWordSuggestions(proximityInfo, xCoordinatesBuffer, yCoordinatesBuffer, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900166 startIndex + codesRemain, bigramMap, bigramFilter, useFullEditDistance, correction,
satoka7e5a5a2011-12-15 16:49:12 +0900167 queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900168}
169
Jean Chalard8950ce62012-05-07 16:28:30 +0900170// bigramMap contains the association <bigram address> -> <bigram frequency>
171// bigramFilter is a bloom filter for fast rejection: see functions setInFilter and isInFilter
172// in bigram_dictionary.cpp
satoka7e5a5a2011-12-15 16:49:12 +0900173int UnigramDictionary::getSuggestions(ProximityInfo *proximityInfo,
satokb1ed1d42012-06-14 16:35:23 -0700174 const int *xcoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900175 const int *ycoordinates, const int *codes, const int codesSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900176 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard6931df92012-07-12 12:55:48 +0900177 const bool useFullEditDistance, unsigned short *outWords, int *frequencies,
178 int *outputTypes) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900179
satokb1ed1d42012-06-14 16:35:23 -0700180 WordsPriorityQueuePool queuePool(MAX_WORDS, SUB_QUEUE_MAX_WORDS, MAX_WORD_LENGTH);
181 queuePool.clearAll();
satok1bc038c2012-06-14 11:25:50 -0700182 Correction masterCorrection;
183 masterCorrection.resetCorrection();
Jean Chalardaa8df592012-04-06 18:54:20 +0900184 if (BinaryFormat::REQUIRES_GERMAN_UMLAUT_PROCESSING & FLAGS)
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900185 { // Incrementally tune the word and try all possibilities
satok9df4a452012-03-23 16:05:18 +0900186 int codesBuffer[getCodesBufferSize(codes, codesSize)];
satok219a5142012-03-08 11:53:18 +0900187 int xCoordinatesBuffer[codesSize];
188 int yCoordinatesBuffer[codesSize];
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900189 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900190 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700191 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
satokb1ed1d42012-06-14 16:35:23 -0700192 &queuePool, GERMAN_UMLAUT_DIGRAPHS,
Jean Chalard6c300612012-03-06 19:54:03 +0900193 sizeof(GERMAN_UMLAUT_DIGRAPHS) / sizeof(GERMAN_UMLAUT_DIGRAPHS[0]));
Jean Chalardaa8df592012-04-06 18:54:20 +0900194 } else if (BinaryFormat::REQUIRES_FRENCH_LIGATURES_PROCESSING & FLAGS) {
satokacb6c542012-03-23 20:58:18 +0900195 int codesBuffer[getCodesBufferSize(codes, codesSize)];
Jean Chalardcc78d032012-03-23 16:48:49 +0900196 int xCoordinatesBuffer[codesSize];
197 int yCoordinatesBuffer[codesSize];
198 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900199 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700200 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
satokb1ed1d42012-06-14 16:35:23 -0700201 &queuePool, FRENCH_LIGATURES_DIGRAPHS,
Jean Chalardcc78d032012-03-23 16:48:49 +0900202 sizeof(FRENCH_LIGATURES_DIGRAPHS) / sizeof(FRENCH_LIGATURES_DIGRAPHS[0]));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900203 } else { // Normal processing
Jean Chalard338d3ec2012-04-06 19:28:34 +0900204 getWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, codesSize,
satokb1ed1d42012-06-14 16:35:23 -0700205 bigramMap, bigramFilter, useFullEditDistance, &masterCorrection, &queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900206 }
207
satok817e5172011-03-04 06:06:45 -0800208 PROF_START(20);
satok8330b482012-01-23 16:52:37 +0900209 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700210 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700211 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900212 ns += 0;
213 AKLOGI("Max normalized score = %f", ns);
214 }
satoka7e5a5a2011-12-15 16:49:12 +0900215 const int suggestedWordsCount =
Jean Chalard926ef062012-08-10 13:14:45 +0900216 queuePool.getMasterQueue()->outputSuggestions(masterCorrection.getPrimaryInputWord(),
217 codesSize, frequencies, outWords, outputTypes);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900218
219 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700220 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700221 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900222 ns += 0;
satok9fb6f472012-01-13 18:01:22 +0900223 AKLOGI("Returning %d words", suggestedWordsCount);
Jean Chalard980d6b62011-06-30 17:02:23 +0900224 /// Print the returned words
225 for (int j = 0; j < suggestedWordsCount; ++j) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900226 short unsigned int *w = outWords + j * MAX_WORD_LENGTH;
Jean Chalard980d6b62011-06-30 17:02:23 +0900227 char s[MAX_WORD_LENGTH];
228 for (int i = 0; i <= MAX_WORD_LENGTH; i++) s[i] = w[i];
Jean-Baptiste Querucd7c4132012-05-16 16:56:11 -0700229 (void)s;
satok9fb6f472012-01-13 18:01:22 +0900230 AKLOGI("%s %i", s, frequencies[j]);
Jean Chalard980d6b62011-06-30 17:02:23 +0900231 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900232 }
satok817e5172011-03-04 06:06:45 -0800233 PROF_END(20);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900234 PROF_CLOSE;
235 return suggestedWordsCount;
236}
237
satok1d7eaf82011-07-13 10:32:02 +0900238void UnigramDictionary::getWordSuggestions(ProximityInfo *proximityInfo,
satok1147c7b2011-12-14 15:04:58 +0900239 const int *xcoordinates, const int *ycoordinates, const int *codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900240 const int inputSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900241 const bool useFullEditDistance, Correction *correction,
242 WordsPriorityQueuePool *queuePool) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900243
satok61e2f852011-01-05 14:13:07 +0900244 PROF_OPEN;
245 PROF_START(0);
satok61e2f852011-01-05 14:13:07 +0900246 PROF_END(0);
satok30088252010-12-01 21:22:15 +0900247
satok61e2f852011-01-05 14:13:07 +0900248 PROF_START(1);
Jean Chalard8950ce62012-05-07 16:28:30 +0900249 getOneWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, bigramMap, bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900250 useFullEditDistance, inputSize, correction, queuePool);
satok61e2f852011-01-05 14:13:07 +0900251 PROF_END(1);
252
253 PROF_START(2);
satok10266c02011-08-19 22:05:59 +0900254 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900255 PROF_END(2);
satokcdbbea72010-12-08 16:04:16 +0900256
satok61e2f852011-01-05 14:13:07 +0900257 PROF_START(3);
satok10266c02011-08-19 22:05:59 +0900258 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900259 PROF_END(3);
satok30088252010-12-01 21:22:15 +0900260
satok61e2f852011-01-05 14:13:07 +0900261 PROF_START(4);
satok8330b482012-01-23 16:52:37 +0900262 bool hasAutoCorrectionCandidate = false;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900263 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
satok8330b482012-01-23 16:52:37 +0900264 if (masterQueue->size() > 0) {
satok0028ed32012-05-16 20:42:12 +0900265 float nsForMaster = masterQueue->getHighestNormalizedScore(
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900266 correction->getPrimaryInputWord(), inputSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900267 hasAutoCorrectionCandidate = (nsForMaster > START_TWO_WORDS_CORRECTION_THRESHOLD);
268 }
satok61e2f852011-01-05 14:13:07 +0900269 PROF_END(4);
satoka3d78f62010-12-09 22:08:33 +0900270
satok61e2f852011-01-05 14:13:07 +0900271 PROF_START(5);
satok99557162012-01-26 22:49:13 +0900272 // Multiple word suggestions
273 if (SUGGEST_MULTIPLE_WORDS
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900274 && inputSize >= MIN_USER_TYPED_LENGTH_FOR_MULTIPLE_WORD_SUGGESTION) {
satoka85f4922012-01-30 18:18:30 +0900275 getSplitMultipleWordsSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900276 useFullEditDistance, inputSize, correction, queuePool,
satok1f6b52e2012-01-30 13:53:58 +0900277 hasAutoCorrectionCandidate);
satok662fe692010-12-08 17:05:39 +0900278 }
satok61e2f852011-01-05 14:13:07 +0900279 PROF_END(5);
satok817e5172011-03-04 06:06:45 -0800280
281 PROF_START(6);
satok99557162012-01-26 22:49:13 +0900282 // Note: This line is intentionally left blank
satok817e5172011-03-04 06:06:45 -0800283 PROF_END(6);
satok99557162012-01-26 22:49:13 +0900284
satok29dc8062012-01-17 15:59:15 +0900285 if (DEBUG_DICT) {
satok6ad15fc2012-01-16 16:21:21 +0900286 queuePool->dumpSubQueue1TopSuggestions();
satok29dc8062012-01-17 15:59:15 +0900287 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900288 WordsPriorityQueue *queue = queuePool->getSubQueue(FIRST_WORD_INDEX, i);
satok29dc8062012-01-17 15:59:15 +0900289 if (queue->size() > 0) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900290 WordsPriorityQueue::SuggestedWord *sw = queue->top();
satok29dc8062012-01-17 15:59:15 +0900291 const int score = sw->mScore;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900292 const unsigned short *word = sw->mWord;
satok29dc8062012-01-17 15:59:15 +0900293 const int wordLength = sw->mWordLength;
satok0028ed32012-05-16 20:42:12 +0900294 float ns = Correction::RankingAlgorithm::calcNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900295 correction->getPrimaryInputWord(), i, word, wordLength, score);
satok29dc8062012-01-17 15:59:15 +0900296 ns += 0;
297 AKLOGI("--- TOP SUB WORDS for %d --- %d %f [%d]", i, score, ns,
satok54af64a2012-01-17 15:58:23 +0900298 (ns > TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD));
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900299 DUMP_WORD(correction->getPrimaryInputWord(), i);
satok29dc8062012-01-17 15:59:15 +0900300 DUMP_WORD(word, wordLength);
301 }
302 }
satok6ad15fc2012-01-16 16:21:21 +0900303 }
satok30088252010-12-01 21:22:15 +0900304}
305
Yusuke Nojima258bfe62011-09-28 12:59:43 +0900306void UnigramDictionary::initSuggestions(ProximityInfo *proximityInfo, const int *xCoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900307 const int *yCoordinates, const int *codes, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900308 Correction *correction) const {
Ken Wakasade3070a2011-03-19 09:16:42 +0900309 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +0900310 AKLOGI("initSuggest");
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900311 DUMP_WORD_INT(codes, inputSize);
Ken Wakasade3070a2011-03-19 09:16:42 +0900312 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900313 correction->initInputParams(proximityInfo, codes, inputSize, xCoordinates, yCoordinates);
314 const int maxDepth = min(inputSize * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
315 correction->initCorrection(proximityInfo, inputSize, maxDepth);
satok30088252010-12-01 21:22:15 +0900316}
317
satok715514d2010-12-02 20:19:59 +0900318static const char QUOTE = '\'';
satok662fe692010-12-08 17:05:39 +0900319static const char SPACE = ' ';
satok30088252010-12-01 21:22:15 +0900320
satok744dab62011-12-15 22:29:05 +0900321void UnigramDictionary::getOneWordSuggestions(ProximityInfo *proximityInfo,
322 const int *xcoordinates, const int *ycoordinates, const int *codes,
Jean Chalard8950ce62012-05-07 16:28:30 +0900323 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900324 const bool useFullEditDistance, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900325 Correction *correction, WordsPriorityQueuePool *queuePool) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900326 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, inputSize, correction);
327 getSuggestionCandidates(useFullEditDistance, inputSize, bigramMap, bigramFilter, correction,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900328 queuePool, true /* doAutoCompletion */, DEFAULT_MAX_ERRORS, FIRST_WORD_INDEX);
satok744dab62011-12-15 22:29:05 +0900329}
330
satok1147c7b2011-12-14 15:04:58 +0900331void UnigramDictionary::getSuggestionCandidates(const bool useFullEditDistance,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900332 const int inputSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900333 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900334 const bool doAutoCompletion, const int maxErrors, const int currentWordIndex) const {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900335 uint8_t totalTraverseCount = correction->pushAndGetTotalTraverseCount();
336 if (DEBUG_DICT) {
337 AKLOGI("Traverse count %d", totalTraverseCount);
338 }
339 if (totalTraverseCount > MULTIPLE_WORDS_SUGGESTION_MAX_TOTAL_TRAVERSE_COUNT) {
340 if (DEBUG_DICT) {
341 AKLOGI("Abort traversing %d", totalTraverseCount);
342 }
343 return;
344 }
satok10266c02011-08-19 22:05:59 +0900345 // TODO: Remove setCorrectionParams
satok1147c7b2011-12-14 15:04:58 +0900346 correction->setCorrectionParams(0, 0, 0,
satokd03317c2011-12-14 21:38:11 +0900347 -1 /* spaceProximityPos */, -1 /* missingSpacePos */, useFullEditDistance,
satok1a6da632011-12-16 23:15:06 +0900348 doAutoCompletion, maxErrors);
satok662fe692010-12-08 17:05:39 +0900349 int rootPosition = ROOT_POS;
Jean Chalard980d6b62011-06-30 17:02:23 +0900350 // Get the number of children of root, then increment the position
Jean Chalard6d419812012-01-16 15:19:47 +0900351 int childCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &rootPosition);
satok208268d2011-08-10 15:44:08 +0900352 int outputIndex = 0;
satokd2997922010-12-07 13:08:39 +0900353
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900354 correction->initCorrectionState(rootPosition, childCount, (inputSize <= 0));
satokd2997922010-12-07 13:08:39 +0900355
satok662fe692010-12-08 17:05:39 +0900356 // Depth first search
satok208268d2011-08-10 15:44:08 +0900357 while (outputIndex >= 0) {
satok1147c7b2011-12-14 15:04:58 +0900358 if (correction->initProcessState(outputIndex)) {
359 int siblingPos = correction->getTreeSiblingPos(outputIndex);
satokd2997922010-12-07 13:08:39 +0900360 int firstChildPos;
satok0f6c8e82011-08-03 02:19:44 +0900361
satok4e4e74e2011-08-03 23:27:32 +0900362 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900363 bigramMap, bigramFilter, correction, &childCount, &firstChildPos, &siblingPos,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900364 queuePool, currentWordIndex);
satok662fe692010-12-08 17:05:39 +0900365 // Update next sibling pos
satok1147c7b2011-12-14 15:04:58 +0900366 correction->setTreeSiblingPos(outputIndex, siblingPos);
satok208268d2011-08-10 15:44:08 +0900367
satokd2997922010-12-07 13:08:39 +0900368 if (needsToTraverseChildrenNodes) {
369 // Goes to child node
satok1147c7b2011-12-14 15:04:58 +0900370 outputIndex = correction->goDownTree(outputIndex, childCount, firstChildPos);
satokd2997922010-12-07 13:08:39 +0900371 }
372 } else {
satokcdbbea72010-12-08 16:04:16 +0900373 // Goes to parent sibling node
satok1147c7b2011-12-14 15:04:58 +0900374 outputIndex = correction->getTreeParentIndex(outputIndex);
satokd2997922010-12-07 13:08:39 +0900375 }
376 }
377}
378
Jean Chalard171d1802012-04-23 18:51:00 +0900379inline void UnigramDictionary::onTerminal(const int probability,
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900380 const TerminalAttributes& terminalAttributes, Correction *correction,
satok8330b482012-01-23 16:52:37 +0900381 WordsPriorityQueuePool *queuePool, const bool addToMasterQueue,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900382 const int currentWordIndex) const {
satok6ad15fc2012-01-16 16:21:21 +0900383 const int inputIndex = correction->getInputIndex();
384 const bool addToSubQueue = inputIndex < SUB_QUEUE_MAX_COUNT;
satok54af64a2012-01-17 15:58:23 +0900385
satok8876b752011-08-04 18:31:57 +0900386 int wordLength;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900387 unsigned short *wordPointer;
satok54af64a2012-01-17 15:58:23 +0900388
satok1f6b52e2012-01-30 13:53:58 +0900389 if ((currentWordIndex == FIRST_WORD_INDEX) && addToMasterQueue) {
satok54af64a2012-01-17 15:58:23 +0900390 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
Jean Chalard171d1802012-04-23 18:51:00 +0900391 const int finalProbability =
392 correction->getFinalProbability(probability, &wordPointer, &wordLength);
satok54af64a2012-01-17 15:58:23 +0900393
Jean Chalard72b1c932012-08-31 15:24:39 +0900394 if (0 != finalProbability && !terminalAttributes.isBlacklistedOrNotAWord()) {
Jean Chalard8af8c152012-08-17 09:37:39 +0900395 // If the probability is 0, we don't want to add this word. However we still
396 // want to add its shortcuts (including a possible whitelist entry) if any.
Jean Chalard72b1c932012-08-31 15:24:39 +0900397 // Furthermore, if this is not a word (shortcut only for example) or a blacklisted
398 // entry then we never want to suggest this.
Jean Chalard8af8c152012-08-17 09:37:39 +0900399 addWord(wordPointer, wordLength, finalProbability, masterQueue,
400 Dictionary::KIND_CORRECTION);
401 }
402
403 const int shortcutProbability = finalProbability > 0 ? finalProbability - 1 : 0;
404 // Please note that the shortcut candidates will be added to the master queue only.
405 TerminalAttributes::ShortcutIterator iterator =
406 terminalAttributes.getShortcutIterator();
407 while (iterator.hasNextShortcutTarget()) {
408 // TODO: addWord only supports weak ordering, meaning we have no means
409 // to control the order of the shortcuts relative to one another or to the word.
410 // We need to either modulate the probability of each shortcut according
411 // to its own shortcut probability or to make the queue
412 // so that the insert order is protected inside the queue for words
413 // with the same score. For the moment we use -1 to make sure the shortcut will
414 // never be in front of the word.
415 uint16_t shortcutTarget[MAX_WORD_LENGTH_INTERNAL];
416 int shortcutFrequency;
417 const int shortcutTargetStringLength = iterator.getNextShortcutTarget(
418 MAX_WORD_LENGTH_INTERNAL, shortcutTarget, &shortcutFrequency);
419 int shortcutScore;
420 int kind;
421 if (shortcutFrequency == BinaryFormat::WHITELIST_SHORTCUT_FREQUENCY
422 && correction->sameAsTyped()) {
423 shortcutScore = S_INT_MAX;
424 kind = Dictionary::KIND_WHITELIST;
425 } else {
426 shortcutScore = shortcutProbability;
427 kind = Dictionary::KIND_CORRECTION;
satok6ad15fc2012-01-16 16:21:21 +0900428 }
Jean Chalard8af8c152012-08-17 09:37:39 +0900429 addWord(shortcutTarget, shortcutTargetStringLength, shortcutScore,
430 masterQueue, kind);
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900431 }
satok54af64a2012-01-17 15:58:23 +0900432 }
satok6ad15fc2012-01-16 16:21:21 +0900433
satok54af64a2012-01-17 15:58:23 +0900434 // We only allow two words + other error correction for words with SUB_QUEUE_MIN_WORD_LENGTH
435 // or more length.
436 if (inputIndex >= SUB_QUEUE_MIN_WORD_LENGTH && addToSubQueue) {
satok8330b482012-01-23 16:52:37 +0900437 WordsPriorityQueue *subQueue;
satok7409d152012-01-26 16:13:25 +0900438 subQueue = queuePool->getSubQueue(currentWordIndex, inputIndex);
439 if (!subQueue) {
satok8330b482012-01-23 16:52:37 +0900440 return;
441 }
Jean Chalard171d1802012-04-23 18:51:00 +0900442 const int finalProbability = correction->getFinalProbabilityForSubQueue(
443 probability, &wordPointer, &wordLength, inputIndex);
Jean Chalard926ef062012-08-10 13:14:45 +0900444 addWord(wordPointer, wordLength, finalProbability, subQueue, Dictionary::KIND_CORRECTION);
Jean Chalardca5ef282011-06-17 15:36:26 +0900445 }
446}
447
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900448int UnigramDictionary::getSubStringSuggestion(
satok7409d152012-01-26 16:13:25 +0900449 ProximityInfo *proximityInfo, const int *xcoordinates, const int *ycoordinates,
satok3c09bb12012-01-26 18:36:19 +0900450 const int *codes, const bool useFullEditDistance, Correction *correction,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900451 WordsPriorityQueuePool *queuePool, const int inputSize,
satok3c09bb12012-01-26 18:36:19 +0900452 const bool hasAutoCorrectionCandidate, const int currentWordIndex,
453 const int inputWordStartPos, const int inputWordLength,
satok99557162012-01-26 22:49:13 +0900454 const int outputWordStartPos, const bool isSpaceProximity, int *freqArray,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900455 int*wordLengthArray, unsigned short *outputWord, int *outputWordLength) const {
Satoshi Kataoka67e3cc82012-05-31 15:04:58 +0900456 if (inputWordLength > MULTIPLE_WORDS_SUGGESTION_MAX_WORD_LENGTH) {
457 return FLAG_MULTIPLE_SUGGEST_ABORT;
458 }
459
460 /////////////////////////////////////////////
461 // safety net for multiple word suggestion //
462 // TODO: Remove this safety net //
463 /////////////////////////////////////////////
464 int smallWordCount = 0;
465 int singleLetterWordCount = 0;
466 if (inputWordLength == 1) {
467 ++singleLetterWordCount;
468 }
469 if (inputWordLength <= 2) {
470 // small word == single letter or 2-letter word
471 ++smallWordCount;
472 }
473 for (int i = 0; i < currentWordIndex; ++i) {
474 const int length = wordLengthArray[i];
475 if (length == 1) {
476 ++singleLetterWordCount;
477 // Safety net to avoid suggesting sequential single letter words
478 if (i < (currentWordIndex - 1)) {
479 if (wordLengthArray[i + 1] == 1) {
480 return FLAG_MULTIPLE_SUGGEST_ABORT;
481 }
482 } else if (inputWordLength == 1) {
483 return FLAG_MULTIPLE_SUGGEST_ABORT;
484 }
485 }
486 if (length <= 2) {
487 ++smallWordCount;
488 }
489 // Safety net to avoid suggesting multiple words with many (4 or more, for now) small words
490 if (singleLetterWordCount >= 3 || smallWordCount >= 4) {
491 return FLAG_MULTIPLE_SUGGEST_ABORT;
492 }
493 }
494 //////////////////////////////////////////////
495 // TODO: Remove the safety net above //
496 //////////////////////////////////////////////
497
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900498 unsigned short *tempOutputWord = 0;
satok1f6b52e2012-01-30 13:53:58 +0900499 int nextWordLength = 0;
satok99557162012-01-26 22:49:13 +0900500 // TODO: Optimize init suggestion
501 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900502 inputSize, correction);
satok99557162012-01-26 22:49:13 +0900503
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900504 unsigned short word[MAX_WORD_LENGTH_INTERNAL];
satok3c09bb12012-01-26 18:36:19 +0900505 int freq = getMostFrequentWordLike(
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900506 inputWordStartPos, inputWordLength, correction, word);
satok3c09bb12012-01-26 18:36:19 +0900507 if (freq > 0) {
satok1f6b52e2012-01-30 13:53:58 +0900508 nextWordLength = inputWordLength;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900509 tempOutputWord = word;
satok3c09bb12012-01-26 18:36:19 +0900510 } else if (!hasAutoCorrectionCandidate) {
511 if (inputWordStartPos > 0) {
512 const int offset = inputWordStartPos;
513 initSuggestions(proximityInfo, &xcoordinates[offset], &ycoordinates[offset],
satok9df4a452012-03-23 16:05:18 +0900514 codes + offset, inputWordLength, correction);
satok3c09bb12012-01-26 18:36:19 +0900515 queuePool->clearSubQueue(currentWordIndex);
Jean Chalard4d9b2022012-04-23 19:25:28 +0900516 // TODO: pass the bigram list for substring suggestion
517 getSuggestionCandidates(useFullEditDistance, inputWordLength,
Jean Chalard8950ce62012-05-07 16:28:30 +0900518 0 /* bigramMap */, 0 /* bigramFilter */, correction, queuePool,
519 false /* doAutoCompletion */, MAX_ERRORS_FOR_TWO_WORDS, currentWordIndex);
satok3c09bb12012-01-26 18:36:19 +0900520 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900521 if (currentWordIndex < MULTIPLE_WORDS_SUGGESTION_MAX_WORDS) {
satok3c09bb12012-01-26 18:36:19 +0900522 AKLOGI("Dump word candidates(%d) %d", currentWordIndex, inputWordLength);
523 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
524 queuePool->getSubQueue(currentWordIndex, i)->dumpTopWord();
525 }
526 }
527 }
528 }
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900529 WordsPriorityQueue *queue = queuePool->getSubQueue(currentWordIndex, inputWordLength);
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900530 // TODO: Return the correct value depending on doAutoCompletion
531 if (!queue || queue->size() <= 0) {
532 return FLAG_MULTIPLE_SUGGEST_ABORT;
satok3c09bb12012-01-26 18:36:19 +0900533 }
534 int score = 0;
satok0028ed32012-05-16 20:42:12 +0900535 const float ns = queue->getHighestNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900536 correction->getPrimaryInputWord(), inputWordLength,
satok1f6b52e2012-01-30 13:53:58 +0900537 &tempOutputWord, &score, &nextWordLength);
satok3c09bb12012-01-26 18:36:19 +0900538 if (DEBUG_DICT) {
539 AKLOGI("NS(%d) = %f, Score = %d", currentWordIndex, ns, score);
540 }
541 // Two words correction won't be done if the score of the first word doesn't exceed the
542 // threshold.
543 if (ns < TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD
satok1f6b52e2012-01-30 13:53:58 +0900544 || nextWordLength < SUB_QUEUE_MIN_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900545 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900546 }
satok1f6b52e2012-01-30 13:53:58 +0900547 freq = score >> (nextWordLength + TWO_WORDS_PLUS_OTHER_ERROR_CORRECTION_DEMOTION_DIVIDER);
satok3c09bb12012-01-26 18:36:19 +0900548 }
549 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900550 AKLOGI("Freq(%d): %d, length: %d, input length: %d, input start: %d (%d)"
551 , currentWordIndex, freq, nextWordLength, inputWordLength, inputWordStartPos,
552 wordLengthArray[0]);
satok3c09bb12012-01-26 18:36:19 +0900553 }
satok1f6b52e2012-01-30 13:53:58 +0900554 if (freq <= 0 || nextWordLength <= 0
555 || MAX_WORD_LENGTH <= (outputWordStartPos + nextWordLength)) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900556 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900557 }
satok1f6b52e2012-01-30 13:53:58 +0900558 for (int i = 0; i < nextWordLength; ++i) {
satok3c09bb12012-01-26 18:36:19 +0900559 outputWord[outputWordStartPos + i] = tempOutputWord[i];
560 }
satok99557162012-01-26 22:49:13 +0900561
562 // Put output values
satok1f6b52e2012-01-30 13:53:58 +0900563 freqArray[currentWordIndex] = freq;
satok99557162012-01-26 22:49:13 +0900564 // TODO: put output length instead of input length
satok1f6b52e2012-01-30 13:53:58 +0900565 wordLengthArray[currentWordIndex] = inputWordLength;
566 const int tempOutputWordLength = outputWordStartPos + nextWordLength;
567 if (outputWordLength) {
568 *outputWordLength = tempOutputWordLength;
569 }
satok99557162012-01-26 22:49:13 +0900570
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900571 if ((inputWordStartPos + inputWordLength) < inputSize) {
satok1f6b52e2012-01-30 13:53:58 +0900572 if (outputWordStartPos + nextWordLength >= MAX_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900573 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900574 }
satoka85f4922012-01-30 18:18:30 +0900575 outputWord[tempOutputWordLength] = SPACE;
satok1f6b52e2012-01-30 13:53:58 +0900576 if (outputWordLength) {
577 ++*outputWordLength;
578 }
579 } else if (currentWordIndex >= 1) {
satok99557162012-01-26 22:49:13 +0900580 // TODO: Handle 3 or more words
satoka85f4922012-01-30 18:18:30 +0900581 const int pairFreq = correction->getFreqForSplitMultipleWords(
582 freqArray, wordLengthArray, currentWordIndex + 1, isSpaceProximity, outputWord);
satok99557162012-01-26 22:49:13 +0900583 if (DEBUG_DICT) {
satoka85f4922012-01-30 18:18:30 +0900584 DUMP_WORD(outputWord, tempOutputWordLength);
satoka0ac31f2012-05-23 19:55:27 +0900585 for (int i = 0; i < currentWordIndex + 1; ++i) {
586 AKLOGI("Split %d,%d words: freq = %d, length = %d", i, currentWordIndex + 1,
587 freqArray[i], wordLengthArray[i]);
588 }
589 AKLOGI("Split two words: freq = %d, length = %d, %d, isSpace ? %d", pairFreq,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900590 inputSize, tempOutputWordLength, isSpaceProximity);
satok99557162012-01-26 22:49:13 +0900591 }
Jean Chalard926ef062012-08-10 13:14:45 +0900592 addWord(outputWord, tempOutputWordLength, pairFreq, queuePool->getMasterQueue(),
593 Dictionary::KIND_CORRECTION);
satok3c09bb12012-01-26 18:36:19 +0900594 }
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900595 return FLAG_MULTIPLE_SUGGEST_CONTINUE;
satok7409d152012-01-26 16:13:25 +0900596}
597
satok1f6b52e2012-01-30 13:53:58 +0900598void UnigramDictionary::getMultiWordsSuggestionRec(ProximityInfo *proximityInfo,
599 const int *xcoordinates, const int *ycoordinates, const int *codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900600 const bool useFullEditDistance, const int inputSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900601 Correction *correction, WordsPriorityQueuePool *queuePool,
satok1f6b52e2012-01-30 13:53:58 +0900602 const bool hasAutoCorrectionCandidate, const int startInputPos, const int startWordIndex,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900603 const int outputWordLength, int *freqArray, int *wordLengthArray,
604 unsigned short *outputWord) const {
satok1f6b52e2012-01-30 13:53:58 +0900605 if (startWordIndex >= (MULTIPLE_WORDS_SUGGESTION_MAX_WORDS - 1)) {
606 // Return if the last word index
607 return;
608 }
satoka85f4922012-01-30 18:18:30 +0900609 if (startWordIndex >= 1
610 && (hasAutoCorrectionCandidate
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900611 || inputSize < MIN_INPUT_LENGTH_FOR_THREE_OR_MORE_WORDS_CORRECTION)) {
satoka85f4922012-01-30 18:18:30 +0900612 // Do not suggest 3+ words if already has auto correction candidate
613 return;
614 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900615 for (int i = startInputPos + 1; i < inputSize; ++i) {
satok1f6b52e2012-01-30 13:53:58 +0900616 if (DEBUG_CORRECTION_FREQ) {
satoka85f4922012-01-30 18:18:30 +0900617 AKLOGI("Multi words(%d), start in %d sep %d start out %d",
618 startWordIndex, startInputPos, i, outputWordLength);
619 DUMP_WORD(outputWord, outputWordLength);
satok1f6b52e2012-01-30 13:53:58 +0900620 }
satoka85f4922012-01-30 18:18:30 +0900621 int tempOutputWordLength = 0;
622 // Current word
623 int inputWordStartPos = startInputPos;
624 int inputWordLength = i - startInputPos;
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900625 const int suggestionFlag = getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900626 codes, useFullEditDistance, correction, queuePool, inputSize,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900627 hasAutoCorrectionCandidate, startWordIndex, inputWordStartPos, inputWordLength,
628 outputWordLength, true /* not used */, freqArray, wordLengthArray, outputWord,
629 &tempOutputWordLength);
630 if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_ABORT) {
631 // TODO: break here
632 continue;
633 } else if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_SKIP) {
satok1f6b52e2012-01-30 13:53:58 +0900634 continue;
635 }
636
satoka85f4922012-01-30 18:18:30 +0900637 if (DEBUG_CORRECTION_FREQ) {
638 AKLOGI("Do missing space correction");
639 }
640 // Next word
satok1f6b52e2012-01-30 13:53:58 +0900641 // Missing space
642 inputWordStartPos = i;
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900643 inputWordLength = inputSize - i;
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900644 if(getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900645 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900646 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900647 false /* missing space */, freqArray, wordLengthArray, outputWord, 0)
648 != FLAG_MULTIPLE_SUGGEST_CONTINUE) {
satoka85f4922012-01-30 18:18:30 +0900649 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900650 useFullEditDistance, inputSize, correction, queuePool,
satoka85f4922012-01-30 18:18:30 +0900651 hasAutoCorrectionCandidate, inputWordStartPos, startWordIndex + 1,
652 tempOutputWordLength, freqArray, wordLengthArray, outputWord);
653 }
satok1f6b52e2012-01-30 13:53:58 +0900654
655 // Mistyped space
656 ++inputWordStartPos;
657 --inputWordLength;
658
659 if (inputWordLength <= 0) {
660 continue;
661 }
662
663 const int x = xcoordinates[inputWordStartPos - 1];
664 const int y = ycoordinates[inputWordStartPos - 1];
665 if (!proximityInfo->hasSpaceProximity(x, y)) {
666 continue;
667 }
668
satoka85f4922012-01-30 18:18:30 +0900669 if (DEBUG_CORRECTION_FREQ) {
670 AKLOGI("Do mistyped space correction");
671 }
satok1f6b52e2012-01-30 13:53:58 +0900672 getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900673 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900674 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
675 true /* mistyped space */, freqArray, wordLengthArray, outputWord, 0);
satok1f6b52e2012-01-30 13:53:58 +0900676 }
677}
678
satoka85f4922012-01-30 18:18:30 +0900679void UnigramDictionary::getSplitMultipleWordsSuggestions(ProximityInfo *proximityInfo,
satok744dab62011-12-15 22:29:05 +0900680 const int *xcoordinates, const int *ycoordinates, const int *codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900681 const bool useFullEditDistance, const int inputSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900682 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900683 const bool hasAutoCorrectionCandidate) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900684 if (inputSize >= MAX_WORD_LENGTH) return;
satok612c6e42011-08-01 19:35:27 +0900685 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900686 AKLOGI("--- Suggest multiple words");
687 }
satok54af64a2012-01-17 15:58:23 +0900688
satokbd6ccdd2012-01-23 12:30:20 +0900689 // Allocating fixed length array on stack
690 unsigned short outputWord[MAX_WORD_LENGTH];
satok1f6b52e2012-01-30 13:53:58 +0900691 int freqArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
692 int wordLengthArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
693 const int outputWordLength = 0;
694 const int startInputPos = 0;
695 const int startWordIndex = 0;
696 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900697 useFullEditDistance, inputSize, correction, queuePool, hasAutoCorrectionCandidate,
satok1f6b52e2012-01-30 13:53:58 +0900698 startInputPos, startWordIndex, outputWordLength, freqArray, wordLengthArray,
699 outputWord);
Jean Chalarde6715e32011-06-30 19:47:25 +0900700}
701
Jean Chalard1059f272011-06-28 20:45:05 +0900702// Wrapper for getMostFrequentWordLikeInner, which matches it to the previous
703// interface.
704inline int UnigramDictionary::getMostFrequentWordLike(const int startInputIndex,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900705 const int inputSize, Correction *correction, unsigned short *word) const {
706 uint16_t inWord[inputSize];
Jean Chalard1059f272011-06-28 20:45:05 +0900707
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900708 for (int i = 0; i < inputSize; ++i) {
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900709 inWord[i] = (uint16_t)correction->getPrimaryCharAt(startInputIndex + i);
Jean Chalard1059f272011-06-28 20:45:05 +0900710 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900711 return getMostFrequentWordLikeInner(inWord, inputSize, word);
Jean Chalard1059f272011-06-28 20:45:05 +0900712}
713
714// This function will take the position of a character array within a CharGroup,
715// and check it actually like-matches the word in inWord starting at startInputIndex,
716// that is, it matches it with case and accents squashed.
717// The function returns true if there was a full match, false otherwise.
718// The function will copy on-the-fly the characters in the CharGroup to outNewWord.
719// It will also place the end position of the array in outPos; in outInputIndex,
720// it will place the index of the first char AFTER the match if there was a match,
721// and the initial position if there was not. It makes sense because if there was
722// a match we want to continue searching, but if there was not, we want to go to
723// the next CharGroup.
724// In and out parameters may point to the same location. This function takes care
725// not to use any input parameters after it wrote into its outputs.
726static inline bool testCharGroupForContinuedLikeness(const uint8_t flags,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900727 const uint8_t *const root, const int startPos,
728 const uint16_t *const inWord, const int startInputIndex,
729 int32_t *outNewWord, int *outInputIndex, int *outPos) {
Jean Chalard19560502012-07-31 23:45:32 +0900730 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Jean Chalard1059f272011-06-28 20:45:05 +0900731 int pos = startPos;
732 int32_t character = BinaryFormat::getCharCodeAndForwardPointer(root, &pos);
Tadashi G. Takaoka6e3cb272011-11-11 14:26:13 +0900733 int32_t baseChar = toBaseLowerCase(character);
734 const uint16_t wChar = toBaseLowerCase(inWord[startInputIndex]);
Jean Chalard1059f272011-06-28 20:45:05 +0900735
736 if (baseChar != wChar) {
737 *outPos = hasMultipleChars ? BinaryFormat::skipOtherCharacters(root, pos) : pos;
738 *outInputIndex = startInputIndex;
739 return false;
740 }
741 int inputIndex = startInputIndex;
742 outNewWord[inputIndex] = character;
743 if (hasMultipleChars) {
744 character = BinaryFormat::getCharCodeAndForwardPointer(root, &pos);
745 while (NOT_A_CHARACTER != character) {
Tadashi G. Takaoka6e3cb272011-11-11 14:26:13 +0900746 baseChar = toBaseLowerCase(character);
747 if (toBaseLowerCase(inWord[++inputIndex]) != baseChar) {
Jean Chalard1059f272011-06-28 20:45:05 +0900748 *outPos = BinaryFormat::skipOtherCharacters(root, pos);
749 *outInputIndex = startInputIndex;
750 return false;
751 }
752 outNewWord[inputIndex] = character;
753 character = BinaryFormat::getCharCodeAndForwardPointer(root, &pos);
754 }
755 }
756 *outInputIndex = inputIndex + 1;
757 *outPos = pos;
758 return true;
759}
760
761// This function is invoked when a word like the word searched for is found.
762// It will compare the frequency to the max frequency, and if greater, will
763// copy the word into the output buffer. In output value maxFreq, it will
764// write the new maximum frequency if it changed.
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900765static inline void onTerminalWordLike(const int freq, int32_t *newWord, const int length,
766 short unsigned int *outWord, int *maxFreq) {
Jean Chalard1059f272011-06-28 20:45:05 +0900767 if (freq > *maxFreq) {
768 for (int q = 0; q < length; ++q)
769 outWord[q] = newWord[q];
770 outWord[length] = 0;
771 *maxFreq = freq;
772 }
773}
774
775// Will find the highest frequency of the words like the one passed as an argument,
776// that is, everything that only differs by case/accents.
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900777int UnigramDictionary::getMostFrequentWordLikeInner(const uint16_t *const inWord,
778 const int length, short unsigned int *outWord) const {
Jean Chalard1059f272011-06-28 20:45:05 +0900779 int32_t newWord[MAX_WORD_LENGTH_INTERNAL];
780 int depth = 0;
781 int maxFreq = -1;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900782 const uint8_t *const root = DICT_ROOT;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900783 int stackChildCount[MAX_WORD_LENGTH_INTERNAL];
784 int stackInputIndex[MAX_WORD_LENGTH_INTERNAL];
785 int stackSiblingPos[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900786
Jean Chalard4c0eca62012-01-16 15:15:53 +0900787 int startPos = 0;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900788 stackChildCount[0] = BinaryFormat::getGroupCountAndForwardPointer(root, &startPos);
789 stackInputIndex[0] = 0;
790 stackSiblingPos[0] = startPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900791 while (depth >= 0) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900792 const int charGroupCount = stackChildCount[depth];
793 int pos = stackSiblingPos[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900794 for (int charGroupIndex = charGroupCount - 1; charGroupIndex >= 0; --charGroupIndex) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900795 int inputIndex = stackInputIndex[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900796 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
797 // Test whether all chars in this group match with the word we are searching for. If so,
798 // we want to traverse its children (or if the length match, evaluate its frequency).
799 // Note that this function will output the position regardless, but will only write
800 // into inputIndex if there is a match.
801 const bool isAlike = testCharGroupForContinuedLikeness(flags, root, pos, inWord,
802 inputIndex, newWord, &inputIndex, &pos);
Jean Chalard19560502012-07-31 23:45:32 +0900803 if (isAlike && (BinaryFormat::FLAG_IS_TERMINAL & flags) && (inputIndex == length)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900804 const int frequency = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
805 onTerminalWordLike(frequency, newWord, inputIndex, outWord, &maxFreq);
806 }
807 pos = BinaryFormat::skipFrequency(flags, pos);
808 const int siblingPos = BinaryFormat::skipChildrenPosAndAttributes(root, flags, pos);
809 const int childrenNodePos = BinaryFormat::readChildrenPosition(root, flags, pos);
810 // If we had a match and the word has children, we want to traverse them. We don't have
811 // to traverse words longer than the one we are searching for, since they will not match
812 // anyway, so don't traverse unless inputIndex < length.
813 if (isAlike && (-1 != childrenNodePos) && (inputIndex < length)) {
814 // Save position for this depth, to get back to this once children are done
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900815 stackChildCount[depth] = charGroupIndex;
816 stackSiblingPos[depth] = siblingPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900817 // Prepare stack values for next depth
818 ++depth;
819 int childrenPos = childrenNodePos;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900820 stackChildCount[depth] =
Jean Chalard1059f272011-06-28 20:45:05 +0900821 BinaryFormat::getGroupCountAndForwardPointer(root, &childrenPos);
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900822 stackSiblingPos[depth] = childrenPos;
823 stackInputIndex[depth] = inputIndex;
Jean Chalard1059f272011-06-28 20:45:05 +0900824 pos = childrenPos;
825 // Go to the next depth level.
826 ++depth;
827 break;
828 } else {
829 // No match, or no children, or word too long to ever match: go the next sibling.
830 pos = siblingPos;
831 }
832 }
833 --depth;
834 }
835 return maxFreq;
836}
837
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900838int UnigramDictionary::getFrequency(const int32_t *const inWord, const int length) const {
839 const uint8_t *const root = DICT_ROOT;
Jean Chalarde9a86e22012-06-28 21:01:29 +0900840 int pos = BinaryFormat::getTerminalPosition(root, inWord, length,
841 false /* forceLowerCaseSearch */);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900842 if (NOT_VALID_WORD == pos) {
843 return NOT_A_PROBABILITY;
844 }
845 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
Jean Chalard72b1c932012-08-31 15:24:39 +0900846 if (flags & (BinaryFormat::FLAG_IS_BLACKLISTED | BinaryFormat::FLAG_IS_NOT_A_WORD)) {
847 // If this is not a word, or if it's a blacklisted entry, it should behave as
848 // having no frequency outside of the suggestion process (where it should be used
849 // for shortcuts).
850 return NOT_A_PROBABILITY;
851 }
Jean Chalard19560502012-07-31 23:45:32 +0900852 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900853 if (hasMultipleChars) {
854 pos = BinaryFormat::skipOtherCharacters(root, pos);
855 } else {
856 BinaryFormat::getCharCodeAndForwardPointer(DICT_ROOT, &pos);
857 }
858 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
859 return unigramFreq;
Jean Chalard1059f272011-06-28 20:45:05 +0900860}
861
862// TODO: remove this function.
863int UnigramDictionary::getBigramPosition(int pos, unsigned short *word, int offset,
864 int length) const {
865 return -1;
866}
867
868// ProcessCurrentNode returns a boolean telling whether to traverse children nodes or not.
869// If the return value is false, then the caller should read in the output "nextSiblingPosition"
870// to find out the address of the next sibling node and pass it to a new call of processCurrentNode.
871// It is worthy to note that when false is returned, the output values other than
872// nextSiblingPosition are undefined.
873// If the return value is true, then the caller must proceed to traverse the children of this
874// node. processCurrentNode will output the information about the children: their count in
875// newCount, their position in newChildrenPosition, the traverseAllNodes flag in
876// newTraverseAllNodes, the match weight into newMatchRate, the input index into newInputIndex, the
877// diffs into newDiffs, the sibling position in nextSiblingPosition, and the output index into
878// newOutputIndex. Please also note the following caveat: processCurrentNode does not know when
879// there aren't any more nodes at this level, it merely returns the address of the first byte after
880// the current node in nextSiblingPosition. Thus, the caller must keep count of the nodes at any
881// given level, as output into newCount when traversing this level's parent.
satok8876b752011-08-04 18:31:57 +0900882inline bool UnigramDictionary::processCurrentNode(const int initialPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900883 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter, Correction *correction,
884 int *newCount, int *newChildrenPosition, int *nextSiblingPosition,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900885 WordsPriorityQueuePool *queuePool, const int currentWordIndex) const {
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900886 if (DEBUG_DICT) {
satokcfca3c62011-08-10 14:30:10 +0900887 correction->checkState();
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900888 }
Jean Chalard0584f022011-06-30 19:23:16 +0900889 int pos = initialPos;
Jean Chalard0584f022011-06-30 19:23:16 +0900890
Jean Chalard1059f272011-06-28 20:45:05 +0900891 // Flags contain the following information:
892 // - Address type (MASK_GROUP_ADDRESS_TYPE) on two bits:
893 // - FLAG_GROUP_ADDRESS_TYPE_{ONE,TWO,THREE}_BYTES means there are children and their address
894 // is on the specified number of bytes.
895 // - FLAG_GROUP_ADDRESS_TYPE_NOADDRESS means there are no children, and therefore no address.
896 // - FLAG_HAS_MULTIPLE_CHARS: whether this node has multiple char or not.
897 // - FLAG_IS_TERMINAL: whether this node is a terminal or not (it may still have children)
898 // - FLAG_HAS_BIGRAMS: whether this node has bigrams or not
899 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(DICT_ROOT, &pos);
Jean Chalard19560502012-07-31 23:45:32 +0900900 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
901 const bool isTerminalNode = (0 != (BinaryFormat::FLAG_IS_TERMINAL & flags));
satok8876b752011-08-04 18:31:57 +0900902
903 bool needsToInvokeOnTerminal = false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900904
Jean Chalard1059f272011-06-28 20:45:05 +0900905 // This gets only ONE character from the stream. Next there will be:
906 // if FLAG_HAS_MULTIPLE CHARS: the other characters of the same node
907 // else if FLAG_IS_TERMINAL: the frequency
908 // else if MASK_GROUP_ADDRESS_TYPE is not NONE: the children address
909 // Note that you can't have a node that both is not a terminal and has no children.
910 int32_t c = BinaryFormat::getCharCodeAndForwardPointer(DICT_ROOT, &pos);
911 assert(NOT_A_CHARACTER != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900912
Jean Chalard1059f272011-06-28 20:45:05 +0900913 // We are going to loop through each character and make it look like it's a different
914 // node each time. To do that, we will process characters in this node in order until
915 // we find the character terminator. This is signalled by getCharCode* returning
916 // NOT_A_CHARACTER.
917 // As a special case, if there is only one character in this node, we must not read the
918 // next bytes so we will simulate the NOT_A_CHARACTER return by testing the flags.
919 // This way, each loop run will look like a "virtual node".
920 do {
921 // We prefetch the next char. If 'c' is the last char of this node, we will have
922 // NOT_A_CHARACTER in the next char. From this we can decide whether this virtual node
923 // should behave as a terminal or not and whether we have children.
924 const int32_t nextc = hasMultipleChars
925 ? BinaryFormat::getCharCodeAndForwardPointer(DICT_ROOT, &pos) : NOT_A_CHARACTER;
926 const bool isLastChar = (NOT_A_CHARACTER == nextc);
927 // If there are more chars in this nodes, then this virtual node is not a terminal.
928 // If we are on the last char, this virtual node is a terminal if this node is.
satok8876b752011-08-04 18:31:57 +0900929 const bool isTerminal = isLastChar && isTerminalNode;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900930
satokcfca3c62011-08-10 14:30:10 +0900931 Correction::CorrectionType stateType = correction->processCharAndCalcState(
satok8876b752011-08-04 18:31:57 +0900932 c, isTerminal);
satokcfca3c62011-08-10 14:30:10 +0900933 if (stateType == Correction::TRAVERSE_ALL_ON_TERMINAL
934 || stateType == Correction::ON_TERMINAL) {
satok8876b752011-08-04 18:31:57 +0900935 needsToInvokeOnTerminal = true;
satokd03317c2011-12-14 21:38:11 +0900936 } else if (stateType == Correction::UNRELATED || correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900937 // We found that this is an unrelated character, so we should give up traversing
938 // this node and its children entirely.
939 // However we may not be on the last virtual node yet so we skip the remaining
940 // characters in this node, the frequency if it's there, read the next sibling
941 // position to output it, then return false.
942 // We don't have to output other values because we return false, as in
943 // "don't traverse children".
Jean Chalard1059f272011-06-28 20:45:05 +0900944 if (!isLastChar) {
945 pos = BinaryFormat::skipOtherCharacters(DICT_ROOT, pos);
946 }
947 pos = BinaryFormat::skipFrequency(flags, pos);
948 *nextSiblingPosition =
949 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
950 return false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900951 }
952
Jean Chalard1059f272011-06-28 20:45:05 +0900953 // Prepare for the next character. Promote the prefetched char to current char - the loop
954 // will take care of prefetching the next. If we finally found our last char, nextc will
955 // contain NOT_A_CHARACTER.
956 c = nextc;
Jean Chalard1059f272011-06-28 20:45:05 +0900957 } while (NOT_A_CHARACTER != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900958
satok8876b752011-08-04 18:31:57 +0900959 if (isTerminalNode) {
satok6ad15fc2012-01-16 16:21:21 +0900960 // The frequency should be here, because we come here only if this is actually
961 // a terminal node, and we are on its last char.
Jean Chalard171d1802012-04-23 18:51:00 +0900962 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(DICT_ROOT, pos);
satok6ad15fc2012-01-16 16:21:21 +0900963 const int childrenAddressPos = BinaryFormat::skipFrequency(flags, pos);
964 const int attributesPos = BinaryFormat::skipChildrenPosition(flags, childrenAddressPos);
965 TerminalAttributes terminalAttributes(DICT_ROOT, flags, attributesPos);
Jean Chalard8950ce62012-05-07 16:28:30 +0900966 // bigramMap contains the bigram frequencies indexed by addresses for fast lookup.
967 // bigramFilter is a bloom filter of said frequencies for even faster rejection.
Jean Chalard49ba1352012-05-07 20:14:00 +0900968 const int probability = BinaryFormat::getProbability(initialPos, bigramMap, bigramFilter,
969 unigramFreq);
Jean Chalard171d1802012-04-23 18:51:00 +0900970 onTerminal(probability, terminalAttributes, correction, queuePool, needsToInvokeOnTerminal,
satok8330b482012-01-23 16:52:37 +0900971 currentWordIndex);
Jean Chalard1059f272011-06-28 20:45:05 +0900972
satok8876b752011-08-04 18:31:57 +0900973 // If there are more chars in this node, then this virtual node has children.
974 // If we are on the last char, this virtual node has children if this node has.
975 const bool hasChildren = BinaryFormat::hasChildrenInFlags(flags);
976
977 // This character matched the typed character (enough to traverse the node at least)
978 // so we just evaluated it. Now we should evaluate this virtual node's children - that
979 // is, if it has any. If it has no children, we're done here - so we skip the end of
980 // the node, output the siblings position, and return false "don't traverse children".
981 // Note that !hasChildren implies isLastChar, so we know we don't have to skip any
982 // remaining char in this group for there can't be any.
983 if (!hasChildren) {
984 pos = BinaryFormat::skipFrequency(flags, pos);
985 *nextSiblingPosition =
986 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
987 return false;
988 }
989
990 // Optimization: Prune out words that are too long compared to how much was typed.
satokcfca3c62011-08-10 14:30:10 +0900991 if (correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900992 pos = BinaryFormat::skipFrequency(flags, pos);
993 *nextSiblingPosition =
994 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
satok10266c02011-08-19 22:05:59 +0900995 if (DEBUG_DICT_FULL) {
satok9fb6f472012-01-13 18:01:22 +0900996 AKLOGI("Traversing was pruned.");
satok10266c02011-08-19 22:05:59 +0900997 }
satok8876b752011-08-04 18:31:57 +0900998 return false;
999 }
1000 }
Jean Chalard1059f272011-06-28 20:45:05 +09001001
1002 // Now we finished processing this node, and we want to traverse children. If there are no
1003 // children, we can't come here.
1004 assert(BinaryFormat::hasChildrenInFlags(flags));
1005
1006 // If this node was a terminal it still has the frequency under the pointer (it may have been
1007 // read, but not skipped - see readFrequencyWithoutMovingPointer).
1008 // Next come the children position, then possibly attributes (attributes are bigrams only for
1009 // now, maybe something related to shortcuts in the future).
1010 // Once this is read, we still need to output the number of nodes in the immediate children of
1011 // this node, so we read and output it before returning true, as in "please traverse children".
1012 pos = BinaryFormat::skipFrequency(flags, pos);
1013 int childrenPos = BinaryFormat::readChildrenPosition(DICT_ROOT, flags, pos);
1014 *nextSiblingPosition = BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
1015 *newCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &childrenPos);
1016 *newChildrenPosition = childrenPos;
1017 return true;
Jean Chalard85a1d1e2011-06-21 22:23:21 +09001018}
satok30088252010-12-01 21:22:15 +09001019} // namespace latinime