blob: ebeef13b9846f0b8cf27b151f155fed86c69d792 [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 Wakasafe9ec6b2012-11-16 19:28:56 +090044UnigramDictionary::UnigramDictionary(const uint8_t *const streamStart, int maxWordLength,
45 int maxWords, const unsigned int flags)
Ken Wakasab02ee3d2012-10-08 11:46:14 +090046 : DICT_ROOT(streamStart), MAX_WORD_LENGTH(maxWordLength), MAX_WORDS(maxWords),
Ken Wakasa44d9c1e2012-11-01 17:05:08 +090047 ROOT_POS(0), MAX_DIGRAPH_SEARCH_DEPTH(DEFAULT_MAX_DIGRAPH_SEARCH_DEPTH), FLAGS(flags) {
Ken Wakasade3070a2011-03-19 09:16:42 +090048 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +090049 AKLOGI("UnigramDictionary - constructor");
Ken Wakasade3070a2011-03-19 09:16:42 +090050 }
satok30088252010-12-01 21:22:15 +090051}
52
satok2df30602011-07-15 13:49:00 +090053UnigramDictionary::~UnigramDictionary() {
satok2df30602011-07-15 13:49:00 +090054}
satok30088252010-12-01 21:22:15 +090055
Ken Wakasa1e614932012-10-29 18:06:22 +090056static inline int getCodesBufferSize(const int *codes, const int codesSize) {
57 return sizeof(*codes) * codesSize;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090058}
59
Ken Wakasa1e614932012-10-29 18:06:22 +090060// TODO: This needs to take a const int* and not tinker with its contents
Ken Wakasa2c2f3a92012-11-02 18:29:03 +090061static void addWord(int *word, int length, int frequency, WordsPriorityQueue *queue, int type) {
Jean Chalard926ef062012-08-10 13:14:45 +090062 queue->push(frequency, word, length, type);
satok1147c7b2011-12-14 15:04:58 +090063}
64
Jean Chalardd3043382012-03-21 18:38:25 +090065// Return the replacement code point for a digraph, or 0 if none.
66int UnigramDictionary::getDigraphReplacement(const int *codes, const int i, const int codesSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +090067 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090068
69 // There can't be a digraph if we don't have at least 2 characters to examine
70 if (i + 2 > codesSize) return false;
71
72 // Search for the first char of some digraph
73 int lastDigraphIndex = -1;
satok9df4a452012-03-23 16:05:18 +090074 const int thisChar = codes[i];
Jean Chalard6c300612012-03-06 19:54:03 +090075 for (lastDigraphIndex = digraphsSize - 1; lastDigraphIndex >= 0; --lastDigraphIndex) {
76 if (thisChar == digraphs[lastDigraphIndex].first) break;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090077 }
78 // No match: return early
Jean Chalardd3043382012-03-21 18:38:25 +090079 if (lastDigraphIndex < 0) return 0;
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090080
81 // It's an interesting digraph if the second char matches too.
satok9df4a452012-03-23 16:05:18 +090082 if (digraphs[lastDigraphIndex].second == codes[i + 1]) {
Jean Chalardd3043382012-03-21 18:38:25 +090083 return digraphs[lastDigraphIndex].replacement;
84 } else {
85 return 0;
86 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +090087}
88
89// Mostly the same arguments as the non-recursive version, except:
90// codes is the original value. It points to the start of the work buffer, and gets passed as is.
91// codesSize is the size of the user input (thus, it is the size of codesSrc).
92// codesDest is the current point in the work buffer.
93// codesSrc is the current point in the user-input, original, content-unmodified buffer.
94// codesRemain is the remaining size in codesSrc.
satok1d7eaf82011-07-13 10:32:02 +090095void UnigramDictionary::getWordWithDigraphSuggestionsRec(ProximityInfo *proximityInfo,
satok1147c7b2011-12-14 15:04:58 +090096 const int *xcoordinates, const int *ycoordinates, const int *codesBuffer,
satok219a5142012-03-08 11:53:18 +090097 int *xCoordinatesBuffer, int *yCoordinatesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +090098 const int codesBufferSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +090099 const bool useFullEditDistance, const int *codesSrc,
satok1147c7b2011-12-14 15:04:58 +0900100 const int codesRemain, const int currentDepth, int *codesDest, Correction *correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900101 WordsPriorityQueuePool *queuePool,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900102 const digraph_t *const digraphs, const unsigned int digraphsSize) const {
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900103 assert(sizeof(codesDest[0]) == sizeof(codesSrc[0]));
104 assert(sizeof(xCoordinatesBuffer[0]) == sizeof(xcoordinates[0]));
105 assert(sizeof(yCoordinatesBuffer[0]) == sizeof(ycoordinates[0]));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900106
Ken Wakasaf2789812012-09-04 12:49:46 +0900107 const int startIndex = static_cast<int>(codesDest - codesBuffer);
Jean Chalard6c300612012-03-06 19:54:03 +0900108 if (currentDepth < MAX_DIGRAPH_SEARCH_DEPTH) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900109 for (int i = 0; i < codesRemain; ++i) {
satok219a5142012-03-08 11:53:18 +0900110 xCoordinatesBuffer[startIndex + i] = xcoordinates[codesBufferSize - codesRemain + i];
111 yCoordinatesBuffer[startIndex + i] = ycoordinates[codesBufferSize - codesRemain + i];
Jean Chalardd3043382012-03-21 18:38:25 +0900112 const int replacementCodePoint =
113 getDigraphReplacement(codesSrc, i, codesRemain, digraphs, digraphsSize);
114 if (0 != replacementCodePoint) {
Jean Chalarda787dba2011-03-04 12:17:48 +0900115 // Found a digraph. We will try both spellings. eg. the word is "pruefen"
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900116
Jean Chalardd3043382012-03-21 18:38:25 +0900117 // Copy the word up to the first char of the digraph, including proximity chars,
118 // and overwrite the primary code with the replacement code point. Then, continue
119 // processing on the remaining part of the word, skipping the second char of the
120 // digraph.
121 // In our example, copy "pru", replace "u" with the version with the diaeresis and
122 // continue running on "fen".
Jean Chalarda787dba2011-03-04 12:17:48 +0900123 // Make i the index of the second char of the digraph for simplicity. Forgetting
124 // to do that results in an infinite recursion so take care!
125 ++i;
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900126 memcpy(codesDest, codesSrc, i * sizeof(codesDest[0]));
127 codesDest[i - 1] = replacementCodePoint;
Jean Chalarda787dba2011-03-04 12:17:48 +0900128 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900129 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900130 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i + 1,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900131 codesRemain - i - 1, currentDepth + 1, codesDest + i, correction,
Jean Chalard6c300612012-03-06 19:54:03 +0900132 queuePool, digraphs, digraphsSize);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900133
Jean Chalarda787dba2011-03-04 12:17:48 +0900134 // Copy the second char of the digraph in place, then continue processing on
135 // the remaining part of the word.
136 // In our example, after "pru" in the buffer copy the "e", and continue on "fen"
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900137 memcpy(codesDest + i, codesSrc + i, sizeof(codesDest[0]));
Jean Chalarda787dba2011-03-04 12:17:48 +0900138 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900139 codesBuffer, xCoordinatesBuffer, yCoordinatesBuffer, codesBufferSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900140 bigramMap, bigramFilter, useFullEditDistance, codesSrc + i, codesRemain - i,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900141 currentDepth + 1, codesDest + i, correction, queuePool, digraphs,
142 digraphsSize);
Jean Chalarda787dba2011-03-04 12:17:48 +0900143 return;
144 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900145 }
146 }
147
148 // If we come here, we hit the end of the word: let's check it against the dictionary.
149 // In our example, we'll come here once for "prufen" and then once for "pruefen".
150 // If the word contains several digraphs, we'll come it for the product of them.
151 // eg. if the word is "ueberpruefen" we'll test, in order, against
152 // "uberprufen", "uberpruefen", "ueberprufen", "ueberpruefen".
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900153 const unsigned int remainingBytes = sizeof(codesDest[0]) * codesRemain;
satok219a5142012-03-08 11:53:18 +0900154 if (0 != remainingBytes) {
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900155 memcpy(codesDest, codesSrc, remainingBytes);
satok219a5142012-03-08 11:53:18 +0900156 memcpy(&xCoordinatesBuffer[startIndex], &xcoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900157 sizeof(xCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900158 memcpy(&yCoordinatesBuffer[startIndex], &ycoordinates[codesBufferSize - codesRemain],
Ken Wakasa44d9c1e2012-11-01 17:05:08 +0900159 sizeof(yCoordinatesBuffer[0]) * codesRemain);
satok219a5142012-03-08 11:53:18 +0900160 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900161
satok219a5142012-03-08 11:53:18 +0900162 getWordSuggestions(proximityInfo, xCoordinatesBuffer, yCoordinatesBuffer, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900163 startIndex + codesRemain, bigramMap, bigramFilter, useFullEditDistance, correction,
satoka7e5a5a2011-12-15 16:49:12 +0900164 queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900165}
166
Jean Chalard8950ce62012-05-07 16:28:30 +0900167// bigramMap contains the association <bigram address> -> <bigram frequency>
168// bigramFilter is a bloom filter for fast rejection: see functions setInFilter and isInFilter
169// in bigram_dictionary.cpp
Ken Wakasaf2789812012-09-04 12:49:46 +0900170int UnigramDictionary::getSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
Jean Chalard338d3ec2012-04-06 19:28:34 +0900171 const int *ycoordinates, const int *codes, const int codesSize,
Jean Chalard8950ce62012-05-07 16:28:30 +0900172 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Ken Wakasa1e614932012-10-29 18:06:22 +0900173 const bool useFullEditDistance, int *outWords, int *frequencies, int *outputTypes) const {
satokb1ed1d42012-06-14 16:35:23 -0700174 WordsPriorityQueuePool queuePool(MAX_WORDS, SUB_QUEUE_MAX_WORDS, MAX_WORD_LENGTH);
175 queuePool.clearAll();
satok1bc038c2012-06-14 11:25:50 -0700176 Correction masterCorrection;
177 masterCorrection.resetCorrection();
Jean Chalardaa8df592012-04-06 18:54:20 +0900178 if (BinaryFormat::REQUIRES_GERMAN_UMLAUT_PROCESSING & FLAGS)
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900179 { // Incrementally tune the word and try all possibilities
satok9df4a452012-03-23 16:05:18 +0900180 int codesBuffer[getCodesBufferSize(codes, codesSize)];
satok219a5142012-03-08 11:53:18 +0900181 int xCoordinatesBuffer[codesSize];
182 int yCoordinatesBuffer[codesSize];
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900183 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900184 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700185 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900186 &queuePool, GERMAN_UMLAUT_DIGRAPHS, NELEMS(GERMAN_UMLAUT_DIGRAPHS));
Jean Chalardaa8df592012-04-06 18:54:20 +0900187 } else if (BinaryFormat::REQUIRES_FRENCH_LIGATURES_PROCESSING & FLAGS) {
satokacb6c542012-03-23 20:58:18 +0900188 int codesBuffer[getCodesBufferSize(codes, codesSize)];
Jean Chalardcc78d032012-03-23 16:48:49 +0900189 int xCoordinatesBuffer[codesSize];
190 int yCoordinatesBuffer[codesSize];
191 getWordWithDigraphSuggestionsRec(proximityInfo, xcoordinates, ycoordinates, codesBuffer,
Jean Chalard8950ce62012-05-07 16:28:30 +0900192 xCoordinatesBuffer, yCoordinatesBuffer, codesSize, bigramMap, bigramFilter,
satok1bc038c2012-06-14 11:25:50 -0700193 useFullEditDistance, codes, codesSize, 0, codesBuffer, &masterCorrection,
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900194 &queuePool, FRENCH_LIGATURES_DIGRAPHS, NELEMS(FRENCH_LIGATURES_DIGRAPHS));
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900195 } else { // Normal processing
Jean Chalard338d3ec2012-04-06 19:28:34 +0900196 getWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, codesSize,
satokb1ed1d42012-06-14 16:35:23 -0700197 bigramMap, bigramFilter, useFullEditDistance, &masterCorrection, &queuePool);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900198 }
199
satok817e5172011-03-04 06:06:45 -0800200 PROF_START(20);
satok8330b482012-01-23 16:52:37 +0900201 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700202 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700203 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900204 ns += 0;
205 AKLOGI("Max normalized score = %f", ns);
206 }
satoka7e5a5a2011-12-15 16:49:12 +0900207 const int suggestedWordsCount =
Jean Chalard926ef062012-08-10 13:14:45 +0900208 queuePool.getMasterQueue()->outputSuggestions(masterCorrection.getPrimaryInputWord(),
209 codesSize, frequencies, outWords, outputTypes);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900210
211 if (DEBUG_DICT) {
satokb1ed1d42012-06-14 16:35:23 -0700212 float ns = queuePool.getMasterQueue()->getHighestNormalizedScore(
satok1bc038c2012-06-14 11:25:50 -0700213 masterCorrection.getPrimaryInputWord(), codesSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900214 ns += 0;
satok9fb6f472012-01-13 18:01:22 +0900215 AKLOGI("Returning %d words", suggestedWordsCount);
Jean Chalard980d6b62011-06-30 17:02:23 +0900216 /// Print the returned words
217 for (int j = 0; j < suggestedWordsCount; ++j) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900218 int *w = outWords + j * MAX_WORD_LENGTH;
Jean Chalard980d6b62011-06-30 17:02:23 +0900219 char s[MAX_WORD_LENGTH];
220 for (int i = 0; i <= MAX_WORD_LENGTH; i++) s[i] = w[i];
Ken Wakasa7914e902012-09-07 08:55:16 +0900221 (void)s; // To suppress compiler warning
satok9fb6f472012-01-13 18:01:22 +0900222 AKLOGI("%s %i", s, frequencies[j]);
Jean Chalard980d6b62011-06-30 17:02:23 +0900223 }
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900224 }
satok817e5172011-03-04 06:06:45 -0800225 PROF_END(20);
Jean Chalardc2bbc6a2011-02-25 17:56:53 +0900226 PROF_CLOSE;
227 return suggestedWordsCount;
228}
229
Ken Wakasa1e614932012-10-29 18:06:22 +0900230void UnigramDictionary::getWordSuggestions(ProximityInfo *proximityInfo, const int *xcoordinates,
231 const int *ycoordinates, const int *codes, const int inputSize,
232 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
233 const bool useFullEditDistance, Correction *correction, WordsPriorityQueuePool *queuePool)
234 const {
satok61e2f852011-01-05 14:13:07 +0900235 PROF_OPEN;
236 PROF_START(0);
satok61e2f852011-01-05 14:13:07 +0900237 PROF_END(0);
satok30088252010-12-01 21:22:15 +0900238
satok61e2f852011-01-05 14:13:07 +0900239 PROF_START(1);
Jean Chalard8950ce62012-05-07 16:28:30 +0900240 getOneWordSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, bigramMap, bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900241 useFullEditDistance, inputSize, correction, queuePool);
satok61e2f852011-01-05 14:13:07 +0900242 PROF_END(1);
243
244 PROF_START(2);
satok10266c02011-08-19 22:05:59 +0900245 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900246 PROF_END(2);
satokcdbbea72010-12-08 16:04:16 +0900247
satok61e2f852011-01-05 14:13:07 +0900248 PROF_START(3);
satok10266c02011-08-19 22:05:59 +0900249 // Note: This line is intentionally left blank
satok61e2f852011-01-05 14:13:07 +0900250 PROF_END(3);
satok30088252010-12-01 21:22:15 +0900251
satok61e2f852011-01-05 14:13:07 +0900252 PROF_START(4);
satok8330b482012-01-23 16:52:37 +0900253 bool hasAutoCorrectionCandidate = false;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900254 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
satok8330b482012-01-23 16:52:37 +0900255 if (masterQueue->size() > 0) {
satok0028ed32012-05-16 20:42:12 +0900256 float nsForMaster = masterQueue->getHighestNormalizedScore(
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900257 correction->getPrimaryInputWord(), inputSize, 0, 0, 0);
satok8330b482012-01-23 16:52:37 +0900258 hasAutoCorrectionCandidate = (nsForMaster > START_TWO_WORDS_CORRECTION_THRESHOLD);
259 }
satok61e2f852011-01-05 14:13:07 +0900260 PROF_END(4);
satoka3d78f62010-12-09 22:08:33 +0900261
satok61e2f852011-01-05 14:13:07 +0900262 PROF_START(5);
satok99557162012-01-26 22:49:13 +0900263 // Multiple word suggestions
264 if (SUGGEST_MULTIPLE_WORDS
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900265 && inputSize >= MIN_USER_TYPED_LENGTH_FOR_MULTIPLE_WORD_SUGGESTION) {
satoka85f4922012-01-30 18:18:30 +0900266 getSplitMultipleWordsSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900267 useFullEditDistance, inputSize, correction, queuePool,
satok1f6b52e2012-01-30 13:53:58 +0900268 hasAutoCorrectionCandidate);
satok662fe692010-12-08 17:05:39 +0900269 }
satok61e2f852011-01-05 14:13:07 +0900270 PROF_END(5);
satok817e5172011-03-04 06:06:45 -0800271
272 PROF_START(6);
satok99557162012-01-26 22:49:13 +0900273 // Note: This line is intentionally left blank
satok817e5172011-03-04 06:06:45 -0800274 PROF_END(6);
satok99557162012-01-26 22:49:13 +0900275
satok29dc8062012-01-17 15:59:15 +0900276 if (DEBUG_DICT) {
satok6ad15fc2012-01-16 16:21:21 +0900277 queuePool->dumpSubQueue1TopSuggestions();
satok29dc8062012-01-17 15:59:15 +0900278 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900279 WordsPriorityQueue *queue = queuePool->getSubQueue(FIRST_WORD_INDEX, i);
satok29dc8062012-01-17 15:59:15 +0900280 if (queue->size() > 0) {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900281 WordsPriorityQueue::SuggestedWord *sw = queue->top();
satok29dc8062012-01-17 15:59:15 +0900282 const int score = sw->mScore;
Ken Wakasa1e614932012-10-29 18:06:22 +0900283 const int *word = sw->mWord;
satok29dc8062012-01-17 15:59:15 +0900284 const int wordLength = sw->mWordLength;
satok0028ed32012-05-16 20:42:12 +0900285 float ns = Correction::RankingAlgorithm::calcNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900286 correction->getPrimaryInputWord(), i, word, wordLength, score);
satok29dc8062012-01-17 15:59:15 +0900287 ns += 0;
288 AKLOGI("--- TOP SUB WORDS for %d --- %d %f [%d]", i, score, ns,
satok54af64a2012-01-17 15:58:23 +0900289 (ns > TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD));
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900290 DUMP_WORD(correction->getPrimaryInputWord(), i);
satok29dc8062012-01-17 15:59:15 +0900291 DUMP_WORD(word, wordLength);
292 }
293 }
satok6ad15fc2012-01-16 16:21:21 +0900294 }
satok30088252010-12-01 21:22:15 +0900295}
296
Yusuke Nojima258bfe62011-09-28 12:59:43 +0900297void UnigramDictionary::initSuggestions(ProximityInfo *proximityInfo, const int *xCoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900298 const int *yCoordinates, const int *codes, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900299 Correction *correction) const {
Ken Wakasade3070a2011-03-19 09:16:42 +0900300 if (DEBUG_DICT) {
satok9fb6f472012-01-13 18:01:22 +0900301 AKLOGI("initSuggest");
Ken Wakasa1e614932012-10-29 18:06:22 +0900302 DUMP_WORD(codes, inputSize);
Ken Wakasade3070a2011-03-19 09:16:42 +0900303 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900304 correction->initInputParams(proximityInfo, codes, inputSize, xCoordinates, yCoordinates);
305 const int maxDepth = min(inputSize * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
306 correction->initCorrection(proximityInfo, inputSize, maxDepth);
satok30088252010-12-01 21:22:15 +0900307}
308
satok744dab62011-12-15 22:29:05 +0900309void UnigramDictionary::getOneWordSuggestions(ProximityInfo *proximityInfo,
310 const int *xcoordinates, const int *ycoordinates, const int *codes,
Jean Chalard8950ce62012-05-07 16:28:30 +0900311 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900312 const bool useFullEditDistance, const int inputSize,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900313 Correction *correction, WordsPriorityQueuePool *queuePool) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900314 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes, inputSize, correction);
315 getSuggestionCandidates(useFullEditDistance, inputSize, bigramMap, bigramFilter, correction,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900316 queuePool, true /* doAutoCompletion */, DEFAULT_MAX_ERRORS, FIRST_WORD_INDEX);
satok744dab62011-12-15 22:29:05 +0900317}
318
satok1147c7b2011-12-14 15:04:58 +0900319void UnigramDictionary::getSuggestionCandidates(const bool useFullEditDistance,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900320 const int inputSize, const std::map<int, int> *bigramMap, const uint8_t *bigramFilter,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900321 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900322 const bool doAutoCompletion, const int maxErrors, const int currentWordIndex) const {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900323 uint8_t totalTraverseCount = correction->pushAndGetTotalTraverseCount();
324 if (DEBUG_DICT) {
325 AKLOGI("Traverse count %d", totalTraverseCount);
326 }
327 if (totalTraverseCount > MULTIPLE_WORDS_SUGGESTION_MAX_TOTAL_TRAVERSE_COUNT) {
328 if (DEBUG_DICT) {
329 AKLOGI("Abort traversing %d", totalTraverseCount);
330 }
331 return;
332 }
satok10266c02011-08-19 22:05:59 +0900333 // TODO: Remove setCorrectionParams
satok1147c7b2011-12-14 15:04:58 +0900334 correction->setCorrectionParams(0, 0, 0,
satokd03317c2011-12-14 21:38:11 +0900335 -1 /* spaceProximityPos */, -1 /* missingSpacePos */, useFullEditDistance,
satok1a6da632011-12-16 23:15:06 +0900336 doAutoCompletion, maxErrors);
satok662fe692010-12-08 17:05:39 +0900337 int rootPosition = ROOT_POS;
Jean Chalard980d6b62011-06-30 17:02:23 +0900338 // Get the number of children of root, then increment the position
Jean Chalard6d419812012-01-16 15:19:47 +0900339 int childCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &rootPosition);
satok208268d2011-08-10 15:44:08 +0900340 int outputIndex = 0;
satokd2997922010-12-07 13:08:39 +0900341
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900342 correction->initCorrectionState(rootPosition, childCount, (inputSize <= 0));
satokd2997922010-12-07 13:08:39 +0900343
satok662fe692010-12-08 17:05:39 +0900344 // Depth first search
satok208268d2011-08-10 15:44:08 +0900345 while (outputIndex >= 0) {
satok1147c7b2011-12-14 15:04:58 +0900346 if (correction->initProcessState(outputIndex)) {
347 int siblingPos = correction->getTreeSiblingPos(outputIndex);
satokd2997922010-12-07 13:08:39 +0900348 int firstChildPos;
satok0f6c8e82011-08-03 02:19:44 +0900349
satok4e4e74e2011-08-03 23:27:32 +0900350 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900351 bigramMap, bigramFilter, correction, &childCount, &firstChildPos, &siblingPos,
Jean Chalard4d9b2022012-04-23 19:25:28 +0900352 queuePool, currentWordIndex);
satok662fe692010-12-08 17:05:39 +0900353 // Update next sibling pos
satok1147c7b2011-12-14 15:04:58 +0900354 correction->setTreeSiblingPos(outputIndex, siblingPos);
satok208268d2011-08-10 15:44:08 +0900355
satokd2997922010-12-07 13:08:39 +0900356 if (needsToTraverseChildrenNodes) {
357 // Goes to child node
satok1147c7b2011-12-14 15:04:58 +0900358 outputIndex = correction->goDownTree(outputIndex, childCount, firstChildPos);
satokd2997922010-12-07 13:08:39 +0900359 }
360 } else {
satokcdbbea72010-12-08 16:04:16 +0900361 // Goes to parent sibling node
satok1147c7b2011-12-14 15:04:58 +0900362 outputIndex = correction->getTreeParentIndex(outputIndex);
satokd2997922010-12-07 13:08:39 +0900363 }
364 }
365}
366
Ken Wakasa19d844c2012-11-02 23:57:13 +0900367void UnigramDictionary::onTerminal(const int probability,
Ken Wakasaa10b1a82013-01-08 17:23:43 +0900368 const TerminalAttributes &terminalAttributes, Correction *correction,
satok8330b482012-01-23 16:52:37 +0900369 WordsPriorityQueuePool *queuePool, const bool addToMasterQueue,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900370 const int currentWordIndex) const {
satok6ad15fc2012-01-16 16:21:21 +0900371 const int inputIndex = correction->getInputIndex();
372 const bool addToSubQueue = inputIndex < SUB_QUEUE_MAX_COUNT;
satok54af64a2012-01-17 15:58:23 +0900373
satok8876b752011-08-04 18:31:57 +0900374 int wordLength;
Ken Wakasa1e614932012-10-29 18:06:22 +0900375 int *wordPointer;
satok54af64a2012-01-17 15:58:23 +0900376
satok1f6b52e2012-01-30 13:53:58 +0900377 if ((currentWordIndex == FIRST_WORD_INDEX) && addToMasterQueue) {
satok54af64a2012-01-17 15:58:23 +0900378 WordsPriorityQueue *masterQueue = queuePool->getMasterQueue();
Jean Chalard171d1802012-04-23 18:51:00 +0900379 const int finalProbability =
380 correction->getFinalProbability(probability, &wordPointer, &wordLength);
satok54af64a2012-01-17 15:58:23 +0900381
Jean Chalard72b1c932012-08-31 15:24:39 +0900382 if (0 != finalProbability && !terminalAttributes.isBlacklistedOrNotAWord()) {
Jean Chalard8af8c152012-08-17 09:37:39 +0900383 // If the probability is 0, we don't want to add this word. However we still
384 // want to add its shortcuts (including a possible whitelist entry) if any.
Jean Chalard72b1c932012-08-31 15:24:39 +0900385 // Furthermore, if this is not a word (shortcut only for example) or a blacklisted
386 // entry then we never want to suggest this.
Jean Chalard8af8c152012-08-17 09:37:39 +0900387 addWord(wordPointer, wordLength, finalProbability, masterQueue,
388 Dictionary::KIND_CORRECTION);
389 }
390
391 const int shortcutProbability = finalProbability > 0 ? finalProbability - 1 : 0;
392 // Please note that the shortcut candidates will be added to the master queue only.
Ken Wakasaa10b1a82013-01-08 17:23:43 +0900393 TerminalAttributes::ShortcutIterator iterator = terminalAttributes.getShortcutIterator();
Jean Chalard8af8c152012-08-17 09:37:39 +0900394 while (iterator.hasNextShortcutTarget()) {
395 // TODO: addWord only supports weak ordering, meaning we have no means
396 // to control the order of the shortcuts relative to one another or to the word.
397 // We need to either modulate the probability of each shortcut according
398 // to its own shortcut probability or to make the queue
399 // so that the insert order is protected inside the queue for words
400 // with the same score. For the moment we use -1 to make sure the shortcut will
401 // never be in front of the word.
Ken Wakasa1e614932012-10-29 18:06:22 +0900402 int shortcutTarget[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard8af8c152012-08-17 09:37:39 +0900403 int shortcutFrequency;
404 const int shortcutTargetStringLength = iterator.getNextShortcutTarget(
405 MAX_WORD_LENGTH_INTERNAL, shortcutTarget, &shortcutFrequency);
406 int shortcutScore;
407 int kind;
408 if (shortcutFrequency == BinaryFormat::WHITELIST_SHORTCUT_FREQUENCY
409 && correction->sameAsTyped()) {
410 shortcutScore = S_INT_MAX;
411 kind = Dictionary::KIND_WHITELIST;
412 } else {
413 shortcutScore = shortcutProbability;
414 kind = Dictionary::KIND_CORRECTION;
satok6ad15fc2012-01-16 16:21:21 +0900415 }
Jean Chalard8af8c152012-08-17 09:37:39 +0900416 addWord(shortcutTarget, shortcutTargetStringLength, shortcutScore,
417 masterQueue, kind);
Jean Chalardcf9dbbd2011-12-26 15:16:59 +0900418 }
satok54af64a2012-01-17 15:58:23 +0900419 }
satok6ad15fc2012-01-16 16:21:21 +0900420
satok54af64a2012-01-17 15:58:23 +0900421 // We only allow two words + other error correction for words with SUB_QUEUE_MIN_WORD_LENGTH
422 // or more length.
423 if (inputIndex >= SUB_QUEUE_MIN_WORD_LENGTH && addToSubQueue) {
satok8330b482012-01-23 16:52:37 +0900424 WordsPriorityQueue *subQueue;
satok7409d152012-01-26 16:13:25 +0900425 subQueue = queuePool->getSubQueue(currentWordIndex, inputIndex);
426 if (!subQueue) {
satok8330b482012-01-23 16:52:37 +0900427 return;
428 }
Jean Chalard171d1802012-04-23 18:51:00 +0900429 const int finalProbability = correction->getFinalProbabilityForSubQueue(
430 probability, &wordPointer, &wordLength, inputIndex);
Jean Chalard926ef062012-08-10 13:14:45 +0900431 addWord(wordPointer, wordLength, finalProbability, subQueue, Dictionary::KIND_CORRECTION);
Jean Chalardca5ef282011-06-17 15:36:26 +0900432 }
433}
434
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900435int UnigramDictionary::getSubStringSuggestion(
satok7409d152012-01-26 16:13:25 +0900436 ProximityInfo *proximityInfo, const int *xcoordinates, const int *ycoordinates,
satok3c09bb12012-01-26 18:36:19 +0900437 const int *codes, const bool useFullEditDistance, Correction *correction,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900438 WordsPriorityQueuePool *queuePool, const int inputSize,
satok3c09bb12012-01-26 18:36:19 +0900439 const bool hasAutoCorrectionCandidate, const int currentWordIndex,
440 const int inputWordStartPos, const int inputWordLength,
satok99557162012-01-26 22:49:13 +0900441 const int outputWordStartPos, const bool isSpaceProximity, int *freqArray,
Ken Wakasa1e614932012-10-29 18:06:22 +0900442 int *wordLengthArray, int *outputWord, int *outputWordLength) const {
Satoshi Kataoka67e3cc82012-05-31 15:04:58 +0900443 if (inputWordLength > MULTIPLE_WORDS_SUGGESTION_MAX_WORD_LENGTH) {
444 return FLAG_MULTIPLE_SUGGEST_ABORT;
445 }
446
447 /////////////////////////////////////////////
448 // safety net for multiple word suggestion //
449 // TODO: Remove this safety net //
450 /////////////////////////////////////////////
451 int smallWordCount = 0;
452 int singleLetterWordCount = 0;
453 if (inputWordLength == 1) {
454 ++singleLetterWordCount;
455 }
456 if (inputWordLength <= 2) {
457 // small word == single letter or 2-letter word
458 ++smallWordCount;
459 }
460 for (int i = 0; i < currentWordIndex; ++i) {
461 const int length = wordLengthArray[i];
462 if (length == 1) {
463 ++singleLetterWordCount;
464 // Safety net to avoid suggesting sequential single letter words
465 if (i < (currentWordIndex - 1)) {
466 if (wordLengthArray[i + 1] == 1) {
467 return FLAG_MULTIPLE_SUGGEST_ABORT;
468 }
469 } else if (inputWordLength == 1) {
470 return FLAG_MULTIPLE_SUGGEST_ABORT;
471 }
472 }
473 if (length <= 2) {
474 ++smallWordCount;
475 }
476 // Safety net to avoid suggesting multiple words with many (4 or more, for now) small words
477 if (singleLetterWordCount >= 3 || smallWordCount >= 4) {
478 return FLAG_MULTIPLE_SUGGEST_ABORT;
479 }
480 }
481 //////////////////////////////////////////////
482 // TODO: Remove the safety net above //
483 //////////////////////////////////////////////
484
Ken Wakasa1e614932012-10-29 18:06:22 +0900485 int *tempOutputWord = 0;
satok1f6b52e2012-01-30 13:53:58 +0900486 int nextWordLength = 0;
satok99557162012-01-26 22:49:13 +0900487 // TODO: Optimize init suggestion
488 initSuggestions(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900489 inputSize, correction);
satok99557162012-01-26 22:49:13 +0900490
Ken Wakasa1e614932012-10-29 18:06:22 +0900491 int word[MAX_WORD_LENGTH_INTERNAL];
satok3c09bb12012-01-26 18:36:19 +0900492 int freq = getMostFrequentWordLike(
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900493 inputWordStartPos, inputWordLength, correction, word);
satok3c09bb12012-01-26 18:36:19 +0900494 if (freq > 0) {
satok1f6b52e2012-01-30 13:53:58 +0900495 nextWordLength = inputWordLength;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900496 tempOutputWord = word;
satok3c09bb12012-01-26 18:36:19 +0900497 } else if (!hasAutoCorrectionCandidate) {
498 if (inputWordStartPos > 0) {
499 const int offset = inputWordStartPos;
500 initSuggestions(proximityInfo, &xcoordinates[offset], &ycoordinates[offset],
satok9df4a452012-03-23 16:05:18 +0900501 codes + offset, inputWordLength, correction);
satok3c09bb12012-01-26 18:36:19 +0900502 queuePool->clearSubQueue(currentWordIndex);
Jean Chalard4d9b2022012-04-23 19:25:28 +0900503 // TODO: pass the bigram list for substring suggestion
504 getSuggestionCandidates(useFullEditDistance, inputWordLength,
Jean Chalard8950ce62012-05-07 16:28:30 +0900505 0 /* bigramMap */, 0 /* bigramFilter */, correction, queuePool,
506 false /* doAutoCompletion */, MAX_ERRORS_FOR_TWO_WORDS, currentWordIndex);
satok3c09bb12012-01-26 18:36:19 +0900507 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900508 if (currentWordIndex < MULTIPLE_WORDS_SUGGESTION_MAX_WORDS) {
satok3c09bb12012-01-26 18:36:19 +0900509 AKLOGI("Dump word candidates(%d) %d", currentWordIndex, inputWordLength);
510 for (int i = 0; i < SUB_QUEUE_MAX_COUNT; ++i) {
511 queuePool->getSubQueue(currentWordIndex, i)->dumpTopWord();
512 }
513 }
514 }
515 }
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900516 WordsPriorityQueue *queue = queuePool->getSubQueue(currentWordIndex, inputWordLength);
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900517 // TODO: Return the correct value depending on doAutoCompletion
518 if (!queue || queue->size() <= 0) {
519 return FLAG_MULTIPLE_SUGGEST_ABORT;
satok3c09bb12012-01-26 18:36:19 +0900520 }
521 int score = 0;
satok0028ed32012-05-16 20:42:12 +0900522 const float ns = queue->getHighestNormalizedScore(
Satoshi Kataoka4a3db702012-06-08 15:29:44 +0900523 correction->getPrimaryInputWord(), inputWordLength,
satok1f6b52e2012-01-30 13:53:58 +0900524 &tempOutputWord, &score, &nextWordLength);
satok3c09bb12012-01-26 18:36:19 +0900525 if (DEBUG_DICT) {
526 AKLOGI("NS(%d) = %f, Score = %d", currentWordIndex, ns, score);
527 }
528 // Two words correction won't be done if the score of the first word doesn't exceed the
529 // threshold.
530 if (ns < TWO_WORDS_CORRECTION_WITH_OTHER_ERROR_THRESHOLD
satok1f6b52e2012-01-30 13:53:58 +0900531 || nextWordLength < SUB_QUEUE_MIN_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900532 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900533 }
satok1f6b52e2012-01-30 13:53:58 +0900534 freq = score >> (nextWordLength + TWO_WORDS_PLUS_OTHER_ERROR_CORRECTION_DEMOTION_DIVIDER);
satok3c09bb12012-01-26 18:36:19 +0900535 }
536 if (DEBUG_DICT) {
Jean Chalard18ebba32012-09-06 20:37:55 +0900537 AKLOGI("Freq(%d): %d, length: %d, input length: %d, input start: %d (%d)",
538 currentWordIndex, freq, nextWordLength, inputWordLength, inputWordStartPos,
539 (currentWordIndex > 0) ? wordLengthArray[0] : 0);
satok3c09bb12012-01-26 18:36:19 +0900540 }
satok1f6b52e2012-01-30 13:53:58 +0900541 if (freq <= 0 || nextWordLength <= 0
542 || MAX_WORD_LENGTH <= (outputWordStartPos + nextWordLength)) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900543 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900544 }
satok1f6b52e2012-01-30 13:53:58 +0900545 for (int i = 0; i < nextWordLength; ++i) {
satok3c09bb12012-01-26 18:36:19 +0900546 outputWord[outputWordStartPos + i] = tempOutputWord[i];
547 }
satok99557162012-01-26 22:49:13 +0900548
549 // Put output values
satok1f6b52e2012-01-30 13:53:58 +0900550 freqArray[currentWordIndex] = freq;
satok99557162012-01-26 22:49:13 +0900551 // TODO: put output length instead of input length
satok1f6b52e2012-01-30 13:53:58 +0900552 wordLengthArray[currentWordIndex] = inputWordLength;
553 const int tempOutputWordLength = outputWordStartPos + nextWordLength;
554 if (outputWordLength) {
555 *outputWordLength = tempOutputWordLength;
556 }
satok99557162012-01-26 22:49:13 +0900557
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900558 if ((inputWordStartPos + inputWordLength) < inputSize) {
satok1f6b52e2012-01-30 13:53:58 +0900559 if (outputWordStartPos + nextWordLength >= MAX_WORD_LENGTH) {
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900560 return FLAG_MULTIPLE_SUGGEST_SKIP;
satok3c09bb12012-01-26 18:36:19 +0900561 }
Ken Wakasab02ee3d2012-10-08 11:46:14 +0900562 outputWord[tempOutputWordLength] = KEYCODE_SPACE;
satok1f6b52e2012-01-30 13:53:58 +0900563 if (outputWordLength) {
564 ++*outputWordLength;
565 }
566 } else if (currentWordIndex >= 1) {
satok99557162012-01-26 22:49:13 +0900567 // TODO: Handle 3 or more words
satoka85f4922012-01-30 18:18:30 +0900568 const int pairFreq = correction->getFreqForSplitMultipleWords(
569 freqArray, wordLengthArray, currentWordIndex + 1, isSpaceProximity, outputWord);
satok99557162012-01-26 22:49:13 +0900570 if (DEBUG_DICT) {
satoka85f4922012-01-30 18:18:30 +0900571 DUMP_WORD(outputWord, tempOutputWordLength);
satoka0ac31f2012-05-23 19:55:27 +0900572 for (int i = 0; i < currentWordIndex + 1; ++i) {
573 AKLOGI("Split %d,%d words: freq = %d, length = %d", i, currentWordIndex + 1,
574 freqArray[i], wordLengthArray[i]);
575 }
576 AKLOGI("Split two words: freq = %d, length = %d, %d, isSpace ? %d", pairFreq,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900577 inputSize, tempOutputWordLength, isSpaceProximity);
satok99557162012-01-26 22:49:13 +0900578 }
Jean Chalard926ef062012-08-10 13:14:45 +0900579 addWord(outputWord, tempOutputWordLength, pairFreq, queuePool->getMasterQueue(),
580 Dictionary::KIND_CORRECTION);
satok3c09bb12012-01-26 18:36:19 +0900581 }
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900582 return FLAG_MULTIPLE_SUGGEST_CONTINUE;
satok7409d152012-01-26 16:13:25 +0900583}
584
satok1f6b52e2012-01-30 13:53:58 +0900585void UnigramDictionary::getMultiWordsSuggestionRec(ProximityInfo *proximityInfo,
586 const int *xcoordinates, const int *ycoordinates, const int *codes,
Ken Wakasaf2789812012-09-04 12:49:46 +0900587 const bool useFullEditDistance, const int inputSize, Correction *correction,
588 WordsPriorityQueuePool *queuePool, const bool hasAutoCorrectionCandidate,
589 const int startInputPos, const int startWordIndex, const int outputWordLength,
Ken Wakasa1e614932012-10-29 18:06:22 +0900590 int *freqArray, int *wordLengthArray, int *outputWord) const {
satok1f6b52e2012-01-30 13:53:58 +0900591 if (startWordIndex >= (MULTIPLE_WORDS_SUGGESTION_MAX_WORDS - 1)) {
592 // Return if the last word index
593 return;
594 }
satoka85f4922012-01-30 18:18:30 +0900595 if (startWordIndex >= 1
596 && (hasAutoCorrectionCandidate
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900597 || inputSize < MIN_INPUT_LENGTH_FOR_THREE_OR_MORE_WORDS_CORRECTION)) {
satoka85f4922012-01-30 18:18:30 +0900598 // Do not suggest 3+ words if already has auto correction candidate
599 return;
600 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900601 for (int i = startInputPos + 1; i < inputSize; ++i) {
satok1f6b52e2012-01-30 13:53:58 +0900602 if (DEBUG_CORRECTION_FREQ) {
satoka85f4922012-01-30 18:18:30 +0900603 AKLOGI("Multi words(%d), start in %d sep %d start out %d",
604 startWordIndex, startInputPos, i, outputWordLength);
605 DUMP_WORD(outputWord, outputWordLength);
satok1f6b52e2012-01-30 13:53:58 +0900606 }
satoka85f4922012-01-30 18:18:30 +0900607 int tempOutputWordLength = 0;
608 // Current word
609 int inputWordStartPos = startInputPos;
610 int inputWordLength = i - startInputPos;
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900611 const int suggestionFlag = getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900612 codes, useFullEditDistance, correction, queuePool, inputSize,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900613 hasAutoCorrectionCandidate, startWordIndex, inputWordStartPos, inputWordLength,
614 outputWordLength, true /* not used */, freqArray, wordLengthArray, outputWord,
615 &tempOutputWordLength);
616 if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_ABORT) {
617 // TODO: break here
618 continue;
619 } else if (suggestionFlag == FLAG_MULTIPLE_SUGGEST_SKIP) {
satok1f6b52e2012-01-30 13:53:58 +0900620 continue;
621 }
622
satoka85f4922012-01-30 18:18:30 +0900623 if (DEBUG_CORRECTION_FREQ) {
624 AKLOGI("Do missing space correction");
625 }
626 // Next word
satok1f6b52e2012-01-30 13:53:58 +0900627 // Missing space
628 inputWordStartPos = i;
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900629 inputWordLength = inputSize - i;
Ken Wakasaf2789812012-09-04 12:49:46 +0900630 if (getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900631 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900632 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
Satoshi Kataoka6cbe2042012-05-30 17:28:34 +0900633 false /* missing space */, freqArray, wordLengthArray, outputWord, 0)
634 != FLAG_MULTIPLE_SUGGEST_CONTINUE) {
satoka85f4922012-01-30 18:18:30 +0900635 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900636 useFullEditDistance, inputSize, correction, queuePool,
satoka85f4922012-01-30 18:18:30 +0900637 hasAutoCorrectionCandidate, inputWordStartPos, startWordIndex + 1,
638 tempOutputWordLength, freqArray, wordLengthArray, outputWord);
639 }
satok1f6b52e2012-01-30 13:53:58 +0900640
641 // Mistyped space
642 ++inputWordStartPos;
643 --inputWordLength;
644
645 if (inputWordLength <= 0) {
646 continue;
647 }
648
649 const int x = xcoordinates[inputWordStartPos - 1];
650 const int y = ycoordinates[inputWordStartPos - 1];
651 if (!proximityInfo->hasSpaceProximity(x, y)) {
652 continue;
653 }
654
satoka85f4922012-01-30 18:18:30 +0900655 if (DEBUG_CORRECTION_FREQ) {
656 AKLOGI("Do mistyped space correction");
657 }
satok1f6b52e2012-01-30 13:53:58 +0900658 getSubStringSuggestion(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900659 useFullEditDistance, correction, queuePool, inputSize, hasAutoCorrectionCandidate,
satoka85f4922012-01-30 18:18:30 +0900660 startWordIndex + 1, inputWordStartPos, inputWordLength, tempOutputWordLength,
661 true /* mistyped space */, freqArray, wordLengthArray, outputWord, 0);
satok1f6b52e2012-01-30 13:53:58 +0900662 }
663}
664
satoka85f4922012-01-30 18:18:30 +0900665void UnigramDictionary::getSplitMultipleWordsSuggestions(ProximityInfo *proximityInfo,
satok744dab62011-12-15 22:29:05 +0900666 const int *xcoordinates, const int *ycoordinates, const int *codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900667 const bool useFullEditDistance, const int inputSize,
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900668 Correction *correction, WordsPriorityQueuePool *queuePool,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900669 const bool hasAutoCorrectionCandidate) const {
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900670 if (inputSize >= MAX_WORD_LENGTH) return;
satok612c6e42011-08-01 19:35:27 +0900671 if (DEBUG_DICT) {
satok1f6b52e2012-01-30 13:53:58 +0900672 AKLOGI("--- Suggest multiple words");
673 }
satok54af64a2012-01-17 15:58:23 +0900674
satokbd6ccdd2012-01-23 12:30:20 +0900675 // Allocating fixed length array on stack
Ken Wakasa1e614932012-10-29 18:06:22 +0900676 int outputWord[MAX_WORD_LENGTH];
satok1f6b52e2012-01-30 13:53:58 +0900677 int freqArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
678 int wordLengthArray[MULTIPLE_WORDS_SUGGESTION_MAX_WORDS];
679 const int outputWordLength = 0;
680 const int startInputPos = 0;
681 const int startWordIndex = 0;
682 getMultiWordsSuggestionRec(proximityInfo, xcoordinates, ycoordinates, codes,
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900683 useFullEditDistance, inputSize, correction, queuePool, hasAutoCorrectionCandidate,
satok1f6b52e2012-01-30 13:53:58 +0900684 startInputPos, startWordIndex, outputWordLength, freqArray, wordLengthArray,
685 outputWord);
Jean Chalarde6715e32011-06-30 19:47:25 +0900686}
687
Jean Chalard1059f272011-06-28 20:45:05 +0900688// Wrapper for getMostFrequentWordLikeInner, which matches it to the previous
689// interface.
Ken Wakasa2c2f3a92012-11-02 18:29:03 +0900690int UnigramDictionary::getMostFrequentWordLike(const int startInputIndex, const int inputSize,
691 Correction *correction, int *word) const {
Ken Wakasa1e614932012-10-29 18:06:22 +0900692 int inWord[inputSize];
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900693 for (int i = 0; i < inputSize; ++i) {
Ken Wakasa1e614932012-10-29 18:06:22 +0900694 inWord[i] = correction->getPrimaryCodePointAt(startInputIndex + i);
Jean Chalard1059f272011-06-28 20:45:05 +0900695 }
Satoshi Kataoka687a2442012-08-23 15:46:43 +0900696 return getMostFrequentWordLikeInner(inWord, inputSize, word);
Jean Chalard1059f272011-06-28 20:45:05 +0900697}
698
699// This function will take the position of a character array within a CharGroup,
700// and check it actually like-matches the word in inWord starting at startInputIndex,
701// that is, it matches it with case and accents squashed.
702// The function returns true if there was a full match, false otherwise.
703// The function will copy on-the-fly the characters in the CharGroup to outNewWord.
704// It will also place the end position of the array in outPos; in outInputIndex,
705// it will place the index of the first char AFTER the match if there was a match,
706// and the initial position if there was not. It makes sense because if there was
707// a match we want to continue searching, but if there was not, we want to go to
708// the next CharGroup.
709// In and out parameters may point to the same location. This function takes care
710// not to use any input parameters after it wrote into its outputs.
711static inline bool testCharGroupForContinuedLikeness(const uint8_t flags,
Ken Wakasa1e614932012-10-29 18:06:22 +0900712 const uint8_t *const root, const int startPos, const int *const inWord,
713 const int startInputIndex, const int inputSize, int *outNewWord, int *outInputIndex,
Ken Wakasaf2789812012-09-04 12:49:46 +0900714 int *outPos) {
Jean Chalard19560502012-07-31 23:45:32 +0900715 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Jean Chalard1059f272011-06-28 20:45:05 +0900716 int pos = startPos;
Ken Wakasa1e614932012-10-29 18:06:22 +0900717 int codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
718 int baseChar = toBaseLowerCase(codePoint);
719 const int wChar = toBaseLowerCase(inWord[startInputIndex]);
Jean Chalard1059f272011-06-28 20:45:05 +0900720
721 if (baseChar != wChar) {
722 *outPos = hasMultipleChars ? BinaryFormat::skipOtherCharacters(root, pos) : pos;
723 *outInputIndex = startInputIndex;
724 return false;
725 }
726 int inputIndex = startInputIndex;
Ken Wakasaf2789812012-09-04 12:49:46 +0900727 outNewWord[inputIndex] = codePoint;
Jean Chalard1059f272011-06-28 20:45:05 +0900728 if (hasMultipleChars) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900729 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
730 while (NOT_A_CODE_POINT != codePoint) {
731 baseChar = toBaseLowerCase(codePoint);
732 if (inputIndex + 1 >= inputSize || toBaseLowerCase(inWord[++inputIndex]) != baseChar) {
Jean Chalard1059f272011-06-28 20:45:05 +0900733 *outPos = BinaryFormat::skipOtherCharacters(root, pos);
734 *outInputIndex = startInputIndex;
735 return false;
736 }
Ken Wakasaf2789812012-09-04 12:49:46 +0900737 outNewWord[inputIndex] = codePoint;
738 codePoint = BinaryFormat::getCodePointAndForwardPointer(root, &pos);
Jean Chalard1059f272011-06-28 20:45:05 +0900739 }
740 }
741 *outInputIndex = inputIndex + 1;
742 *outPos = pos;
743 return true;
744}
745
746// This function is invoked when a word like the word searched for is found.
747// It will compare the frequency to the max frequency, and if greater, will
748// copy the word into the output buffer. In output value maxFreq, it will
749// write the new maximum frequency if it changed.
Ken Wakasa1e614932012-10-29 18:06:22 +0900750static inline void onTerminalWordLike(const int freq, int *newWord, const int length, int *outWord,
751 int *maxFreq) {
Jean Chalard1059f272011-06-28 20:45:05 +0900752 if (freq > *maxFreq) {
Ken Wakasaf2789812012-09-04 12:49:46 +0900753 for (int q = 0; q < length; ++q) {
Jean Chalard1059f272011-06-28 20:45:05 +0900754 outWord[q] = newWord[q];
Ken Wakasaf2789812012-09-04 12:49:46 +0900755 }
Jean Chalard1059f272011-06-28 20:45:05 +0900756 outWord[length] = 0;
757 *maxFreq = freq;
758 }
759}
760
761// Will find the highest frequency of the words like the one passed as an argument,
762// that is, everything that only differs by case/accents.
Ken Wakasa1e614932012-10-29 18:06:22 +0900763int UnigramDictionary::getMostFrequentWordLikeInner(const int *const inWord, const int inputSize,
764 int *outWord) const {
765 int newWord[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900766 int depth = 0;
767 int maxFreq = -1;
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900768 const uint8_t *const root = DICT_ROOT;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900769 int stackChildCount[MAX_WORD_LENGTH_INTERNAL];
770 int stackInputIndex[MAX_WORD_LENGTH_INTERNAL];
771 int stackSiblingPos[MAX_WORD_LENGTH_INTERNAL];
Jean Chalard1059f272011-06-28 20:45:05 +0900772
Jean Chalard4c0eca62012-01-16 15:15:53 +0900773 int startPos = 0;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900774 stackChildCount[0] = BinaryFormat::getGroupCountAndForwardPointer(root, &startPos);
775 stackInputIndex[0] = 0;
776 stackSiblingPos[0] = startPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900777 while (depth >= 0) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900778 const int charGroupCount = stackChildCount[depth];
779 int pos = stackSiblingPos[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900780 for (int charGroupIndex = charGroupCount - 1; charGroupIndex >= 0; --charGroupIndex) {
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900781 int inputIndex = stackInputIndex[depth];
Jean Chalard1059f272011-06-28 20:45:05 +0900782 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
783 // Test whether all chars in this group match with the word we are searching for. If so,
Ken Wakasaf2789812012-09-04 12:49:46 +0900784 // we want to traverse its children (or if the inputSize match, evaluate its frequency).
Jean Chalard1059f272011-06-28 20:45:05 +0900785 // Note that this function will output the position regardless, but will only write
786 // into inputIndex if there is a match.
787 const bool isAlike = testCharGroupForContinuedLikeness(flags, root, pos, inWord,
Ken Wakasaf2789812012-09-04 12:49:46 +0900788 inputIndex, inputSize, newWord, &inputIndex, &pos);
Jean Chalardd03e0652012-10-18 07:28:18 +0900789 if (isAlike && (!(BinaryFormat::FLAG_IS_NOT_A_WORD & flags))
790 && (BinaryFormat::FLAG_IS_TERMINAL & flags) && (inputIndex == inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900791 const int frequency = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
792 onTerminalWordLike(frequency, newWord, inputIndex, outWord, &maxFreq);
793 }
794 pos = BinaryFormat::skipFrequency(flags, pos);
795 const int siblingPos = BinaryFormat::skipChildrenPosAndAttributes(root, flags, pos);
796 const int childrenNodePos = BinaryFormat::readChildrenPosition(root, flags, pos);
797 // If we had a match and the word has children, we want to traverse them. We don't have
798 // to traverse words longer than the one we are searching for, since they will not match
Ken Wakasaf2789812012-09-04 12:49:46 +0900799 // anyway, so don't traverse unless inputIndex < inputSize.
800 if (isAlike && (-1 != childrenNodePos) && (inputIndex < inputSize)) {
Jean Chalard1059f272011-06-28 20:45:05 +0900801 // Save position for this depth, to get back to this once children are done
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900802 stackChildCount[depth] = charGroupIndex;
803 stackSiblingPos[depth] = siblingPos;
Jean Chalard1059f272011-06-28 20:45:05 +0900804 // Prepare stack values for next depth
805 ++depth;
806 int childrenPos = childrenNodePos;
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900807 stackChildCount[depth] =
Jean Chalard1059f272011-06-28 20:45:05 +0900808 BinaryFormat::getGroupCountAndForwardPointer(root, &childrenPos);
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900809 stackSiblingPos[depth] = childrenPos;
810 stackInputIndex[depth] = inputIndex;
Jean Chalard1059f272011-06-28 20:45:05 +0900811 pos = childrenPos;
812 // Go to the next depth level.
813 ++depth;
814 break;
815 } else {
816 // No match, or no children, or word too long to ever match: go the next sibling.
817 pos = siblingPos;
818 }
819 }
820 --depth;
821 }
822 return maxFreq;
823}
824
Ken Wakasa1e614932012-10-29 18:06:22 +0900825int UnigramDictionary::getFrequency(const int *const inWord, const int length) const {
Ken Wakasa0bbb9172012-07-25 17:51:43 +0900826 const uint8_t *const root = DICT_ROOT;
Jean Chalarde9a86e22012-06-28 21:01:29 +0900827 int pos = BinaryFormat::getTerminalPosition(root, inWord, length,
828 false /* forceLowerCaseSearch */);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900829 if (NOT_VALID_WORD == pos) {
830 return NOT_A_PROBABILITY;
831 }
832 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(root, &pos);
Jean Chalard72b1c932012-08-31 15:24:39 +0900833 if (flags & (BinaryFormat::FLAG_IS_BLACKLISTED | BinaryFormat::FLAG_IS_NOT_A_WORD)) {
834 // If this is not a word, or if it's a blacklisted entry, it should behave as
835 // having no frequency outside of the suggestion process (where it should be used
836 // for shortcuts).
837 return NOT_A_PROBABILITY;
838 }
Jean Chalard19560502012-07-31 23:45:32 +0900839 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900840 if (hasMultipleChars) {
841 pos = BinaryFormat::skipOtherCharacters(root, pos);
842 } else {
Ken Wakasaf2789812012-09-04 12:49:46 +0900843 BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Satoshi Kataoka2f854e12012-05-29 15:58:13 +0900844 }
845 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(root, pos);
846 return unigramFreq;
Jean Chalard1059f272011-06-28 20:45:05 +0900847}
848
849// TODO: remove this function.
Ken Wakasa1e614932012-10-29 18:06:22 +0900850int UnigramDictionary::getBigramPosition(int pos, int *word, int offset, int length) const {
Jean Chalard1059f272011-06-28 20:45:05 +0900851 return -1;
852}
853
854// ProcessCurrentNode returns a boolean telling whether to traverse children nodes or not.
855// If the return value is false, then the caller should read in the output "nextSiblingPosition"
856// to find out the address of the next sibling node and pass it to a new call of processCurrentNode.
857// It is worthy to note that when false is returned, the output values other than
858// nextSiblingPosition are undefined.
859// If the return value is true, then the caller must proceed to traverse the children of this
860// node. processCurrentNode will output the information about the children: their count in
861// newCount, their position in newChildrenPosition, the traverseAllNodes flag in
862// newTraverseAllNodes, the match weight into newMatchRate, the input index into newInputIndex, the
863// diffs into newDiffs, the sibling position in nextSiblingPosition, and the output index into
864// newOutputIndex. Please also note the following caveat: processCurrentNode does not know when
865// there aren't any more nodes at this level, it merely returns the address of the first byte after
866// the current node in nextSiblingPosition. Thus, the caller must keep count of the nodes at any
867// given level, as output into newCount when traversing this level's parent.
Ken Wakasa2c2f3a92012-11-02 18:29:03 +0900868bool UnigramDictionary::processCurrentNode(const int initialPos,
Jean Chalard8950ce62012-05-07 16:28:30 +0900869 const std::map<int, int> *bigramMap, const uint8_t *bigramFilter, Correction *correction,
870 int *newCount, int *newChildrenPosition, int *nextSiblingPosition,
Satoshi Kataoka6bc051d2012-06-08 19:52:19 +0900871 WordsPriorityQueuePool *queuePool, const int currentWordIndex) const {
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900872 if (DEBUG_DICT) {
satokcfca3c62011-08-10 14:30:10 +0900873 correction->checkState();
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900874 }
Jean Chalard0584f022011-06-30 19:23:16 +0900875 int pos = initialPos;
Jean Chalard0584f022011-06-30 19:23:16 +0900876
Jean Chalard1059f272011-06-28 20:45:05 +0900877 // Flags contain the following information:
878 // - Address type (MASK_GROUP_ADDRESS_TYPE) on two bits:
879 // - FLAG_GROUP_ADDRESS_TYPE_{ONE,TWO,THREE}_BYTES means there are children and their address
880 // is on the specified number of bytes.
881 // - FLAG_GROUP_ADDRESS_TYPE_NOADDRESS means there are no children, and therefore no address.
882 // - FLAG_HAS_MULTIPLE_CHARS: whether this node has multiple char or not.
883 // - FLAG_IS_TERMINAL: whether this node is a terminal or not (it may still have children)
884 // - FLAG_HAS_BIGRAMS: whether this node has bigrams or not
885 const uint8_t flags = BinaryFormat::getFlagsAndForwardPointer(DICT_ROOT, &pos);
Jean Chalard19560502012-07-31 23:45:32 +0900886 const bool hasMultipleChars = (0 != (BinaryFormat::FLAG_HAS_MULTIPLE_CHARS & flags));
887 const bool isTerminalNode = (0 != (BinaryFormat::FLAG_IS_TERMINAL & flags));
satok8876b752011-08-04 18:31:57 +0900888
889 bool needsToInvokeOnTerminal = false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900890
Jean Chalard1059f272011-06-28 20:45:05 +0900891 // This gets only ONE character from the stream. Next there will be:
892 // if FLAG_HAS_MULTIPLE CHARS: the other characters of the same node
893 // else if FLAG_IS_TERMINAL: the frequency
894 // else if MASK_GROUP_ADDRESS_TYPE is not NONE: the children address
895 // Note that you can't have a node that both is not a terminal and has no children.
Ken Wakasa1e614932012-10-29 18:06:22 +0900896 int c = BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos);
Ken Wakasaf2789812012-09-04 12:49:46 +0900897 assert(NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900898
Jean Chalard1059f272011-06-28 20:45:05 +0900899 // We are going to loop through each character and make it look like it's a different
900 // node each time. To do that, we will process characters in this node in order until
Ken Wakasaf2789812012-09-04 12:49:46 +0900901 // we find the character terminator. This is signalled by getCodePoint* returning
902 // NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900903 // As a special case, if there is only one character in this node, we must not read the
Ken Wakasaf2789812012-09-04 12:49:46 +0900904 // next bytes so we will simulate the NOT_A_CODE_POINT return by testing the flags.
Jean Chalard1059f272011-06-28 20:45:05 +0900905 // This way, each loop run will look like a "virtual node".
906 do {
907 // We prefetch the next char. If 'c' is the last char of this node, we will have
Ken Wakasaf2789812012-09-04 12:49:46 +0900908 // NOT_A_CODE_POINT in the next char. From this we can decide whether this virtual node
Jean Chalard1059f272011-06-28 20:45:05 +0900909 // should behave as a terminal or not and whether we have children.
Ken Wakasa1e614932012-10-29 18:06:22 +0900910 const int nextc = hasMultipleChars
Ken Wakasaf2789812012-09-04 12:49:46 +0900911 ? BinaryFormat::getCodePointAndForwardPointer(DICT_ROOT, &pos) : NOT_A_CODE_POINT;
912 const bool isLastChar = (NOT_A_CODE_POINT == nextc);
Jean Chalard1059f272011-06-28 20:45:05 +0900913 // If there are more chars in this nodes, then this virtual node is not a terminal.
914 // If we are on the last char, this virtual node is a terminal if this node is.
satok8876b752011-08-04 18:31:57 +0900915 const bool isTerminal = isLastChar && isTerminalNode;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900916
satokcfca3c62011-08-10 14:30:10 +0900917 Correction::CorrectionType stateType = correction->processCharAndCalcState(
satok8876b752011-08-04 18:31:57 +0900918 c, isTerminal);
satokcfca3c62011-08-10 14:30:10 +0900919 if (stateType == Correction::TRAVERSE_ALL_ON_TERMINAL
920 || stateType == Correction::ON_TERMINAL) {
satok8876b752011-08-04 18:31:57 +0900921 needsToInvokeOnTerminal = true;
satokd03317c2011-12-14 21:38:11 +0900922 } else if (stateType == Correction::UNRELATED || correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900923 // We found that this is an unrelated character, so we should give up traversing
924 // this node and its children entirely.
925 // However we may not be on the last virtual node yet so we skip the remaining
926 // characters in this node, the frequency if it's there, read the next sibling
927 // position to output it, then return false.
928 // We don't have to output other values because we return false, as in
929 // "don't traverse children".
Jean Chalard1059f272011-06-28 20:45:05 +0900930 if (!isLastChar) {
931 pos = BinaryFormat::skipOtherCharacters(DICT_ROOT, pos);
932 }
933 pos = BinaryFormat::skipFrequency(flags, pos);
934 *nextSiblingPosition =
935 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
936 return false;
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900937 }
938
Jean Chalard1059f272011-06-28 20:45:05 +0900939 // Prepare for the next character. Promote the prefetched char to current char - the loop
940 // will take care of prefetching the next. If we finally found our last char, nextc will
Ken Wakasaf2789812012-09-04 12:49:46 +0900941 // contain NOT_A_CODE_POINT.
Jean Chalard1059f272011-06-28 20:45:05 +0900942 c = nextc;
Ken Wakasaf2789812012-09-04 12:49:46 +0900943 } while (NOT_A_CODE_POINT != c);
Jean Chalard85a1d1e2011-06-21 22:23:21 +0900944
satok8876b752011-08-04 18:31:57 +0900945 if (isTerminalNode) {
satok6ad15fc2012-01-16 16:21:21 +0900946 // The frequency should be here, because we come here only if this is actually
947 // a terminal node, and we are on its last char.
Jean Chalard171d1802012-04-23 18:51:00 +0900948 const int unigramFreq = BinaryFormat::readFrequencyWithoutMovingPointer(DICT_ROOT, pos);
satok6ad15fc2012-01-16 16:21:21 +0900949 const int childrenAddressPos = BinaryFormat::skipFrequency(flags, pos);
950 const int attributesPos = BinaryFormat::skipChildrenPosition(flags, childrenAddressPos);
951 TerminalAttributes terminalAttributes(DICT_ROOT, flags, attributesPos);
Jean Chalard8950ce62012-05-07 16:28:30 +0900952 // bigramMap contains the bigram frequencies indexed by addresses for fast lookup.
953 // bigramFilter is a bloom filter of said frequencies for even faster rejection.
Jean Chalard49ba1352012-05-07 20:14:00 +0900954 const int probability = BinaryFormat::getProbability(initialPos, bigramMap, bigramFilter,
955 unigramFreq);
Jean Chalard171d1802012-04-23 18:51:00 +0900956 onTerminal(probability, terminalAttributes, correction, queuePool, needsToInvokeOnTerminal,
satok8330b482012-01-23 16:52:37 +0900957 currentWordIndex);
Jean Chalard1059f272011-06-28 20:45:05 +0900958
satok8876b752011-08-04 18:31:57 +0900959 // If there are more chars in this node, then this virtual node has children.
960 // If we are on the last char, this virtual node has children if this node has.
961 const bool hasChildren = BinaryFormat::hasChildrenInFlags(flags);
962
963 // This character matched the typed character (enough to traverse the node at least)
964 // so we just evaluated it. Now we should evaluate this virtual node's children - that
965 // is, if it has any. If it has no children, we're done here - so we skip the end of
966 // the node, output the siblings position, and return false "don't traverse children".
967 // Note that !hasChildren implies isLastChar, so we know we don't have to skip any
968 // remaining char in this group for there can't be any.
969 if (!hasChildren) {
970 pos = BinaryFormat::skipFrequency(flags, pos);
971 *nextSiblingPosition =
972 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
973 return false;
974 }
975
976 // Optimization: Prune out words that are too long compared to how much was typed.
satokcfca3c62011-08-10 14:30:10 +0900977 if (correction->needsToPrune()) {
satok8876b752011-08-04 18:31:57 +0900978 pos = BinaryFormat::skipFrequency(flags, pos);
979 *nextSiblingPosition =
980 BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
satok10266c02011-08-19 22:05:59 +0900981 if (DEBUG_DICT_FULL) {
satok9fb6f472012-01-13 18:01:22 +0900982 AKLOGI("Traversing was pruned.");
satok10266c02011-08-19 22:05:59 +0900983 }
satok8876b752011-08-04 18:31:57 +0900984 return false;
985 }
986 }
Jean Chalard1059f272011-06-28 20:45:05 +0900987
988 // Now we finished processing this node, and we want to traverse children. If there are no
989 // children, we can't come here.
990 assert(BinaryFormat::hasChildrenInFlags(flags));
991
992 // If this node was a terminal it still has the frequency under the pointer (it may have been
993 // read, but not skipped - see readFrequencyWithoutMovingPointer).
994 // Next come the children position, then possibly attributes (attributes are bigrams only for
995 // now, maybe something related to shortcuts in the future).
996 // Once this is read, we still need to output the number of nodes in the immediate children of
997 // this node, so we read and output it before returning true, as in "please traverse children".
998 pos = BinaryFormat::skipFrequency(flags, pos);
999 int childrenPos = BinaryFormat::readChildrenPosition(DICT_ROOT, flags, pos);
1000 *nextSiblingPosition = BinaryFormat::skipChildrenPosAndAttributes(DICT_ROOT, flags, pos);
1001 *newCount = BinaryFormat::getGroupCountAndForwardPointer(DICT_ROOT, &childrenPos);
1002 *newChildrenPosition = childrenPos;
1003 return true;
Jean Chalard85a1d1e2011-06-21 22:23:21 +09001004}
satok30088252010-12-01 21:22:15 +09001005} // namespace latinime