Skip to content

Apache Lucene open-source search software

StableTfl Similarity (#16243)

Tianxiao Weie3a7a733c8a9
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 927c1a12f88..3eba5cc772f 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -295,7 +295,10 @@ API Changes
New Features
---------------------
-(No changes)
+
+* GITHUB#16243: Add StableTflSimilarity, a similarity that estimates term rarity from term length
+ and document length instead of corpus statistics such as document frequency. It also supports k3
+ query-term frequency saturation. (Tianxiao Wei)
Improvements
---------------------
diff --git a/lucene/core/src/java/org/apache/lucene/search/similarities/StableTflSimilarity.java b/lucene/core/src/java/org/apache/lucene/search/similarities/StableTflSimilarity.java
new file mode 100644
index 00000000000..3eb2337a52c
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/search/similarities/StableTflSimilarity.java
@@ -0,0 +1,370 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.search.similarities;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.lucene.search.Explanation;
+import org.apache.lucene.search.FieldStats;
+import org.apache.lucene.search.TermStats;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.SmallFloat;
+import org.apache.lucene.util.UnicodeUtil;
+
+/**
+ * StableTfl Similarity. A similarity algorithm that estimates term rarity based on term length and
+ * document length, rather than relying on corpus-level statistics like document frequency.
+ *
+ * <p>Inspired by BM25, this similarity model replaces IDF with a synthetic function that increases
+ * with term length (as a proxy for rarity) and adjusts based on document length.
+ *
+ * <p>Scoring formula:
+ *
+ * <pre>
+ * tf = freq / (freq + k1)
+ * p = 1 - (1 - m * 2 ^ (-c * |t|)) ^ |d|
+ * tr = log(1 + (1 - p + 0.05) / (p + 0.05))
+ * score = boost * tr * tf
+ * </pre>
+ *
+ * <p>This similarity is parameterized by:
+ *
+ * <ul>
+ * <li>{@code k1} - saturation parameter for term frequency
+ * <li>{@code c} - decay constant controlling how term length impacts rarity
+ * <li>{@code k3} - query-side saturation for repeated query terms (disabled by default)
+ * </ul>
+ *
+ * <p>The constant {@code m} is fixed internally and controls the base term-match probability.
+ *
+ * @lucene.experimental
+ */
+public class StableTflSimilarity extends Similarity {
+
+ /** Default k1 value used in Lucene's implementation of BM25. */
+ public static final float DEFAULT_K1 = 1.2f;
+
+ /** Empirical value of c derived from modeling term frequency in English corpuses. */
+ public static final float DEFAULT_C = 0.917f;
+
+ /** Default k3 value. A negative value disables query-term frequency saturation. */
+ public static final float DEFAULT_K3 = -1f;
+
+ /** Multiplicative constant to term matching probability. Non-adjustable by users. */
+ private static final float M = 0.00781f;
+
+ /**
+ * Default term length if term BytesRef can't be decoded with UTF_8. This is close to the average
+ * word length in English.
+ */
+ private static final float NON_UTF_8_DEFAULT_TERM_LENGTH = 5;
+
+ /** Cache of decoded bytes. */
+ private static final float[] LENGTH_TABLE = new float[256];
+
+ static {
+ for (int i = 0; i < 256; i++) {
+ LENGTH_TABLE[i] = SmallFloat.byte4ToInt((byte) i);
+ }
+ }
+
+ /** Controls non-linear term frequency normalization (saturation). */
+ private final float k1;
+
+ /** Controls how much term length affects term rarity. */
+ private final float c;
+
+ /**
+ * Controls query-side term frequency saturation. A negative value disables saturation (linear
+ * behavior).
+ */
+ private final float k3;
+
+ /**
+ * StableTFL with the supplied parameter values.
+ *
+ * @param k1 Controls non-linear term frequency normalization (saturation).
+ * @param c Controls how much term length affects term rarity (decay constant).
+ * @param k3 Controls query-side term frequency saturation. When duplicate terms appear in a
+ * query, their boost is computed as ((k3 + 1) * qtf) / (k3 + qtf) instead of linear summing.
+ * A negative value disables saturation (linear behavior). Common values are 7 or 8.
+ * @throws IllegalArgumentException if {@code k1} is infinite or negative
+ * @throws IllegalArgumentException if {@code c} is infinite or negative
+ * @throws IllegalArgumentException if {@code k3} is infinite
+ */
+ public StableTflSimilarity(float k1, float c, float k3) {
+ if (Float.isFinite(k1) == false || k1 < 0) {
+ throw new IllegalArgumentException(
+ "illegal k1 value: " + k1 + ", must be a non-negative finite value");
+ }
+ if (Float.isFinite(c) == false || c < 0) {
+ throw new IllegalArgumentException(
+ "illegal c value: " + c + ", must be a non-negative finite value");
+ }
+ if (Float.isFinite(k3) == false) {
+ throw new IllegalArgumentException(
+ "illegal k3 value: " + k3 + ", must be a finite value (negative to disable)");
+ }
+ this.k1 = k1;
+ this.c = c;
+ this.k3 = k3;
+ }
+
+ /**
+ * StableTFL with the supplied parameter values and query-term frequency saturation disabled.
+ *
+ * @param k1 Controls non-linear term frequency normalization (saturation).
+ * @param c Controls how much term length affects term rarity (decay constant).
+ * @throws IllegalArgumentException if {@code k1} is infinite or negative
+ * @throws IllegalArgumentException if {@code c} is infinite or negative
+ */
+ public StableTflSimilarity(float k1, float c) {
+ this(k1, c, DEFAULT_K3);
+ }
+
+ /**
+ * StableTFL with these default values:
+ *
+ * <ul>
+ * <li>{@code k1 = 1.2}
+ * <li>{@code c = 0.917}
+ * <li>{@code k3 = -1} (query-term frequency saturation disabled)
+ * </ul>
+ */
+ public StableTflSimilarity() {
+ this(DEFAULT_K1, DEFAULT_C, DEFAULT_K3);
+ }
+
+ /**
+ * Computes the query-term weight using the same k3 saturation formula as BM25: ((k3 + 1) * qtf) /
+ * (k3 + qtf). When k3 is negative (disabled), falls back to linear weighting where the weight
+ * equals the query term frequency.
+ */
+ @Override
+ public float computeQueryTermWeight(int queryTermFrequency) {
+ if (k3 < 0) {
+ return (float) queryTermFrequency;
+ }
+ return ((k3 + 1f) * queryTermFrequency) / (k3 + queryTermFrequency);
+ }
+
+ /**
+ * Implemented as <code>log(1 + (1 - p + 0.05)/(p + 0.05))</code>, where <code>
+ * p = 1 - (1 - m * 2 ^ (-c * termLength)) ^ docLength </code>
+ */
+ private float tr(float termLength, float docLength) {
+ // The probability that a term is present in a document with length docLength.
+ double p = (1 - Math.pow(1 - M * Math.pow(2, -c * termLength), docLength));
+
+ return (float) Math.log(1 + (1 - p + 0.05D) / (p + 0.05D));
+ }
+
+ /**
+ * Returns the number of code points in this UTF8 sequence. If invalid codepoint header byte
+ * occurs or the content is prematurely truncated, return NON_UTF_8_DEFAULT_TERM_LENGTH.
+ */
+ private static float getTermLength(BytesRef termText) {
+ try {
+ return UnicodeUtil.codePointCount(termText);
+ } catch (IllegalArgumentException _) {
+ return NON_UTF_8_DEFAULT_TERM_LENGTH;
+ }
+ }
+
+ @Override
+ public final SimScorer scorer(float boost, FieldStats fieldStats, TermStats... termStats) {
+ float[] cache = new float[256];
+ float[] termLengths = new float[termStats.length];
+
+ for (int i = 0; i < termStats.length; i++) {
+ float termLength = getTermLength(termStats[i].term());
+ termLengths[i] = termLength;
+ for (int j = 0; j < cache.length; j++) {
+ float docLength = LENGTH_TABLE[j];
+ cache[j] += tr(termLength, docLength);
+ }
+ }
+
+ // Fold the constant boost into the per-doc-length cache so score() doesn't repeat this
+ // multiply for every scored document.
+ for (int j = 0; j < cache.length; j++) {
+ cache[j] *= boost;
+ }
+
+ return new TflScorer(boost, k1, c, termLengths, cache);
+ }
+
+ private static class TflScorer extends SimScorer {
+ private final float boost;
+ private final float k1;
+ private final float c;
+
+ /**
+ * termLengths[i] stores the decoded UTF-8 term length (in code points) of the i-th query term.
+ */
+ private final float[] termLengths;
+
+ /**
+ * cache[i] stores the precomputed weight (boost times the summed term rarity (tr) of all query
+ * terms) for a specific document length (LENGTH_TABLE[i]).
+ */
+ private final float[] cache;
+
+ TflScorer(float boost, float k1, float c, float[] termLengths, float[] cache) {
+ this.boost = boost;
+ this.k1 = k1;
+ this.c = c;
+ this.termLengths = termLengths;
+ this.cache = cache;
+ }
+
+ @Override
+ public float score(float freq, long encodedNorm) {
+ // In order to guarantee monotonicity with freq without promoting to doubles, we rewrite
+ // freq / (freq + k1) to 1 - 1 / (1 + freq / k1).
+ // freq / k1 is guaranteed to be monotonic. And then monotonicity is preserved through
+ // composition via x -> 1 + x and x -> 1 - 1 / x.
+ // Finally, we expand weight * (1 - 1 / (1 + freq / k1)) to
+ // weight - weight / (1 + freq / k1), which runs slightly faster.
+ float weight = cache[((byte) encodedNorm) & 0xFF];
+ return weight - weight / (1 + freq / k1);
+ }
+
+ @Override
+ public BulkSimScorer asBulkSimScorer() {
+ return new BulkSimScorer() {
+
+ private float[] weights = new float[0];
+
+ @Override
+ public void score(int size, float[] freqs, long[] norms, float[] scores) {
+ if (weights.length < size) {
+ weights = new float[ArrayUtil.oversize(size, Float.BYTES)];
+ }
+ // Scalar gather of the per-doc-length weight (boost * tr); this lookup can't vectorize.
+ for (int i = 0; i < size; ++i) {
+ weights[i] = cache[((byte) norms[i]) & 0xFF];
+ }
+
+ // This loop auto-vectorizes. Kept bit-identical to score() so asBulkSimScorer() agrees.
+ for (int i = 0; i < size; ++i) {
+ scores[i] = weights[i] - weights[i] / (1f + freqs[i] / k1);
+ }
+ }
+ };
+ }
+
+ @Override
+ public Explanation explain(Explanation freq, long norm) {
+ List<Explanation> subs = new ArrayList<>();
+ subs.add(Explanation.match(boost, "boost"));
+ subs.add(explainTF(freq));
+ subs.add(explainTR(termLengths, norm));
+
+ float weight = cache[((byte) norm) & 0xFF];
+ return Explanation.match(
+ weight - weight / (1f + freq.getValue().floatValue() / k1),
+ "score(freq=" + freq.getValue() + "), computed as boost * tr * tf from:",
+ subs);
+ }
+
+ private Explanation explainTR(float termLength, long norm) {
+ float docLength = LENGTH_TABLE[((byte) norm) & 0xff];
+ List<Explanation> subs = new ArrayList<>(explainTrConstantFactors());
+ subs.add(Explanation.match(termLength, "tl, term length"));
+ subs.add(Explanation.match(docLength, "dl, document length"));
+
+ // The probability that a term is present in a document with length docLength.
+ double p = (1 - Math.pow(1 - M * Math.pow(2, -c * termLength), docLength));
+ Explanation probExplanation =
+ Explanation.match(
+ p,
+ "p, probability that the term appears in the doc, "
+ + "computed as 1 - (1 - m * 2 ^ (-c * tl)) ^ dl from:",
+ subs);
+
+ float tr = (float) Math.log(1 + (1 - p + 0.05D) / (p + 0.05D));
+ return Explanation.match(
+ tr,
+ "tr, term rarity, computed as log(1 + (1 - p + 0.05) / (p + 0.05)) from:",
+ probExplanation);
+ }
+
+ private Explanation explainTR(float[] termLengths, long norm) {
+ if (termLengths.length == 1) {
+ return explainTR(termLengths[0], norm);
+ }
+
+ double tr = 0d;
+ List<Explanation> details = new ArrayList<>();
+ for (float termLength : termLengths) {
+ Explanation trExplain = explainTR(termLength, norm);
+ details.add(trExplain);
+ tr += trExplain.getValue().floatValue();
+ }
+ return Explanation.match(tr, "tr, term rarity, computed as the sum of:", details);
+ }
+
+ private List<Explanation> explainTrConstantFactors() {
+ return List.of(
+ Explanation.match(M, "m, multiplicative constant to term match probability"),
+ Explanation.match(c, "c, decaying constant for term length"));
+ }
+
+ private Explanation explainTF(Explanation freq) {
+ List<Explanation> subs =
+ List.of(freq, Explanation.match(k1, "k1, term saturation parameter"));
+
+ return Explanation.match(
+ 1f - 1f / (1 + freq.getValue().floatValue() / k1),
+ "tf, computed as freq / (freq + k1) from:",
+ subs);
+ }
+ }
+
+ /**
+ * Returns the <code>k1</code> parameter.
+ *
+ * @see #StableTflSimilarity(float, float)
+ */
+ public final float getK1() {
+ return k1;
+ }
+
+ /**
+ * Returns the <code>c</code> parameter.
+ *
+ * @see #StableTflSimilarity(float, float)
+ */
+ public final float getC() {
+ return c;
+ }
+
+ /**
+ * Returns the <code>k3</code> parameter for query-side term frequency saturation. A negative
+ * value means saturation is disabled.
+ */
+ public final float getK3() {
+ return k3;
+ }
+
+ @Override
+ public String toString() {
+ return "StableTflSimilarity(k1=" + k1 + ", c=" + c + (k3 >= 0 ? ", k3=" + k3 : "") + ")";
+ }
+}
diff --git a/lucene/core/src/test/org/apache/lucene/search/similarities/TestStableTflSimilarity.java b/lucene/core/src/test/org/apache/lucene/search/similarities/TestStableTflSimilarity.java
new file mode 100644
index 00000000000..e6b518ca2b4
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/search/similarities/TestStableTflSimilarity.java
@@ -0,0 +1,337 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.lucene.search.similarities;
+
+import java.util.Random;
+import org.apache.lucene.search.Explanation;
+import org.apache.lucene.search.FieldStats;
+import org.apache.lucene.search.TermStats;
+import org.apache.lucene.search.similarities.Similarity.SimScorer;
+import org.apache.lucene.tests.search.similarities.BaseSimilarityTestCase;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.SmallFloat;
+
+public class TestStableTflSimilarity extends BaseSimilarityTestCase {
+
+ public void testIllegalK1() {
+ IllegalArgumentException expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(Float.POSITIVE_INFINITY, 0.917f);
+ });
+ assertTrue(expected.getMessage().contains("illegal k1 value"));
+
+ expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(-1, 0.917f);
+ });
+ assertTrue(expected.getMessage().contains("illegal k1 value"));
+
+ expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(Float.NaN, 0.917f);
+ });
+ assertTrue(expected.getMessage().contains("illegal k1 value"));
+ }
+
+ public void testIllegalC() {
+ IllegalArgumentException expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(1.2f, Float.POSITIVE_INFINITY);
+ });
+ assertTrue(expected.getMessage().contains("illegal c value"));
+
+ expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(1.2f, -1f);
+ });
+ assertTrue(expected.getMessage().contains("illegal c value"));
+
+ expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(1.2f, Float.NaN);
+ });
+ assertTrue(expected.getMessage().contains("illegal c value"));
+ }
+
+ public void testIllegalK3() {
+ IllegalArgumentException expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(1.2f, 0.917f, Float.POSITIVE_INFINITY);
+ });
+ assertTrue(expected.getMessage().contains("illegal k3 value"));
+
+ expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(1.2f, 0.917f, Float.NEGATIVE_INFINITY);
+ });
+ assertTrue(expected.getMessage().contains("illegal k3 value"));
+
+ expected =
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> {
+ new StableTflSimilarity(1.2f, 0.917f, Float.NaN);
+ });
+ assertTrue(expected.getMessage().contains("illegal k3 value"));
+ }
+
+ public void testValidK3() {
+ // negative k3 disables saturation — should be allowed
+ StableTflSimilarity sim = new StableTflSimilarity(1.2f, 0.917f, -1f);
+ assertEquals(-1f, sim.getK3(), 0f);
+
+ // zero k3 — maximum saturation
+ sim = new StableTflSimilarity(1.2f, 0.917f, 0f);
+ assertEquals(0f, sim.getK3(), 0f);
+
+ // typical k3 value
+ sim = new StableTflSimilarity(1.2f, 0.917f, 8f);
+ assertEquals(8f, sim.getK3(), 0f);
+ }
+
+ public void testComputeQueryTermWeight() {
+ // negative k3 disables saturation: weight is the (linear) query term frequency
+ StableTflSimilarity disabled = new StableTflSimilarity(1.2f, 0.917f, -1f);
+ for (int qtf = 1; qtf <= 5; qtf++) {
+ assertEquals((float) qtf, disabled.computeQueryTermWeight(qtf), 0f);
+ }
+
+ // k3 = 0 fully saturates: any positive frequency yields a weight of 1
+ StableTflSimilarity saturated = new StableTflSimilarity(1.2f, 0.917f, 0f);
+ for (int qtf = 1; qtf <= 5; qtf++) {
+ assertEquals(1f, saturated.computeQueryTermWeight(qtf), 0f);
+ }
+
+ // positive k3 saturates: ((k3 + 1) * qtf) / (k3 + qtf), monotonic but sub-linear
+ float k3 = 8f;
+ StableTflSimilarity sim = new StableTflSimilarity(1.2f, 0.917f, k3);
+ float prev = 0f;
+ for (int qtf = 1; qtf <= 10; qtf++) {
+ float expected = ((k3 + 1f) * qtf) / (k3 + qtf);
+ float weight = sim.computeQueryTermWeight(qtf);
+ assertEquals(expected, weight, 0f);
+ assertTrue("weight should not decrease as qtf increases", weight >= prev);
+ assertTrue("saturation should keep weight at or below linear", weight <= qtf);
+ prev = weight;
+ }
+ }
+
+ public void testValidParameters() {
+ // boundary values: zero is allowed for both parameters
+ StableTflSimilarity sim = new StableTflSimilarity(0f, 0f);
+ assertEquals(0f, sim.getK1(), 0f);
+ assertEquals(0f, sim.getC(), 0f);
+
+ // typical values are returned as set
+ sim = new StableTflSimilarity(1.5f, 0.9f, 8f);
+ assertEquals(1.5f, sim.getK1(), 0f);
+ assertEquals(0.9f, sim.getC(), 0f);
+ assertEquals(8f, sim.getK3(), 0f);
+
+ // the no-arg constructor uses the documented defaults
+ StableTflSimilarity defaults = new StableTflSimilarity();
+ assertEquals(StableTflSimilarity.DEFAULT_K1, defaults.getK1(), 0f);
+ assertEquals(StableTflSimilarity.DEFAULT_C, defaults.getC(), 0f);
+ assertEquals(StableTflSimilarity.DEFAULT_K3, defaults.getK3(), 0f);
+ }
+
+ public void testToString() {
+ StableTflSimilarity sim = new StableTflSimilarity();
+ assertEquals("StableTflSimilarity(k1=1.2, c=0.917)", sim.toString());
+
+ // k3 is only rendered when saturation is enabled (non-negative)
+ StableTflSimilarity withK3 = new StableTflSimilarity(1.2f, 0.917f, 8.0f);
+ assertEquals("StableTflSimilarity(k1=1.2, c=0.917, k3=8.0)", withK3.toString());
+ }
+
+ /**
+ * Reproduces the canonical scoring example: term rarity is derived from the term length and the
+ * document length rather than from corpus statistics, so the supplied {@link FieldStats}/{@link
+ * TermStats} do not affect the score.
+ */
+ public void testExplain() throws Exception {
+ StableTflSimilarity similarity = new StableTflSimilarity();
+ FieldStats fieldStats = new FieldStats("field", 4, 4, 3003, 2000);
+ TermStats termStats = new TermStats(new BytesRef("photosynthesis"), 3, 3);
+ SimScorer scorer = similarity.scorer(1, fieldStats, termStats);
+
+ int numTerms = 1000;
+ long norm = SmallFloat.intToByte4(numTerms);
+ float score = scorer.score(1, norm);
+ assertEquals(1.3955811f, score, 0f);
+
+ Explanation explain = scorer.explain(Explanation.match(1, "freq"), norm);
+ assertEquals(score, explain.getValue().floatValue(), 0f);
+
+ String explainString =
+ """
+ 1.3955811 = score(freq=1), computed as boost * tr * tf from:
+ 1.0 = boost
+ 0.45454544 = tf, computed as freq / (freq + k1) from:
+ 1 = freq
+ 1.2 = k1, term saturation parameter
+ 3.0702786 = tr, term rarity, computed as log(1 + (1 - p + 0.05) / (p + 0.05)) from:
+ 0.001049047818598714 = p, probability that the term appears in the doc, \
+ computed as 1 - (1 - m * 2 ^ (-c * tl)) ^ dl from:
+ 0.00781 = m, multiplicative constant to term match probability
+ 0.917 = c, decaying constant for term length
+ 14.0 = tl, term length
+ 984.0 = dl, document length
+ """;
+ assertEquals(explainString, explain.toString());
+ }
+
+ /** Multi-term queries sum the term rarity of each query term. */
+ public void testMultiTermExplain() throws Exception {
+ StableTflSimilarity similarity = new StableTflSimilarity();
+ FieldStats fieldStats = new FieldStats("field", 4, 4, 3003, 2000);
+ SimScorer scorer =
+ similarity.scorer(
+ 1,
+ fieldStats,
+ new TermStats(new BytesRef("photosynthesis"), 3, 3),
+ new TermStats(new BytesRef("chlorophyll"), 3, 3));
+
+ long norm = SmallFloat.intToByte4(1000);
+ Explanation explain = scorer.explain(Explanation.match(1, "freq"), norm);
+ // the combined term rarity must be the sum of the individual per-term rarities
+ assertTrue(explain.toString().contains("tr, term rarity, computed as the sum of:"));
+ assertEquals(scorer.score(1, norm), explain.getValue().floatValue(), 0f);
+ }
+
+ /**
+ * A term that is not valid UTF-8 falls back to the default term length of 5 code points instead
+ * of throwing.
+ */
+ public void testNonUtf8TermFallsBackToDefaultLength() {
+ StableTflSimilarity similarity = new StableTflSimilarity();
+ FieldStats fieldStats = new FieldStats("field", 4, 4, 3003, 2000);
+ long norm = SmallFloat.intToByte4(1000);
+
+ // 0xFF is never a valid UTF-8 leading byte
+ BytesRef invalidUtf8 = new BytesRef(new byte[] {(byte) 0xFF, (byte) 0xFF});
+ SimScorer invalidScorer = similarity.scorer(1, fieldStats, new TermStats(invalidUtf8, 3, 3));
+
+ // "hello" has exactly 5 code points, the default term length for undecodable terms
+ SimScorer fiveCharScorer =
+ similarity.scorer(1, fieldStats, new TermStats(new BytesRef("hello"), 3, 3));
+
+ assertEquals(fiveCharScorer.score(1, norm), invalidScorer.score(1, norm), 0f);
+ }
+
+ /** Scores depend only on term length and document length, never on corpus statistics. */
+ public void testScoreIndependentOfCorpusStats() {
+ StableTflSimilarity similarity = new StableTflSimilarity();
+ BytesRef term = new BytesRef("photosynthesis");
+ long norm = SmallFloat.intToByte4(1000);
+
+ SimScorer sparse =
+ similarity.scorer(1, new FieldStats("field", 4, 4, 3003, 2000), new TermStats(term, 1, 1));
+ SimScorer dense =
+ similarity.scorer(
+ 1,
+ new FieldStats("field", 1_000_000, 999_999, 123_456_789, 99_999_999),
+ new TermStats(term, 999_999, 12_345_678));
+
+ assertEquals(sparse.score(1, norm), dense.score(1, norm), 0f);
+ }
+
+ /**
+ * A multi-term scorer's score equals the sum of the corresponding single-term scores (modulo
+ * float summation order).
+ */
+ public void testMultiTermScoreIsSumOfSingleTermScores() {
+ StableTflSimilarity similarity = new StableTflSimilarity();
+ FieldStats fieldStats = new FieldStats("field", 4, 4, 3003, 2000);
+ TermStats term1 = new TermStats(new BytesRef("photosynthesis"), 3, 3);
+ TermStats term2 = new TermStats(new BytesRef("chlorophyll"), 3, 3);
+ long norm = SmallFloat.intToByte4(1000);
+ float freq = 2;
+
+ float combined = similarity.scorer(1, fieldStats, term1, term2).score(freq, norm);
+ float sum =
+ similarity.scorer(1, fieldStats, term1).score(freq, norm)
+ + similarity.scorer(1, fieldStats, term2).score(freq, norm);
+
+ assertEquals(sum, combined, 1e-6f);
+ }
+
+ @Override
+ protected Similarity getSimilarity(Random random) {
+ // term frequency saturation parameter k1
+ final float k1;
+ switch (random.nextInt(4)) {
+ case 0:
+ // minimum value
+ k1 = 0;
+ break;
+ case 1:
+ // tiny value
+ k1 = Float.MIN_VALUE;
+ break;
+ case 2:
+ // maximum value
+ k1 = Integer.MAX_VALUE;
+ break;
+ default:
+ // random value
+ k1 = Integer.MAX_VALUE * random.nextFloat();
+ break;
+ }
+
+ // term length decay parameter c [0 .. infinity)
+ final float c;
+ switch (random.nextInt(4)) {
+ case 0:
+ // minimum value
+ c = 0;
+ break;
+ case 1:
+ // tiny value
+ c = Float.MIN_VALUE;
+ break;
+ case 2:
+ // large value
+ c = Integer.MAX_VALUE;
+ break;
+ default:
+ // random value
+ c = Integer.MAX_VALUE * random.nextFloat();
+ break;
+ }
+
+ // query-term saturation parameter k3: negative (disabled) or a finite non-negative value
+ final float k3 = random.nextBoolean() ? -1f : random.nextFloat() * 20f;
+ return new StableTflSimilarity(k1, c, k3);
+ }
+}