Debian Codegraph @

morfologik-speller/src/main/java/morfologik/speller/Speller.java

raw symbols SCIP
1 package morfologik.speller;
2
3 import static morfologik.fsa.MatchResult.EXACT_MATCH;
4 import static morfologik.fsa.MatchResult.SEQUENCE_IS_A_PREFIX;
5
6 import java.nio.ByteBuffer;
7 import java.nio.CharBuffer;
8 import java.nio.charset.CharsetDecoder;
9 import java.nio.charset.CharsetEncoder;
10 import java.nio.charset.CoderResult;
11 import java.text.Normalizer;
12 import java.text.Normalizer.Form;
13 import java.util.*;
14
15 import morfologik.fsa.FSA;
16 import morfologik.fsa.ByteSequenceIterator;
17 import morfologik.fsa.FSATraversal;
18 import morfologik.fsa.MatchResult;
19 import morfologik.stemming.BufferUtils;
20 import morfologik.stemming.Dictionary;
21 import morfologik.stemming.DictionaryLookup;
22 import morfologik.stemming.DictionaryMetadata;
23 import morfologik.stemming.UnmappableInputException;
24
25 /**
26 * Finds spelling suggestions. Implements K. Oflazer's algorithm as described
27 * in: Oflazer, Kemal. 1996.
28 * "Error-Tolerant Finite-State Recognition with Applications to Morphological Analysis and Spelling Correction."
29 * <i>Computational Linguistics</i> 22 (1): 73–89.
30 *
31 * <p>
32 * See Jan Daciuk's <code>s_fsa</code> package.
33 */
34 public class Speller {
35 /**
36 * Maximum length of the word to be checked.
37 */
38 public static final int MAX_WORD_LENGTH = 120;
39 static final int FREQ_RANGES = 'Z' - 'A' + 1;
40 static final int FIRST_RANGE_CODE = 'A'; // less frequent words
41
42 //FIXME: this is an upper limit for replacement searches, we need
43 //proper tree traversal instead of generation of all possible candidates
44 static final int UPPER_SEARCH_LIMIT = 15;
45 private static final int MIN_WORD_LENGTH = 4;
46 private static final int MAX_RECURSION_LEVEL = 6;
47
48 private final int editDistance;
49 private int effectEditDistance; // effective edit distance
50
51 private final HMatrix hMatrix;
52
53 private char[] candidate; /* current replacement */
54 private int candLen;
55 private int wordLen; /* length of word being processed */
56 private char[] wordProcessed; /* word being processed */
57
58 private Map<Character, List<char[]>> replacementsAnyToOne = new HashMap<Character, List<char[]>>();
59 private Map<String, List<char[]>> replacementsAnyToTwo = new HashMap<String, List<char[]>>();
60 private Map<String, List<String>> replacementsTheRest = new HashMap<String, List<String>>();
61
62 private boolean containsSeparators = true;
63
64 /**
65 * Internal reusable buffer for encoding words into byte arrays using
66 * {@link #encoder}.
67 */
68 private ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_WORD_LENGTH);
69
70 /**
71 * Internal reusable buffer for encoding words into byte arrays using
72 * {@link #encoder}.
73 */
74 private CharBuffer charBuffer = CharBuffer.allocate(MAX_WORD_LENGTH);
75
76 /**
77 * Reusable match result.
78 */
79 private final MatchResult matchResult = new MatchResult();
80
81 /**
82 * Features of the compiled dictionary.
83 *
84 * @see DictionaryMetadata
85 */
86 private final DictionaryMetadata dictionaryMetadata;
87
88 /**
89 * Charset encoder for the FSA.
90 */
91 private final CharsetEncoder encoder;
92
93 /**
94 * Charset decoder for the FSA.
95 */
96 private final CharsetDecoder decoder;
97
98 /** An FSA used for lookups. */
99 private final FSATraversal matcher;
100
101 /** FSA's root node. */
102 private final int rootNode;
103
104 /**
105 * The FSA we are using.
106 */
107 private final FSA fsa;
108
109 /** An iterator for walking along the final states of {@link #fsa}. */
110 private final ByteSequenceIterator finalStatesIterator;
111
112 public Speller(final Dictionary dictionary) {
113 this(dictionary, 1);
114 }
115
116 public Speller(final Dictionary dictionary, final int editDistance) {
117 this.editDistance = editDistance;
118 this.hMatrix = new HMatrix(editDistance, MAX_WORD_LENGTH);
119
120 this.dictionaryMetadata = dictionary.metadata;
121 this.rootNode = dictionary.fsa.getRootNode();
122 this.fsa = dictionary.fsa;
123 this.matcher = new FSATraversal(fsa);
124 this.finalStatesIterator = new ByteSequenceIterator(fsa, rootNode);
125
126 if (rootNode == 0) {
127 throw new IllegalArgumentException("Dictionary must have at least the root node.");
128 }
129
130 if (dictionaryMetadata == null) {
131 throw new IllegalArgumentException("Dictionary metadata must not be null.");
132 }
133
134 encoder = dictionaryMetadata.getEncoder();
135 decoder = dictionaryMetadata.getDecoder();
136
137 // Multibyte separator will result in an exception here.
138 dictionaryMetadata.getSeparatorAsChar();
139
140 this.createReplacementsMaps();
141 }
142
143 private void createReplacementsMaps() {
144 for (Map.Entry<String, List<String>> entry : dictionaryMetadata.getReplacementPairs().entrySet()) {
145 for (String s : entry.getValue()) {
146 // replacements any to one
147 // the new key is the target of the replacement pair
148 if (s.length() == 1) {
149 if (!replacementsAnyToOne.containsKey(s.charAt(0))) {
150 List<char[]> charList = new ArrayList<char[]>();
151 charList.add(entry.getKey().toCharArray());
152 replacementsAnyToOne.put(s.charAt(0), charList);
153 } else {
154 replacementsAnyToOne.get(s.charAt(0)).add(entry.getKey().toCharArray());
155 }
156 }
157 // replacements any to two
158 // the new key is the target of the replacement pair
159 else if (s.length() == 2) {
160 if (!replacementsAnyToTwo.containsKey(s)) {
161 List<char[]> charList = new ArrayList<char[]>();
162 charList.add(entry.getKey().toCharArray());
163 replacementsAnyToTwo.put(s, charList);
164 } else {
165 replacementsAnyToTwo.get(s).add(entry.getKey().toCharArray());
166 }
167 } else {
168 if (!replacementsTheRest.containsKey(entry.getKey())) {
169 List<String> charList = new ArrayList<String>();
170 charList.add(s);
171 replacementsTheRest.put(entry.getKey(), charList);
172 } else {
173 replacementsTheRest.get(entry.getKey()).add(s);
174 }
175 }
176 }
177 }
178 }
179
180 private ByteBuffer charSequenceToBytes(final CharSequence word) throws UnmappableInputException {
181 // Encode word characters into bytes in the same encoding as the FSA's.
182 charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, word.length());
183 for (int i = 0; i < word.length(); i++) {
184 final char chr = word.charAt(i);
185 charBuffer.put(chr);
186 }
187 charBuffer.flip();
188
189 return BufferUtils.charsToBytes(encoder, charBuffer, byteBuffer);
190 }
191
192 /**
193 * Checks whether the word is misspelled, by performing a series of checks
194 * according to properties of the dictionary.
195 *
196 * If the flag <code>fsa.dict.speller.ignore-punctuation</code> is set, then
197 * all non-alphabetic characters are considered to be correctly spelled.
198 *
199 * If the flag <code>fsa.dict.speller.ignore-numbers</code> is set, then all
200 * words containing decimal digits are considered to be correctly spelled.
201 *
202 * If the flag <code>fsa.dict.speller.ignore-camel-case</code> is set, then
203 * all CamelCase words are considered to be correctly spelled.
204 *
205 * If the flag <code>fsa.dict.speller.ignore-all-uppercase</code> is set, then
206 * all alphabetic words composed of only uppercase characters are considered
207 * to be correctly spelled.
208 *
209 * Otherwise, the word is checked in the dictionary. If the test fails, and
210 * the dictionary does not perform any case conversions (as set by
211 * <code>fsa.dict.speller.convert-case</code> flag), then the method returns
212 * false. In case of case conversions, it is checked whether a non-mixed case
213 * word is found in its lowercase version in the dictionary, and for
214 * all-uppercase words, whether the word is found in the dictionary with the
215 * initial uppercase letter.
216 *
217 * @param word
218 * - the word to be checked
219 * @return true if the word is misspelled
220 **/
221 public boolean isMisspelled(final String word) {
222 // dictionaries usually do not contain punctuation
223 String wordToCheck = word;
224 if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) {
225 wordToCheck = DictionaryLookup.applyReplacements(word, dictionaryMetadata.getInputConversionPairs());
226 }
227 boolean isAlphabetic = wordToCheck.length() != 1 || isAlphabetic(wordToCheck.charAt(0));
228 return wordToCheck.length() > 0
229 && (!dictionaryMetadata.isIgnoringPunctuation() || isAlphabetic)
230 && (!dictionaryMetadata.isIgnoringNumbers() || containsNoDigit(wordToCheck))
231 && !(dictionaryMetadata.isIgnoringCamelCase() && isCamelCase(wordToCheck))
232 && !(dictionaryMetadata.isIgnoringAllUppercase() && isAlphabetic && isAllUppercase(wordToCheck))
233 && !isInDictionary(wordToCheck)
234 && (!dictionaryMetadata.isConvertingCase() ||
235 !(!isMixedCase(wordToCheck) &&
236 (isInDictionary(wordToCheck.toLowerCase(dictionaryMetadata.getLocale()))
237 || isAllUppercase(wordToCheck) && isInDictionary(initialUppercase(wordToCheck)))));
238 }
239
240 private CharSequence initialUppercase(final String wordToCheck) {
241 return wordToCheck.substring(0, 1) + wordToCheck.substring(1).toLowerCase(dictionaryMetadata.getLocale());
242 }
243
244 /**
245 * Test whether the word is found in the dictionary.
246 *
247 * @param word
248 * the word to be tested
249 * @return True if it is found.
250 */
251 public boolean isInDictionary(final CharSequence word) {
252 try {
253 byteBuffer = charSequenceToBytes(word);
254 } catch (UnmappableInputException e) {
255 return false;
256 }
257
258 // Try to find a partial match in the dictionary.
259 final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode);
260
261 // Make sure the word doesn't contain a separator if there is an exact match
262 if (containsSeparators && match.kind == EXACT_MATCH) {
263 containsSeparators = false;
264 for (int i=0; i<word.length(); i++) {
265 if (word.charAt(i) == dictionaryMetadata.getSeparator()) {
266 containsSeparators = true;
267 break;
268 }
269 }
270 }
271
272 if (match.kind == EXACT_MATCH && !containsSeparators) {
273 return true;
274 }
275
276 return containsSeparators && match.kind == SEQUENCE_IS_A_PREFIX && byteBuffer.remaining() > 0
277 && fsa.getArc(match.node, dictionaryMetadata.getSeparator()) != 0;
278 }
279
280 /**
281 * Get the frequency value for a word form. It is taken from the first entry
282 * with this word form.
283 *
284 * @param word
285 * the word to be tested
286 * @return frequency value in range: 0..FREQ_RANGE-1 (0: less frequent).
287 */
288
289 public int getFrequency(final CharSequence word) {
290 if (!dictionaryMetadata.isFrequencyIncluded()) {
291 return 0;
292 }
293
294 final byte separator = dictionaryMetadata.getSeparator();
295 try {
296 byteBuffer = charSequenceToBytes(word);
297 } catch (UnmappableInputException e) {
298 return 0;
299 }
300
301 final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode);
302 if (match.kind == SEQUENCE_IS_A_PREFIX) {
303 final int arc = fsa.getArc(match.node, separator);
304 if (arc != 0 && !fsa.isArcFinal(arc)) {
305 finalStatesIterator.restartFrom(fsa.getEndNode(arc));
306 if (finalStatesIterator.hasNext()) {
307 final ByteBuffer bb = finalStatesIterator.next();
308 final byte[] ba = bb.array();
309 final int bbSize = bb.remaining();
310 //the last byte contains the frequency after a separator
311 return ba[bbSize - 1] - FIRST_RANGE_CODE;
312 }
313 }
314 }
315 return 0;
316 }
317
318 /**
319 * Propose suggestions for misspelled run-on words. This algorithm is inspired
320 * by spell.cc in s_fsa package by Jan Daciuk.
321 *
322 * @param original
323 * The original misspelled word.
324 * @return The list of suggested pairs, as space-concatenated strings.
325 */
326 public List<String> replaceRunOnWords(final String original) {
327 final List<String> candidates = new ArrayList<String>();
328 String wordToCheck = original;
329 if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) {
330 wordToCheck = DictionaryLookup.applyReplacements(original, dictionaryMetadata.getInputConversionPairs());
331 }
332 if (!isInDictionary(wordToCheck) && dictionaryMetadata.isSupportingRunOnWords()) {
333 Locale locale = dictionaryMetadata.getLocale();
334 for (int i = 1; i < wordToCheck.length(); i++) {
335 // chop from left to right
336 final String prefix = wordToCheck.substring(0, i);
337 final String suffix = wordToCheck.substring(i);
338 if (isInDictionary(suffix)) {
339 if (isInDictionary(prefix)) {
340 addReplacement(candidates, prefix + " " + suffix);
341 } else if (Character.isUpperCase(prefix.charAt(0)) && isInDictionary(prefix.toLowerCase(locale))) {
342 // a word that's uppercase just because used at sentence start
343 addReplacement(candidates, prefix + " " + suffix);
344 }
345 }
346 }
347 }
348 return candidates;
349 }
350
351 private void addReplacement(List<String> candidates, String replacement) {
352 if (dictionaryMetadata.getOutputConversionPairs().isEmpty()) {
353 candidates.add(replacement);
354 } else {
355 candidates.add(DictionaryLookup.applyReplacements(replacement,
356 dictionaryMetadata.getOutputConversionPairs()));
357 }
358 }
359
360 /**
361 * Find suggestions by using K. Oflazer's algorithm. See Jan Daciuk's s_fsa
362 * package, spell.cc for further explanation.
363 *
364 * @param word The original misspelled word.
365 * @return A list of suggested replacements.
366 */
367 public ArrayList<String> findReplacements(String word) {
368 final List<CandidateData> result = findReplacementCandidates(word);
369
370 final ArrayList<String> resultSuggestions = new ArrayList<String>(result.size());
371 for (CandidateData cd : result) {
372 resultSuggestions.add(cd.getWord());
373 }
374 return resultSuggestions;
375 }
376
377 /**
378 * Find and return suggestions by using K. Oflazer's algorithm. See Jan Daciuk's s_fsa
379 * package, spell.cc for further explanation. This method is identical to
380 * {@link #findReplacements}, but returns candidate terms with their edit distance scores.
381 *
382 * @param word The original misspelled word.
383 * @return A list of suggested candidate replacements.
384 */
385 public ArrayList<CandidateData> findReplacementCandidates(String word) {
386 if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) {
387 word = DictionaryLookup.applyReplacements(word, dictionaryMetadata.getInputConversionPairs());
388 }
389
390 // candidate strings, including same additional data such as edit distance from the original word.
391 List<CandidateData> candidates = new ArrayList<CandidateData>();
392
393 if (word.length() > 0 && word.length() < MAX_WORD_LENGTH && !isInDictionary(word)) {
394 List<String> wordsToCheck = new ArrayList<String>();
395 if (replacementsTheRest != null && word.length() > 1) {
396 for (final String wordChecked : getAllReplacements(word, 0, 0)) {
397 if (isInDictionary(wordChecked)) {
398 candidates.add(new CandidateData(wordChecked, 0));
399 } else {
400 String lowerWord = wordChecked.toLowerCase(dictionaryMetadata.getLocale());
401 String upperWord = wordChecked.toUpperCase(dictionaryMetadata.getLocale());
402 if (isInDictionary(lowerWord)) {
403 //add the word as it is in the dictionary, not mixed-case versions of it
404 candidates.add(new CandidateData(lowerWord, 0));
405 }
406 if (isInDictionary(upperWord)) {
407 candidates.add(new CandidateData(upperWord, 0));
408 }
409 if (lowerWord.length() > 1) {
410 String firstUpperWord = Character.toUpperCase(lowerWord.charAt(0)) + lowerWord.substring(1);
411 if (isInDictionary(firstUpperWord)) {
412 candidates.add(new CandidateData(firstUpperWord, 0));
413 }
414 }
415 }
416 wordsToCheck.add(wordChecked);
417 }
418 } else {
419 wordsToCheck.add(word);
420 }
421
422 // Even if a candidate was found with the replacement pairs (which are usual errors),
423 // there might be more good candidates (see issue #94):
424 int i = 1;
425 for (final String wordChecked : wordsToCheck) {
426 i++;
427 if (i > UPPER_SEARCH_LIMIT) { // for performance reasons, do not search too deeply
428 break;
429 }
430 wordProcessed = wordChecked.toCharArray();
431 wordLen = wordProcessed.length;
432 if (wordLen < MIN_WORD_LENGTH && i > 2) { // three-letter replacements make little sense anyway
433 break;
434 }
435 candidate = new char[MAX_WORD_LENGTH];
436 candLen = candidate.length;
437 effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance;
438 charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, MAX_WORD_LENGTH);
439 byteBuffer = BufferUtils.clearAndEnsureCapacity(byteBuffer, MAX_WORD_LENGTH);
440 final byte[] prevBytes = new byte[0];
441 findRepl(candidates, 0, fsa.getRootNode(), prevBytes, 0, 0);
442 }
443 }
444
445 Collections.sort(candidates);
446
447 // Apply replacements, prune duplicates while preserving the candidate order.
448 final Set<String> words = new HashSet<String>();
449 final ArrayList<CandidateData> result = new ArrayList<>(candidates.size());
450 for (final CandidateData cd : candidates) {
451 String replaced = DictionaryLookup.applyReplacements(cd.getWord(), dictionaryMetadata.getOutputConversionPairs());
452 // Add only the first occurrence of a given word.
453 if (words.add(replaced)) {
454 result.add(new CandidateData(replaced, cd.distance));
455 }
456 }
457
458 return result;
459 }
460
461 private void findRepl(List<CandidateData> candidates, final int depth, final int node, final byte[] prevBytes, final int wordIndex, final int candIndex) {
462 int dist = 0;
463 for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) {
464 byteBuffer = BufferUtils.clearAndEnsureCapacity(byteBuffer, prevBytes.length + 1);
465 byteBuffer.put(prevBytes);
466 byteBuffer.put(fsa.getArcLabel(arc));
467 final int bufPos = byteBuffer.position();
468 byteBuffer.flip();
469 decoder.reset();
470 // FIXME: this isn't correct -- no checks for overflows, no decoder flush. I don't think this should be in here
471 // too, the decoder should run once on accumulated temporary byte buffer (current path) only when there's
472 // a potential that this buffer can become a replacement candidate (isEndOfCandidate). Because we assume candidates
473 // are valid input strings (this is verified when building the dictionary), it's save a lot of conversions.
474 final CoderResult c = decoder.decode(byteBuffer, charBuffer, true);
475 if (c.isMalformed()) { // assume that only valid
476 // encodings are there
477 final byte[] prev = new byte[bufPos];
478 byteBuffer.position(0);
479 byteBuffer.get(prev);
480 if (!fsa.isArcTerminal(arc)) {
481 findRepl(candidates, depth, fsa.getEndNode(arc), prev, wordIndex, candIndex); // note: depth is not incremented
482 }
483 byteBuffer.clear();
484 } else if (!c.isError()) { // unmappable characters are silently discarded
485 charBuffer.flip();
486 candidate[candIndex] = charBuffer.get();
487 charBuffer.clear();
488 byteBuffer.clear();
489
490 int lengthReplacement;
491 // replacement "any to two"
492 if ((lengthReplacement = matchAnyToTwo(wordIndex, candIndex)) > 0) {
493 // the replacement takes place at the end of the candidate
494 if (isEndOfCandidate(arc, wordIndex) && (dist = hMatrix.get(depth - 1, depth - 1)) <= effectEditDistance) {
495 if (Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 2)) > 0) {
496 // there are extra letters in the word after the replacement
497 dist = dist + Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 2));
498 }
499 if (dist <= effectEditDistance) {
500 candidates.add(new CandidateData(String.valueOf(candidate, 0, candIndex + 1), dist));
501 }
502 }
503 if (isArcNotTerminal(arc, candIndex)) {
504 int x = hMatrix.get(depth, depth);
505 hMatrix.set(depth, depth, hMatrix.get(depth - 1, depth - 1));
506 findRepl(candidates, Math.max(0, depth), fsa.getEndNode(arc), new byte[0], wordIndex + lengthReplacement - 1,
507 candIndex + 1);
508 hMatrix.set(depth, depth, x);
509 }
510 }
511 //replacement "any to one"
512 if ((lengthReplacement = matchAnyToOne(wordIndex, candIndex)) > 0) {
513 // the replacement takes place at the end of the candidate
514 if (isEndOfCandidate(arc, wordIndex) && (dist = hMatrix.get(depth, depth)) <= effectEditDistance) {
515 if (Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 1)) > 0) {
516 // there are extra letters in the word after the replacement
517 dist = dist + Math.abs(wordLen - 1 - (wordIndex + lengthReplacement - 1));
518 }
519 if (dist <= effectEditDistance) {
520 candidates.add(new CandidateData(String.valueOf(candidate, 0, candIndex + 1), dist));
521 }
522 }
523 if (isArcNotTerminal(arc, candIndex)) {
524 findRepl(candidates, depth, fsa.getEndNode(arc), new byte[0], wordIndex + lengthReplacement, candIndex + 1);
525 }
526 }
527 //general
528 if (cuted(depth, wordIndex, candIndex) <= effectEditDistance) {
529 if ((isEndOfCandidate(arc, wordIndex))
530 && (dist = ed(wordLen - 1 - (wordIndex - depth), depth, wordLen - 1, candIndex)) <= effectEditDistance) {
531 candidates.add(new CandidateData(String.valueOf(candidate, 0, candIndex + 1), dist));
532 }
533 if (isArcNotTerminal(arc, candIndex)) {
534 findRepl(candidates, depth + 1, fsa.getEndNode(arc), new byte[0], wordIndex + 1, candIndex + 1);
535 }
536 }
537 }
538 }
539 }
540
541 private boolean isArcNotTerminal(final int arc, final int candIndex) {
542 return !fsa.isArcTerminal(arc)
543 && !(containsSeparators && candidate[candIndex] == dictionaryMetadata.getSeparatorAsChar());
544 }
545
546 private boolean isEndOfCandidate(final int arc, final int wordIndex) {
547 return (fsa.isArcFinal(arc) || isBeforeSeparator(arc))
548 //candidate has proper length
549 && (Math.abs(wordLen - 1 - (wordIndex)) <= effectEditDistance);
550 }
551
552 private boolean isBeforeSeparator(final int arc) {
553 if (containsSeparators) {
554 final int arc1 = fsa.getArc(fsa.getEndNode(arc), dictionaryMetadata.getSeparator());
555 return arc1 != 0 && !fsa.isArcTerminal(arc1);
556 }
557 return false;
558 }
559
560 /**
561 * Calculates edit distance.
562 *
563 * @param i length of first word (here: misspelled) - 1;
564 * @param j length of second word (here: candidate) - 1.
565 * @param wordIndex (TODO: javadoc?)
566 * @param candIndex (TODO: javadoc?)
567 * @return Edit distance between the two words. Remarks: See Oflazer.
568 */
569 public int ed(final int i, final int j, final int wordIndex, final int candIndex) {
570 int result;
571 int a, b, c;
572
573 if (areEqual(wordProcessed[wordIndex], candidate[candIndex])) {
574 // last characters are the same
575 result = hMatrix.get(i, j);
576 } else if (wordIndex > 0 && candIndex > 0 && wordProcessed[wordIndex] == candidate[candIndex - 1]
577 && wordProcessed[wordIndex - 1] == candidate[candIndex]) {
578 // last two characters are transposed
579 a = hMatrix.get(i - 1, j - 1); // transposition, e.g. ababab, ababba
580 b = hMatrix.get(i + 1, j); // deletion, e.g. abab, aba
581 c = hMatrix.get(i, j + 1); // insertion e.g. aba, abab
582 result = 1 + min(a, b, c);
583 } else {
584 // otherwise
585 a = hMatrix.get(i, j); // replacement, e.g. ababa, ababb
586 b = hMatrix.get(i + 1, j); // deletion, e.g. ab, a
587 c = hMatrix.get(i, j + 1); // insertion e.g. a, ab
588 result = 1 + min(a, b, c);
589 }
590
591 hMatrix.set(i + 1, j + 1, result);
592 return result;
593 }
594
595 // by Jaume Ortola
596 private boolean areEqual(final char x, final char y) {
597 if (x == y) {
598 return true;
599 }
600 if (dictionaryMetadata.getEquivalentChars() != null) {
601 List<Character> chars = dictionaryMetadata.getEquivalentChars().get(x);
602 if (chars != null && chars.contains(y)) {
603 return true;
604 }
605 }
606 if (dictionaryMetadata.isIgnoringDiacritics()) {
607 String xn = Normalizer.normalize(Character.toString(x), Form.NFD);
608 String yn = Normalizer.normalize(Character.toString(y), Form.NFD);
609 if (xn.charAt(0) == yn.charAt(0)) { // avoid case conversion, if possible
610 return true;
611 }
612 if (dictionaryMetadata.isConvertingCase()) {
613 //again case conversion only when needed -- we
614 // do not need String.lowercase because we only check
615 // single characters, so a cheaper method is enough
616 if (Character.isLetter(xn.charAt(0))) {
617 boolean testNeeded = Character.isLowerCase(xn.charAt(0)) != Character.isLowerCase(yn.charAt(0));
618 if (testNeeded) {
619 return Character.toLowerCase(xn.charAt(0)) == Character.toLowerCase(yn.charAt(0));
620 }
621 }
622 }
623 return xn.charAt(0) == yn.charAt(0);
624 }
625 return false;
626 }
627
628 /**
629 * Calculates cut-off edit distance.
630 *
631 * @param depth current length of candidates.
632 * @param wordIndex (TODO: javadoc?)
633 * @param candIndex (TODO: javadoc?)
634 * @return Cut-off edit distance. Remarks: See Oflazer.
635 */
636
637 public int cuted(final int depth, final int wordIndex, final int candIndex) {
638 final int l = Math.max(0, depth - effectEditDistance); // min chars from word to consider - 1
639 final int u = Math.min(wordLen - 1 - (wordIndex - depth), depth + effectEditDistance); // max chars from word to
640 // consider - 1
641 int minEd = effectEditDistance + 1; // what is to be computed
642 int wi = wordIndex + l - depth;
643 int d;
644
645 for (int i = l; i <= u; i++, wi++) {
646 if ((d = ed(i, depth, wi, candIndex)) < minEd) {
647 minEd = d;
648 }
649 }
650 return minEd;
651 }
652
653 // Match the last letter of the candidate against two or more letters of the word.
654 private int matchAnyToOne(final int wordIndex, final int candIndex) {
655 if (replacementsAnyToOne.containsKey(candidate[candIndex])) {
656 for (final char[] rep : replacementsAnyToOne.get(candidate[candIndex])) {
657 int i = 0;
658 while (i < rep.length && (wordIndex + i) < wordLen && rep[i] == wordProcessed[wordIndex + i]) {
659 i++;
660 }
661 if (i == rep.length) {
662 return i;
663 }
664 }
665 }
666 return 0;
667 }
668
669 private int matchAnyToTwo(final int wordIndex, final int candIndex) {
670 if (candIndex > 0 && candIndex < candidate.length && wordIndex > 0) {
671 char[] twoChar = { candidate[candIndex - 1], candidate[candIndex] };
672 String sTwoChar = new String(twoChar);
673 if (replacementsAnyToTwo.containsKey(sTwoChar)) {
674 for (final char[] rep : replacementsAnyToTwo.get(sTwoChar)) {
675 if (rep.length == 2 && wordIndex < wordLen && candidate[candIndex - 1] == wordProcessed[wordIndex - 1]
676 && candidate[candIndex] == wordProcessed[wordIndex]) {
677 return 0; //unnecessary replacements
678 }
679 int i = 0;
680 while (i < rep.length && (wordIndex - 1 + i) < wordLen && rep[i] == wordProcessed[wordIndex - 1 + i]) {
681 i++;
682 }
683 if (i == rep.length) {
684 return i;
685 }
686 }
687 }
688 }
689 return 0;
690 }
691
692 private static int min(final int a, final int b, final int c) {
693 return Math.min(a, Math.min(b, c));
694 }
695
696 /**
697 * Copy-paste of Character.isAlphabetic() (needed as we require only 1.6)
698 *
699 * @param codePoint
700 * The input character.
701 * @return True if the character is a Unicode alphabetic character.
702 */
703 static boolean isAlphabetic(final int codePoint) {
704 return ((1 << Character.UPPERCASE_LETTER | 1 << Character.LOWERCASE_LETTER | 1 << Character.TITLECASE_LETTER
705 | 1 << Character.MODIFIER_LETTER | 1 << Character.OTHER_LETTER | 1 << Character.LETTER_NUMBER) >> Character
706 .getType(codePoint) & 1) != 0;
707 }
708
709 /**
710 * Checks whether a string contains a digit. Used for ignoring words with
711 * numbers
712 *
713 * @param s
714 * Word to be checked.
715 * @return True if there is a digit inside the word.
716 */
717 static boolean containsNoDigit(final String s) {
718 for (int k = 0; k < s.length(); k++) {
719 if (Character.isDigit(s.charAt(k))) {
720 return false;
721 }
722 }
723 return true;
724 }
725
726 /**
727 * Returns true if <code>str</code> is made up of all-uppercase characters
728 * (ignoring characters for which no upper-/lowercase distinction exists).
729 */
730 boolean isAllUppercase(final String str) {
731 for (int i = 0; i < str.length(); i++) {
732 char c = str.charAt(i);
733 if (Character.isLetter(c) && Character.isLowerCase(c)) {
734 return false;
735 }
736 }
737 return true;
738 }
739
740 /**
741 * Returns true if <code>str</code> is made up of all-lowercase characters
742 * (ignoring characters for which no upper-/lowercase distinction exists).
743 */
744 boolean isNotAllLowercase(final String str) {
745 for (int i = 0; i < str.length(); i++) {
746 char c = str.charAt(i);
747 if (Character.isLetter(c) && !Character.isLowerCase(c)) {
748 return true;
749 }
750 }
751 return false;
752 }
753
754 /**
755 * @param str
756 * input string
757 */
758 boolean isNotCapitalizedWord(final String str) {
759 if (isNotEmpty(str) && Character.isUpperCase(str.charAt(0))) {
760 for (int i = 1; i < str.length(); i++) {
761 char c = str.charAt(i);
762 if (Character.isLetter(c) && !Character.isLowerCase(c)) {
763 return true;
764 }
765 }
766 return false;
767 }
768 return true;
769 }
770
771 /**
772 * Helper method to replace calls to "".equals().
773 *
774 * @param str
775 * String to check
776 * @return true if string is empty OR null
777 */
778 static boolean isNotEmpty(final String str) {
779 return str != null && str.length() != 0;
780 }
781
782 /**
783 * @param str
784 * input str
785 * @return Returns true if str is MixedCase.
786 */
787 boolean isMixedCase(final String str) {
788 return !isAllUppercase(str) && isNotCapitalizedWord(str) && isNotAllLowercase(str);
789 }
790
791 /**
792 * @param str The string to check.
793 * @return Returns true if str is CamelCase. Note that German compounds with a dash
794 * (like "Waschmaschinen-Test") are also considered camel case by this method.
795 */
796 public boolean isCamelCase(final String str) {
797 return isNotEmpty(str) &&
798 !isAllUppercase(str) &&
799 isNotCapitalizedWord(str) &&
800 Character.isUpperCase(str.charAt(0)) &&
801 (!(str.length() > 1) || Character.isLowerCase(str.charAt(1)))
802 && isNotAllLowercase(str);
803 }
804
805 /**
806 * Used to determine whether the dictionary supports case conversions.
807 *
808 * @return boolean value that answers this question in a deep and meaningful
809 * way.
810 *
811 * @since 1.9
812 *
813 */
814 public boolean convertsCase() {
815 return dictionaryMetadata.isConvertingCase();
816 }
817
818 /**
819 * @param str
820 * The string to find the replacements for.
821 * @param fromIndex
822 * The index from which replacements are found.
823 * @param level
824 * The recursion level. The search stops if level is &gt; MAX_RECURSION_LEVEL.
825 * @return A list of all possible replacements of a {#link str} given string
826 */
827 public List<String> getAllReplacements(final String str, final int fromIndex, final int level) {
828 List<String> replaced = new ArrayList<>();
829 if (level > MAX_RECURSION_LEVEL) { // Stop searching at some point
830 replaced.add(str);
831 return replaced;
832 }
833 StringBuilder sb = new StringBuilder();
834 sb.append(str);
835 int index = MAX_WORD_LENGTH;
836 String key = "";
837 int keyLength = 0;
838 boolean found = false;
839 // find first possible replacement after fromIndex position
840 for (final String auxKey : replacementsTheRest.keySet()) {
841 int auxIndex = sb.indexOf(auxKey, fromIndex);
842 if (auxIndex > -1 && (auxIndex < index || (auxIndex == index && !(auxKey.length() < keyLength)))) { //select the longest possible key
843 index = auxIndex;
844 key = auxKey;
845 keyLength = auxKey.length();
846 }
847 }
848 if (index < MAX_WORD_LENGTH) {
849 for (final String rep : replacementsTheRest.get(key)) {
850 // start a branch without replacement (only once per key)
851 if (!found) {
852 replaced.addAll(getAllReplacements(str, index + key.length(), level + 1));
853 found = true;
854 }
855 // avoid unnecessary replacements (ex. don't replace L by L·L when L·L already present)
856 int ind = sb.indexOf(rep, fromIndex - rep.length() + 1);
857 if (rep.length() > key.length() && ind > -1 && (ind == index || ind == index - rep.length() + 1)) {
858 continue;
859 }
860 // start a branch with replacement
861 sb.replace(index, index + key.length(), rep);
862 replaced.addAll(getAllReplacements(sb.toString(), index + rep.length(), level + 1));
863 sb.setLength(0);
864 sb.append(str);
865 }
866 }
867 if (!found) {
868 replaced.add(sb.toString());
869 }
870 return replaced;
871 }
872
873 /**
874 * Sets up the word and candidate. Used only to test the edit distance in
875 * JUnit tests.
876 *
877 * @param word
878 * the first word
879 * @param candidate
880 * the second word used for edit distance calculation
881 */
882 void setWordAndCandidate(final String word, final String candidate) {
883 wordProcessed = word.toCharArray();
884 wordLen = wordProcessed.length;
885 this.candidate = candidate.toCharArray();
886 candLen = this.candidate.length;
887 effectEditDistance = wordLen <= editDistance ? wordLen - 1 : editDistance;
888 }
889
890 public final int getWordLen() {
891 return wordLen;
892 }
893
894 public final int getCandLen() {
895 return candLen;
896 }
897
898 public final int getEffectiveED() {
899 return effectEditDistance;
900 }
901
902 /**
903 * Used to sort candidates according to edit distance, and possibly according
904 * to their frequency in the future.
905 */
906 public final class CandidateData implements Comparable<CandidateData> {
907 private final String word;
908 private final int distance;
909
910 CandidateData(final String word, final int distance) {
911 this.word = word;
912 this.distance = distance * FREQ_RANGES + FREQ_RANGES - getFrequency(word) - 1;
913 }
914
915 final String getWord() {
916 return word;
917 }
918
919 final int getDistance() {
920 return distance;
921 }
922
923 @Override
924 public int compareTo(final CandidateData cd) {
925 // Assume no overflow.
926 return Integer.compare(this.distance, cd.getDistance());
927 }
928 }
929 }