ICU-5385 Port over the compact trie dictionary and thai break iterator code from ICU4C.

X-SVN-Rev: 23146
This commit is contained in:
Michael Ow 2008-01-02 19:04:12 +00:00
parent 18c7c33675
commit b58d931e17
3 changed files with 604 additions and 0 deletions

2
.gitattributes vendored
View File

@ -323,7 +323,9 @@ icu4j/src/com/ibm/icu/impl/duration/impl/data/pfd_zh_Hans.xml -text
icu4j/src/com/ibm/icu/impl/duration/impl/data/pfd_zh_Hans_SG.xml -text
icu4j/src/com/ibm/icu/impl/duration/impl/data/pfd_zh_Hant.xml -text
icu4j/src/com/ibm/icu/impl/duration/impl/data/pfd_zh_Hant_HK.xml -text
icu4j/src/com/ibm/icu/text/BreakCTDictionary.java -text
icu4j/src/com/ibm/icu/text/DurationFormat.java -text
icu4j/src/com/ibm/icu/text/ThaiBreakIterator.java -text
icu4j/src/com/ibm/richtext/textapps/resources/unicode.arabic.red -text
icu4j/src/com/ibm/richtext/textapps/resources/unicode.hebrew.red -text
tools/unicodetools/com/ibm/rbm/docs/images/TitleLogo_transparent.gif -text

View File

@ -0,0 +1,227 @@
/*
*******************************************************************************
* Copyright (C) 1996-2008, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import com.ibm.icu.impl.ICUBinary;
import java.io.IOException;
import java.io.InputStream;
import java.io.DataInputStream;
import java.text.CharacterIterator;
public class BreakCTDictionary {
private CompactTrieHeader fData;
private class CompactTrieHeader {
int size; // Size of data in bytes
int magic; // Magic number (including versions)
int nodeCount; // Number of entries in offsets[]
int root; // Node number of the root node
int offset[]; // Offsets to nodes from start of data
CompactTrieHeader() {
size = 0;
magic = 0;
nodeCount = 0;
root = 0;
offset = null;
}
}
private static final class CompactTrieNodeFlags {
static final int kVerticalNode = 0x1000; // This is a vertical node
static final int kParentEndsWord= 0x2000; // The node whose equal link points to this ends a word
static final int kReservedFlag1 = 0x4000;
static final int kReservedFlag2 = 0x8000;
static final int kCountMask = 0x0FFF; // The count portion of flagscount
static final int kFlagMask = 0xF000; // The flags portion of flagscount
}
// The two node types are distinguished by the kVerticalNode flag.
private class CompactTrieHorizontalNode {
char ch; // UChar
int equal; // Equal link node index
CompactTrieHorizontalNode(char newCh, int newEqual) {
ch = newCh;
equal = newEqual;
}
}
private class CompactTrieVerticalNode {
int equal; // Equal link node index
char chars[]; // Code units
CompactTrieVerticalNode() {
equal = 0;
chars = null;
}
}
private CompactTrieNodes getCompactTrieNode(int node) {
return nodes[node];
}
// private class to hold both node information
private class CompactTrieNodes {
short flagscount; // Count of sub-entries, plus flags
CompactTrieHorizontalNode[] hnode;
CompactTrieVerticalNode vnode;
CompactTrieNodes() {
flagscount = 0;
hnode = null;
vnode = null;
}
}
private CompactTrieNodes[] nodes;
// Constructor
public BreakCTDictionary(InputStream is) throws IOException {
ICUBinary.readHeader(is, DATA_FORMAT_ID, null);
DataInputStream in = new DataInputStream(is);
// Get header information
fData = new CompactTrieHeader();
fData.size = in.readInt();
fData.magic = in.readInt();
fData.nodeCount = in.readShort();
fData.root = in.readShort();
loadBreakCTDictionary(in);
}
// Loads the compact trie dictionary file into the CompactTrieNodes
private void loadBreakCTDictionary(DataInputStream in) throws IOException {
// skip over offset information
for (int i = 0; i < fData.nodeCount; i++) {
in.readInt();
}
// Create compact trie dictionary
nodes = new CompactTrieNodes[fData.nodeCount];
nodes[0] = new CompactTrieNodes();
// Load in compact trie dictionary
for (int j = 1; j < fData.nodeCount; j++) {
nodes[j] = new CompactTrieNodes();
nodes[j].flagscount = in.readShort();
int count = nodes[j].flagscount & CompactTrieNodeFlags.kCountMask;
if (count != 0) {
boolean isVerticalNode = (nodes[j].flagscount & CompactTrieNodeFlags.kVerticalNode) != 0;
// Vertical node
if (isVerticalNode) {
nodes[j].vnode = new CompactTrieVerticalNode();
nodes[j].vnode.equal = in.readShort();
nodes[j].vnode.chars = new char[count];
for (int l = 0; l < count; l++) {
nodes[j].vnode.chars[l] = in.readChar();
}
} else { // Horizontal node
nodes[j].hnode = new CompactTrieHorizontalNode[count];
for (int n = 0; n < count; n++) {
nodes[j].hnode[n] = new CompactTrieHorizontalNode(in.readChar(), in.readShort());
}
}
}
}
}
/**
* Find dictionary words that match the text.
*
* @param text A CharacterIterator representing the text. The
* iterator is left after the longest prefix match in the dictionary.
* @param maxLength The maximum number of code units to match.
* @param lengths An array that is filled with the lengths of words that matched.
* @param count Filled with the number of elements output in lengths.
* @param limit The size of the lengths array; this limits the number of words output.
* @return The number of characters in text that were matched.
*/
public int matches(CharacterIterator text, int maxLength, int lengths[], int count[], int limit) {
// Current implementation works in UTF-16 space
CompactTrieNodes node = getCompactTrieNode(fData.root);
int mycount = 0;
char uc = (char)text.current();
int i = 0;
boolean exitFlag = false;
while (node != null) {
// Check if the node we just exited ends a word
if (limit > 0 && (node.flagscount & CompactTrieNodeFlags.kParentEndsWord) != 0 ) {
lengths[mycount++] = i;
--limit;
}
// Check that we haven't exceeded the maximum number of input characters.
// We have to do that here rather than in the while condition so that
// we can check for ending of a word above.
if (i >= maxLength) {
break;
}
int nodeCount = (node.flagscount &CompactTrieNodeFlags.kCountMask);
if (nodeCount == 0) {
// Special terminal node; return now
break;
}
if ((node.flagscount & CompactTrieNodeFlags.kVerticalNode) != 0) {
// Vertical node; check all the characters in it
CompactTrieVerticalNode vnode = node.vnode;
for (int j = 0; j < nodeCount && i < maxLength; j++) {
if (uc != vnode.chars[j]) {
// We hit a non equal character return;
exitFlag = true;
break;
}
text.next();
uc = (char)text.current();
i++;
}
if (exitFlag) {
break;
}
// To get here, we must have come through the whole list successfully;
// go on to the next node. Note that a word cannot end in the middle
// of a vertical node.
node = getCompactTrieNode(vnode.equal);
} else {
// Horizontal node; do binary search
CompactTrieHorizontalNode[] hnode = node.hnode;
int low = 0;
int high = nodeCount - 1;
int middle;
node = null; // If we don't find a match, we'll fall out of the loop
while (high >= low) {
middle = (high+low)/2;
if (uc == hnode[middle].ch) {
// We hit a match; get the next node and next character
node = getCompactTrieNode(hnode[middle].equal);
text.next();
uc = (char)text.current();
i++;
break;
} else if (uc < hnode[middle].ch) {
high = middle - 1;
} else {
low = middle + 1;
}
}
}
}
count[0] = mycount;
return i;
}
// Use for reading the header portion of the file
private static final byte DATA_FORMAT_ID[] = {(byte)0x54, (byte)0x72, (byte)0x44, (byte)0x63};
}

View File

@ -0,0 +1,375 @@
/*
*******************************************************************************
* Copyright (C) 1996-2008, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package com.ibm.icu.text;
import com.ibm.icu.impl.Assert;
import com.ibm.icu.text.UnicodeSet;
import java.util.Stack;
import java.io.InputStream;
import java.text.CharacterIterator;
import java.io.IOException;
public class ThaiBreakIterator extends DictionaryBasedBreakIterator {
/* Helper class for improving readability of the Thai word break
* algorithm.
*/
private class PossibleWord {
// List size, limited by the maximum number of words in the dictionary
// that form a nested sequence.
private final int POSSIBLE_WORD_LIST_MAX = 20;
//list of word candidate lengths, in increasing length order
private int lengths[];
private int count[]; // Count of candidates
private int prefix; // The longeset match with a dictionary word
private int offset; // Offset in the text of these candidates
private int mark; // The preferred candidate's offset
private int current; // The candidate we're currently looking at
// Default constructor
public PossibleWord() {
lengths = new int[POSSIBLE_WORD_LIST_MAX];
count = new int[1]; // count needs to be an array of 1 so that it can be pass as reference
offset = -1;
}
// Fill the list of candidates if needed, select the longest, and return the number found
public int candidates(CharacterIterator fIter, BreakCTDictionary dict, int rangeEnd) {
int start = fIter.getIndex();
if (start != offset) {
offset = start;
prefix = dict.matches(fIter, rangeEnd - start, lengths, count, lengths.length);
// Dictionary leaves text after longest prefix, not longest word. Back up.
if (count[0] <= 0) {
fIter.setIndex(start);
}
}
if (count[0] > 0) {
fIter.setIndex(start + lengths[count[0]-1]);
}
current = count[0] - 1;
mark = current;
return count[0];
}
// Select the currently marked candidate, point after it in the text, and invalidate self
public int acceptMarked(CharacterIterator fIter) {
fIter.setIndex(offset + lengths[mark]);
return lengths[mark];
}
// Backup from the current candidate to the next shorter one; rreturn true if that exists
// and point the text after it
public boolean backUp(CharacterIterator fIter) {
if (current > 0) {
fIter.setIndex(offset + lengths[--current]);
return true;
}
return false;
}
// Return the longest prefix this candidate location shares with a dictionary word
public int longestPrefix() {
return prefix;
}
// Mark the current candidate as the one we like
public void markCurrent() {
mark = current;
}
}
private UnicodeSet fThaiWordSet;
private UnicodeSet fEndWordSet;
private UnicodeSet fBeginWordSet;
private UnicodeSet fSuffixSet;
private UnicodeSet fMarkSet;
private BreakCTDictionary fDictionary;
// Constants for ThaiBreakIterator
// How many words in a row are "good enough"?
private final byte THAI_LOOKAHEAD = 3;
// Will not combine a non-word with a preceding dictionary word longer than this
private final byte THAI_ROOT_COMBINE_THRESHOLD = 3;
// Will not combine a non-word that shares at least this much prefix with a
// dictionary word with a preceding word
private final byte THAI_PREFIX_COMBINE_THRESHOLD = 3;
// Ellision character
private final char THAI_PAIYANNOI = 0x0E2F;
// Repeat character
private final char THAI_MAIYAMOK = 0x0E46;
// Minimum word size
private final byte THAI_MIN_WORD = 2;
// Minimum number of characters for two words
private final int THAI_MIN_WORD_SPAN = THAI_MIN_WORD * 2;
public ThaiBreakIterator(InputStream ruleStream, InputStream dictionaryStream) throws IOException {
super(ruleStream);
// Initialize UnicodeSets
fThaiWordSet = new UnicodeSet();
fMarkSet = new UnicodeSet();
fEndWordSet = new UnicodeSet();
fBeginWordSet = new UnicodeSet();
fSuffixSet = new UnicodeSet();
fThaiWordSet.applyPattern(new String("[[:Thai:]&[:LineBreak=SA:]]"));
fThaiWordSet.compact();
fMarkSet.applyPattern(new String("[[:Thai:]&[:LineBreak=SA:]&[:M:]]"));
fEndWordSet = fThaiWordSet;
fEndWordSet.remove(0x0E31); // MAI HAN-AKAT
fEndWordSet.remove(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
fBeginWordSet.add(0x0E01, 0x0E2E); //KO KAI through HO NOKHUK
fBeginWordSet.add(0x0E40, 0x0E44); // SARA E through SARA AI MAIMALAI
fSuffixSet.add(THAI_PAIYANNOI);
fSuffixSet.add(THAI_MAIYAMOK);
// Compact for caching
fMarkSet.compact();
fEndWordSet.compact();
fBeginWordSet.compact();
fSuffixSet.compact();
// Initialize diciontary
fDictionary = new BreakCTDictionary(dictionaryStream);
}
/**
* This is the implementation function for next().
* @internal
* @deprecated This API is ICU internal only.
*/
protected int handleNext() {
CharacterIterator text = getText();
// if there are no cached break positions, or if we've just moved
// off the end of the range covered by the cache, we have to dump
// and possibly regenerate the cache
if (cachedBreakPositions == null || positionInCache == cachedBreakPositions.length - 1) {
// start by using the inherited handleNext() to find a tentative return
// value. dictionaryCharCount tells us how many dictionary characters
// we passed over on our way to the tentative return value
int startPos = text.getIndex();
fDictionaryCharCount = 0;
int result = super.handleNext();
// if we passed over more than one dictionary character, then we use
// divideUpDictionaryRange() to regenerate the cached break positions
// for the new range
if (fDictionaryCharCount > 1 && result - startPos > 1) {
divideUpDictionaryRange(startPos, result);
}
// otherwise, the value we got back from the inherited fuction
// is our return value, and we can dump the cache
else {
cachedBreakPositions = null;
return result;
}
}
// if the cache of break positions has been regenerated (or existed all
// along), then just advance to the next break position in the cache
// and return it
if (cachedBreakPositions != null) {
++positionInCache;
text.setIndex(cachedBreakPositions[positionInCache]);
return cachedBreakPositions[positionInCache];
}
Assert.assrt(false);
return -9999; // SHOULD NEVER GET HERE!
}
/**
* Divide up a range of known dictionary characters.
*
* @param rangeStart The start of the range of dictionary characters
* @param rangeEnd The end of the range of dictionary characters
* @return The number of breaks found
*/
public int divideUpDictionaryRange(int rangeStart, int rangeEnd) {
if ((rangeEnd - rangeStart) < THAI_MIN_WORD_SPAN) {
return 0; // Not enough chacters for two words
}
CharacterIterator fIter = getText();
int wordsFound = 0;
int wordLength;
int current;
Stack foundBreaks = new Stack();
PossibleWord words[] = new PossibleWord[THAI_LOOKAHEAD];
for (int i = 0; i < THAI_LOOKAHEAD; i++) {
words[i] = new PossibleWord();
}
int uc;
fIter.setIndex(rangeStart);
while ((current = fIter.getIndex()) < rangeEnd) {
wordLength = 0;
//Look for candidate words at the current position
int candidates = words[wordsFound%THAI_LOOKAHEAD].candidates(fIter, fDictionary, rangeEnd);
// If we found exactly one, use that
if (candidates == 1) {
wordLength = words[wordsFound%THAI_LOOKAHEAD].acceptMarked(fIter);
wordsFound += 1;
}
// If there was more than one, see which one can take use forward the most words
else if (candidates > 1) {
boolean foundBest = false;
// If we're already at the end of the range, we're done
if (fIter.getIndex() < rangeEnd) {
do {
int wordsMatched = 1;
if (words[(wordsFound+1)%THAI_LOOKAHEAD].candidates(fIter, fDictionary, rangeEnd) > 0) {
if (wordsMatched < 2) {
// Followed by another dictionary word; mark first word as a good candidate
words[wordsFound%THAI_LOOKAHEAD].markCurrent();
wordsMatched = 2;
}
// If we're already at the end of the range, we're done
if (fIter.getIndex() >= rangeEnd) {
break;
}
// See if any of the possible second words is followed by a third word
do {
// If we find a third word, stop right away
if (words[(wordsFound+2)%THAI_LOOKAHEAD].candidates(fIter, fDictionary, rangeEnd) > 0) {
words[wordsFound%THAI_LOOKAHEAD].markCurrent();
foundBest = true;
break;
}
} while (words[(wordsFound+1)%THAI_LOOKAHEAD].backUp(fIter));
}
} while (words[(wordsFound+1)%THAI_LOOKAHEAD].backUp(fIter) && !foundBest);
}
/* foundBest: */wordLength = words[wordsFound%THAI_LOOKAHEAD].acceptMarked(fIter);
wordsFound += 1;
}
// We come here after having either found a word or not. We look ahead to the
// next word. If it's not a dictionary word, we will combine it with the word we
// just found (if there is one), but only if the preceding word does not exceed
// the threshold.
// The text iterator should now be positioned at the end of the word we found.
if (fIter.getIndex() < rangeEnd && wordLength < THAI_ROOT_COMBINE_THRESHOLD) {
// If it is a dictionary word, do nothing. If it isn't, then if there is
// no preceding word, or the non-word shares less than the minimum threshold
// of characters with a dictionary word, then scan to resynchronize
if (words[wordsFound%THAI_LOOKAHEAD].candidates(fIter, fDictionary, rangeEnd) <= 0 &&
(wordLength == 0 ||
words[wordsFound%THAI_LOOKAHEAD].longestPrefix() < THAI_PREFIX_COMBINE_THRESHOLD)) {
// Look for a plausible word boundary
int remaining = rangeEnd - (current + wordLength);
int pc = fIter.current();
int chars = 0;
for (;;) {
fIter.next();
uc = fIter.current();
chars += 1;
if (--remaining <= 0) {
break;
}
if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
// Maybe. See if it's in the dictionary.
// Note: In the original Apple code, checked that the next
// two characters after uc were not 0x0E4C THANTHAKHAT before
// checking the dictionary. That is just a performance filter,
// but it's not clear it's faster than checking the trie
int candidate = words[(wordsFound+1)%THAI_LOOKAHEAD].candidates(fIter, fDictionary, rangeEnd);
fIter.setIndex(current+wordLength+chars);
if (candidate > 0) {
break;
}
}
pc = uc;
}
// Bump the word cound if there wasn't already one
if (wordLength <= 0) {
wordsFound += 1;
}
// Update the length with the passed-over characters
wordLength += chars;
} else {
// Backup to where we were for next iteration
fIter.setIndex(current+wordLength);
}
}
// Never stop before a combining mark.
int currPos;
while ((currPos = fIter.getIndex()) < rangeEnd && fMarkSet.contains(fIter.current())) {
fIter.next();
wordLength += fIter.getIndex() - currPos;
}
// Look ahead for possible suffixes if a dictionary word does not follow.
// We do this in code rather than using a rule so that the heuristic
// resynch continues to function. For example, one of the suffix characters
// could be a typo in the middle of a word.
if (fIter.getIndex() < rangeEnd && wordLength > 0) {
if (words[wordsFound%THAI_LOOKAHEAD].candidates(fIter, fDictionary, rangeEnd) <= 0 &&
fSuffixSet.contains(uc = fIter.current())) {
if (uc == THAI_PAIYANNOI) {
if (!fSuffixSet.contains(fIter.previous())) {
// Skip over previous end and PAIYANNOI
fIter.next();
fIter.next();
wordLength += 1;
uc = fIter.current();
} else {
// Restore prior position
fIter.next();
}
}
if (uc == THAI_MAIYAMOK) {
if (fIter.previous() != THAI_MAIYAMOK) {
// Skip over previous end and MAIYAMOK
fIter.next();
fIter.next();
wordLength += 1;
} else {
// restore prior position
fIter.next();
}
}
} else {
fIter.setIndex(current+wordLength);
}
}
// Did we find a word on this iteration? If so, push it on the break stack
if (wordLength > 0) {
foundBreaks.push(new Integer(current+wordLength));
}
}
// Don't return a break for the end of the dictionary range if there is one there
if (((Integer)foundBreaks.peek()).intValue() >= rangeEnd) {
foundBreaks.pop();
wordsFound -= 1;
}
// Store the break points in cachedBreakPositions.
cachedBreakPositions = new int[foundBreaks.size() + 2];
cachedBreakPositions[0] = rangeStart;
int i;
for (i = 0; i < foundBreaks.size(); i++) {
cachedBreakPositions[i + 1] = ((Integer)foundBreaks.elementAt(i)).intValue();
}
cachedBreakPositions[i + 1] = rangeEnd;
positionInCache = 0;
return wordsFound;
}
}