Apache Lucene open-source search software
Add n-best output to JapaneseTokenizer (LUCENE-6837)
Christian Moendf9c6a835f65
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txtindex 23c128bd719..34eb1063d22 100644--- a/lucene/CHANGES.txt+++ b/lucene/CHANGES.txt@@ -52,6 +52,9 @@ New Features* LUCENE-6881: Cutover all BKD implementations to dimensional values(Mike McCandless)+* LUCENE-6837: Add N-best output support to JapaneseTokenizer.+ (Hiroharu Konno via Christian Moen)+API Changes* LUCENE-3312: The API of oal.document was restructured todiff --git a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizer.java b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizer.javaindex 614c7390972..a1f9545049f 100644--- a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizer.java+++ b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizer.java@@ -18,10 +18,13 @@ package org.apache.lucene.analysis.ja;*/import java.io.IOException;+import java.io.StringReader;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;+import java.util.Comparator;import java.util.EnumMap;+import java.util.HashMap;import java.util.List;import org.apache.lucene.analysis.Tokenizer;@@ -60,13 +63,13 @@ import org.apache.lucene.util.fst.FST;* information for inflected forms.* </ul>* <p>- * This tokenizer uses a rolling Viterbi search to find the- * least cost segmentation (path) of the incoming characters.+ * This tokenizer uses a rolling Viterbi search to find the+ * least cost segmentation (path) of the incoming characters.* For tokens that appear to be compound (> length 2 for all* Kanji, or > length 7 for non-Kanji), we see if there is a* 2nd best segmentation of that token after applying* penalties to the long tokens. If so, and the Mode is- * {@link Mode#SEARCH}, we output the alternate segmentation+ * {@link Mode#SEARCH}, we output the alternate segmentation* as well.*/public final class JapaneseTokenizer extends Tokenizer {@@ -79,14 +82,14 @@ public final class JapaneseTokenizer extends Tokenizer {/*** Ordinary segmentation: no decomposition for compounds,*/- NORMAL,+ NORMAL,/**- * Segmentation geared towards search: this includes a+ * Segmentation geared towards search: this includes a* decompounding process for long nouns, also including* the full compound token as a synonym.*/- SEARCH,+ SEARCH,/*** Extended mode outputs unigrams for unknown words.@@ -156,6 +159,10 @@ public final class JapaneseTokenizer extends Tokenizer {private final boolean searchMode;private final boolean extendedMode;private final boolean outputCompounds;+ private boolean outputNBest = false;++ // Allowable cost difference for N-best output:+ private int nBestCost = 0;// Index of the last character of unknown word:private int unknownWordEndIndex = -1;@@ -189,7 +196,7 @@ public final class JapaneseTokenizer extends Tokenizer {* Create a new JapaneseTokenizer.* <p>* Uses the default AttributeFactory.- *+ ** @param userDictionary Optional: if non-null, user dictionary.* @param discardPunctuation true if punctuation tokens should be dropped from the output.* @param mode tokenization mode.@@ -490,6 +497,11 @@ public final class JapaneseTokenizer extends Tokenizer {if (token.getPosition() == lastTokenPos) {posIncAtt.setPositionIncrement(0);posLengthAtt.setPositionLength(token.getPositionLength());+ } else if (outputNBest) {+ // The position length is always calculated if outputNBest is true.+ assert token.getPosition() > lastTokenPos;+ posIncAtt.setPositionIncrement(1);+ posLengthAtt.setPositionLength(token.getPositionLength());} else {assert token.getPosition() > lastTokenPos;posIncAtt.setPositionIncrement(1);@@ -519,7 +531,7 @@ public final class JapaneseTokenizer extends Tokenizer {// Next position to write:private int nextPos;-+// How many valid Position instances are held in the// positions array:private int count;@@ -644,7 +656,13 @@ public final class JapaneseTokenizer extends Tokenizer {// alive, so whatever the eventual best path is must// come through this node. So we can safely commit// to the prefix of the best path at this point:+ if (outputNBest) {+ backtraceNBest(posData, false);+ }backtrace(posData, 0);+ if (outputNBest) {+ fixupPendingList();+ }// Re-base cost so we don't risk int overflow:posData.costs[0] = 0;@@ -689,6 +707,10 @@ public final class JapaneseTokenizer extends Tokenizer {// We will always have at least one live path:assert leastIDX != -1;+ if (outputNBest) {+ backtraceNBest(leastPosData, false);+ }+// Second pass: prune all but the best path:for(int pos2=pos;pos2<positions.getNextPos();pos2++) {final Position posData2 = positions.get(pos2);@@ -708,6 +730,9 @@ public final class JapaneseTokenizer extends Tokenizer {}backtrace(leastPosData, 0);+ if (outputNBest) {+ fixupPendingList();+ }// Re-base cost so we don't risk int overflow:Arrays.fill(leastPosData.costs, 0, leastPosData.count, 0);@@ -775,7 +800,7 @@ public final class JapaneseTokenizer extends Tokenizer {break;}//System.out.println(" match " + (char) ch + " posAhead=" + posAhead);-+if (fst.findTargetArc(ch, arc, arc, posAhead == posData.pos, fstReader) == null) {break;}@@ -870,7 +895,13 @@ public final class JapaneseTokenizer extends Tokenizer {}}+ if (outputNBest) {+ backtraceNBest(endPosData, true);+ }backtrace(endPosData, leastIDX);+ if (outputNBest) {+ fixupPendingList();+ }} else {// No characters in the input string; return no tokens!}@@ -947,7 +978,7 @@ public final class JapaneseTokenizer extends Tokenizer {final Dictionary dict2 = getDict(forwardType);final int wordID = posData.forwardID[forwardArcIDX];final int toPos = posData.forwardPos[forwardArcIDX];- final int newCost = pathCost + dict2.getWordCost(wordID) ++ final int newCost = pathCost + dict2.getWordCost(wordID) +costs.get(rightID, dict2.getLeftId(wordID)) +computePenalty(pos, toPos-pos);if (VERBOSE) {@@ -981,6 +1012,557 @@ public final class JapaneseTokenizer extends Tokenizer {}}+ // yet another lattice data structure+ private final static class Lattice {+ char[] fragment;+ EnumMap<Type, Dictionary> dictionaryMap;+ boolean useEOS;++ int rootCapacity = 0;+ int rootSize = 0;+ int rootBase = 0;++ // root pointers of node chain by leftChain_ that have same start offset.+ int[] lRoot;+ // root pointers of node chain by rightChain_ that have same end offset.+ int[] rRoot;++ int capacity = 0;+ int nodeCount = 0;++ // The variables below are elements of lattice node that indexed by node number.+ Type[] nodeDicType;+ int[] nodeWordID;+ // nodeMark - -1:excluded, 0:unused, 1:bestpath, 2:2-best-path, ... N:N-best-path+ int[] nodeMark;+ int[] nodeLeftID;+ int[] nodeRightID;+ int[] nodeWordCost;+ int[] nodeLeftCost;+ int[] nodeRightCost;+ // nodeLeftNode, nodeRightNode - are left/right node number with minimum cost path.+ int[] nodeLeftNode;+ int[] nodeRightNode;+ // nodeLeft, nodeRight - start/end offset+ int[] nodeLeft;+ int[] nodeRight;+ int[] nodeLeftChain;+ int[] nodeRightChain;++ private void setupRoot(int baseOffset, int lastOffset) {+ assert baseOffset <= lastOffset;+ int size = lastOffset - baseOffset + 1;+ if (rootCapacity < size) {+ int oversize = ArrayUtil.oversize(size, RamUsageEstimator.NUM_BYTES_INT);+ lRoot = new int[oversize];+ rRoot = new int[oversize];+ rootCapacity = oversize;+ }+ Arrays.fill(lRoot, 0, size, -1);+ Arrays.fill(rRoot, 0, size, -1);+ rootSize = size;+ rootBase = baseOffset;+ }++ // Reserve at least N nodes.+ private void reserve(int n) {+ if (capacity < n) {+ int oversize = ArrayUtil.oversize(n, RamUsageEstimator.NUM_BYTES_INT);+ nodeDicType = new Type[oversize];+ nodeWordID = new int[oversize];+ nodeMark = new int[oversize];+ nodeLeftID = new int[oversize];+ nodeRightID = new int[oversize];+ nodeWordCost = new int[oversize];+ nodeLeftCost = new int[oversize];+ nodeRightCost = new int[oversize];+ nodeLeftNode = new int[oversize];+ nodeRightNode = new int[oversize];+ nodeLeft = new int[oversize];+ nodeRight = new int[oversize];+ nodeLeftChain = new int[oversize];+ nodeRightChain = new int[oversize];+ capacity = oversize;+ }+ }++ private void setupNodePool(int n) {+ reserve(n);+ nodeCount = 0;+ if (VERBOSE) {+ System.out.printf("DEBUG: setupNodePool: n = %d\n", n);+ System.out.printf("DEBUG: setupNodePool: lattice.capacity = %d\n", capacity);+ }+ }++ private int addNode(Type dicType, int wordID, int left, int right) {+ if (VERBOSE) {+ System.out.printf("DEBUG: addNode: dicType=%s, wordID=%d, left=%d, right=%d, str=%s\n",+ dicType.toString(), wordID, left, right,+ left == -1 ? "BOS" : right == -1 ? "EOS" : new String(fragment, left, right - left));+ }+ assert nodeCount < capacity;+ assert left == -1 || right == -1 || left < right;+ assert left == -1 || (0 <= left && left < rootSize);+ assert right == -1 || (0 <= right && right < rootSize);++ int node = nodeCount++;++ if (VERBOSE) {+ System.out.printf("DEBUG: addNode: node=%d\n", node);+ }++ nodeDicType[node] = dicType;+ nodeWordID[node] = wordID;+ nodeMark[node] = 0;++ if (wordID < 0) {+ nodeWordCost[node] = 0;+ nodeLeftCost[node] = 0;+ nodeRightCost[node] = 0;+ nodeLeftID[node] = 0;+ nodeRightID[node] = 0;+ } else {+ Dictionary dic = dictionaryMap.get(dicType);+ nodeWordCost[node] = dic.getWordCost(wordID);+ nodeLeftID[node] = dic.getLeftId(wordID);+ nodeRightID[node] = dic.getRightId(wordID);+ }++ if (VERBOSE) {+ System.out.printf("DEBUG: addNode: wordCost=%d, leftID=%d, rightID=%d\n",+ nodeWordCost[node], nodeLeftID[node], nodeRightID[node]);+ }++ nodeLeft[node] = left;+ nodeRight[node] = right;+ if (0 <= left) {+ nodeLeftChain[node] = lRoot[left];+ lRoot[left] = node;+ } else {+ nodeLeftChain[node] = -1;+ }+ if (0 <= right) {+ nodeRightChain[node] = rRoot[right];+ rRoot[right] = node;+ } else {+ nodeRightChain[node] = -1;+ }+ return node;+ }++ // Sum of positions.get(i).count in [beg, end) range.+ // using stream:+ // return IntStream.range(beg, end).map(i -> positions.get(i).count).sum();+ private int positionCount(WrappedPositionArray positions, int beg, int end) {+ int count = 0;+ for (int i = beg; i < end; ++i) {+ count += positions.get(i).count;+ }+ return count;+ }+++ void setup(char[] fragment,+ EnumMap<Type, Dictionary> dictionaryMap,+ WrappedPositionArray positions, int prevOffset, int endOffset, boolean useEOS) {+ assert positions.get(prevOffset).count == 1;+ if (VERBOSE) {+ System.out.printf("DEBUG: setup: prevOffset=%d, endOffset=%d\n", prevOffset, endOffset);+ }++ this.fragment = fragment;+ this.dictionaryMap = dictionaryMap;+ this.useEOS = useEOS;++ // Initialize lRoot and rRoot.+ setupRoot(prevOffset, endOffset);++ // "+ 2" for first/last record.+ setupNodePool(positionCount(positions, prevOffset + 1, endOffset + 1) + 2);++ // substitute for BOS = 0+ Position first = positions.get(prevOffset);+ if (addNode(first.backType[0], first.backID[0], -1, 0) != 0) {+ assert false;+ }++ // EOS = 1+ if (addNode(Type.KNOWN, -1, endOffset - rootBase, -1) != 1) {+ assert false;+ }++ for (int offset = endOffset; prevOffset < offset; --offset) {+ int right = offset - rootBase;+ // optimize: exclude disconnected nodes.+ if (0 <= lRoot[right]) {+ Position pos = positions.get(offset);+ for (int i = 0; i < pos.count; ++i) {+ addNode(pos.backType[i], pos.backID[i], pos.backPos[i] - rootBase, right);+ }+ }+ }+ }++ // set mark = -1 for unreachable nodes.+ void markUnreachable() {+ for (int index = 1; index < rootSize - 1; ++index) {+ if (rRoot[index] < 0) {+ for (int node = lRoot[index]; 0 <= node; node = nodeLeftChain[node]) {+ if (VERBOSE) {+ System.out.printf("DEBUG: markUnreachable: node=%d\n", node);+ }+ nodeMark[node] = -1;+ }+ }+ }+ }++ int connectionCost(ConnectionCosts costs, int left, int right) {+ int leftID = nodeLeftID[right];+ return ((leftID == 0 && !useEOS) ? 0 : costs.get(nodeRightID[left], leftID));+ }++ void calcLeftCost(ConnectionCosts costs) {+ for (int index = 0; index < rootSize; ++index) {+ for (int node = lRoot[index]; 0 <= node; node = nodeLeftChain[node]) {+ if (0 <= nodeMark[node]) {+ int leastNode = -1;+ int leastCost = Integer.MAX_VALUE;+ for (int leftNode = rRoot[index]; 0 <= leftNode; leftNode = nodeRightChain[leftNode]) {+ if (0 <= nodeMark[leftNode]) {+ int cost = nodeLeftCost[leftNode] + nodeWordCost[leftNode] + connectionCost(costs, leftNode, node);+ if (cost < leastCost) {+ leastCost = cost;+ leastNode = leftNode;+ }+ }+ }+ assert 0 <= leastNode;+ nodeLeftNode[node] = leastNode;+ nodeLeftCost[node] = leastCost;+ if (VERBOSE) {+ System.out.printf("DEBUG: calcLeftCost: node=%d, leftNode=%d, leftCost=%d\n",+ node, nodeLeftNode[node], nodeLeftCost[node]);+ }+ }+ }+ }+ }++ void calcRightCost(ConnectionCosts costs) {+ for (int index = rootSize - 1; 0 <= index; --index) {+ for (int node = rRoot[index]; 0 <= node; node = nodeRightChain[node]) {+ if (0 <= nodeMark[node]) {+ int leastNode = -1;+ int leastCost = Integer.MAX_VALUE;+ for (int rightNode = lRoot[index]; 0 <= rightNode; rightNode = nodeLeftChain[rightNode]) {+ if (0 <= nodeMark[rightNode]) {+ int cost = nodeRightCost[rightNode] + nodeWordCost[rightNode] + connectionCost(costs, node, rightNode);+ if (cost < leastCost) {+ leastCost = cost;+ leastNode = rightNode;+ }+ }+ }+ assert 0 <= leastNode;+ nodeRightNode[node] = leastNode;+ nodeRightCost[node] = leastCost;+ if (VERBOSE) {+ System.out.printf("DEBUG: calcRightCost: node=%d, rightNode=%d, rightCost=%d\n",+ node, nodeRightNode[node], nodeRightCost[node]);+ }+ }+ }+ }+ }++ // Mark all nodes that have same text and different par-of-speech or reading.+ void markSameSpanNode(int refNode, int value) {+ int left = nodeLeft[refNode];+ int right = nodeRight[refNode];+ for (int node = lRoot[left]; 0 <= node; node = nodeLeftChain[node]) {+ if (nodeRight[node] == right) {+ nodeMark[node] = value;+ }+ }+ }++ List<Integer> bestPathNodeList() {+ List<Integer> list = new ArrayList<>();+ for (int node = nodeRightNode[0]; node != 1; node = nodeRightNode[node]) {+ list.add(node);+ markSameSpanNode(node, 1);+ }+ return list;+ }++ private int cost(int node) {+ return nodeLeftCost[node] + nodeWordCost[node] + nodeRightCost[node];+ }++ List<Integer> nBestNodeList(int N) {+ List<Integer> list = new ArrayList<>();+ int leastCost = Integer.MAX_VALUE;+ int leastLeft = -1;+ int leastRight = -1;+ for (int node = 2; node < nodeCount; ++node) {+ if (nodeMark[node] == 0) {+ int cost = cost(node);+ if (cost < leastCost) {+ leastCost = cost;+ leastLeft = nodeLeft[node];+ leastRight = nodeRight[node];+ list.clear();+ list.add(node);+ } else if (cost == leastCost && (nodeLeft[node] != leastLeft || nodeRight[node] != leastRight)) {+ list.add(node);+ }+ }+ }+ for (int node : list) {+ markSameSpanNode(node, N);+ }+ return list;+ }++ int bestCost() {+ return nodeLeftCost[1];+ }++ int probeDelta(int start, int end) {+ int left = start - rootBase;+ int right = end - rootBase;+ if (left < 0 || rootSize < right) {+ return Integer.MAX_VALUE;+ }+ int probedCost = Integer.MAX_VALUE;+ for (int node = lRoot[left]; 0 <= node; node = nodeLeftChain[node]) {+ if (nodeRight[node] == right) {+ probedCost = Math.min(probedCost, cost(node));+ }+ }+ return probedCost - bestCost();+ }++ void debugPrint() {+ if (VERBOSE) {+ for (int node = 0; node < nodeCount; ++node) {+ System.out.printf("DEBUG NODE: node=%d, mark=%d, cost=%d, left=%d, right=%d\n",+ node, nodeMark[node], cost(node), nodeLeft[node], nodeRight[node]);+ }+ }+ }+ }++ private Lattice lattice = null;++ private void registerNode(int node, char[] fragment) {+ int left = lattice.nodeLeft[node];+ int right = lattice.nodeRight[node];+ Type type = lattice.nodeDicType[node];+ if (!discardPunctuation || !isPunctuation(fragment[left])) {+ if (type == Type.USER) {+ // The code below are based on backtrace().+ //+ // Expand the phraseID we recorded into the actual segmentation:+ final int[] wordIDAndLength = userDictionary.lookupSegmentation(lattice.nodeWordID[node]);+ int wordID = wordIDAndLength[0];+ pending.add(new Token(wordID,+ fragment,+ left,+ right - left,+ Type.USER,+ lattice.rootBase + left,+ userDictionary));+ // Output compound+ int current = 0;+ for (int j = 1; j < wordIDAndLength.length; j++) {+ final int len = wordIDAndLength[j];+ if (len < right - left) {+ pending.add(new Token(wordID + j - 1,+ fragment,+ current + left,+ len,+ Type.USER,+ lattice.rootBase + current + left,+ userDictionary));+ }+ current += len;+ }+ } else {+ pending.add(new Token(lattice.nodeWordID[node],+ fragment,+ left,+ right - left,+ type,+ lattice.rootBase + left,+ getDict(type)));+ }+ }+ }++ // Sort pending tokens, and set position increment values.+ private void fixupPendingList() {+ // Sort for removing same tokens.+ // USER token should be ahead from normal one.+ Collections.sort(pending,+ new Comparator<Token>() {+ @Override+ public int compare(Token a, Token b) {+ int aOff = a.getOffset();+ int bOff = b.getOffset();+ if (aOff != bOff) {+ return aOff - bOff;+ }+ int aLen = a.getLength();+ int bLen = b.getLength();+ if (aLen != bLen) {+ return aLen - bLen;+ }+ // order of Type is KNOWN, UNKNOWN, USER,+ // so we use reversed comparison here.+ return b.getType().ordinal() - a.getType().ordinal();+ }+ });++ // Remove same token.+ for (int i = 1; i < pending.size(); ++i) {+ Token a = pending.get(i - 1);+ Token b = pending.get(i);+ if (a.getOffset() == b.getOffset() && a.getLength() == b.getLength()) {+ pending.remove(i);+ // It is important to decrement "i" here, because a next may be removed.+ --i;+ }+ }++ // offset=>position map+ HashMap<Integer, Integer> map = new HashMap<>();+ for (Token t : pending) {+ map.put(t.getOffset(), 0);+ map.put(t.getOffset() + t.getLength(), 0);+ }++ // Get uniqe and sorted list of all edge position of tokens.+ Integer[] offsets = map.keySet().toArray(new Integer[0]);+ Arrays.sort(offsets);++ // setup all value of map. It specify N-th position from begin.+ for (int i = 0; i < offsets.length; ++i) {+ map.put(offsets[i], i);+ }++ // We got all position length now.+ for (Token t : pending) {+ t.setPositionLength(map.get(t.getOffset() + t.getLength()) - map.get(t.getOffset()));+ }++ // Make PENDING to be reversed order to fit its usage.+ // If you would like to speedup, you can try reversed order sort+ // at first of this function.+ Collections.reverse(pending);+ }++ private int probeDelta(String inText, String requiredToken) throws IOException {+ int start = inText.indexOf(requiredToken);+ if (start < 0) {+ // -1 when no requiredToken.+ return -1;+ }++ int delta = Integer.MAX_VALUE;+ int saveNBestCost = nBestCost;+ setReader(new StringReader(inText));+ reset();+ try {+ setNBestCost(1);+ int prevRootBase = -1;+ while (incrementToken()) {+ if (lattice.rootBase != prevRootBase) {+ prevRootBase = lattice.rootBase;+ delta = Math.min(delta, lattice.probeDelta(start, start + requiredToken.length()));+ }+ }+ } finally {+ // reset & end+ end();+ // setReader & close+ close();+ setNBestCost(saveNBestCost);+ }++ if (VERBOSE) {+ System.out.printf("JapaneseTokenizer: delta = %d: %s-%s\n", delta, inText, requiredToken);+ }+ return delta == Integer.MAX_VALUE ? -1 : delta;+ }++ public int calcNBestCost(String examples) {+ int maxDelta = 0;+ for (String example : examples.split("/")) {+ if (!example.isEmpty()) {+ String[] pair = example.split("-");+ if (pair.length != 2) {+ throw new RuntimeException("Unexpected example form: " + example + " (expected two '-')");+ } else {+ try {+ maxDelta = Math.max(maxDelta, probeDelta(pair[0], pair[1]));+ } catch (IOException e) {+ throw new RuntimeException("Internal error calculating best costs from examples. Got ", e);+ }+ }+ }+ }+ return maxDelta;+ }++ public void setNBestCost(int value) {+ nBestCost = value;+ outputNBest = 0 < nBestCost;+ }++ private void backtraceNBest(final Position endPosData, final boolean useEOS) throws IOException {+ if (lattice == null) {+ lattice = new Lattice();+ }++ final int endPos = endPosData.pos;+ char[] fragment = buffer.get(lastBackTracePos, endPos - lastBackTracePos);+ lattice.setup(fragment, dictionaryMap, positions, lastBackTracePos, endPos, useEOS);+ lattice.markUnreachable();+ lattice.calcLeftCost(costs);+ lattice.calcRightCost(costs);++ int bestCost = lattice.bestCost();+ if (VERBOSE) {+ System.out.printf("DEBUG: 1-BEST COST: %d\n", bestCost);+ }+ for (int node : lattice.bestPathNodeList()) {+ registerNode(node, fragment);+ }++ for (int n = 2;; ++n) {+ List<Integer> nbest = lattice.nBestNodeList(n);+ if (nbest.isEmpty()) {+ break;+ }+ int cost = lattice.cost(nbest.get(0));+ if (VERBOSE) {+ System.out.printf("DEBUG: %d-BEST COST: %d\n", n, cost);+ }+ if (bestCost + nBestCost < cost) {+ break;+ }+ for (int node : nbest) {+ registerNode(node, fragment);+ }+ }+ if (VERBOSE) {+ lattice.debugPrint();+ }+ }+// Backtrace from the provided position, back to the last// time we back-traced, accumulating the resulting tokens to// the pending list. The pending list is then in-reverse@@ -1029,7 +1611,7 @@ public final class JapaneseTokenizer extends Tokenizer {int nextBestIDX = posData.backIndex[bestIDX];if (outputCompounds && searchMode && altToken == null && backType != Type.USER) {-+// In searchMode, if best path had picked a too-long// token, we use the "penalty" to compute the allowed// max cost of an alternate back-trace. If we find an@@ -1039,7 +1621,7 @@ public final class JapaneseTokenizer extends Tokenizer {//System.out.println(" 2nd best backPos=" + backPos + " pos=" + pos);final int penalty = computeSecondBestThreshold(backPos, pos-backPos);-+if (penalty > 0) {if (VERBOSE) {System.out.println(" compound=" + new String(buffer.get(backPos, pos-backPos)) + " backPos=" + backPos + " pos=" + pos + " penalty=" + penalty + " cost=" + posData.costs[bestIDX] + " bestIDX=" + bestIDX + " lastLeftID=" + lastLeftWordID);@@ -1063,7 +1645,7 @@ public final class JapaneseTokenizer extends Tokenizer {for(int idx=0;idx<posData.count;idx++) {int cost = posData.costs[idx];//System.out.println(" idx=" + idx + " prevCost=" + cost);-+if (lastLeftWordID != -1) {cost += costs.get(getDict(posData.backType[idx]).getRightId(posData.backID[idx]),lastLeftWordID);@@ -1108,7 +1690,7 @@ public final class JapaneseTokenizer extends Tokenizer {backID = posData.backID[bestIDX];backCount = 0;//System.out.println(" do alt token!");-+} else {// I think in theory it's possible there is no// 2nd best path, which is fine; in this case we@@ -1212,7 +1794,7 @@ public final class JapaneseTokenizer extends Tokenizer {}}backCount += unigramTokenCount;-+} else if (!discardPunctuation || length == 0 || !isPunctuation(fragment[offset])) {pending.add(new Token(backID,fragment,diff --git a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizerFactory.java b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizerFactory.javaindex 13a2de5fcbd..6afd54cce04 100644--- a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizerFactory.java+++ b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/JapaneseTokenizerFactory.java@@ -50,23 +50,66 @@ import org.apache.lucene.analysis.util.ResourceLoaderAware;* </analyzer>* </fieldType>* </pre>+ * <p>+ * Additional expert user parameters nBestCost and nBestExamples can be+ * used to include additional searchable tokens that those most likely+ * according to the statistical model. A typical use-case for this is to+ * improve recall and make segmentation more resilient to mistakes.+ * The feature can also be used to get a decompounding effect.+ * <p>+ * The nBestCost parameter specifies an additional Viterbi cost, and+ * when used, JapaneseTokenizer will include all tokens in Viterbi paths+ * that are within the nBestCost value of the best path.+ * <p>+ * Finding a good value for nBestCost can be difficult to do by hand. The+ * nBestExamples parameter can be used to find an nBestCost value based on+ * examples with desired segmentation outcomes.+ * <p>+ * For example, a value of /箱根山-箱根/成田空港-成田/ indicates that in+ * the texts, 箱根山 (Mt. Hakone) and 成田空港 (Narita Airport) we'd like+ * a cost that gives is us 箱根 (Hakone) and 成田 (Narita). Notice that+ * costs are estimated for each example individually, and the maximum+ * nBestCost found across all examples is used.+ * <p>+ * If both nBestCost and nBestExamples is used in a configuration,+ * the largest value of the two is used.+ * <p>+ * Parameters nBestCost and nBestExamples work with all tokenizer+ * modes, but it makes the most sense to use them with NORMAL mode.*/public class JapaneseTokenizerFactory extends TokenizerFactory implements ResourceLoaderAware {private static final String MODE = "mode";-+private static final String USER_DICT_PATH = "userDictionary";-+private static final String USER_DICT_ENCODING = "userDictionaryEncoding";private static final String DISCARD_PUNCTUATION = "discardPunctuation"; // Expert option+ private static final String NBEST_COST = "nBestCost";++ private static final String NBEST_EXAMPLES = "nBestExamples";+private UserDictionary userDictionary;private final Mode mode;- private final boolean discardPunctuation;+ private final boolean discardPunctuation;private final String userDictionaryPath;private final String userDictionaryEncoding;+ /* Example string for NBEST output.+ * its form as:+ * nbestExamples := [ / ] example [ / example ]... [ / ]+ * example := TEXT - TOKEN+ * TEXT := input text+ * TOKEN := token should be in nbest result+ * Ex. /箱根山-箱根/成田空港-成田/+ * When the result tokens are "箱根山", "成田空港" in NORMAL mode,+ * /箱根山-箱根/成田空港-成田/ requests "箱根" and "成田" to be in the result in NBEST output.+ */+ private final String nbestExamples;+ private int nbestCost = -1;+/** Creates a new JapaneseTokenizerFactory */public JapaneseTokenizerFactory(Map<String,String> args) {super(args);@@ -74,11 +117,13 @@ public class JapaneseTokenizerFactory extends TokenizerFactory implements ResouruserDictionaryPath = args.remove(USER_DICT_PATH);userDictionaryEncoding = args.remove(USER_DICT_ENCODING);discardPunctuation = getBoolean(args, DISCARD_PUNCTUATION, true);+ nbestCost = getInt(args, NBEST_COST, 0);+ nbestExamples = args.remove(NBEST_EXAMPLES);if (!args.isEmpty()) {throw new IllegalArgumentException("Unknown parameters: " + args);}}-+@Overridepublic void inform(ResourceLoader loader) throws IOException {if (userDictionaryPath != null) {@@ -96,9 +141,14 @@ public class JapaneseTokenizerFactory extends TokenizerFactory implements ResouruserDictionary = null;}}-+@Overridepublic JapaneseTokenizer create(AttributeFactory factory) {- return new JapaneseTokenizer(factory, userDictionary, discardPunctuation, mode);+ JapaneseTokenizer t = new JapaneseTokenizer(factory, userDictionary, discardPunctuation, mode);+ if (nbestExamples != null) {+ nbestCost = Math.max(nbestCost, t.calcNBestCost(nbestExamples));+ }+ t.setNBestCost(nbestCost);+ return t;}}diff --git a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/Token.java b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/Token.javaindex ad3bcc06263..81a10c85b13 100644--- a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/Token.java+++ b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/Token.java@@ -25,18 +25,18 @@ import org.apache.lucene.analysis.ja.dict.Dictionary;*/public class Token {private final Dictionary dictionary;-+private final int wordId;-+private final char[] surfaceForm;private final int offset;private final int length;-+private final int position;private int positionLength;-+private final Type type;-+public Token(int wordId, char[] surfaceForm, int offset, int length, Type type, int position, Dictionary dictionary) {this.wordId = wordId;this.surfaceForm = surfaceForm;@@ -53,77 +53,85 @@ public class Token {" posLen=" + positionLength + " type=" + type + " wordId=" + wordId +" leftID=" + dictionary.getLeftId(wordId) + ")";}-+/*** @return surfaceForm*/public char[] getSurfaceForm() {return surfaceForm;}-+/*** @return offset into surfaceForm*/public int getOffset() {return offset;}-+/*** @return length of surfaceForm*/public int getLength() {return length;}-+/*** @return surfaceForm as a String*/public String getSurfaceFormString() {return new String(surfaceForm, offset, length);}-+/*** @return reading. null if token doesn't have reading.*/public String getReading() {return dictionary.getReading(wordId, surfaceForm, offset, length);}-+/*** @return pronunciation. null if token doesn't have pronunciation.*/public String getPronunciation() {return dictionary.getPronunciation(wordId, surfaceForm, offset, length);}-+/*** @return part of speech.*/public String getPartOfSpeech() {return dictionary.getPartOfSpeech(wordId);}-+/*** @return inflection type or null*/public String getInflectionType() {return dictionary.getInflectionType(wordId);}-+/*** @return inflection form or null*/public String getInflectionForm() {return dictionary.getInflectionForm(wordId);}-+/*** @return base form or null if token is not inflected*/public String getBaseForm() {return dictionary.getBaseForm(wordId, surfaceForm, offset, length);}-++ /**+ * Returns the type of this token+ * @return token type, not null+ */+ public Type getType() {+ return type;+ }+/*** Returns true if this token is known word* @return true if this token is in standard dictionary. false if not.@@ -131,7 +139,7 @@ public class Token {public boolean isKnown() {return type == Type.KNOWN;}-+/*** Returns true if this token is unknown word* @return true if this token is unknown word. false if not.@@ -139,7 +147,7 @@ public class Token {public boolean isUnknown() {return type == Type.UNKNOWN;}-+/*** Returns true if this token is defined in user dictionary* @return true if this token is in user dictionary. false if not.@@ -147,7 +155,7 @@ public class Token {public boolean isUser() {return type == Type.USER;}-+/*** Get index of this token in input text* @return position of token@@ -163,7 +171,7 @@ public class Token {public void setPositionLength(int positionLength) {this.positionLength = positionLength;}-+/*** Get the length (in tokens) of this token. For normal* tokens this is 1; for compound tokens it's > 1.diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizer.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizer.javaindex ba172a00222..a707dc7fb03 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizer.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizer.java@@ -24,6 +24,7 @@ import java.io.LineNumberReader;import java.io.Reader;import java.io.StringReader;import java.nio.charset.StandardCharsets;+import java.util.ArrayList;import java.util.Random;import org.apache.lucene.analysis.Analyzer;@@ -59,9 +60,22 @@ public classthrow new RuntimeException(ioe);}}-- private Analyzer analyzer, analyzerNormal, analyzerNoPunct, extendedModeAnalyzerNoPunct;-++ private Analyzer analyzer, analyzerNormal, analyzerNormalNBest, analyzerNoPunct, extendedModeAnalyzerNoPunct;++ private JapaneseTokenizer makeTokenizer(boolean discardPunctuation, Mode mode) {+ return new JapaneseTokenizer(newAttributeFactory(), readDict(), discardPunctuation, mode);+ }++ private Analyzer makeAnalyzer(final Tokenizer t) {+ return new Analyzer() {+ @Override+ protected TokenStreamComponents createComponents(String fieldName) {+ return new TokenStreamComponents(t, t);+ }+ };+ }+@Overridepublic void setUp() throws Exception {super.setUp();@@ -79,6 +93,14 @@ public classreturn new TokenStreamComponents(tokenizer, tokenizer);}};+ analyzerNormalNBest = new Analyzer() {+ @Override+ protected TokenStreamComponents createComponents(String fieldName) {+ JapaneseTokenizer tokenizer = new JapaneseTokenizer(newAttributeFactory(), readDict(), false, Mode.NORMAL);+ tokenizer.setNBestCost(2000);+ return new TokenStreamComponents(tokenizer, tokenizer);+ }+ };analyzerNoPunct = new Analyzer() {@Overrideprotected TokenStreamComponents createComponents(String fieldName) {@@ -94,7 +116,7 @@ public class}};}-+@Overridepublic void tearDown() throws Exception {IOUtils.close(analyzer, analyzerNormal, analyzerNoPunct, extendedModeAnalyzerNoPunct);@@ -107,14 +129,109 @@ public classnew String[] {"シニアソフトウェアエンジニア"});}+ public void testNormalModeNbest() throws Exception {+ JapaneseTokenizer t = makeTokenizer(true, Mode.NORMAL);+ Analyzer a = makeAnalyzer(t);++ t.setNBestCost(2000);+ assertAnalyzesTo(a,+ "シニアソフトウェアエンジニア",+ new String[] {"シニア", "シニアソフトウェアエンジニア", "ソフトウェア", "エンジニア"});++ t.setNBestCost(5000);+ assertAnalyzesTo(a,+ "シニアソフトウェアエンジニア",+ new String[] {"シニア", "シニアソフトウェアエンジニア", "ソフト", "ソフトウェア", "ウェア", "エンジニア"});++ t.setNBestCost(0);+ assertAnalyzesTo(a,+ "数学部長谷川",+ new String[] {"数学", "部長", "谷川"});++ t.setNBestCost(3000);+ assertAnalyzesTo(a,+ "数学部長谷川",+ new String[] {"数学", "部", "部長", "長谷川", "谷川"});++ t.setNBestCost(0);+ assertAnalyzesTo(a,+ "経済学部長",+ new String[] {"経済", "学", "部長"});++ t.setNBestCost(2000);+ assertAnalyzesTo(a,+ "経済学部長",+ new String[] {"経済", "経済学部", "学", "部長", "長"});++ t.setNBestCost(0);+ assertAnalyzesTo(a,+ "成田空港、米原油流出",+ new String[] {"成田空港", "米", "原油", "流出"});++ t.setNBestCost(4000);+ assertAnalyzesTo(a,+ "成田空港、米原油流出",+ new String[] {"成田空港", "米", "米原", "原油", "油", "流出"});+ }++ public void testSearchModeNbest() throws Exception {+ JapaneseTokenizer t = makeTokenizer(true, Mode.SEARCH);+ Analyzer a = makeAnalyzer(t);++ t.setNBestCost(0);+ assertAnalyzesTo(a,+ "成田空港、米原油流出",+ new String[] {"成田", "成田空港", "空港", "米", "原油", "流出"});++ t.setNBestCost(4000);+ assertAnalyzesTo(a,+ "成田空港、米原油流出",+ new String[] {"成田", "成田空港", "空港", "米", "米原", "原油", "油", "流出"});+ }++ private ArrayList<String> makeTokenList(Analyzer a, String in) throws Exception {+ ArrayList<String> list = new ArrayList<>();+ TokenStream ts = a.tokenStream("dummy", in);+ CharTermAttribute termAtt = ts.getAttribute(CharTermAttribute.class);++ ts.reset();+ while (ts.incrementToken()) {+ list.add(termAtt.toString());+ }+ ts.end();+ ts.close();+ return list;+ }++ private boolean checkToken(Analyzer a, String in, String requitedToken) throws Exception {+ return makeTokenList(a, in).indexOf(requitedToken) != -1;+ }++ public void testNBestCost() throws Exception {+ JapaneseTokenizer t = makeTokenizer(true, Mode.NORMAL);+ Analyzer a = makeAnalyzer(t);++ t.setNBestCost(0);+ assertFalse("学部 is not a token of 数学部長谷川", checkToken(a, "数学部長谷川", "学部"));++ assertTrue("cost calculated /数学部長谷川-学部/", 0 <= t.calcNBestCost("/数学部長谷川-学部/"));+ t.setNBestCost(t.calcNBestCost("/数学部長谷川-学部/"));+ assertTrue("学部 is a token of 数学部長谷川", checkToken(a, "数学部長谷川", "学部"));++ assertTrue("cost calculated /数学部長谷川-数/成田空港-成/", 0 <= t.calcNBestCost("/数学部長谷川-数/成田空港-成/"));+ t.setNBestCost(t.calcNBestCost("/数学部長谷川-数/成田空港-成/"));+ assertTrue("数 is a token of 数学部長谷川", checkToken(a, "数学部長谷川", "数"));+ assertTrue("成 is a token of 成田空港", checkToken(a, "成田空港", "成"));+ }+public void testDecomposition1() throws Exception {assertAnalyzesTo(analyzerNoPunct, "本来は、貧困層の女性や子供に医療保護を提供するために創設された制度である、" +"アメリカ低所得者医療援助制度が、今日では、その予算の約3分の1を老人に費やしている。",- new String[] { "本来", "は", "貧困", "層", "の", "女性", "や", "子供", "に", "医療", "保護", "を",- "提供", "する", "ため", "に", "創設", "さ", "れ", "た", "制度", "で", "ある", "アメリカ",+ new String[] { "本来", "は", "貧困", "層", "の", "女性", "や", "子供", "に", "医療", "保護", "を",+ "提供", "する", "ため", "に", "創設", "さ", "れ", "た", "制度", "で", "ある", "アメリカ","低", "所得", "者", "医療", "援助", "制度", "が", "今日", "で", "は", "その","予算", "の", "約", "3", "分の", "1", "を", "老人", "に", "費やし", "て", "いる" },- new int[] { 0, 2, 4, 6, 7, 8, 10, 11, 13, 14, 16, 18, 19, 21, 23, 25, 26, 28, 29, 30,+ new int[] { 0, 2, 4, 6, 7, 8, 10, 11, 13, 14, 16, 18, 19, 21, 23, 25, 26, 28, 29, 30,31, 33, 34, 37, 41, 42, 44, 45, 47, 49, 51, 53, 55, 56, 58, 60,62, 63, 64, 65, 67, 68, 69, 71, 72, 75, 76 },new int[] { 2, 3, 6, 7, 8, 10, 11, 13, 14, 16, 18, 19, 21, 23, 25, 26, 28, 29, 30, 31,@@ -122,7 +239,7 @@ public class63, 64, 65, 67, 68, 69, 71, 72, 75, 76, 78 });}-+public void testDecomposition2() throws Exception {assertAnalyzesTo(analyzerNoPunct, "麻薬の密売は根こそぎ絶やさなければならない",new String[] { "麻薬", "の", "密売", "は", "根こそぎ", "絶やさ", "なけれ", "ば", "なら", "ない" },@@ -130,7 +247,7 @@ public classnew int[] { 2, 3, 5, 6, 10, 13, 16, 17, 19, 21 });}-+public void testDecomposition3() throws Exception {assertAnalyzesTo(analyzerNoPunct, "魔女狩大将マシュー・ホプキンス。",new String[] { "魔女", "狩", "大将", "マシュー", "ホプキンス" },@@ -154,7 +271,7 @@ public classtry (TokenStream ts = analyzer.tokenStream("bogus", "くよくよくよくよくよくよくよくよくよくよくよくよくよくよくよくよくよくよくよくよ")) {ts.reset();while (ts.incrementToken()) {-+}ts.end();}@@ -196,13 +313,15 @@ public classpublic void testRandomStrings() throws Exception {checkRandomData(random(), analyzer, 500*RANDOM_MULTIPLIER);checkRandomData(random(), analyzerNoPunct, 500*RANDOM_MULTIPLIER);+ checkRandomData(random(), analyzerNormalNBest, 500*RANDOM_MULTIPLIER);}-+/** blast some random large strings through the analyzer */public void testRandomHugeStrings() throws Exception {Random random = random();checkRandomData(random, analyzer, 20*RANDOM_MULTIPLIER, 8192);checkRandomData(random, analyzerNoPunct, 20*RANDOM_MULTIPLIER, 8192);+ checkRandomData(random, analyzerNormalNBest, 20*RANDOM_MULTIPLIER, 8192);}public void testRandomHugeStringsMockGraphAfter() throws Exception {@@ -231,13 +350,13 @@ public class}}}-+/** simple test for supplementary characters */public void testSurrogates() throws IOException {assertAnalyzesTo(analyzer, "𩬅艱鍟䇹愯瀛",new String[] { "𩬅", "艱", "鍟", "䇹", "愯", "瀛" });}-+/** random test ensuring we don't ever split supplementaries */public void testSurrogates2() throws IOException {int numIterations = atLeast(10000);@@ -272,7 +391,7 @@ public classts.end();}}-+// note: test is kinda silly since kuromoji emits punctuation tokens.// but, when/if we filter these out it will be useful.public void testEnd() throws Exception {@@ -338,7 +457,7 @@ public class);}*/-+public void testSegmentation() throws Exception {// Skip tests for Michelle Kwan -- UniDic segments Kwan as ク ワン// String input = "ミシェル・クワンが優勝しました。スペースステーションに行きます。うたがわしい。";@@ -376,7 +495,7 @@ public classassertAnalyzesTo(analyzer,input,surfaceForms);-+assertTrue(gv2.finish().indexOf("22.0") != -1);analyzer.close();}@@ -406,7 +525,7 @@ public classts.end();}}-+private void assertBaseForms(String input, String... baseForms) throws IOException {try (TokenStream ts = analyzer.tokenStream("ignored", input)) {BaseFormAttribute baseFormAtt = ts.addAttribute(BaseFormAttribute.class);@@ -445,7 +564,7 @@ public classts.end();}}-+private void assertPartsOfSpeech(String input, String... partsOfSpeech) throws IOException {try (TokenStream ts = analyzer.tokenStream("ignored", input)) {PartOfSpeechAttribute partOfSpeechAtt = ts.addAttribute(PartOfSpeechAttribute.class);@@ -458,7 +577,7 @@ public classts.end();}}-+public void testReadings() throws Exception {assertReadings("寿司が食べたいです。","スシ",@@ -468,7 +587,7 @@ public class"デス","。");}-+public void testReadings2() throws Exception {assertReadings("多くの学生が試験に落ちた。","オオク",@@ -481,7 +600,7 @@ public class"タ","。");}-+public void testPronunciations() throws Exception {assertPronunciations("寿司が食べたいです。","スシ",@@ -491,7 +610,7 @@ public class"デス","。");}-+public void testPronunciations2() throws Exception {// pronunciation differs from reading hereassertPronunciations("多くの学生が試験に落ちた。",@@ -505,7 +624,7 @@ public class"タ","。");}-+public void testBasicForms() throws Exception {assertBaseForms("それはまだ実験段階にあります。",null,@@ -518,7 +637,7 @@ public classnull,null);}-+public void testInflectionTypes() throws Exception {assertInflectionTypes("それはまだ実験段階にあります。",null,@@ -531,7 +650,7 @@ public class"特殊・マス",null);}-+public void testInflectionForms() throws Exception {assertInflectionForms("それはまだ実験段階にあります。",null,@@ -544,7 +663,7 @@ public class"基本形",null);}-+public void testPartOfSpeech() throws Exception {assertPartsOfSpeech("それはまだ実験段階にあります。","名詞-代名詞-一般",@@ -626,13 +745,13 @@ public class}*/-+private void doTestBocchan(int numIterations) throws Exception {LineNumberReader reader = new LineNumberReader(new InputStreamReader(this.getClass().getResourceAsStream("bocchan.utf-8"), StandardCharsets.UTF_8));String line = reader.readLine();reader.close();-+if (VERBOSE) {System.out.println("Test for Bocchan without pre-splitting sentences");}diff --git a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.java b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.javaindex a409a4a3124..1d63c6f46d6 100644--- a/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.java+++ b/lucene/analysis/kuromoji/src/test/org/apache/lucene/analysis/ja/TestJapaneseTokenizerFactory.java@@ -19,7 +19,6 @@ package org.apache.lucene.analysis.ja;import java.io.IOException;import java.io.StringReader;-import java.util.Collections;import java.util.HashMap;import java.util.Map;@@ -42,7 +41,7 @@ public class TestJapaneseTokenizerFactory extends BaseTokenStreamTestCase {new int[] { 2, 3, 4, 5, 6, 8 });}-+/*** Test that search mode is enabled and working by default*/@@ -55,7 +54,7 @@ public class TestJapaneseTokenizerFactory extends BaseTokenStreamTestCase {new String[] { "シニア", "シニアソフトウェアエンジニア", "ソフトウェア", "エンジニア" });}-+/*** Test mode parameter: specifying normal mode*/@@ -75,7 +74,7 @@ public class TestJapaneseTokenizerFactory extends BaseTokenStreamTestCase {* Test user dictionary*/public void testUserDict() throws IOException {- String userDict =+ String userDict ="# Custom segmentation for long entries\n" +"日本経済新聞,日本 経済 新聞,ニホン ケイザイ シンブン,カスタム名詞\n" +"関西国際空港,関西 国際 空港,カンサイ コクサイ クウコウ,テスト名詞\n" +@@ -109,7 +108,7 @@ public class TestJapaneseTokenizerFactory extends BaseTokenStreamTestCase {"お", "寿司", "が", "食べ", "たい", "な", "。", "。", "。"});}-+/** Test that bogus arguments result in exception */public void testBogusArguments() throws Exception {try {@@ -121,4 +120,31 @@ public class TestJapaneseTokenizerFactory extends BaseTokenStreamTestCase {assertTrue(expected.getMessage().contains("Unknown parameters"));}}++ private TokenStream makeTokenStream(HashMap<String, String> args, String in) throws IOException {+ JapaneseTokenizerFactory factory = new JapaneseTokenizerFactory(args);+ factory.inform(new StringMockResourceLoader(""));+ Tokenizer t = factory.create(newAttributeFactory());+ t.setReader(new StringReader(in));+ return t;+ }++ /**+ * Test nbestCost parameter+ */+ public void testNbestCost() throws IOException {+ assertTokenStreamContents(makeTokenStream(new HashMap<String, String>() {{put("nBestCost", "2000");}},+ "鳩山積み"),+ new String[] {"鳩", "鳩山", "山積み", "積み"});+ }++ /**+ * Test nbestExamples parameter+ */+ public void testNbestExample() throws IOException {+ assertTokenStreamContents(makeTokenStream(new HashMap<String, String>()+ {{put("nBestExamples", "/鳩山積み-鳩山/鳩山積み-鳩/");}},+ "鳩山積み"),+ new String[] {"鳩", "鳩山", "山積み", "積み"});+ }}