|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package opennlp.wordnet; |
| 19 | + |
| 20 | +import java.util.ArrayDeque; |
| 21 | +import java.util.Deque; |
| 22 | +import java.util.HashMap; |
| 23 | +import java.util.LinkedHashMap; |
| 24 | +import java.util.List; |
| 25 | +import java.util.Map; |
| 26 | +import java.util.Optional; |
| 27 | + |
| 28 | +import opennlp.tools.commons.ThreadSafe; |
| 29 | +import opennlp.tools.util.StringUtil; |
| 30 | +import opennlp.tools.wordnet.LexicalKnowledgeBase; |
| 31 | +import opennlp.tools.wordnet.Synset; |
| 32 | +import opennlp.tools.wordnet.WordNetPOS; |
| 33 | +import opennlp.tools.wordnet.WordNetRelation; |
| 34 | + |
| 35 | +/** |
| 36 | + * Types a noun by walking its hypernym chain to the nearest registered anchor: the |
| 37 | + * caller names anchor concepts by lemma, {@code person}, {@code organization}, |
| 38 | + * {@code location}, and any word whose senses lead up to an anchor's synsets receives |
| 39 | + * that anchor's label. The nearest anchor wins, so a more specific registered concept |
| 40 | + * beats a general one. |
| 41 | + * |
| 42 | + * <p>Anchors are resolved against the knowledge base at construction and follow its |
| 43 | + * sense inventory; nothing beyond the caller's anchor choice is built in. Words with no |
| 44 | + * sense reaching an anchor get no type.</p> |
| 45 | + * |
| 46 | + * <p>The typer reads only immutable state and is safe to share between threads.</p> |
| 47 | + */ |
| 48 | +@ThreadSafe |
| 49 | +public class HypernymTyper { |
| 50 | + |
| 51 | + /** The relations that lead from a synset to its generalizations. */ |
| 52 | + private static final List<WordNetRelation> UPWARD_RELATIONS = |
| 53 | + List.of(WordNetRelation.HYPERNYM, WordNetRelation.INSTANCE_HYPERNYM); |
| 54 | + |
| 55 | + private final LexicalKnowledgeBase knowledgeBase; |
| 56 | + private final Map<String, String> labelBySynsetId; |
| 57 | + |
| 58 | + /** |
| 59 | + * Initializes the typer. |
| 60 | + * |
| 61 | + * @param knowledgeBase The knowledge base to walk. Must not be {@code null}. |
| 62 | + * @param anchors The anchor lemmas mapped to the labels they confer, for example |
| 63 | + * {@code person} to {@code person}. Every lemma is resolved as a noun; |
| 64 | + * all its senses anchor. Must not be {@code null} or empty, and no |
| 65 | + * lemma or label may be blank. |
| 66 | + * @throws IllegalArgumentException Thrown if a parameter is {@code null}, |
| 67 | + * {@code anchors} is empty or holds a blank entry, or an anchor lemma is |
| 68 | + * unknown to the knowledge base. |
| 69 | + */ |
| 70 | + public HypernymTyper(LexicalKnowledgeBase knowledgeBase, Map<String, String> anchors) { |
| 71 | + if (knowledgeBase == null) { |
| 72 | + throw new IllegalArgumentException("knowledgeBase must not be null"); |
| 73 | + } |
| 74 | + if (anchors == null || anchors.isEmpty()) { |
| 75 | + throw new IllegalArgumentException("anchors must not be null or empty"); |
| 76 | + } |
| 77 | + this.knowledgeBase = knowledgeBase; |
| 78 | + final Map<String, String> labels = new LinkedHashMap<>(); |
| 79 | + for (final Map.Entry<String, String> anchor : anchors.entrySet()) { |
| 80 | + if (anchor.getKey() == null || StringUtil.isBlank(anchor.getKey()) |
| 81 | + || anchor.getValue() == null || StringUtil.isBlank(anchor.getValue())) { |
| 82 | + throw new IllegalArgumentException("anchors must not contain blank entries"); |
| 83 | + } |
| 84 | + final List<Synset> senses = knowledgeBase.lookup(anchor.getKey(), WordNetPOS.NOUN); |
| 85 | + if (senses.isEmpty()) { |
| 86 | + throw new IllegalArgumentException( |
| 87 | + "anchor lemma is unknown to the knowledge base: " + anchor.getKey()); |
| 88 | + } |
| 89 | + for (final Synset sense : senses) { |
| 90 | + labels.putIfAbsent(sense.id(), anchor.getValue()); |
| 91 | + } |
| 92 | + } |
| 93 | + this.labelBySynsetId = Map.copyOf(labels); |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Types a noun by its nearest anchored hypernym. |
| 98 | + * |
| 99 | + * @param lemma The noun lemma to type. Must not be {@code null} or blank. |
| 100 | + * @return The label of the nearest anchor over all senses, or empty when no sense |
| 101 | + * reaches an anchor. |
| 102 | + * @throws IllegalArgumentException Thrown if {@code lemma} is {@code null} or blank. |
| 103 | + */ |
| 104 | + public Optional<String> type(String lemma) { |
| 105 | + if (lemma == null || StringUtil.isBlank(lemma)) { |
| 106 | + throw new IllegalArgumentException("lemma must not be null or blank"); |
| 107 | + } |
| 108 | + String bestLabel = null; |
| 109 | + int bestDistance = Integer.MAX_VALUE; |
| 110 | + for (final Synset sense : knowledgeBase.lookup(lemma, WordNetPOS.NOUN)) { |
| 111 | + final int[] distance = new int[1]; |
| 112 | + final String label = nearestAnchor(sense.id(), distance); |
| 113 | + if (label != null && distance[0] < bestDistance) { |
| 114 | + bestDistance = distance[0]; |
| 115 | + bestLabel = label; |
| 116 | + } |
| 117 | + } |
| 118 | + return Optional.ofNullable(bestLabel); |
| 119 | + } |
| 120 | + |
| 121 | + /** |
| 122 | + * Types a specific synset by its nearest anchored hypernym. |
| 123 | + * |
| 124 | + * @param synsetId The synset identifier. Must not be {@code null}. |
| 125 | + * @return The nearest anchor's label, or empty when no ancestor is anchored. |
| 126 | + * @throws IllegalArgumentException Thrown if {@code synsetId} is {@code null}. |
| 127 | + */ |
| 128 | + public Optional<String> typeSynset(String synsetId) { |
| 129 | + if (synsetId == null) { |
| 130 | + throw new IllegalArgumentException("synsetId must not be null"); |
| 131 | + } |
| 132 | + return Optional.ofNullable(nearestAnchor(synsetId, new int[1])); |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * Walks up the hypernym graph breadth first to the closest anchored synset. Visiting each |
| 137 | + * synset once bounds the walk even on cyclic data. |
| 138 | + * |
| 139 | + * @param synsetId The synset to start from. Must not be {@code null}. |
| 140 | + * @param distanceOut A single-element array that receives the edge count to the anchor found; |
| 141 | + * left untouched when no ancestor is anchored. |
| 142 | + * @return The label of the nearest anchored synset, or {@code null} when none is reachable. |
| 143 | + */ |
| 144 | + private String nearestAnchor(String synsetId, int[] distanceOut) { |
| 145 | + final Deque<String> queue = new ArrayDeque<>(); |
| 146 | + final Map<String, Integer> depths = new HashMap<>(); |
| 147 | + queue.add(synsetId); |
| 148 | + depths.put(synsetId, 0); |
| 149 | + while (!queue.isEmpty()) { |
| 150 | + final String current = queue.remove(); |
| 151 | + final String label = labelBySynsetId.get(current); |
| 152 | + if (label != null) { |
| 153 | + distanceOut[0] = depths.get(current); |
| 154 | + return label; |
| 155 | + } |
| 156 | + final int parentDepth = depths.get(current) + 1; |
| 157 | + for (final WordNetRelation relation : UPWARD_RELATIONS) { |
| 158 | + for (final String parent : knowledgeBase.related(current, relation)) { |
| 159 | + if (depths.putIfAbsent(parent, parentDepth) == null) { |
| 160 | + queue.add(parent); |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + return null; |
| 166 | + } |
| 167 | +} |
0 commit comments