code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public static void convertPKUtoCWS(String inputFolder, String outputFile, final int begin, final int end) throws IOException { final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); CorpusLoader.walk(inputFolder, new CorpusLoader.Handler() { int doc = 0; @Override public void handle(Document document) { ++doc; if (doc < begin || doc > end) return; try { List<List<Word>> sentenceList = convertComplexWordToSimpleWord(document.getComplexSentenceList()); if (sentenceList.size() == 0) return; for (List<Word> sentence : sentenceList) { if (sentence.size() == 0) continue; int index = 0; for (IWord iWord : sentence) { bw.write(iWord.getValue()); if (++index != sentence.size()) { bw.write(' '); } } bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } } } ); bw.close(); }
将人民日报格式的分词语料转化为空格分割的语料 @param inputFolder 输入人民日报语料的上级目录(该目录下的所有文件都是一篇人民日报分词文章) @param outputFile 输出一整个CRF训练格式的语料 @param begin 取多少个文档之后 @param end @throws IOException 转换过程中的IO异常
public static List<String[]> convertSentenceToNER(Sentence sentence, NERTagSet tagSet) { List<String[]> collector = new LinkedList<String[]>(); Set<String> nerLabels = tagSet.nerLabels; for (IWord word : sentence.wordList) { if (word instanceof CompoundWord) { List<Word> wordList = ((CompoundWord) word).innerList; Word[] words = wordList.toArray(new Word[0]); if (nerLabels.contains(word.getLabel())) { collector.add(new String[]{words[0].value, words[0].label, tagSet.B_TAG_PREFIX + word.getLabel()}); for (int i = 1; i < words.length - 1; i++) { collector.add(new String[]{words[i].value, words[i].label, tagSet.M_TAG_PREFIX + word.getLabel()}); } collector.add(new String[]{words[words.length - 1].value, words[words.length - 1].label, tagSet.E_TAG_PREFIX + word.getLabel()}); } else { for (Word w : words) { collector.add(new String[]{w.value, w.label, tagSet.O_TAG}); } } } else { if (nerLabels.contains(word.getLabel())) { // 单个实体 collector.add(new String[]{word.getValue(), word.getLabel(), tagSet.S_TAG}); } else { collector.add(new String[]{word.getValue(), word.getLabel(), tagSet.O_TAG}); } } } return collector; }
将句子转换为 (单词,词性,NER标签)三元组 @param sentence @param tagSet @return
public static double bytesHighFirstToDouble(byte[] bytes, int start) { long l = ((long) bytes[start] << 56) & 0xFF00000000000000L; // 如果不强制转换为long,那么默认会当作int,导致最高32位丢失 l |= ((long) bytes[1 + start] << 48) & 0xFF000000000000L; l |= ((long) bytes[2 + start] << 40) & 0xFF0000000000L; l |= ((long) bytes[3 + start] << 32) & 0xFF00000000L; l |= ((long) bytes[4 + start] << 24) & 0xFF000000L; l |= ((long) bytes[5 + start] << 16) & 0xFF0000L; l |= ((long) bytes[6 + start] << 8) & 0xFF00L; l |= (long) bytes[7 + start] & 0xFFL; return Double.longBitsToDouble(l); }
读取double,高位在前 @param bytes @param start @return
public static int bytesToInt(byte[] b) { int i = (b[0] << 24) & 0xFF000000; i |= (b[1] << 16) & 0xFF0000; i |= (b[2] << 8) & 0xFF00; i |= b[3] & 0xFF; return i; }
将一个4位字节数组转换为4整数。<br> 注意,函数中不会对字节数组长度进行判断,请自行保证传入参数的正确性。 @param b 字节数组 @return 整数
public static long bytesToLong(byte[] b) { long l = ((long) b[0] << 56) & 0xFF00000000000000L; // 如果不强制转换为long,那么默认会当作int,导致最高32位丢失 l |= ((long) b[1] << 48) & 0xFF000000000000L; l |= ((long) b[2] << 40) & 0xFF0000000000L; l |= ((long) b[3] << 32) & 0xFF00000000L; l |= ((long) b[4] << 24) & 0xFF000000L; l |= ((long) b[5] << 16) & 0xFF0000L; l |= ((long) b[6] << 8) & 0xFF00L; l |= (long) b[7] & 0xFFL; return l; }
将一个8位字节数组转换为长整数。<br> 注意,函数中不会对字节数组长度进行判断,请自行保证传入参数的正确性。 @param b 字节数组 @return 长整数
public static int bytesToInt(byte[] bytes, int start) { int num = bytes[start] & 0xFF; num |= ((bytes[start + 1] << 8) & 0xFF00); num |= ((bytes[start + 2] << 16) & 0xFF0000); num |= ((bytes[start + 3] << 24) & 0xFF000000); return num; }
字节数组和整型的转换 @param bytes 字节数组 @return 整型
public static int bytesHighFirstToInt(byte[] bytes, int start) { int num = bytes[start + 3] & 0xFF; num |= ((bytes[start + 2] << 8) & 0xFF00); num |= ((bytes[start + 1] << 16) & 0xFF0000); num |= ((bytes[start] << 24) & 0xFF000000); return num; }
字节数组和整型的转换,高位在前,适用于读取writeInt的数据 @param bytes 字节数组 @return 整型
public static float bytesHighFirstToFloat(byte[] bytes, int start) { int l = bytesHighFirstToInt(bytes, start); return Float.intBitsToFloat(l); }
读取float,高位在前 @param bytes @param start @return
public static void writeUnsignedInt(DataOutputStream out, int uint) throws IOException { out.writeByte((byte) ((uint >>> 8) & 0xFF)); out.writeByte((byte) ((uint >>> 0) & 0xFF)); }
无符号整型输出 @param out @param uint @throws IOException
public static void parsePattern(List<NS> nsList, List<Vertex> vertexList, final WordNet wordNetOptimum, final WordNet wordNetAll) { // ListIterator<Vertex> listIterator = vertexList.listIterator(); StringBuilder sbPattern = new StringBuilder(nsList.size()); for (NS ns : nsList) { sbPattern.append(ns.toString()); } String pattern = sbPattern.toString(); final Vertex[] wordArray = vertexList.toArray(new Vertex[0]); trie.parseText(pattern, new AhoCorasickDoubleArrayTrie.IHit<String>() { @Override public void hit(int begin, int end, String value) { StringBuilder sbName = new StringBuilder(); for (int i = begin; i < end; ++i) { sbName.append(wordArray[i].realWord); } String name = sbName.toString(); // 对一些bad case做出调整 if (isBadCase(name)) return; // 正式算它是一个名字 if (HanLP.Config.DEBUG) { System.out.printf("识别出地名:%s %s\n", name, value); } int offset = 0; for (int i = 0; i < begin; ++i) { offset += wordArray[i].realWord.length(); } wordNetOptimum.insert(offset, new Vertex(Predefine.TAG_PLACE, name, ATTRIBUTE, WORD_ID), wordNetAll); } }); }
模式匹配 @param nsList 确定的标注序列 @param vertexList 原始的未加角色标注的序列 @param wordNetOptimum 待优化的图 @param wordNetAll
static boolean isBadCase(String name) { EnumItem<NS> nrEnumItem = dictionary.get(name); if (nrEnumItem == null) return false; return nrEnumItem.containsLabel(NS.Z); }
因为任何算法都无法解决100%的问题,总是有一些bad case,这些bad case会以“盖公章 A 1”的形式加入词典中<BR> 这个方法返回是否是bad case @param name @return
public void setLabels(String[] outcomeLabels) { this.numOutcomes = outcomeLabels.length; r = Math.log(1.0 / numOutcomes); }
初始化 @param outcomeLabels
public boolean isNonprojective() { for (int dep1 : goldDependencies.keySet()) { int head1 = goldDependencies.get(dep1).headIndex; for (int dep2 : goldDependencies.keySet()) { int head2 = goldDependencies.get(dep2).headIndex; if (head1 < 0 || head2 < 0) continue; if (dep1 > head1 && head1 != head2) if ((dep1 > head2 && dep1 < dep2 && head1 < head2) || (dep1 < head2 && dep1 > dep2 && head1 < dep2)) return true; if (dep1 < head1 && head1 != head2) if ((head1 > head2 && head1 < dep2 && dep1 < head2) || (head1 < head2 && head1 > dep2 && dep1 < dep2)) return true; } } return false; }
Shows whether the tree to train is projective or not @return true if the tree is non-projective
public int actionCost(Action action, int dependency, State state) { if (!ArcEager.canDo(action, state)) return Integer.MAX_VALUE; int cost = 0; // added by me to take care of labels if (action == Action.LeftArc) { // left arc int bufferHead = state.bufferHead(); int stackHead = state.stackTop(); if (goldDependencies.containsKey(stackHead) && goldDependencies.get(stackHead).headIndex == bufferHead && goldDependencies.get(stackHead).relationId != (dependency)) cost += 1; } else if (action == Action.RightArc) { //right arc int bufferHead = state.bufferHead(); int stackHead = state.stackTop(); if (goldDependencies.containsKey(bufferHead) && goldDependencies.get(bufferHead).headIndex == stackHead && goldDependencies.get(bufferHead).relationId != (dependency)) cost += 1; } if (action == Action.Shift) { //shift int bufferHead = state.bufferHead(); for (int stackItem : state.getStack()) { if (goldDependencies.containsKey(stackItem) && goldDependencies.get(stackItem).headIndex == (bufferHead)) cost += 1; if (goldDependencies.containsKey(bufferHead) && goldDependencies.get(bufferHead).headIndex == (stackItem)) cost += 1; } } else if (action == Action.Reduce) { //reduce int stackHead = state.stackTop(); if (!state.bufferEmpty()) for (int bufferItem = state.bufferHead(); bufferItem <= state.maxSentenceSize; bufferItem++) { if (goldDependencies.containsKey(bufferItem) && goldDependencies.get(bufferItem).headIndex == (stackHead)) cost += 1; } } else if (action == Action.LeftArc && cost == 0) { //left arc int stackHead = state.stackTop(); if (!state.bufferEmpty()) for (int bufferItem = state.bufferHead(); bufferItem <= state.maxSentenceSize; bufferItem++) { if (goldDependencies.containsKey(bufferItem) && goldDependencies.get(bufferItem).headIndex == (stackHead)) cost += 1; if (goldDependencies.containsKey(stackHead) && goldDependencies.get(stackHead).headIndex == (bufferItem)) if (bufferItem != state.bufferHead()) cost += 1; } } else if (action == Action.RightArc && cost == 0) { //right arc int stackHead = state.stackTop(); int bufferHead = state.bufferHead(); for (int stackItem : state.getStack()) { if (goldDependencies.containsKey(bufferHead) && goldDependencies.get(bufferHead).headIndex == (stackItem)) if (stackItem != stackHead) cost += 1; if (goldDependencies.containsKey(stackItem) && goldDependencies.get(stackItem).headIndex == (bufferHead)) cost += 1; } if (!state.bufferEmpty()) for (int bufferItem = state.bufferHead(); bufferItem <= state.maxSentenceSize; bufferItem++) { if (goldDependencies.containsKey(bufferHead) && goldDependencies.get(bufferHead).headIndex == (bufferItem)) cost += 1; } } return cost; }
For the cost of an action given the gold dependencies For more information see: Yoav Goldberg and Joakim Nivre. "Training Deterministic Parsers with Non-Deterministic Oracles." TACL 1 (2013): 403-414. @param action @param dependency @param state @return oracle cost of the action @throws Exception
public boolean load(String path) { String binPath = path + Predefine.BIN_EXT; if (load(ByteArrayStream.createByteArrayStream(binPath))) return true; if (!loadTxt(path)) return false; try { logger.info("正在缓存" + binPath); DataOutputStream out = new DataOutputStream(IOUtil.newOutputStream(binPath)); save(out); out.close(); } catch (Exception e) { logger.warning("缓存" + binPath + "失败:\n" + TextUtility.exceptionToString(e)); } return true; }
加载parser模型 @param path @return
public boolean loadTxt(String path) { IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(path); model_header = lineIterator.next(); if (model_header == null) return false; root = lineIterator.next(); use_distance = "1".equals(lineIterator.next()); use_valency = "1".equals(lineIterator.next()); use_cluster = "1".equals(lineIterator.next()); W1 = read_matrix(lineIterator); W2 = read_matrix(lineIterator); E = read_matrix(lineIterator); b1 = read_vector(lineIterator); saved = read_matrix(lineIterator); forms_alphabet = read_alphabet(lineIterator); postags_alphabet = read_alphabet(lineIterator); deprels_alphabet = read_alphabet(lineIterator); precomputation_id_encoder = read_map(lineIterator); if (use_cluster) { cluster4_types_alphabet = read_alphabet(lineIterator); cluster6_types_alphabet = read_alphabet(lineIterator); cluster_types_alphabet = read_alphabet(lineIterator); form_to_cluster4 = read_map(lineIterator); form_to_cluster6 = read_map(lineIterator); form_to_cluster = read_map(lineIterator); } assert !lineIterator.hasNext() : "文件有残留,可能是读取逻辑不对"; classifier = new NeuralNetworkClassifier(W1, W2, E, b1, saved, precomputation_id_encoder); classifier.canonical(); return true; }
从txt加载 @param path @return
public void save(DataOutputStream out) throws Exception { TextUtility.writeString(model_header, out); TextUtility.writeString(root, out); out.writeInt(use_distance ? 1 : 0); out.writeInt(use_valency ? 1 : 0); out.writeInt(use_cluster ? 1 : 0); W1.save(out); W2.save(out); E.save(out); b1.save(out); saved.save(out); forms_alphabet.save(out); postags_alphabet.save(out); deprels_alphabet.save(out); save_map(precomputation_id_encoder, out); if (use_cluster) { cluster4_types_alphabet.save(out); cluster6_types_alphabet.save(out); cluster_types_alphabet.save(out); save_map(form_to_cluster4, out); save_map(form_to_cluster6 , out); save_map(form_to_cluster , out); } }
保存到磁盘 @param out @throws Exception
public boolean load(ByteArray byteArray) { if (byteArray == null) return false; model_header = byteArray.nextString(); root = byteArray.nextString(); use_distance = byteArray.nextInt() == 1; use_valency = byteArray.nextInt() == 1; use_cluster = byteArray.nextInt() == 1; W1 = new Matrix(); W1.load(byteArray); W2 = new Matrix(); W2.load(byteArray); E = new Matrix(); E .load(byteArray); b1 = new Matrix(); b1 .load(byteArray); saved = new Matrix(); saved .load(byteArray); forms_alphabet = new Alphabet(); forms_alphabet .load(byteArray); postags_alphabet = new Alphabet(); postags_alphabet .load(byteArray); deprels_alphabet = new Alphabet(); deprels_alphabet .load(byteArray); precomputation_id_encoder = read_map(byteArray); if (use_cluster) { cluster4_types_alphabet = new Alphabet(); cluster4_types_alphabet.load(byteArray); cluster6_types_alphabet = new Alphabet(); cluster6_types_alphabet .load(byteArray); cluster_types_alphabet = new Alphabet(); cluster_types_alphabet .load(byteArray); form_to_cluster4 = read_map(byteArray); form_to_cluster6 = read_map(byteArray); form_to_cluster = read_map(byteArray); } assert !byteArray.hasMore() : "文件有残留,可能是读取逻辑不对"; classifier = new NeuralNetworkClassifier(W1, W2, E, b1, saved, precomputation_id_encoder); classifier.canonical(); return true; }
从bin加载 @param byteArray @return
void setup_system() { system = new TransitionSystem(); system.set_root_relation(deprels_alphabet.idOf(root)); system.set_number_of_relations(deprels_alphabet.size() - 2); }
初始化
void build_feature_space() { kFormInFeaturespace = 0; kNilForm = forms_alphabet.idOf(SpecialOption.NIL); kFeatureSpaceEnd = forms_alphabet.size(); kPostagInFeaturespace = kFeatureSpaceEnd; kNilPostag = kFeatureSpaceEnd + postags_alphabet.idOf(SpecialOption.NIL); kFeatureSpaceEnd += postags_alphabet.size(); kDeprelInFeaturespace = kFeatureSpaceEnd; kNilDeprel = kFeatureSpaceEnd + deprels_alphabet.idOf(SpecialOption.NIL); kFeatureSpaceEnd += deprels_alphabet.size(); kDistanceInFeaturespace = kFeatureSpaceEnd; kNilDistance = kFeatureSpaceEnd + (use_distance ? 8 : 0); kFeatureSpaceEnd += (use_distance ? 9 : 0); kValencyInFeaturespace = kFeatureSpaceEnd; kNilValency = kFeatureSpaceEnd + (use_valency ? 8 : 0); kFeatureSpaceEnd += (use_valency ? 9 : 0); kCluster4InFeaturespace = kFeatureSpaceEnd; if (use_cluster) { kNilCluster4 = kFeatureSpaceEnd + cluster4_types_alphabet.idOf(SpecialOption.NIL); kFeatureSpaceEnd += cluster4_types_alphabet.size(); } else { kNilCluster4 = kFeatureSpaceEnd; } kCluster6InFeaturespace = kFeatureSpaceEnd; if (use_cluster) { kNilCluster6 = kFeatureSpaceEnd + cluster6_types_alphabet.idOf(SpecialOption.NIL); kFeatureSpaceEnd += cluster6_types_alphabet.size(); } else { kNilCluster6 = kFeatureSpaceEnd; } kClusterInFeaturespace = kFeatureSpaceEnd; if (use_cluster) { kNilCluster = kFeatureSpaceEnd + cluster_types_alphabet.idOf(SpecialOption.NIL); kFeatureSpaceEnd += cluster_types_alphabet.size(); } else { kNilCluster = kFeatureSpaceEnd; } }
初始化特征空间的长度等信息
void transduce_instance_to_dependency(final Instance data, Dependency dependency, boolean with_dependencies) { int L = data.forms.size(); for (int i = 0; i < L; ++i) { Integer form = forms_alphabet.idOf(data.forms.get(i)); if (form == null) { form = forms_alphabet.idOf(SpecialOption.UNKNOWN); } Integer postag = postags_alphabet.idOf(data.postags.get(i)); if (postag == null) postag = postags_alphabet.idOf(SpecialOption.UNKNOWN); int deprel = (with_dependencies ? deprels_alphabet.idOf(data.deprels.get(i)) : -1); dependency.forms.add(form); dependency.postags.add(postag); dependency.heads.add(with_dependencies ? data.heads.get(i) : -1); dependency.deprels.add(with_dependencies ? deprel : -1); } }
将实例转为依存树 @param data 实例 @param dependency 输出的依存树 @param with_dependencies 是否输出依存关系(仅在解析后才有意义)
void get_cluster_from_dependency(final Dependency data, List<Integer> cluster4, List<Integer> cluster6, List<Integer> cluster) { if (use_cluster) { int L = data.forms.size(); for (int i = 0; i < L; ++i) { int form = data.forms.get(i); cluster4.add(i == 0 ? cluster4_types_alphabet.idOf(SpecialOption.ROOT) : form_to_cluster4.get(form)); cluster6.add(i == 0 ? cluster6_types_alphabet.idOf(SpecialOption.ROOT) : form_to_cluster6.get(form)); cluster.add(i == 0 ? cluster_types_alphabet.idOf(SpecialOption.ROOT) : form_to_cluster.get(form)); } } }
获取词聚类特征 @param data 输入数据 @param cluster4 @param cluster6 @param cluster
void predict(final Instance data, List<Integer> heads, List<String> deprels) { Dependency dependency = new Dependency(); List<Integer> cluster = new ArrayList<Integer>(), cluster4 = new ArrayList<Integer>(), cluster6 = new ArrayList<Integer>(); transduce_instance_to_dependency(data, dependency, false); get_cluster_from_dependency(dependency, cluster4, cluster6, cluster); int L = data.forms.size(); State[] states = new State[L * 2]; for (int i = 0; i < states.length; i++) { states[i] = new State(); } states[0].copy(new State(dependency)); system.transit(states[0], ActionFactory.make_shift(), states[1]); for (int step = 1; step < L * 2 - 1; ++step) { List<Integer> attributes = new ArrayList<Integer>(); if (use_cluster) { get_features(states[step], cluster4, cluster6, cluster, attributes); } else { get_features(states[step], attributes); } List<Double> scores = new ArrayList<Double>(system.number_of_transitions()); classifier.score(attributes, scores); List<Action> possible_actions = new ArrayList<Action>(); system.get_possible_actions(states[step], possible_actions); int best = -1; for (int j = 0; j < possible_actions.size(); ++j) { int l = system.transform(possible_actions.get(j)); if (best == -1 || scores.get(best) < scores.get(l)) { best = l; } } Action act = system.transform(best); system.transit(states[step], act, states[step + 1]); } // heads.resize(L); // deprels.resize(L); for (int i = 0; i < L; ++i) { heads.add(states[L * 2 - 1].heads.get(i)); deprels.add(deprels_alphabet.labelOf(states[L * 2 - 1].deprels.get(i))); } }
依存分析 @param data 实例 @param heads 依存指向的储存位置 @param deprels 依存关系的储存位置
void get_context(final State s, Context ctx) { ctx.S0 = (s.stack.size() > 0 ? s.stack.get(s.stack.size() - 1) : -1); ctx.S1 = (s.stack.size() > 1 ? s.stack.get(s.stack.size() - 2) : -1); ctx.S2 = (s.stack.size() > 2 ? s.stack.get(s.stack.size() - 3) : -1); ctx.N0 = (s.buffer < s.ref.size() ? s.buffer : -1); ctx.N1 = (s.buffer + 1 < s.ref.size() ? s.buffer + 1 : -1); ctx.N2 = (s.buffer + 2 < s.ref.size() ? s.buffer + 2 : -1); ctx.S0L = (ctx.S0 >= 0 ? s.left_most_child.get(ctx.S0) : -1); ctx.S0R = (ctx.S0 >= 0 ? s.right_most_child.get(ctx.S0) : -1); ctx.S0L2 = (ctx.S0 >= 0 ? s.left_2nd_most_child.get(ctx.S0) : -1); ctx.S0R2 = (ctx.S0 >= 0 ? s.right_2nd_most_child.get(ctx.S0) : -1); ctx.S0LL = (ctx.S0L >= 0 ? s.left_most_child.get(ctx.S0L) : -1); ctx.S0RR = (ctx.S0R >= 0 ? s.right_most_child.get(ctx.S0R) : -1); ctx.S1L = (ctx.S1 >= 0 ? s.left_most_child.get(ctx.S1) : -1); ctx.S1R = (ctx.S1 >= 0 ? s.right_most_child.get(ctx.S1) : -1); ctx.S1L2 = (ctx.S1 >= 0 ? s.left_2nd_most_child.get(ctx.S1) : -1); ctx.S1R2 = (ctx.S1 >= 0 ? s.right_2nd_most_child.get(ctx.S1) : -1); ctx.S1LL = (ctx.S1L >= 0 ? s.left_most_child.get(ctx.S1L) : -1); ctx.S1RR = (ctx.S1R >= 0 ? s.right_most_child.get(ctx.S1R) : -1); }
获取某个状态的上下文 @param s 状态 @param ctx 上下文
void get_features(final State s, final List<Integer> cluster4, final List<Integer> cluster6, final List<Integer> cluster, List<Integer> features) { Context ctx = new Context(); get_context(s, ctx); get_basic_features(ctx, s.ref.forms, s.ref.postags, s.deprels, features); get_distance_features(ctx, features); get_valency_features(ctx, s.nr_left_children, s.nr_right_children, features); get_cluster_features(ctx, cluster4, cluster6, cluster, features); }
生成特征 @param s 当前状态 @param cluster4 @param cluster6 @param cluster @param features 输出特征
int FORM(final List<Integer> forms, int id) { return ((id != -1) ? (forms.get(id)) : kNilForm); }
获取单词 @param forms 单词列表 @param id 单词下标 @return 单词
int POSTAG(final List<Integer> postags, int id) { return ((id != -1) ? (postags.get(id) + kPostagInFeaturespace) : kNilPostag); }
获取词性 @param postags 词性列表 @param id 词性下标 @return 词性
int DEPREL(final List<Integer> deprels, int id) { return ((id != -1) ? (deprels.get(id) + kDeprelInFeaturespace) : kNilDeprel); }
获取依存 @param deprels 依存列表 @param id 依存下标 @return 依存
void get_basic_features(final Context ctx, final List<Integer> forms, final List<Integer> postags, final List<Integer> deprels, List<Integer> features) { PUSH(features, FORM(forms, ctx.S0)); PUSH(features, POSTAG(postags, ctx.S0)); PUSH(features, FORM(forms, ctx.S1)); PUSH(features, POSTAG(postags, ctx.S1)); PUSH(features, FORM(forms, ctx.S2)); PUSH(features, POSTAG(postags, ctx.S2)); PUSH(features, FORM(forms, ctx.N0)); PUSH(features, POSTAG(postags, ctx.N0)); PUSH(features, FORM(forms, ctx.N1)); PUSH(features, POSTAG(postags, ctx.N1)); PUSH(features, FORM(forms, ctx.N2)); PUSH(features, POSTAG(postags, ctx.N2)); PUSH(features, FORM(forms, ctx.S0L)); PUSH(features, POSTAG(postags, ctx.S0L)); PUSH(features, DEPREL(deprels, ctx.S0L)); PUSH(features, FORM(forms, ctx.S0R)); PUSH(features, POSTAG(postags, ctx.S0R)); PUSH(features, DEPREL(deprels, ctx.S0R)); PUSH(features, FORM(forms, ctx.S0L2)); PUSH(features, POSTAG(postags, ctx.S0L2)); PUSH(features, DEPREL(deprels, ctx.S0L2)); PUSH(features, FORM(forms, ctx.S0R2)); PUSH(features, POSTAG(postags, ctx.S0R2)); PUSH(features, DEPREL(deprels, ctx.S0R2)); PUSH(features, FORM(forms, ctx.S0LL)); PUSH(features, POSTAG(postags, ctx.S0LL)); PUSH(features, DEPREL(deprels, ctx.S0LL)); PUSH(features, FORM(forms, ctx.S0RR)); PUSH(features, POSTAG(postags, ctx.S0RR)); PUSH(features, DEPREL(deprels, ctx.S0RR)); PUSH(features, FORM(forms, ctx.S1L)); PUSH(features, POSTAG(postags, ctx.S1L)); PUSH(features, DEPREL(deprels, ctx.S1L)); PUSH(features, FORM(forms, ctx.S1R)); PUSH(features, POSTAG(postags, ctx.S1R)); PUSH(features, DEPREL(deprels, ctx.S1R)); PUSH(features, FORM(forms, ctx.S1L2)); PUSH(features, POSTAG(postags, ctx.S1L2)); PUSH(features, DEPREL(deprels, ctx.S1L2)); PUSH(features, FORM(forms, ctx.S1R2)); PUSH(features, POSTAG(postags, ctx.S1R2)); PUSH(features, DEPREL(deprels, ctx.S1R2)); PUSH(features, FORM(forms, ctx.S1LL)); PUSH(features, POSTAG(postags, ctx.S1LL)); PUSH(features, DEPREL(deprels, ctx.S1LL)); PUSH(features, FORM(forms, ctx.S1RR)); PUSH(features, POSTAG(postags, ctx.S1RR)); PUSH(features, DEPREL(deprels, ctx.S1RR)); }
获取基本特征 @param ctx 上下文 @param forms 单词 @param postags 词性 @param deprels 依存 @param features 输出特征的储存位置
void get_distance_features(final Context ctx, List<Integer> features) { if (!use_distance) { return; } int dist = 8; if (ctx.S0 >= 0 && ctx.S1 >= 0) { dist = math.binned_1_2_3_4_5_6_10[ctx.S0 - ctx.S1]; if (dist == 10) { dist = 7; } } features.add(dist + kDistanceInFeaturespace); }
获取距离特征 @param ctx 当前特征 @param features 输出特征
void get_valency_features(final Context ctx, final List<Integer> nr_left_children, final List<Integer> nr_right_children, List<Integer> features) { if (!use_valency) { return; } int lvc = 8; int rvc = 8; if (ctx.S0 >= 0) { lvc = math.binned_1_2_3_4_5_6_10[nr_left_children.get(ctx.S0)]; rvc = math.binned_1_2_3_4_5_6_10[nr_right_children.get(ctx.S0)]; if (lvc == 10) { lvc = 7; } if (rvc == 10) { rvc = 7; } } features.add(lvc + kValencyInFeaturespace); features.add(rvc + kValencyInFeaturespace); lvc = 8; rvc = 8; if (ctx.S1 >= 0) { lvc = math.binned_1_2_3_4_5_6_10[nr_left_children.get(ctx.S1)]; rvc = math.binned_1_2_3_4_5_6_10[nr_right_children.get(ctx.S1)]; if (lvc == 10) { lvc = 7; } if (rvc == 10) { rvc = 7; } } features.add(lvc + kValencyInFeaturespace); features.add(rvc + kValencyInFeaturespace); }
获取(S0和S1的)配价特征 @param ctx 上下文 @param nr_left_children 左孩子数量列表 @param nr_right_children 右孩子数量列表 @param features 输出特征
void get_cluster_features(final Context ctx, final List<Integer> cluster4, final List<Integer> cluster6, final List<Integer> cluster, List<Integer> features) { if (!use_cluster) { return; } PUSH(features, CLUSTER(cluster, ctx.S0)); PUSH(features, CLUSTER4(cluster4, ctx.S0)); PUSH(features, CLUSTER6(cluster6, ctx.S0)); PUSH(features, CLUSTER(cluster, ctx.S1)); PUSH(features, CLUSTER(cluster, ctx.S2)); PUSH(features, CLUSTER(cluster, ctx.N0)); PUSH(features, CLUSTER4(cluster4, ctx.N0)); PUSH(features, CLUSTER6(cluster6, ctx.N0)); PUSH(features, CLUSTER(cluster, ctx.N1)); PUSH(features, CLUSTER(cluster, ctx.N2)); PUSH(features, CLUSTER(cluster, ctx.S0L)); PUSH(features, CLUSTER(cluster, ctx.S0R)); PUSH(features, CLUSTER(cluster, ctx.S0L2)); PUSH(features, CLUSTER(cluster, ctx.S0R2)); PUSH(features, CLUSTER(cluster, ctx.S0LL)); PUSH(features, CLUSTER(cluster, ctx.S0RR)); PUSH(features, CLUSTER(cluster, ctx.S1L)); PUSH(features, CLUSTER(cluster, ctx.S1R)); PUSH(features, CLUSTER(cluster, ctx.S1L2)); PUSH(features, CLUSTER(cluster, ctx.S1R2)); PUSH(features, CLUSTER(cluster, ctx.S1LL)); PUSH(features, CLUSTER(cluster, ctx.S1RR)); }
获取词聚类特征 @param ctx 上下文 @param cluster4 @param cluster6 @param cluster @param features 输出特征
public Result getResult(boolean percentage) { float p = A_cap_B_size / (float) B_size; float r = A_cap_B_size / (float) A_size; if (percentage) { p *= 100; r *= 100; } float oov_r = Float.NaN; if (OOV > 0) { oov_r = OOV_R / (float) OOV; if (percentage) oov_r *= 100; } float iv_r = Float.NaN; if (IV > 0) { iv_r = IV_R / (float) IV; if (percentage) iv_r *= 100; } return new Result(p, r, 2 * p * r / (p + r), oov_r, iv_r); }
获取PRF @param percentage 百分制 @return
public void compare(String gold, String pred) { String[] wordArray = gold.split("\\s+"); A_size += wordArray.length; String[] predArray = pred.split("\\s+"); B_size += predArray.length; int goldIndex = 0, predIndex = 0; int goldLen = 0, predLen = 0; while (goldIndex < wordArray.length && predIndex < predArray.length) { if (goldLen == predLen) { if (wordArray[goldIndex].equals(predArray[predIndex])) { if (dic != null) { if (dic.contains(wordArray[goldIndex])) IV_R += 1; else OOV_R += 1; } A_cap_B_size++; goldLen += wordArray[goldIndex].length(); predLen += wordArray[goldIndex].length(); goldIndex++; predIndex++; } else { goldLen += wordArray[goldIndex].length(); predLen += predArray[predIndex].length(); goldIndex++; predIndex++; } } else if (goldLen < predLen) { goldLen += wordArray[goldIndex].length(); goldIndex++; } else { predLen += predArray[predIndex].length(); predIndex++; } } if (dic != null) { for (String word : wordArray) { if (dic.contains(word)) IV += 1; else OOV += 1; } } }
比较标准答案与分词结果 @param gold @param pred
public static Result evaluate(String goldFile, String predFile) throws IOException { return evaluate(goldFile, predFile, null); }
在标准答案与分词结果上执行评测 @param goldFile @param predFile @return
public static CWSEvaluator.Result evaluate(Segment segment, String outputPath, String goldFile, String dictPath) throws IOException { IOUtil.LineIterator lineIterator = new IOUtil.LineIterator(goldFile); BufferedWriter bw = IOUtil.newBufferedWriter(outputPath); for (String line : lineIterator) { List<Term> termList = segment.seg(line.replaceAll("\\s+", "")); // 一些testFile与goldFile根本不匹配,比如MSR的testFile有些行缺少单词,所以用goldFile去掉空格代替 int i = 0; for (Term term : termList) { bw.write(term.word); if (++i != termList.size()) bw.write(" "); } bw.newLine(); } bw.close(); CWSEvaluator.Result result = CWSEvaluator.evaluate(goldFile, outputPath, dictPath); return result; }
标准化评测分词器 @param segment 分词器 @param outputPath 分词预测输出文件 @param goldFile 测试集segmented file @param dictPath 训练集单词列表 @return 一个储存准确率的结构 @throws IOException
public static CWSEvaluator.Result evaluate(Segment segment, String testFile, String outputPath, String goldFile, String dictPath) throws IOException { return evaluate(segment, outputPath, goldFile, dictPath); }
标准化评测分词器 @param segment 分词器 @param testFile 测试集raw text @param outputPath 分词预测输出文件 @param goldFile 测试集segmented file @param dictPath 训练集单词列表 @return 一个储存准确率的结构 @throws IOException
public static Result evaluate(String goldFile, String predFile, String dictPath) throws IOException { IOUtil.LineIterator goldIter = new IOUtil.LineIterator(goldFile); IOUtil.LineIterator predIter = new IOUtil.LineIterator(predFile); CWSEvaluator evaluator = new CWSEvaluator(dictPath); while (goldIter.hasNext() && predIter.hasNext()) { evaluator.compare(goldIter.next(), predIter.next()); } return evaluator.getResult(); }
在标准答案与分词结果上执行评测 @param goldFile @param predFile @return
protected static void generateWord(List<Vertex> linkedArray, WordNet wordNetOptimum) { fixResultByRule(linkedArray); //-------------------------------------------------------------------- // 建造新词网 wordNetOptimum.addAll(linkedArray); }
对粗分结果执行一些规则上的合并拆分等等,同时合成新词网 @param linkedArray 粗分结果 @param wordNetOptimum 合并了所有粗分结果的词网
protected static void fixResultByRule(List<Vertex> linkedArray) { //-------------------------------------------------------------------- //Merge all seperate continue num into one number mergeContinueNumIntoOne(linkedArray); //-------------------------------------------------------------------- //The delimiter "--" changeDelimiterPOS(linkedArray); //-------------------------------------------------------------------- //如果前一个词是数字,当前词以“-”或“-”开始,并且不止这一个字符, //那么将此“-”符号从当前词中分离出来。 //例如 “3 / -4 / 月”需要拆分成“3 / - / 4 / 月” splitMiddleSlashFromDigitalWords(linkedArray); //-------------------------------------------------------------------- //1、如果当前词是数字,下一个词是“月、日、时、分、秒、月份”中的一个,则合并,且当前词词性是时间 //2、如果当前词是可以作为年份的数字,下一个词是“年”,则合并,词性为时间,否则为数字。 //3、如果最后一个汉字是"点" ,则认为当前数字是时间 //4、如果当前串最后一个汉字不是"∶·./"和半角的'.''/',那么是数 //5、当前串最后一个汉字是"∶·./"和半角的'.''/',且长度大于1,那么去掉最后一个字符。例如"1." checkDateElements(linkedArray); }
通过规则修正一些结果 @param linkedArray
private static void splitMiddleSlashFromDigitalWords(List<Vertex> linkedArray) { if (linkedArray.size() < 2) return; ListIterator<Vertex> listIterator = linkedArray.listIterator(); Vertex next = listIterator.next(); Vertex current = next; while (listIterator.hasNext()) { next = listIterator.next(); // System.out.println("current:" + current + " next:" + next); Nature currentNature = current.getNature(); if (currentNature == Nature.nx && (next.hasNature(Nature.q) || next.hasNature(Nature.n))) { String[] param = current.realWord.split("-", 1); if (param.length == 2) { if (TextUtility.isAllNum(param[0]) && TextUtility.isAllNum(param[1])) { current = current.copy(); current.realWord = param[0]; current.confirmNature(Nature.m); listIterator.previous(); listIterator.previous(); listIterator.set(current); listIterator.next(); listIterator.add(Vertex.newPunctuationInstance("-")); listIterator.add(Vertex.newNumberInstance(param[1])); } } } current = next; } // logger.trace("杠号识别后:" + Graph.parseResult(linkedArray)); }
====================================================================
private static void checkDateElements(List<Vertex> linkedArray) { if (linkedArray.size() < 2) return; ListIterator<Vertex> listIterator = linkedArray.listIterator(); Vertex next = listIterator.next(); Vertex current = next; while (listIterator.hasNext()) { next = listIterator.next(); if (TextUtility.isAllNum(current.realWord) || TextUtility.isAllChineseNum(current.realWord)) { //===== 1、如果当前词是数字,下一个词是“月、日、时、分、秒、月份”中的一个,则合并且当前词词性是时间 String nextWord = next.realWord; if ((nextWord.length() == 1 && "月日时分秒".contains(nextWord)) || (nextWord.length() == 2 && nextWord.equals("月份"))) { mergeDate(listIterator, next, current); } //===== 2、如果当前词是可以作为年份的数字,下一个词是“年”,则合并,词性为时间,否则为数字。 else if (nextWord.equals("年")) { if (TextUtility.isYearTime(current.realWord)) { mergeDate(listIterator, next, current); } //===== 否则当前词就是数字了 ===== else { current.confirmNature(Nature.m); } } else { //===== 3、如果最后一个汉字是"点" ,则认为当前数字是时间 if (current.realWord.endsWith("点")) { current.confirmNature(Nature.t, true); } else { char[] tmpCharArray = current.realWord.toCharArray(); String lastChar = String.valueOf(tmpCharArray[tmpCharArray.length - 1]); //===== 4、如果当前串最后一个汉字不是"∶·./"和半角的'.''/',那么是数 if (!"∶·././".contains(lastChar)) { current.confirmNature(Nature.m, true); } //===== 5、当前串最后一个汉字是"∶·./"和半角的'.''/',且长度大于1,那么去掉最后一个字符。例如"1." else if (current.realWord.length() > 1) { char last = current.realWord.charAt(current.realWord.length() - 1); current = Vertex.newNumberInstance(current.realWord.substring(0, current.realWord.length() - 1)); listIterator.previous(); listIterator.previous(); listIterator.set(current); listIterator.next(); listIterator.add(Vertex.newPunctuationInstance(String.valueOf(last))); } } } } current = next; } // logger.trace("日期识别后:" + Graph.parseResult(linkedArray)); }
====================================================================
private static List<AtomNode> atomSegment(String sSentence, int start, int end) { if (end < start) { throw new RuntimeException("start=" + start + " < end=" + end); } List<AtomNode> atomSegment = new ArrayList<AtomNode>(); int pCur = 0, nCurType, nNextType; StringBuilder sb = new StringBuilder(); char c; //============================================================================================== // by zhenyulu: // // TODO: 使用一系列正则表达式将句子中的完整成分(百分比、日期、电子邮件、URL等)预先提取出来 //============================================================================================== char[] charArray = sSentence.substring(start, end).toCharArray(); int[] charTypeArray = new int[charArray.length]; // 生成对应单个汉字的字符类型数组 for (int i = 0; i < charArray.length; ++i) { c = charArray[i]; charTypeArray[i] = CharType.get(c); if (c == '.' && i < (charArray.length - 1) && CharType.get(charArray[i + 1]) == CharType.CT_NUM) charTypeArray[i] = CharType.CT_NUM; else if (c == '.' && i < (charArray.length - 1) && charArray[i + 1] >= '0' && charArray[i + 1] <= '9') charTypeArray[i] = CharType.CT_SINGLE; else if (charTypeArray[i] == CharType.CT_LETTER) charTypeArray[i] = CharType.CT_SINGLE; } // 根据字符类型数组中的内容完成原子切割 while (pCur < charArray.length) { nCurType = charTypeArray[pCur]; if (nCurType == CharType.CT_CHINESE || nCurType == CharType.CT_INDEX || nCurType == CharType.CT_DELIMITER || nCurType == CharType.CT_OTHER) { String single = String.valueOf(charArray[pCur]); if (single.length() != 0) atomSegment.add(new AtomNode(single, nCurType)); pCur++; } //如果是字符、数字或者后面跟随了数字的小数点“.”则一直取下去。 else if (pCur < charArray.length - 1 && ((nCurType == CharType.CT_SINGLE) || nCurType == CharType.CT_NUM)) { sb.delete(0, sb.length()); sb.append(charArray[pCur]); boolean reachEnd = true; while (pCur < charArray.length - 1) { nNextType = charTypeArray[++pCur]; if (nNextType == nCurType) sb.append(charArray[pCur]); else { reachEnd = false; break; } } atomSegment.add(new AtomNode(sb.toString(), nCurType)); if (reachEnd) pCur++; } // 对于所有其它情况 else { atomSegment.add(new AtomNode(charArray[pCur], nCurType)); pCur++; } } // logger.trace("原子分词:" + atomSegment); return atomSegment; }
原子分词 @param sSentence @param start @param end @return @deprecated 应该使用字符数组的版本
private static void mergeContinueNumIntoOne(List<Vertex> linkedArray) { if (linkedArray.size() < 2) return; ListIterator<Vertex> listIterator = linkedArray.listIterator(); Vertex next = listIterator.next(); Vertex current = next; while (listIterator.hasNext()) { next = listIterator.next(); // System.out.println("current:" + current + " next:" + next); if ((TextUtility.isAllNum(current.realWord) || TextUtility.isAllChineseNum(current.realWord)) && (TextUtility.isAllNum(next.realWord) || TextUtility.isAllChineseNum(next.realWord))) { /////////// 这部分从逻辑上等同于current.realWord = current.realWord + next.realWord; // 但是current指针被几个路径共享,需要备份,不然修改了一处就修改了全局 current = Vertex.newNumberInstance(current.realWord + next.realWord); listIterator.previous(); listIterator.previous(); listIterator.set(current); listIterator.next(); listIterator.next(); /////////// end 这部分 // System.out.println("before:" + linkedArray); listIterator.remove(); // System.out.println("after:" + linkedArray); } else { current = next; } } // logger.trace("数字识别后:" + Graph.parseResult(linkedArray)); }
将连续的数字节点合并为一个 @param linkedArray
protected void generateWordNet(final WordNet wordNetStorage) { final char[] charArray = wordNetStorage.charArray; // 核心词典查询 DoubleArrayTrie<CoreDictionary.Attribute>.Searcher searcher = CoreDictionary.trie.getSearcher(charArray, 0); while (searcher.next()) { wordNetStorage.add(searcher.begin + 1, new Vertex(new String(charArray, searcher.begin, searcher.length), searcher.value, searcher.index)); } // 强制用户词典查询 if (config.forceCustomDictionary) { CustomDictionary.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute>() { @Override public void hit(int begin, int end, CoreDictionary.Attribute value) { wordNetStorage.add(begin + 1, new Vertex(new String(charArray, begin, end - begin), value)); } }); } // 原子分词,保证图连通 LinkedList<Vertex>[] vertexes = wordNetStorage.getVertexes(); for (int i = 1; i < vertexes.length; ) { if (vertexes[i].isEmpty()) { int j = i + 1; for (; j < vertexes.length - 1; ++j) { if (!vertexes[j].isEmpty()) break; } wordNetStorage.add(i, quickAtomSegment(charArray, i - 1, j - 1)); i = j; } else i += vertexes[i].getLast().realWord.length(); } }
生成一元词网 @param wordNetStorage
protected List<Term> decorateResultForIndexMode(List<Vertex> vertexList, WordNet wordNetAll) { List<Term> termList = new LinkedList<Term>(); int line = 1; ListIterator<Vertex> listIterator = vertexList.listIterator(); listIterator.next(); int length = vertexList.size() - 2; for (int i = 0; i < length; ++i) { Vertex vertex = listIterator.next(); Term termMain = convert(vertex); termList.add(termMain); termMain.offset = line - 1; if (vertex.realWord.length() > 2) { // 过长词所在的行 int currentLine = line; while (currentLine < line + vertex.realWord.length()) { Iterator<Vertex> iterator = wordNetAll.descendingIterator(currentLine);// 这一行的词,逆序遍历保证字典序稳定地由大到小 while (iterator.hasNext())// 这一行的短词 { Vertex smallVertex = iterator.next(); if ( ((termMain.nature == Nature.mq && smallVertex.hasNature(Nature.q)) || smallVertex.realWord.length() >= config.indexMode) && smallVertex != vertex // 防止重复添加 && currentLine + smallVertex.realWord.length() <= line + vertex.realWord.length() // 防止超出边界 ) { listIterator.add(smallVertex); Term termSub = convert(smallVertex); termSub.offset = currentLine - 1; termList.add(termSub); } } ++currentLine; } } line += vertex.realWord.length(); } return termList; }
为了索引模式修饰结果 @param vertexList @param wordNetAll
public void build(Keyset keyset) { if (keyset.hasValues()) { DawgBuilder dawgBuilder = new DawgBuilder(); buildDawg(keyset, dawgBuilder); buildFromDawg(dawgBuilder); dawgBuilder.clear(); } else { buildFromKeyset(keyset); } }
构建 @param keyset
private void buildDawg(Keyset keyset, DawgBuilder dawgBuilder) { dawgBuilder.init(); for (int i = 0; i < keyset.numKeys(); ++i) { dawgBuilder.insert(keyset.getKey(i), keyset.getValue(i)); } dawgBuilder.finish(); }
构建 @param keyset @param dawgBuilder
public int parse(List<String> words, List<String> postags, List<Integer> heads, List<String> deprels) { Instance inst = new Instance(); inst.forms.add(SpecialOption.ROOT); inst.postags.add(SpecialOption.ROOT); for (int i = 0; i < words.size(); i++) { inst.forms.add(words.get(i)); inst.postags.add(postags.get(i)); } parser.predict(inst, heads, deprels); heads.remove(0); deprels.remove(0); return heads.size(); }
分析句法 @param words 词语列表 @param postags 词性列表 @param heads 输出依存指向列表 @param deprels 输出依存名称列表 @return 节点的个数
public void enQueue(QueueElement newElement) { QueueElement pCur = pHead, pPre = null; while (pCur != null && pCur.weight < newElement.weight) { pPre = pCur; pCur = pCur.next; } newElement.next = pCur; if (pPre == null) pHead = newElement; else pPre.next = newElement; }
将QueueElement根据eWeight由小到大的顺序插入队列 @param newElement
public QueueElement deQueue() { if (pHead == null) return null; QueueElement pRet = pHead; pHead = pHead.next; return pRet; }
从队列中取出前面的一个元素 @return
public void build(byte[][] keys, int[] values) { Keyset keyset = new Keyset(keys, values); DoubleArrayBuilder builder = new DoubleArrayBuilder(); builder.build(keyset); _array = builder.copy(); }
构建 @param keys 字节形式的键 @param values 值
public void open(InputStream stream) throws IOException { int size = (int) (stream.available() / UNIT_SIZE); _array = new int[size]; DataInputStream in = null; try { in = new DataInputStream(new BufferedInputStream( stream)); for (int i = 0; i < size; ++i) { _array[i] = in.readInt(); } } finally { if (in != null) { in.close(); } } }
Read from a stream. The stream must implement the available() method. @param stream @throws java.io.IOException
public void save(OutputStream stream) throws IOException { DataOutputStream out = null; try { out = new DataOutputStream(new BufferedOutputStream( stream)); for (int i = 0; i < _array.length; ++i) { out.writeInt(_array[i]); } } finally { if (out != null) { out.close(); } } }
Saves the trie data into a stream. @param stream @throws java.io.IOException
public int exactMatchSearch(byte[] key) { int unit = _array[0]; int nodePos = 0; for (byte b : key) { // nodePos ^= unit.offset() ^ b nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)) ^ (b & 0xFF); unit = _array[nodePos]; // if (unit.label() != b) if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff)) { return -1; } } // if (!unit.has_leaf()) { if (((unit >>> 8) & 1) != 1) { return -1; } // unit = _array[nodePos ^ unit.offset()]; unit = _array[nodePos ^ ((unit >>> 10) << ((unit & (1 << 9)) >>> 6))]; // return unit.value(); return unit & ((1 << 31) - 1); }
Returns the corresponding value if the key is found. Otherwise returns -1. @param key search key @return found value
public List<Pair<Integer, Integer>> commonPrefixSearch(byte[] key, int offset, int maxResults) { ArrayList<Pair<Integer, Integer>> result = new ArrayList<Pair<Integer, Integer>>(); int unit = _array[0]; int nodePos = 0; // nodePos ^= unit.offset(); nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)); for (int i = offset; i < key.length; ++i) { byte b = key[i]; nodePos ^= (b & 0xff); unit = _array[nodePos]; // if (unit.label() != b) { if ((unit & ((1 << 31) | 0xFF)) != (b & 0xff)) { return result; } // nodePos ^= unit.offset(); nodePos ^= ((unit >>> 10) << ((unit & (1 << 9)) >>> 6)); // if (unit.has_leaf()) { if (((unit >>> 8) & 1) == 1) { if (result.size() < maxResults) { // result.add(new Pair<i, _array[nodePos].value()); result.add(new Pair<Integer, Integer>(i + 1, _array[nodePos] & ((1 << 31) - 1))); } } } return result; }
Returns the keys that begins with the given key and its corresponding values. The first of the returned pair represents the length of the found key. @param key @param offset @param maxResults @return found keys and values
private void writeArrayHeader(ByteBufAllocator allocator, ArrayHeaderRedisMessage msg, List<Object> out) { writeArrayHeader(allocator, msg.isNull(), msg.length(), out); }
Write array header only without body. Use this if you want to write arrays as streaming.
private void writeArrayMessage(ByteBufAllocator allocator, ArrayRedisMessage msg, List<Object> out) { if (msg.isNull()) { writeArrayHeader(allocator, msg.isNull(), RedisConstants.NULL_VALUE, out); } else { writeArrayHeader(allocator, msg.isNull(), msg.children().size(), out); for (RedisMessage child : msg.children()) { writeRedisMessage(allocator, child, out); } } }
Write full constructed array message.
private static byte[] readFrom(File src) throws IOException { long srcsize = src.length(); if (srcsize > Integer.MAX_VALUE) { throw new IllegalArgumentException( "File too big to be loaded in memory"); } FileInputStream inputStream = new FileInputStream(src); byte[] array = new byte[(int) srcsize]; try { FileChannel fileChannel = inputStream.getChannel(); ByteBuffer byteBuffer = ByteBuffer.wrap(array); int read = 0; while (read < srcsize) { read += fileChannel.read(byteBuffer); } } finally { inputStream.close(); } return array; }
Utility function @return the array of bytes
public static ByteBuf wrappedBuffer(byte[] array) { if (array.length == 0) { return EMPTY_BUFFER; } return new UnpooledHeapByteBuf(ALLOC, array, array.length); }
Creates a new big-endian buffer which wraps the specified {@code array}. A modification on the specified array's content will be visible to the returned buffer.
public static ByteBuf wrappedBuffer(byte[] array, int offset, int length) { if (length == 0) { return EMPTY_BUFFER; } if (offset == 0 && length == array.length) { return wrappedBuffer(array); } return wrappedBuffer(array).slice(offset, length); }
Creates a new big-endian buffer which wraps the sub-region of the specified {@code array}. A modification on the specified array's content will be visible to the returned buffer.
public static ByteBuf wrappedBuffer(ByteBuffer buffer) { if (!buffer.hasRemaining()) { return EMPTY_BUFFER; } if (!buffer.isDirect() && buffer.hasArray()) { return wrappedBuffer( buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()).order(buffer.order()); } else if (PlatformDependent.hasUnsafe()) { if (buffer.isReadOnly()) { if (buffer.isDirect()) { return new ReadOnlyUnsafeDirectByteBuf(ALLOC, buffer); } else { return new ReadOnlyByteBufferBuf(ALLOC, buffer); } } else { return new UnpooledUnsafeDirectByteBuf(ALLOC, buffer, buffer.remaining()); } } else { if (buffer.isReadOnly()) { return new ReadOnlyByteBufferBuf(ALLOC, buffer); } else { return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining()); } } }
Creates a new buffer which wraps the specified NIO buffer's current slice. A modification on the specified buffer's content will be visible to the returned buffer.
public static ByteBuf wrappedBuffer(long memoryAddress, int size, boolean doFree) { return new WrappedUnpooledUnsafeDirectByteBuf(ALLOC, memoryAddress, size, doFree); }
Creates a new buffer which wraps the specified memory address. If {@code doFree} is true the memoryAddress will automatically be freed once the reference count of the {@link ByteBuf} reaches {@code 0}.
public static ByteBuf wrappedBuffer(ByteBuf buffer) { if (buffer.isReadable()) { return buffer.slice(); } else { buffer.release(); return EMPTY_BUFFER; } }
Creates a new buffer which wraps the specified buffer's readable bytes. A modification on the specified buffer's content will be visible to the returned buffer. @param buffer The buffer to wrap. Reference count ownership of this variable is transferred to this method. @return The readable portion of the {@code buffer}, or an empty buffer if there is no readable portion. The caller is responsible for releasing this buffer.
public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuf... buffers) { switch (buffers.length) { case 0: break; case 1: ByteBuf buffer = buffers[0]; if (buffer.isReadable()) { return wrappedBuffer(buffer.order(BIG_ENDIAN)); } else { buffer.release(); } break; default: for (int i = 0; i < buffers.length; i++) { ByteBuf buf = buffers[i]; if (buf.isReadable()) { return new CompositeByteBuf(ALLOC, false, maxNumComponents, buffers, i); } buf.release(); } break; } return EMPTY_BUFFER; }
Creates a new big-endian composite buffer which wraps the readable bytes of the specified buffers without copying them. A modification on the content of the specified buffers will be visible to the returned buffer. @param maxNumComponents Advisement as to how many independent buffers are allowed to exist before consolidation occurs. @param buffers The buffers to wrap. Reference count ownership of all variables is transferred to this method. @return The readable portion of the {@code buffers}. The caller is responsible for releasing this buffer.
public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuffer... buffers) { return wrappedBuffer(maxNumComponents, CompositeByteBuf.BYTE_BUFFER_WRAPPER, buffers); }
Creates a new big-endian composite buffer which wraps the slices of the specified NIO buffers without copying them. A modification on the content of the specified buffers will be visible to the returned buffer.
public static ByteBuf copiedBuffer(byte[] array, int offset, int length) { if (length == 0) { return EMPTY_BUFFER; } byte[] copy = PlatformDependent.allocateUninitializedArray(length); System.arraycopy(array, offset, copy, 0, length); return wrappedBuffer(copy); }
Creates a new big-endian buffer whose content is a copy of the specified {@code array}'s sub-region. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the specified {@code length} respectively.
public static ByteBuf copiedBuffer(ByteBuffer buffer) { int length = buffer.remaining(); if (length == 0) { return EMPTY_BUFFER; } byte[] copy = PlatformDependent.allocateUninitializedArray(length); // Duplicate the buffer so we not adjust the position during our get operation. // See https://github.com/netty/netty/issues/3896 ByteBuffer duplicate = buffer.duplicate(); duplicate.get(copy); return wrappedBuffer(copy).order(duplicate.order()); }
Creates a new buffer whose content is a copy of the specified {@code buffer}'s current slice. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and {@code buffer.remaining} respectively.
public static ByteBuf copiedBuffer(ByteBuf buffer) { int readable = buffer.readableBytes(); if (readable > 0) { ByteBuf copy = buffer(readable); copy.writeBytes(buffer, buffer.readerIndex(), readable); return copy; } else { return EMPTY_BUFFER; } }
Creates a new buffer whose content is a copy of the specified {@code buffer}'s readable bytes. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and {@code buffer.readableBytes} respectively.
public static ByteBuf copiedBuffer(byte[]... arrays) { switch (arrays.length) { case 0: return EMPTY_BUFFER; case 1: if (arrays[0].length == 0) { return EMPTY_BUFFER; } else { return copiedBuffer(arrays[0]); } } // Merge the specified arrays into one array. int length = 0; for (byte[] a: arrays) { if (Integer.MAX_VALUE - length < a.length) { throw new IllegalArgumentException( "The total length of the specified arrays is too big."); } length += a.length; } if (length == 0) { return EMPTY_BUFFER; } byte[] mergedArray = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = 0; i < arrays.length; i ++) { byte[] a = arrays[i]; System.arraycopy(a, 0, mergedArray, j, a.length); j += a.length; } return wrappedBuffer(mergedArray); }
Creates a new big-endian buffer whose content is a merged copy of the specified {@code arrays}. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the sum of all arrays' {@code length} respectively.
public static ByteBuf copiedBuffer(ByteBuf... buffers) { switch (buffers.length) { case 0: return EMPTY_BUFFER; case 1: return copiedBuffer(buffers[0]); } // Merge the specified buffers into one buffer. ByteOrder order = null; int length = 0; for (ByteBuf b: buffers) { int bLen = b.readableBytes(); if (bLen <= 0) { continue; } if (Integer.MAX_VALUE - length < bLen) { throw new IllegalArgumentException( "The total length of the specified buffers is too big."); } length += bLen; if (order != null) { if (!order.equals(b.order())) { throw new IllegalArgumentException("inconsistent byte order"); } } else { order = b.order(); } } if (length == 0) { return EMPTY_BUFFER; } byte[] mergedArray = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = 0; i < buffers.length; i ++) { ByteBuf b = buffers[i]; int bLen = b.readableBytes(); b.getBytes(b.readerIndex(), mergedArray, j, bLen); j += bLen; } return wrappedBuffer(mergedArray).order(order); }
Creates a new buffer whose content is a merged copy of the specified {@code buffers}' readable bytes. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the sum of all buffers' {@code readableBytes} respectively. @throws IllegalArgumentException if the specified buffers' endianness are different from each other
public static ByteBuf copiedBuffer(ByteBuffer... buffers) { switch (buffers.length) { case 0: return EMPTY_BUFFER; case 1: return copiedBuffer(buffers[0]); } // Merge the specified buffers into one buffer. ByteOrder order = null; int length = 0; for (ByteBuffer b: buffers) { int bLen = b.remaining(); if (bLen <= 0) { continue; } if (Integer.MAX_VALUE - length < bLen) { throw new IllegalArgumentException( "The total length of the specified buffers is too big."); } length += bLen; if (order != null) { if (!order.equals(b.order())) { throw new IllegalArgumentException("inconsistent byte order"); } } else { order = b.order(); } } if (length == 0) { return EMPTY_BUFFER; } byte[] mergedArray = PlatformDependent.allocateUninitializedArray(length); for (int i = 0, j = 0; i < buffers.length; i ++) { // Duplicate the buffer so we not adjust the position during our get operation. // See https://github.com/netty/netty/issues/3896 ByteBuffer b = buffers[i].duplicate(); int bLen = b.remaining(); b.get(mergedArray, j, bLen); j += bLen; } return wrappedBuffer(mergedArray).order(order); }
Creates a new buffer whose content is a merged copy of the specified {@code buffers}' slices. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the sum of all buffers' {@code remaining} respectively. @throws IllegalArgumentException if the specified buffers' endianness are different from each other
public static ByteBuf copiedBuffer(CharSequence string, Charset charset) { if (string == null) { throw new NullPointerException("string"); } if (string instanceof CharBuffer) { return copiedBuffer((CharBuffer) string, charset); } return copiedBuffer(CharBuffer.wrap(string), charset); }
Creates a new big-endian buffer whose content is the specified {@code string} encoded in the specified {@code charset}. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the length of the encoded string respectively.
public static ByteBuf copiedBuffer( CharSequence string, int offset, int length, Charset charset) { if (string == null) { throw new NullPointerException("string"); } if (length == 0) { return EMPTY_BUFFER; } if (string instanceof CharBuffer) { CharBuffer buf = (CharBuffer) string; if (buf.hasArray()) { return copiedBuffer( buf.array(), buf.arrayOffset() + buf.position() + offset, length, charset); } buf = buf.slice(); buf.limit(length); buf.position(offset); return copiedBuffer(buf, charset); } return copiedBuffer(CharBuffer.wrap(string, offset, offset + length), charset); }
Creates a new big-endian buffer whose content is a subregion of the specified {@code string} encoded in the specified {@code charset}. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the length of the encoded string respectively.
public static ByteBuf copiedBuffer(char[] array, Charset charset) { if (array == null) { throw new NullPointerException("array"); } return copiedBuffer(array, 0, array.length, charset); }
Creates a new big-endian buffer whose content is the specified {@code array} encoded in the specified {@code charset}. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the length of the encoded string respectively.
public static ByteBuf copiedBuffer(char[] array, int offset, int length, Charset charset) { if (array == null) { throw new NullPointerException("array"); } if (length == 0) { return EMPTY_BUFFER; } return copiedBuffer(CharBuffer.wrap(array, offset, length), charset); }
Creates a new big-endian buffer whose content is a subregion of the specified {@code array} encoded in the specified {@code charset}. The new buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the length of the encoded string respectively.
@Deprecated public static ByteBuf unmodifiableBuffer(ByteBuf buffer) { ByteOrder endianness = buffer.order(); if (endianness == BIG_ENDIAN) { return new ReadOnlyByteBuf(buffer); } return new ReadOnlyByteBuf(buffer.order(BIG_ENDIAN)).order(LITTLE_ENDIAN); }
Creates a read-only buffer which disallows any modification operations on the specified {@code buffer}. The new buffer has the same {@code readerIndex} and {@code writerIndex} with the specified {@code buffer}. @deprecated Use {@link ByteBuf#asReadOnly()}.
public static ByteBuf copyInt(int value) { ByteBuf buf = buffer(4); buf.writeInt(value); return buf; }
Creates a new 4-byte big-endian buffer that holds the specified 32-bit integer.
public static ByteBuf copyInt(int... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 4); for (int v: values) { buffer.writeInt(v); } return buffer; }
Create a big-endian buffer that holds a sequence of the specified 32-bit integers.
public static ByteBuf copyShort(int value) { ByteBuf buf = buffer(2); buf.writeShort(value); return buf; }
Creates a new 2-byte big-endian buffer that holds the specified 16-bit integer.
public static ByteBuf copyShort(short... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 2); for (int v: values) { buffer.writeShort(v); } return buffer; }
Create a new big-endian buffer that holds a sequence of the specified 16-bit integers.
public static ByteBuf copyMedium(int value) { ByteBuf buf = buffer(3); buf.writeMedium(value); return buf; }
Creates a new 3-byte big-endian buffer that holds the specified 24-bit integer.
public static ByteBuf copyMedium(int... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 3); for (int v: values) { buffer.writeMedium(v); } return buffer; }
Create a new big-endian buffer that holds a sequence of the specified 24-bit integers.
public static ByteBuf copyLong(long value) { ByteBuf buf = buffer(8); buf.writeLong(value); return buf; }
Creates a new 8-byte big-endian buffer that holds the specified 64-bit integer.
public static ByteBuf copyLong(long... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 8); for (long v: values) { buffer.writeLong(v); } return buffer; }
Create a new big-endian buffer that holds a sequence of the specified 64-bit integers.
public static ByteBuf copyBoolean(boolean value) { ByteBuf buf = buffer(1); buf.writeBoolean(value); return buf; }
Creates a new single-byte big-endian buffer that holds the specified boolean value.
public static ByteBuf copyBoolean(boolean... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length); for (boolean v: values) { buffer.writeBoolean(v); } return buffer; }
Create a new big-endian buffer that holds a sequence of the specified boolean values.
public static ByteBuf copyFloat(float value) { ByteBuf buf = buffer(4); buf.writeFloat(value); return buf; }
Creates a new 4-byte big-endian buffer that holds the specified 32-bit floating point number.
public static ByteBuf copyFloat(float... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 4); for (float v: values) { buffer.writeFloat(v); } return buffer; }
Create a new big-endian buffer that holds a sequence of the specified 32-bit floating point numbers.
public static ByteBuf copyDouble(double value) { ByteBuf buf = buffer(8); buf.writeDouble(value); return buf; }
Creates a new 8-byte big-endian buffer that holds the specified 64-bit floating point number.
public static ByteBuf copyDouble(double... values) { if (values == null || values.length == 0) { return EMPTY_BUFFER; } ByteBuf buffer = buffer(values.length * 8); for (double v: values) { buffer.writeDouble(v); } return buffer; }
Create a new big-endian buffer that holds a sequence of the specified 64-bit floating point numbers.
private static void encodeExtras(ByteBuf buf, ByteBuf extras) { if (extras == null || !extras.isReadable()) { return; } buf.writeBytes(extras); }
Encode the extras. @param buf the {@link ByteBuf} to write into. @param extras the extras to encode.
private static void encodeKey(ByteBuf buf, ByteBuf key) { if (key == null || !key.isReadable()) { return; } buf.writeBytes(key); }
Encode the key. @param buf the {@link ByteBuf} to write into. @param key the key to encode.
public AddressResolver<InetSocketAddress> asAddressResolver() { AddressResolver<InetSocketAddress> result = addressResolver; if (result == null) { synchronized (this) { result = addressResolver; if (result == null) { addressResolver = result = new InetSocketAddressResolver(executor(), this); } } } return result; }
Return a {@link AddressResolver} that will use this name resolver underneath. It's cached internally, so the same instance is always returned.
public WebSocketServerHandshaker newHandshaker(HttpRequest req) { CharSequence version = req.headers().get(HttpHeaderNames.SEC_WEBSOCKET_VERSION); if (version != null) { if (version.equals(WebSocketVersion.V13.toHttpHeaderValue())) { // Version 13 of the wire protocol - RFC 6455 (version 17 of the draft hybi specification). return new WebSocketServerHandshaker13( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V08.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 10 of the draft hybi specification. return new WebSocketServerHandshaker08( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else if (version.equals(WebSocketVersion.V07.toHttpHeaderValue())) { // Version 8 of the wire protocol - version 07 of the draft hybi specification. return new WebSocketServerHandshaker07( webSocketURL, subprotocols, allowExtensions, maxFramePayloadLength, allowMaskMismatch); } else { return null; } } else { // Assume version 00 where version header was not specified return new WebSocketServerHandshaker00(webSocketURL, subprotocols, maxFramePayloadLength); } }
Instances a new handshaker @return A new WebSocketServerHandshaker for the requested web socket version. Null if web socket version is not supported.
public static ChannelFuture sendUnsupportedVersionResponse(Channel channel, ChannelPromise promise) { HttpResponse res = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.UPGRADE_REQUIRED); res.headers().set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, WebSocketVersion.V13.toHttpHeaderValue()); HttpUtil.setContentLength(res, 0); return channel.writeAndFlush(res, promise); }
Return that we need cannot not support the web socket version
static PemEncoded toPEM(ByteBufAllocator allocator, boolean useDirect, PrivateKey key) { // We can take a shortcut if the private key happens to be already // PEM/PKCS#8 encoded. This is the ideal case and reason why all // this exists. It allows the user to pass pre-encoded bytes straight // into OpenSSL without having to do any of the extra work. if (key instanceof PemEncoded) { return ((PemEncoded) key).retain(); } byte[] bytes = key.getEncoded(); if (bytes == null) { throw new IllegalArgumentException(key.getClass().getName() + " does not support encoding"); } return toPEM(allocator, useDirect, bytes); }
Creates a {@link PemEncoded} value from the {@link PrivateKey}.
public static ReadOnlyHttp2Headers clientHeaders(boolean validateHeaders, AsciiString method, AsciiString path, AsciiString scheme, AsciiString authority, AsciiString... otherHeaders) { return new ReadOnlyHttp2Headers(validateHeaders, new AsciiString[] { PseudoHeaderName.METHOD.value(), method, PseudoHeaderName.PATH.value(), path, PseudoHeaderName.SCHEME.value(), scheme, PseudoHeaderName.AUTHORITY.value(), authority }, otherHeaders); }
Create a new read only representation of headers used by clients. @param validateHeaders {@code true} will run validation on each header name/value pair to ensure protocol compliance. @param method The value for {@link PseudoHeaderName#METHOD}. @param path The value for {@link PseudoHeaderName#PATH}. @param scheme The value for {@link PseudoHeaderName#SCHEME}. @param authority The value for {@link PseudoHeaderName#AUTHORITY}. @param otherHeaders A an array of key:value pairs. Must not contain any <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.1">pseudo headers</a> or {@code null} names/values. A copy will <strong>NOT</strong> be made of this array. If the contents of this array may be modified externally you are responsible for passing in a copy. @return a new read only representation of headers used by clients.
public static ReadOnlyHttp2Headers serverHeaders(boolean validateHeaders, AsciiString status, AsciiString... otherHeaders) { return new ReadOnlyHttp2Headers(validateHeaders, new AsciiString[] { PseudoHeaderName.STATUS.value(), status }, otherHeaders); }
Create a new read only representation of headers used by servers. @param validateHeaders {@code true} will run validation on each header name/value pair to ensure protocol compliance. @param status The value for {@link PseudoHeaderName#STATUS}. @param otherHeaders A an array of key:value pairs. Must not contain any <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.1">pseudo headers</a> or {@code null} names/values. A copy will <strong>NOT</strong> be made of this array. If the contents of this array may be modified externally you are responsible for passing in a copy. @return a new read only representation of headers used by servers.
private int trGetC(final int isa, final int isaD, final int isaN, final int p) { return isaD + p < isaN ? SA[isaD + p] : SA[isa + ((isaD - isa + p) % (isaN - isa))]; }
/*----------------------------------------------------------------------------