You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by kr...@apache.org on 2026/08/16 01:12:55 UTC
(opennlp) 02/06: OPENNLP-1897: Address review: fold the constructor chain, split aggregation by mode
This is an automated email from the ASF dual-hosted git repository.
krickert pushed a commit to branch OPENNLP-1897-term-vectors
in repository https://gitbox.apache.org/repos/asf/opennlp.git
commit 448d1dc6561421557b0051ebbe5f292db36b7cf9
Author: Kristian Rickert <kr...@gmail.com>
AuthorDate: Tue Jul 28 07:00:16 2026 -0400
OPENNLP-1897: Address review: fold the constructor chain, split aggregation by mode
- Delegate the two convenience constructors of TermVectorAnnotator through
this(...) instead of repeating the field assignments, so the no-arg form is
defined as FULL mode and the normalizer-only form as normalizer plus FULL.
- Drop the requireMode and requireNormalizer helpers and do the null checks
inline in the two canonical constructors, matching the argument-validation
style used elsewhere in the module and keeping the thrown message next to
the parameter it guards.
- Split annotate into fullVectors and countVectors, one per Mode, so the
scoring-only path no longer carries a null span map as a mode sentinel and
the per-term branch inside the emit loop disappears. Each helper is
documented and returns the annotations in first-occurrence order, which is
the ordering the tests pin.
- Make termOf an instance method, since it is now only reached from the two
mode helpers and no longer needs to be static to be shared.
- Tighten the TermVector class javadoc: the two shapes are told apart by
whether spans() is empty, stated once, without the redundant aside about a
flag, and the closing sentence now names the invariant instead of repeating
the shape list.
- Tighten the TermVectorAnnotator class javadoc the same way, and fix the
termOf parameter doc that read "or null likewise" to spell out the
condition.
- Remove the javadoc references to AlignmentTest and DocumentPipelineExampleTest
from the test fixtures. Those tests are not part of the contract under test
here and the pointers go stale as soon as either file moves.
- Add a DigitDeletingNormalizer fixture and a pinning test for a token the
normalizer deletes entirely. It groups under the empty term rather than
being dropped, which the class javadoc promises but nothing exercised.
- Parameterize the frequency rejection test over 0, -1 and Integer.MIN_VALUE
instead of only 0, so the guard is pinned across the whole illegal range.
- Fix the span assertion in TermVectorPipelineTest. It compared
Span.getCoveredText against an equivalent subSequence of the same text,
which holds for any span, so it now asserts that the covered text equals
the vector's own term.
---
.../java/opennlp/tools/termvector/TermVector.java | 11 +-
.../tools/termvector/TermVectorAnnotator.java | 128 +++++++++++----------
.../tools/termvector/TermVectorAnnotatorTest.java | 58 +++++++++-
.../tools/termvector/TermVectorPipelineTest.java | 12 +-
.../opennlp/tools/termvector/TermVectorTest.java | 9 +-
5 files changed, 139 insertions(+), 79 deletions(-)
diff --git a/opennlp-api/src/main/java/opennlp/tools/termvector/TermVector.java b/opennlp-api/src/main/java/opennlp/tools/termvector/TermVector.java
index 7dba46c04..676bf0131 100644
--- a/opennlp-api/src/main/java/opennlp/tools/termvector/TermVector.java
+++ b/opennlp-api/src/main/java/opennlp/tools/termvector/TermVector.java
@@ -31,12 +31,11 @@ import opennlp.tools.util.Span;
* always point into the document's <em>original</em> text, never into a normalized form,
* so an index consumer can highlight every occurrence in what the caller supplied.</p>
*
- * <p>A term vector comes in one of two shapes. A <em>full</em> vector carries one span
- * per occurrence, so {@code spans().size() == frequency()}. A <em>scoring-only</em>
- * vector carries no spans at all, so consumers that only need term frequencies do not
- * pay for offset storage; the empty span list is what distinguishes the shape, never a
- * flag. These are the only legal shapes: a non-empty span list must match the frequency
- * exactly.</p>
+ * <p>A term vector comes in one of two shapes, told apart by whether {@link #spans()} is
+ * empty. A <em>full</em> vector carries one span per occurrence, so
+ * {@code spans().size() == frequency()}. A <em>scoring-only</em> vector carries no spans
+ * at all, so consumers that only need term frequencies do not pay for offset storage.
+ * There is no third shape: a non-empty span list must match the frequency exactly.</p>
*
* <p>Instances are immutable: the span list is copied on construction and the copy is
* unmodifiable.</p>
diff --git a/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java b/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java
index ff3f2af7b..e30dd6e7a 100644
--- a/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java
+++ b/opennlp-api/src/main/java/opennlp/tools/termvector/TermVectorAnnotator.java
@@ -37,14 +37,13 @@ import opennlp.tools.util.normalizer.OffsetAwareNormalizer;
* {@link TermVector} per distinct term, carrying the term string, its occurrence count,
* and (in {@link Mode#FULL full mode}) the occurrence offsets.
*
- * <p>The annotator aggregates; it does not analyze. What makes two tokens the same term
- * is decided by the inputs it is given, never by logic of its own. Without a normalizer,
- * the term is the token layer's value as-is, that is, the token's covered text in the
- * original document. With an {@link OffsetAwareNormalizer}, the whole document text is
- * normalized once with its alignment recorded, each token span is mapped forward to the
- * normalized form, and the covered normalized text is the term, so tokens that differ
- * only by a normalization fold (case, an eszett expansion, collapsed whitespace around
- * them) group together. Either way, the occurrence spans emitted in
+ * <p>Term identity comes from the annotator's inputs, not from logic of its own. Without
+ * a normalizer, the term is the token layer's value as-is, that is, the token's covered
+ * text in the original document. With an {@link OffsetAwareNormalizer}, the whole
+ * document text is normalized once with its alignment recorded, each token span is
+ * mapped forward to the normalized form, and the covered normalized text is the term, so
+ * tokens that differ only by a normalization fold (case, an eszett expansion, collapsed
+ * whitespace) group together. Either way, the occurrence spans emitted in
* {@link Mode#FULL full mode} are the token layer's own spans and therefore always
* point into the original text. A token whose normalized form is empty, for example one
* the normalizer deleted entirely, groups under the empty string rather than being
@@ -90,8 +89,7 @@ public class TermVectorAnnotator implements DocumentAnnotator {
* covered text as-is.
*/
public TermVectorAnnotator() {
- this.normalizer = null;
- this.mode = Mode.FULL;
+ this(Mode.FULL);
}
/**
@@ -101,8 +99,11 @@ public class TermVectorAnnotator implements DocumentAnnotator {
* @throws IllegalArgumentException Thrown if {@code mode} is {@code null}.
*/
public TermVectorAnnotator(Mode mode) {
+ if (mode == null) {
+ throw new IllegalArgumentException("mode must not be null");
+ }
this.normalizer = null;
- this.mode = requireMode(mode);
+ this.mode = mode;
}
/**
@@ -115,8 +116,7 @@ public class TermVectorAnnotator implements DocumentAnnotator {
* @throws IllegalArgumentException Thrown if {@code normalizer} is {@code null}.
*/
public TermVectorAnnotator(OffsetAwareNormalizer normalizer) {
- this.normalizer = requireNormalizer(normalizer);
- this.mode = Mode.FULL;
+ this(normalizer, Mode.FULL);
}
/**
@@ -130,8 +130,14 @@ public class TermVectorAnnotator implements DocumentAnnotator {
* {@code null}.
*/
public TermVectorAnnotator(OffsetAwareNormalizer normalizer, Mode mode) {
- this.normalizer = requireNormalizer(normalizer);
- this.mode = requireMode(mode);
+ if (normalizer == null) {
+ throw new IllegalArgumentException("normalizer must not be null");
+ }
+ if (mode == null) {
+ throw new IllegalArgumentException("mode must not be null");
+ }
+ this.normalizer = normalizer;
+ this.mode = mode;
}
/**
@@ -159,27 +165,57 @@ public class TermVectorAnnotator implements DocumentAnnotator {
final AlignedText aligned =
normalizer != null ? normalizer.normalizeAligned(document.text()) : null;
final String normalized = aligned != null ? aligned.normalizedString() : null;
+ return document.with(TERM_VECTORS, mode == Mode.FULL
+ ? fullVectors(tokens, aligned, normalized)
+ : countVectors(tokens, aligned, normalized));
+ }
- final Map<String, Integer> frequencies = new LinkedHashMap<>();
- // Null in SCORING_ONLY mode, so offset storage is never allocated.
- final Map<String, List<Span>> spansByTerm = mode == Mode.FULL
- ? new LinkedHashMap<>() : null;
+ /**
+ * Aggregates the tokens into full term vectors, keeping every occurrence span.
+ *
+ * @param tokens The token layer.
+ * @param aligned The normalized document text with its alignment, or {@code null} when
+ * no normalizer is present.
+ * @param normalized The normalized document text, or {@code null} when no normalizer is
+ * present.
+ * @return One annotation per distinct term, in first-occurrence order.
+ */
+ private List<Annotation<TermVector>> fullVectors(List<Annotation<String>> tokens,
+ AlignedText aligned, String normalized) {
+ final Map<String, List<Span>> spansByTerm = new LinkedHashMap<>();
for (final Annotation<String> token : tokens) {
- final String term = termOf(token, aligned, normalized);
- frequencies.merge(term, 1, Integer::sum);
- if (spansByTerm != null) {
- spansByTerm.computeIfAbsent(term, key -> new ArrayList<>()).add(token.span());
- }
+ spansByTerm.computeIfAbsent(termOf(token, aligned, normalized), key -> new ArrayList<>())
+ .add(token.span());
+ }
+ final List<Annotation<TermVector>> vectors = new ArrayList<>(spansByTerm.size());
+ for (final Map.Entry<String, List<Span>> entry : spansByTerm.entrySet()) {
+ vectors.add(Annotation.of(TermVector.withSpans(entry.getKey(), entry.getValue())));
}
+ return vectors;
+ }
+ /**
+ * Aggregates the tokens into scoring-only term vectors, so no offset storage is ever
+ * allocated.
+ *
+ * @param tokens The token layer.
+ * @param aligned The normalized document text with its alignment, or {@code null} when
+ * no normalizer is present.
+ * @param normalized The normalized document text, or {@code null} when no normalizer is
+ * present.
+ * @return One annotation per distinct term, in first-occurrence order.
+ */
+ private List<Annotation<TermVector>> countVectors(List<Annotation<String>> tokens,
+ AlignedText aligned, String normalized) {
+ final Map<String, Integer> frequencies = new LinkedHashMap<>();
+ for (final Annotation<String> token : tokens) {
+ frequencies.merge(termOf(token, aligned, normalized), 1, Integer::sum);
+ }
final List<Annotation<TermVector>> vectors = new ArrayList<>(frequencies.size());
for (final Map.Entry<String, Integer> entry : frequencies.entrySet()) {
- final TermVector vector = spansByTerm != null
- ? TermVector.withSpans(entry.getKey(), spansByTerm.get(entry.getKey()))
- : TermVector.count(entry.getKey(), entry.getValue());
- vectors.add(Annotation.of(vector));
+ vectors.add(Annotation.of(TermVector.count(entry.getKey(), entry.getValue())));
}
- return document.with(TERM_VECTORS, vectors);
+ return vectors;
}
/** {@inheritDoc} */
@@ -201,43 +237,15 @@ public class TermVectorAnnotator implements DocumentAnnotator {
* @param token The token annotation.
* @param aligned The normalized document text with its alignment, or {@code null}
* when no normalizer is present.
- * @param normalized The normalized document text, or {@code null} likewise.
+ * @param normalized The normalized document text, or {@code null} when no normalizer is
+ * present.
* @return The term string. Never {@code null}, possibly empty.
*/
- private static String termOf(Annotation<String> token, AlignedText aligned,
- String normalized) {
+ private String termOf(Annotation<String> token, AlignedText aligned, String normalized) {
if (aligned == null) {
return token.value();
}
final Span span = aligned.toNormalizedSpan(token.span().getStart(), token.span().getEnd());
return normalized.substring(span.getStart(), span.getEnd());
}
-
- /**
- * Validates a mode argument.
- *
- * @param mode The mode to validate.
- * @return The validated mode.
- * @throws IllegalArgumentException Thrown if {@code mode} is {@code null}.
- */
- private static Mode requireMode(Mode mode) {
- if (mode == null) {
- throw new IllegalArgumentException("mode must not be null");
- }
- return mode;
- }
-
- /**
- * Validates a normalizer argument.
- *
- * @param normalizer The normalizer to validate.
- * @return The validated normalizer.
- * @throws IllegalArgumentException Thrown if {@code normalizer} is {@code null}.
- */
- private static OffsetAwareNormalizer requireNormalizer(OffsetAwareNormalizer normalizer) {
- if (normalizer == null) {
- throw new IllegalArgumentException("normalizer must not be null");
- }
- return normalizer;
- }
}
diff --git a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java
index 869431d59..ee6f852cd 100644
--- a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java
+++ b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorAnnotatorTest.java
@@ -50,9 +50,8 @@ public class TermVectorAnnotatorTest {
/**
* A deterministic {@link OffsetAwareNormalizer} that collapses every run of
* whitespace to one space and applies a full case fold, including the German eszett
- * expansion {@code ß -> ss}. Every edit is recorded in an {@link Alignment} built the
- * way {@code AlignmentTest} builds them, so the expected spans below follow directly
- * from the input text.
+ * expansion {@code ß -> ss}. Every edit is recorded in an {@link Alignment}, so the
+ * expected spans below follow directly from the input text.
*/
private static final class WhitespaceCaseFoldNormalizer implements OffsetAwareNormalizer {
@@ -99,8 +98,43 @@ public class TermVectorAnnotatorTest {
}
}
+ /**
+ * A deterministic {@link OffsetAwareNormalizer} that deletes every digit and copies
+ * every other character unchanged, so a token made up of digits alone normalizes to
+ * the empty string.
+ */
+ private static final class DigitDeletingNormalizer implements OffsetAwareNormalizer {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public CharSequence normalize(CharSequence text) {
+ return normalizeAligned(text).normalized();
+ }
+
+ @Override
+ public AlignedText normalizeAligned(CharSequence text) {
+ final String source = text.toString();
+ final StringBuilder out = new StringBuilder(source.length());
+ final Alignment.Builder alignment = new Alignment.Builder(source.length());
+ for (int i = 0; i < source.length(); i++) {
+ final char c = source.charAt(i);
+ if (Character.isDigit(c)) {
+ alignment.replace(1, 0);
+ } else {
+ out.append(c);
+ alignment.equal(1);
+ }
+ }
+ return new AlignedText(source, out.toString(), alignment.build(source.length()));
+ }
+ }
+
private static final OffsetAwareNormalizer FOLD = new WhitespaceCaseFoldNormalizer();
+ private static final OffsetAwareNormalizer DROP_DIGITS = new DigitDeletingNormalizer();
+
/**
* Splits a text on single space characters into a token layer, skipping the empty
* tokens a collapsed run would produce, so double spaces yield no tokens.
@@ -232,6 +266,24 @@ public class TermVectorAnnotatorTest {
assertEquals(TermVector.count("gross", 3), vectors.get(0).value());
}
+ /**
+ * A token the normalizer deletes entirely groups under the empty string instead of
+ * being dropped, so the term vector layer still accounts for every token.
+ */
+ @Test
+ void testTokensNormalizedAwayGroupUnderTheEmptyTerm() {
+ final Document document = new TermVectorAnnotator(DROP_DIGITS)
+ .annotate(documentWithTokens("dog 42 dog 7"));
+
+ final List<Annotation<TermVector>> vectors =
+ document.get(TermVectorAnnotator.TERM_VECTORS);
+ assertEquals(2, vectors.size());
+ assertEquals(new TermVector("dog", 2, List.of(new Span(0, 3), new Span(7, 10))),
+ vectors.get(0).value());
+ assertEquals(new TermVector("", 2, List.of(new Span(4, 6), new Span(11, 12))),
+ vectors.get(1).value());
+ }
+
@Test
void testEmptyTokenLayerYieldsPresentButEmptyLayer() {
final Document document = new TermVectorAnnotator()
diff --git a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorPipelineTest.java b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorPipelineTest.java
index 2e558f7f2..a00fba96b 100644
--- a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorPipelineTest.java
+++ b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorPipelineTest.java
@@ -36,10 +36,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Wires the {@link TermVectorAnnotator} into a {@link DocumentAnalyzer} behind a
- * {@link TokenizerAnnotator}, the way {@code DocumentPipelineExampleTest} demonstrates
- * the pipeline: the token layer goes in, the term vector layer comes out, and nothing
- * else about the document changes. The tokenizer is a deterministic stand-in defined
- * here, so every expected span follows directly from the input text.
+ * {@link TokenizerAnnotator}: the token layer goes in, the term vector layer comes out,
+ * and nothing else about the document changes. The tokenizer is a deterministic stand-in
+ * defined here, so every expected span follows directly from the input text.
*/
public class TermVectorPipelineTest {
@@ -100,11 +99,10 @@ public class TermVectorPipelineTest {
assertEquals(new TermVector("naps.", 1, List.of(new Span(23, 28))),
vectors.get(3).value());
- // Every occurrence span indexes into the original text.
+ // Every occurrence span indexes into the original text and covers its own term.
for (final Annotation<TermVector> vector : vectors) {
for (final Span span : vector.value().spans()) {
- assertEquals(span.getCoveredText(document.text()).toString(),
- document.text().subSequence(span.getStart(), span.getEnd()).toString());
+ assertEquals(vector.value().term(), span.getCoveredText(document.text()).toString());
}
}
}
diff --git a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorTest.java b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorTest.java
index 7f0106992..286b7a2c3 100644
--- a/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorTest.java
+++ b/opennlp-api/src/test/java/opennlp/tools/termvector/TermVectorTest.java
@@ -21,6 +21,8 @@ import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import opennlp.tools.util.Span;
@@ -73,9 +75,10 @@ public class TermVectorTest {
assertThrows(IllegalArgumentException.class, () -> new TermVector("dog", 1, null));
}
- @Test
- void testZeroFrequencyIsRejected() {
- assertThrows(IllegalArgumentException.class, () -> TermVector.count("dog", 0));
+ @ParameterizedTest
+ @ValueSource(ints = {0, -1, Integer.MIN_VALUE})
+ void testFrequencyBelowOneIsRejected(int frequency) {
+ assertThrows(IllegalArgumentException.class, () -> TermVector.count("dog", frequency));
}
@Test