okapibm25 1.4.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/BM25.js CHANGED
@@ -1,64 +1,352 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getIDF = exports.getTermFrequency = exports.getWordCount = void 0;
4
- /** Gets word count. */
5
- var getWordCount = function (corpus) {
6
- return ((corpus || "").match(/\w+/g) || []).length;
4
+ exports.BM25 = BM25;
5
+ exports.createIndex = createIndex;
6
+ /** Default value of the free parameter `b`. */
7
+ const DEFAULT_B = 0.75;
8
+ /** Default value of the free parameter `k1`. */
9
+ const DEFAULT_K1 = 1.2;
10
+ /** Anything that is not a string is scored as an empty document. */
11
+ const toText = (value) => typeof value === "string" ? value : "";
12
+ /** A free parameter is used when it is a real number, `0` included. Anything else falls back to the default. */
13
+ const resolveConstant = (value, fallback) => typeof value === "number" && !Number.isNaN(value) ? value : fallback;
14
+ /** 1 for the ASCII characters that `\w` matches (letters, digits, underscore), 0 for the rest. */
15
+ const WORD_CHARACTERS = new Uint8Array(128);
16
+ for (let code = 0; code < 128; code++) {
17
+ const isWordCharacter = (code >= 97 && code <= 122) || // a-z
18
+ (code >= 65 && code <= 90) || // A-Z
19
+ (code >= 48 && code <= 57) || // 0-9
20
+ code === 95; // _
21
+ WORD_CHARACTERS[code] = isWordCharacter ? 1 : 0;
22
+ }
23
+ /**
24
+ * Gets word count. A word is a run of ASCII letters, digits and underscores,
25
+ * the same as the regular expression `\w+`.
26
+ */
27
+ const getWordCount = (corpus) => {
28
+ const text = toText(corpus);
29
+ let count = 0;
30
+ let insideWord = 0;
31
+ for (let i = 0; i < text.length; i++) {
32
+ const code = text.charCodeAt(i);
33
+ const isWordCharacter = code < 128 ? WORD_CHARACTERS[code] : 0;
34
+ // A word starts where a word character follows a character that is not one.
35
+ count += isWordCharacter & ~insideWord;
36
+ insideWord = isWordCharacter;
37
+ }
38
+ return count;
7
39
  };
8
40
  exports.getWordCount = getWordCount;
9
- /** Number of occurences of a word in a string. */
10
- var getTermFrequency = function (term, corpus) {
11
- return ((corpus || "").match(new RegExp(term, "g")) || []).length;
41
+ /** Counts occurrences of `needle` in `text` that do not overlap. An empty needle occurs zero times. */
42
+ const countOccurrences = (needle, text) => {
43
+ if (needle.length === 0) {
44
+ return 0;
45
+ }
46
+ let count = 0;
47
+ let position = text.indexOf(needle);
48
+ while (position !== -1) {
49
+ count++;
50
+ position = text.indexOf(needle, position + needle.length);
51
+ }
52
+ return count;
12
53
  };
54
+ /**
55
+ * Number of occurrences of a term in a string.
56
+ *
57
+ * The term is matched literally and case-sensitively, and occurrences do not
58
+ * overlap. It is never interpreted as a regular expression, so terms such as
59
+ * `c++` or `(a+)+$` are safe to pass straight from user input. An empty term
60
+ * occurs zero times.
61
+ */
62
+ const getTermFrequency = (term, corpus) => countOccurrences(toText(term), toText(corpus));
13
63
  exports.getTermFrequency = getTermFrequency;
14
64
  /** Inverse document frequency. */
15
- var getIDF = function (term, documents) {
16
- // Number of relevant documents.
17
- var relevantDocuments = documents.filter(function (document) {
18
- return document.includes(term);
19
- }).length;
65
+ const getIDF = (term, documents) => {
66
+ let relevantDocuments = 0;
67
+ for (let i = 0; i < documents.length; i++) {
68
+ if (toText(documents[i]).includes(term)) {
69
+ relevantDocuments++;
70
+ }
71
+ }
20
72
  return Math.log((documents.length - relevantDocuments + 0.5) / (relevantDocuments + 0.5) + 1);
21
73
  };
22
74
  exports.getIDF = getIDF;
23
- /** Implementation of Okapi BM25 algorithm.
24
- * @param documents: Collection of documents.
25
- * @param keywords: query terms.
26
- * @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.
27
- * @param sort: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.
28
- * If this option is provided, the return type will not be an array of scores but an array of documents with their scores.
29
- */
30
75
  function BM25(documents, keywords, constants, sorter) {
31
- var b = constants && constants.b ? constants.b : 0.75;
32
- var k1 = constants && constants.k1 ? constants.k1 : 1.2;
33
- var documentLengths = documents.map(function (document) {
34
- return exports.getWordCount(document);
35
- });
36
- var averageDocumentLength = documentLengths.reduce(function (a, b) { return a + b; }, 0) / documents.length;
37
- var idfByKeyword = keywords.reduce(function (obj, keyword) {
38
- obj.set(keyword, exports.getIDF(keyword, documents));
39
- return obj;
40
- }, new Map());
41
- var scores = documents.map(function (document, index) {
42
- var score = keywords
43
- .map(function (keyword) {
44
- var inverseDocumentFrequency = idfByKeyword.get(keyword);
45
- var termFrequency = exports.getTermFrequency(keyword, document);
46
- var documentLength = documentLengths[index];
47
- return ((inverseDocumentFrequency * (termFrequency * (k1 + 1))) /
48
- (termFrequency +
49
- k1 * (1 - b + (b * documentLength) / averageDocumentLength)));
50
- })
51
- .reduce(function (a, b) { return a + b; }, 0);
52
- if (sorter) {
53
- return { score: score, document: document };
76
+ if (!Array.isArray(documents)) {
77
+ throw new TypeError("BM25: `documents` must be an array of strings.");
78
+ }
79
+ if (!Array.isArray(keywords)) {
80
+ throw new TypeError("BM25: `keywords` must be an array of strings.");
81
+ }
82
+ const b = resolveConstant(constants ? constants.b : undefined, DEFAULT_B);
83
+ const k1 = resolveConstant(constants ? constants.k1 : undefined, DEFAULT_K1);
84
+ const documentCount = documents.length;
85
+ // Each document is measured once.
86
+ const texts = new Array(documentCount);
87
+ const documentLengths = new Float64Array(documentCount);
88
+ let totalLength = 0;
89
+ for (let i = 0; i < documentCount; i++) {
90
+ const text = toText(documents[i]);
91
+ const length = (0, exports.getWordCount)(text);
92
+ texts[i] = text;
93
+ documentLengths[i] = length;
94
+ totalLength += length;
95
+ }
96
+ const averageDocumentLength = documentCount > 0 ? totalLength / documentCount : 0;
97
+ // The part of the denominator that depends only on the document. A
98
+ // collection with no countable words has no length to normalize by, so every
99
+ // document is treated as being of average length.
100
+ const lengthNorms = new Float64Array(documentCount);
101
+ for (let i = 0; i < documentCount; i++) {
102
+ const relativeLength = averageDocumentLength > 0
103
+ ? (b * documentLengths[i]) / averageDocumentLength
104
+ : b;
105
+ lengthNorms[i] = k1 * (1 - b + relativeLength);
106
+ }
107
+ const scores = new Array(documentCount);
108
+ for (let i = 0; i < documentCount; i++) {
109
+ scores[i] = 0;
110
+ }
111
+ // Each keyword reads every document once. That single pass gives both the
112
+ // term frequencies and the number of documents containing the keyword.
113
+ const matchedDocuments = new Uint32Array(documentCount);
114
+ const matchedFrequencies = new Uint32Array(documentCount);
115
+ for (let k = 0; k < keywords.length; k++) {
116
+ // JavaScript callers may pass a number, such as a year. It is searched as text.
117
+ const rawKeyword = keywords[k];
118
+ const keyword = typeof rawKeyword === "number" ? String(rawKeyword) : toText(rawKeyword);
119
+ let matches = 0;
120
+ for (let i = 0; i < documentCount; i++) {
121
+ const termFrequency = countOccurrences(keyword, texts[i]);
122
+ if (termFrequency > 0) {
123
+ matchedDocuments[matches] = i;
124
+ matchedFrequencies[matches] = termFrequency;
125
+ matches++;
126
+ }
127
+ }
128
+ const inverseDocumentFrequency = Math.log((documentCount - matches + 0.5) / (matches + 0.5) + 1);
129
+ for (let m = 0; m < matches; m++) {
130
+ const i = matchedDocuments[m];
131
+ const termFrequency = matchedFrequencies[m];
132
+ scores[i] +=
133
+ (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /
134
+ (termFrequency + lengthNorms[i]);
54
135
  }
55
- return score;
56
- });
57
- // sort the results
136
+ }
58
137
  if (sorter) {
59
- return scores.sort(sorter);
138
+ const scoredDocuments = new Array(documentCount);
139
+ for (let i = 0; i < documentCount; i++) {
140
+ scoredDocuments[i] = { score: scores[i], document: documents[i] };
141
+ }
142
+ return scoredDocuments.sort(sorter);
60
143
  }
61
144
  return scores;
62
145
  }
146
+ /** `undefined` when the JavaScript engine does not support the pattern. */
147
+ const compilePattern = (source, flags) => {
148
+ try {
149
+ return new RegExp(source, flags);
150
+ }
151
+ catch (error) {
152
+ return undefined;
153
+ }
154
+ };
155
+ /**
156
+ * The default definition of a word for an index: a run of letters, marks that
157
+ * combine with letters, digits and underscores, in any script. For ASCII text
158
+ * these are the words that `getWordCount` counts. The pattern is compiled at
159
+ * run time because its syntax is newer than the ES2015 this file is built
160
+ * for; engines from before 2018 fall back to ASCII words.
161
+ */
162
+ const WORDS = compilePattern("[\\p{L}\\p{M}\\p{N}_]+", "gu") || /\w+/g;
163
+ /** Reads an option that has to be a number from 0 to `max`. `undefined` gives the default. */
164
+ const readNumber = (value, fallback, max, rule) => {
165
+ if (value === undefined) {
166
+ return fallback;
167
+ }
168
+ if (typeof value !== "number") {
169
+ throw new TypeError("BM25 index: " + rule);
170
+ }
171
+ // Written so that NaN fails it too.
172
+ if (!(value >= 0 && value <= max)) {
173
+ throw new RangeError("BM25 index: " + rule);
174
+ }
175
+ return value;
176
+ };
177
+ /**
178
+ * Reads the documents once and builds an index of their words, so that each
179
+ * later search looks words up instead of reading the text again. Worth it when
180
+ * the same documents are searched many times.
181
+ *
182
+ * Matching differs from {@link BM25}: the index matches whole words. `cat`
183
+ * finds the word `cat` and not `concatenate`, and case is ignored unless
184
+ * `caseSensitive` is set. Keywords are split into words the same way as the
185
+ * documents, so the keyword `dog?` finds the word `dog`. The scoring formula
186
+ * and the defaults of `k1` and `b` are those of {@link BM25}.
187
+ *
188
+ * The index is a snapshot. Changing the array afterwards does not change it.
189
+ *
190
+ * @throws TypeError when `documents` is not an array, when `tokenizer` is not
191
+ * a function, or when it returns something other than an array of strings.
192
+ * `search` and `scores` throw a TypeError when `keywords` is not an array or
193
+ * an option is not a number, and a RangeError when an option is out of range.
194
+ *
195
+ * @example
196
+ * const index = createIndex(["A quick dog", "A lazy cat", "Stock markets"]);
197
+ * index.search(["Dog?"]); // [{ index: 0, document: "A quick dog", score: 0.93... }]
198
+ * index.scores(["dog"]); // [0.93..., 0, 0]
199
+ */
200
+ function createIndex(documents, options) {
201
+ if (!Array.isArray(documents)) {
202
+ throw new TypeError("createIndex: `documents` must be an array of strings.");
203
+ }
204
+ const caseSensitive = options ? options.caseSensitive === true : false;
205
+ const tokenizer = options ? options.tokenizer : undefined;
206
+ if (tokenizer !== undefined && typeof tokenizer !== "function") {
207
+ throw new TypeError("createIndex: `tokenizer` must be a function.");
208
+ }
209
+ /** The words of a text. A custom tokenizer may return empty words; callers skip those. */
210
+ const toWords = (text) => {
211
+ const prepared = caseSensitive ? text : text.toLowerCase();
212
+ if (tokenizer === undefined) {
213
+ return prepared.match(WORDS) || [];
214
+ }
215
+ const words = tokenizer(prepared);
216
+ if (!Array.isArray(words)) {
217
+ throw new TypeError("createIndex: `tokenizer` must return an array of strings.");
218
+ }
219
+ for (let w = 0; w < words.length; w++) {
220
+ if (typeof words[w] !== "string") {
221
+ throw new TypeError("createIndex: `tokenizer` must return an array of strings.");
222
+ }
223
+ }
224
+ return words;
225
+ };
226
+ const documentCount = documents.length;
227
+ const originals = documents.slice();
228
+ // A Map, not an object, so that words such as `constructor` are ordinary keys.
229
+ const postings = new Map();
230
+ const documentLengths = new Float64Array(documentCount);
231
+ let totalLength = 0;
232
+ for (let i = 0; i < documentCount; i++) {
233
+ const words = toWords(toText(documents[i]));
234
+ let length = 0;
235
+ for (let w = 0; w < words.length; w++) {
236
+ const word = words[w];
237
+ if (word.length === 0) {
238
+ continue;
239
+ }
240
+ length++;
241
+ const posting = postings.get(word);
242
+ if (posting === undefined) {
243
+ postings.set(word, { documents: [i], frequencies: [1] });
244
+ continue;
245
+ }
246
+ // Documents are added in order, so a repeat of the word within this
247
+ // document is always at the end of the list.
248
+ const last = posting.documents.length - 1;
249
+ if (posting.documents[last] === i) {
250
+ posting.frequencies[last]++;
251
+ }
252
+ else {
253
+ posting.documents.push(i);
254
+ posting.frequencies.push(1);
255
+ }
256
+ }
257
+ documentLengths[i] = length;
258
+ totalLength += length;
259
+ }
260
+ // Only read once a word has been found, and then at least one document has
261
+ // a word, so it is a positive number wherever it is used.
262
+ const averageDocumentLength = totalLength / documentCount;
263
+ // Working memory shared by all searches, so that a search costs time in
264
+ // proportion to the documents it finds and not to the size of the index.
265
+ // Both are all zeros between searches: `clear` undoes what `collect` wrote.
266
+ const totals = new Float64Array(documentCount);
267
+ const isMatched = new Uint8Array(documentCount);
268
+ /**
269
+ * Adds the score of every document that contains a keyword into `totals`
270
+ * and returns the positions of those documents, in the order they were
271
+ * first found. The caller reads `totals` and then calls `clear`.
272
+ */
273
+ const collect = (keywords, constants) => {
274
+ if (!Array.isArray(keywords)) {
275
+ throw new TypeError("BM25 index: `keywords` must be an array of strings.");
276
+ }
277
+ const b = readNumber(constants ? constants.b : undefined, DEFAULT_B, 1, "`b` must be a number from 0 to 1.");
278
+ const k1 = readNumber(constants ? constants.k1 : undefined, DEFAULT_K1, Number.MAX_VALUE, "`k1` must be a finite number, 0 or more.");
279
+ // Every keyword is split into words before any score is added. The
280
+ // tokenizer is the caller's code, and none of it runs, and nothing can
281
+ // throw, while `totals` holds a search in progress.
282
+ const words = [];
283
+ for (let k = 0; k < keywords.length; k++) {
284
+ // As in BM25, a number is searched as text and other values match nothing.
285
+ const rawKeyword = keywords[k];
286
+ const keywordWords = toWords(typeof rawKeyword === "number" ? String(rawKeyword) : toText(rawKeyword));
287
+ for (let w = 0; w < keywordWords.length; w++) {
288
+ words.push(keywordWords[w]);
289
+ }
290
+ }
291
+ const matched = [];
292
+ for (let w = 0; w < words.length; w++) {
293
+ const posting = postings.get(words[w]);
294
+ if (posting === undefined) {
295
+ continue;
296
+ }
297
+ const matches = posting.documents.length;
298
+ // The arithmetic below is the same, operation for operation, as in
299
+ // BM25, so both give identical scores when they match the same words.
300
+ const inverseDocumentFrequency = Math.log((documentCount - matches + 0.5) / (matches + 0.5) + 1);
301
+ for (let m = 0; m < matches; m++) {
302
+ const i = posting.documents[m];
303
+ const termFrequency = posting.frequencies[m];
304
+ const relativeLength = (b * documentLengths[i]) / averageDocumentLength;
305
+ const lengthNorm = k1 * (1 - b + relativeLength);
306
+ totals[i] +=
307
+ (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /
308
+ (termFrequency + lengthNorm);
309
+ if (isMatched[i] === 0) {
310
+ isMatched[i] = 1;
311
+ matched.push(i);
312
+ }
313
+ }
314
+ }
315
+ return matched;
316
+ };
317
+ const clear = (matched) => {
318
+ for (let m = 0; m < matched.length; m++) {
319
+ totals[matched[m]] = 0;
320
+ isMatched[matched[m]] = 0;
321
+ }
322
+ };
323
+ return {
324
+ search(keywords, options) {
325
+ const limit = readNumber(options ? options.limit : undefined, Infinity, Infinity, "`limit` must be a number, 0 or more.");
326
+ const matched = collect(keywords, options);
327
+ // The position breaks ties, so the order never depends on the engine's sort.
328
+ matched.sort((first, second) => totals[second] - totals[first] || first - second);
329
+ const hits = new Array(Math.floor(Math.min(matched.length, limit)));
330
+ for (let m = 0; m < hits.length; m++) {
331
+ const i = matched[m];
332
+ hits[m] = { index: i, document: originals[i], score: totals[i] };
333
+ }
334
+ clear(matched);
335
+ return hits;
336
+ },
337
+ scores(keywords, constants) {
338
+ const matched = collect(keywords, constants);
339
+ const scores = new Array(documentCount);
340
+ for (let i = 0; i < documentCount; i++) {
341
+ scores[i] = 0;
342
+ }
343
+ for (let m = 0; m < matched.length; m++) {
344
+ scores[matched[m]] = totals[matched[m]];
345
+ }
346
+ clear(matched);
347
+ return scores;
348
+ },
349
+ };
350
+ }
63
351
  exports.default = BM25;
64
352
  //# sourceMappingURL=BM25.js.map
package/dist/BM25.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"BM25.js","sourceRoot":"","sources":["../BM25.ts"],"names":[],"mappings":";;;AAAA,uBAAuB;AAChB,IAAM,YAAY,GAAG,UAAC,MAAc;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;AACrD,CAAC,CAAC;AAFW,QAAA,YAAY,gBAEvB;AAEF,kDAAkD;AAC3C,IAAM,gBAAgB,GAAG,UAAC,IAAY,EAAE,MAAc;IAC3D,OAAO,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,K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I,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACxC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1C,CAAC;YACD,KAAK,CAAC,OAAO,CAAC,CAAC;YACf,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC;kBAEc,IAAI","sourcesContent":["/** Default value of the free parameter `b`. */\nconst DEFAULT_B = 0.75;\n/** Default value of the free parameter `k1`. */\nconst DEFAULT_K1 = 1.2;\n\n/** Anything that is not a string is scored as an empty document. */\nconst toText = (value: unknown): string =>\n typeof value === \"string\" ? value : \"\";\n\n/** A free parameter is used when it is a real number, `0` included. Anything else falls back to the default. */\nconst resolveConstant = (value: unknown, fallback: number): number =>\n typeof value === \"number\" && !Number.isNaN(value) ? value : fallback;\n\n/** 1 for the ASCII characters that `\\w` matches (letters, digits, underscore), 0 for the rest. */\nconst WORD_CHARACTERS = new Uint8Array(128);\nfor (let code = 0; code < 128; code++) {\n const isWordCharacter =\n (code >= 97 && code <= 122) || // a-z\n (code >= 65 && code <= 90) || // A-Z\n (code >= 48 && code <= 57) || // 0-9\n code === 95; // _\n WORD_CHARACTERS[code] = isWordCharacter ? 1 : 0;\n}\n\n/**\n * Gets word count. A word is a run of ASCII letters, digits and underscores,\n * the same as the regular expression `\\w+`.\n */\nexport const getWordCount = (corpus: string): number => {\n const text = toText(corpus);\n let count = 0;\n let insideWord = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n const isWordCharacter = code < 128 ? WORD_CHARACTERS[code] : 0;\n // A word starts where a word character follows a character that is not one.\n count += isWordCharacter & ~insideWord;\n insideWord = isWordCharacter;\n }\n return count;\n};\n\n/** Counts occurrences of `needle` in `text` that do not overlap. An empty needle occurs zero times. */\nconst countOccurrences = (needle: string, text: string): number => {\n if (needle.length === 0) {\n return 0;\n }\n let count = 0;\n let position = text.indexOf(needle);\n while (position !== -1) {\n count++;\n position = text.indexOf(needle, position + needle.length);\n }\n return count;\n};\n\n/**\n * Number of occurrences of a term in a string.\n *\n * The term is matched literally and case-sensitively, and occurrences do not\n * overlap. It is never interpreted as a regular expression, so terms such as\n * `c++` or `(a+)+$` are safe to pass straight from user input. An empty term\n * occurs zero times.\n */\nexport const getTermFrequency = (term: string, corpus: string): number =>\n countOccurrences(toText(term), toText(corpus));\n\n/** Inverse document frequency. */\nexport const getIDF = (term: string, documents: readonly string[]): number => {\n let relevantDocuments = 0;\n for (let i = 0; i < documents.length; i++) {\n if (toText(documents[i]).includes(term)) {\n relevantDocuments++;\n }\n }\n return Math.log(\n (documents.length - relevantDocuments + 0.5) / (relevantDocuments + 0.5) + 1\n );\n};\n\n/** Represents a document; useful when sorting results.\n */\nexport interface BMDocument {\n /** The document that was scored. */\n document: string;\n /** The score that the document receives. */\n score: number;\n}\n\n/** Constants that are free parameters used in BM25, specifically when generating inverse document frequency. */\nexport interface BMConstants {\n /** Free parameter. Is 0.75 by default. `0` turns length normalization off, `1` applies it fully. */\n b?: number;\n /** Free parameter. Is 1.2 by default. Generally in range [1.2, 2.0]. `0` ignores how often a term occurs. */\n k1?: number;\n}\n\n/** If returns positive, the sorting results in secondEl coming before firstEl, else, firstEl comes before secondEL */\nexport type BMSorter = (firstEl: BMDocument, secondEl: BMDocument) => number;\n\n/** Implementation of Okapi BM25 algorithm.\n *\n * Keywords are matched literally and case-sensitively anywhere in a document.\n *\n * @param documents: Collection of documents.\n * @param keywords: query terms.\n * @param constants: Contains free parameters k1 and b. b=0.75 and k1=1.2 by default.\n * @param sorter: A function that allows you to sort queries by a given rule. If not provided, returns results corresponding to the original order.\n * If this option is provided, the return type will not be an array of scores but an array of documents with their scores.\n *\n * @example\n * const scores = BM25([\"a cat\", \"a dog\"], [\"cat\"]); // number[]\n * const ranked = BM25([\"a cat\", \"a dog\"], [\"cat\"], undefined, (x, y) => y.score - x.score); // BMDocument[]\n */\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants\n): number[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants: BMConstants | undefined,\n sorter: BMSorter\n): BMDocument[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants,\n sorter?: BMSorter\n): number[] | BMDocument[];\nexport function BM25(\n documents: readonly string[],\n keywords: readonly string[],\n constants?: BMConstants,\n sorter?: BMSorter\n): number[] | BMDocument[] {\n if (!Array.isArray(documents)) {\n throw new TypeError(\"BM25: `documents` must be an array of strings.\");\n }\n if (!Array.isArray(keywords)) {\n throw new TypeError(\"BM25: `keywords` must be an array of strings.\");\n }\n const b = resolveConstant(constants ? constants.b : undefined, DEFAULT_B);\n const k1 = resolveConstant(constants ? constants.k1 : undefined, DEFAULT_K1);\n const documentCount = documents.length;\n\n // Each document is measured once.\n const texts: string[] = new Array(documentCount);\n const documentLengths = new Float64Array(documentCount);\n let totalLength = 0;\n for (let i = 0; i < documentCount; i++) {\n const text = toText(documents[i]);\n const length = getWordCount(text);\n texts[i] = text;\n documentLengths[i] = length;\n totalLength += length;\n }\n const averageDocumentLength =\n documentCount > 0 ? totalLength / documentCount : 0;\n\n // The part of the denominator that depends only on the document. A\n // collection with no countable words has no length to normalize by, so every\n // document is treated as being of average length.\n const lengthNorms = new Float64Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n const relativeLength =\n averageDocumentLength > 0\n ? (b * documentLengths[i]) / averageDocumentLength\n : b;\n lengthNorms[i] = k1 * (1 - b + relativeLength);\n }\n\n const scores: number[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scores[i] = 0;\n }\n\n // Each keyword reads every document once. That single pass gives both the\n // term frequencies and the number of documents containing the keyword.\n const matchedDocuments = new Uint32Array(documentCount);\n const matchedFrequencies = new Uint32Array(documentCount);\n for (let k = 0; k < keywords.length; k++) {\n // JavaScript callers may pass a number, such as a year. It is searched as text.\n const rawKeyword: unknown = keywords[k];\n const keyword =\n typeof rawKeyword === \"number\" ? String(rawKeyword) : toText(rawKeyword);\n let matches = 0;\n for (let i = 0; i < documentCount; i++) {\n const termFrequency = countOccurrences(keyword, texts[i]);\n if (termFrequency > 0) {\n matchedDocuments[matches] = i;\n matchedFrequencies[matches] = termFrequency;\n matches++;\n }\n }\n const inverseDocumentFrequency = Math.log(\n (documentCount - matches + 0.5) / (matches + 0.5) + 1\n );\n for (let m = 0; m < matches; m++) {\n const i = matchedDocuments[m];\n const termFrequency = matchedFrequencies[m];\n scores[i] +=\n (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /\n (termFrequency + lengthNorms[i]);\n }\n }\n\n if (sorter) {\n const scoredDocuments: BMDocument[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scoredDocuments[i] = { score: scores[i], document: documents[i] };\n }\n return scoredDocuments.sort(sorter);\n }\n return scores;\n}\n\n/** Options for {@link createIndex}. */\nexport interface BMIndexOptions {\n /**\n * Whether `Dog` and `dog` are different words. `false` by default: documents\n * and keywords are lowercased before they are split into words.\n */\n caseSensitive?: boolean;\n /**\n * Splits a text into words. It is called for every document and for every\n * keyword, after lowercasing unless `caseSensitive` is set. Empty words are\n * dropped. By default a word is a run of letters, digits and underscores in\n * any script. Pass a tokenizer for languages that are written without\n * spaces, or to remove common words or endings.\n */\n tokenizer?: (text: string) => string[];\n}\n\n/**\n * Options for {@link BMIndex.search}. Unlike `BM25`, an index rejects values\n * that cannot give a meaningful score: `k1` must be a finite number of 0 or\n * more and `b` a number from 0 to 1.\n */\nexport interface BMSearchOptions extends BMConstants {\n /** Return at most this many results. All matching documents by default. */\n limit?: number;\n}\n\n/** A document found by {@link BMIndex.search}. */\nexport interface BMHit extends BMDocument {\n /** Position of the document in the array given to {@link createIndex}. */\n index: number;\n}\n\n/** A searchable index of a fixed set of documents, made by {@link createIndex}. */\nexport interface BMIndex {\n /**\n * The documents that contain at least one of the keywords, best match first.\n * Documents with equal scores keep the order they were indexed in.\n */\n search(keywords: readonly string[], options?: BMSearchOptions): BMHit[];\n /**\n * One score per document, in the order the documents were indexed in. A\n * document that contains none of the keywords scores `0`.\n */\n scores(keywords: readonly string[], constants?: BMConstants): number[];\n}\n\n/** The documents containing a word, and how often each one contains it. */\ninterface Posting {\n documents: number[];\n frequencies: number[];\n}\n\n/** `undefined` when the JavaScript engine does not support the pattern. */\nconst compilePattern = (source: string, flags: string): RegExp | undefined => {\n try {\n return new RegExp(source, flags);\n } catch (error) {\n return undefined;\n }\n};\n\n/**\n * The default definition of a word for an index: a run of letters, marks that\n * combine with letters, digits and underscores, in any script. For ASCII text\n * these are the words that `getWordCount` counts. The pattern is compiled at\n * run time because its syntax is newer than the ES2015 this file is built\n * for; engines from before 2018 fall back to ASCII words.\n */\nconst WORDS = compilePattern(\"[\\\\p{L}\\\\p{M}\\\\p{N}_]+\", \"gu\") || /\\w+/g;\n\n/** Reads an option that has to be a number from 0 to `max`. `undefined` gives the default. */\nconst readNumber = (\n value: unknown,\n fallback: number,\n max: number,\n rule: string\n): number => {\n if (value === undefined) {\n return fallback;\n }\n if (typeof value !== \"number\") {\n throw new TypeError(\"BM25 index: \" + rule);\n }\n // Written so that NaN fails it too.\n if (!(value >= 0 && value <= max)) {\n throw new RangeError(\"BM25 index: \" + rule);\n }\n return value;\n};\n\n/**\n * Reads the documents once and builds an index of their words, so that each\n * later search looks words up instead of reading the text again. Worth it when\n * the same documents are searched many times.\n *\n * Matching differs from {@link BM25}: the index matches whole words. `cat`\n * finds the word `cat` and not `concatenate`, and case is ignored unless\n * `caseSensitive` is set. Keywords are split into words the same way as the\n * documents, so the keyword `dog?` finds the word `dog`. The scoring formula\n * and the defaults of `k1` and `b` are those of {@link BM25}.\n *\n * The index is a snapshot. Changing the array afterwards does not change it.\n *\n * @throws TypeError when `documents` is not an array, when `tokenizer` is not\n * a function, or when it returns something other than an array of strings.\n * `search` and `scores` throw a TypeError when `keywords` is not an array or\n * an option is not a number, and a RangeError when an option is out of range.\n *\n * @example\n * const index = createIndex([\"A quick dog\", \"A lazy cat\", \"Stock markets\"]);\n * index.search([\"Dog?\"]); // [{ index: 0, document: \"A quick dog\", score: 0.93... }]\n * index.scores([\"dog\"]); // [0.93..., 0, 0]\n */\nexport function createIndex(\n documents: readonly string[],\n options?: BMIndexOptions\n): BMIndex {\n if (!Array.isArray(documents)) {\n throw new TypeError(\n \"createIndex: `documents` must be an array of strings.\"\n );\n }\n const caseSensitive = options ? options.caseSensitive === true : false;\n const tokenizer = options ? options.tokenizer : undefined;\n if (tokenizer !== undefined && typeof tokenizer !== \"function\") {\n throw new TypeError(\"createIndex: `tokenizer` must be a function.\");\n }\n\n /** The words of a text. A custom tokenizer may return empty words; callers skip those. */\n const toWords = (text: string): string[] => {\n const prepared = caseSensitive ? text : text.toLowerCase();\n if (tokenizer === undefined) {\n return prepared.match(WORDS) || [];\n }\n const words: unknown = tokenizer(prepared);\n if (!Array.isArray(words)) {\n throw new TypeError(\n \"createIndex: `tokenizer` must return an array of strings.\"\n );\n }\n for (let w = 0; w < words.length; w++) {\n if (typeof words[w] !== \"string\") {\n throw new TypeError(\n \"createIndex: `tokenizer` must return an array of strings.\"\n );\n }\n }\n return words;\n };\n\n const documentCount = documents.length;\n const originals = documents.slice();\n // A Map, not an object, so that words such as `constructor` are ordinary keys.\n const postings = new Map<string, Posting>();\n const documentLengths = new Float64Array(documentCount);\n let totalLength = 0;\n for (let i = 0; i < documentCount; i++) {\n const words = toWords(toText(documents[i]));\n let length = 0;\n for (let w = 0; w < words.length; w++) {\n const word = words[w];\n if (word.length === 0) {\n continue;\n }\n length++;\n const posting = postings.get(word);\n if (posting === undefined) {\n postings.set(word, { documents: [i], frequencies: [1] });\n continue;\n }\n // Documents are added in order, so a repeat of the word within this\n // document is always at the end of the list.\n const last = posting.documents.length - 1;\n if (posting.documents[last] === i) {\n posting.frequencies[last]++;\n } else {\n posting.documents.push(i);\n posting.frequencies.push(1);\n }\n }\n documentLengths[i] = length;\n totalLength += length;\n }\n // Only read once a word has been found, and then at least one document has\n // a word, so it is a positive number wherever it is used.\n const averageDocumentLength = totalLength / documentCount;\n\n // Working memory shared by all searches, so that a search costs time in\n // proportion to the documents it finds and not to the size of the index.\n // Both are all zeros between searches: `clear` undoes what `collect` wrote.\n const totals = new Float64Array(documentCount);\n const isMatched = new Uint8Array(documentCount);\n\n /**\n * Adds the score of every document that contains a keyword into `totals`\n * and returns the positions of those documents, in the order they were\n * first found. The caller reads `totals` and then calls `clear`.\n */\n const collect = (\n keywords: readonly string[],\n constants: BMConstants | undefined\n ): number[] => {\n if (!Array.isArray(keywords)) {\n throw new TypeError(\n \"BM25 index: `keywords` must be an array of strings.\"\n );\n }\n const b = readNumber(\n constants ? constants.b : undefined,\n DEFAULT_B,\n 1,\n \"`b` must be a number from 0 to 1.\"\n );\n const k1 = readNumber(\n constants ? constants.k1 : undefined,\n DEFAULT_K1,\n Number.MAX_VALUE,\n \"`k1` must be a finite number, 0 or more.\"\n );\n // Every keyword is split into words before any score is added. The\n // tokenizer is the caller's code, and none of it runs, and nothing can\n // throw, while `totals` holds a search in progress.\n const words: string[] = [];\n for (let k = 0; k < keywords.length; k++) {\n // As in BM25, a number is searched as text and other values match nothing.\n const rawKeyword: unknown = keywords[k];\n const keywordWords = toWords(\n typeof rawKeyword === \"number\" ? String(rawKeyword) : toText(rawKeyword)\n );\n for (let w = 0; w < keywordWords.length; w++) {\n words.push(keywordWords[w]);\n }\n }\n\n const matched: number[] = [];\n for (let w = 0; w < words.length; w++) {\n const posting = postings.get(words[w]);\n if (posting === undefined) {\n continue;\n }\n const matches = posting.documents.length;\n // The arithmetic below is the same, operation for operation, as in\n // BM25, so both give identical scores when they match the same words.\n const inverseDocumentFrequency = Math.log(\n (documentCount - matches + 0.5) / (matches + 0.5) + 1\n );\n for (let m = 0; m < matches; m++) {\n const i = posting.documents[m];\n const termFrequency = posting.frequencies[m];\n const relativeLength =\n (b * documentLengths[i]) / averageDocumentLength;\n const lengthNorm = k1 * (1 - b + relativeLength);\n totals[i] +=\n (inverseDocumentFrequency * (termFrequency * (k1 + 1))) /\n (termFrequency + lengthNorm);\n if (isMatched[i] === 0) {\n isMatched[i] = 1;\n matched.push(i);\n }\n }\n }\n return matched;\n };\n\n const clear = (matched: number[]): void => {\n for (let m = 0; m < matched.length; m++) {\n totals[matched[m]] = 0;\n isMatched[matched[m]] = 0;\n }\n };\n\n return {\n search(keywords, options) {\n const limit = readNumber(\n options ? options.limit : undefined,\n Infinity,\n Infinity,\n \"`limit` must be a number, 0 or more.\"\n );\n const matched = collect(keywords, options);\n // The position breaks ties, so the order never depends on the engine's sort.\n matched.sort(\n (first, second) => totals[second] - totals[first] || first - second\n );\n const hits: BMHit[] = new Array(\n Math.floor(Math.min(matched.length, limit))\n );\n for (let m = 0; m < hits.length; m++) {\n const i = matched[m];\n hits[m] = { index: i, document: originals[i], score: totals[i] };\n }\n clear(matched);\n return hits;\n },\n scores(keywords, constants) {\n const matched = collect(keywords, constants);\n const scores: number[] = new Array(documentCount);\n for (let i = 0; i < documentCount; i++) {\n scores[i] = 0;\n }\n for (let m = 0; m < matched.length; m++) {\n scores[matched[m]] = totals[matched[m]];\n }\n clear(matched);\n return scores;\n },\n };\n}\n\nexport default BM25;\n"]}
package/package.json CHANGED
@@ -1,13 +1,25 @@
1
1
  {
2
2
  "name": "okapibm25",
3
- "version": "1.4.1",
3
+ "version": "2.1.0",
4
4
  "description": "A simple, easy to use implementation of the Okapi BM25 algorithm.",
5
5
  "main": "dist/BM25.js",
6
6
  "types": "dist/BM25.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "sideEffects": false,
7
11
  "scripts": {
12
+ "build": "node scripts/clean.mjs && tsc -p tsconfig.build.json",
13
+ "typecheck": "tsc -p tsconfig.json",
8
14
  "test": "jest",
9
- "prepublish": "npm run test && npm run make-badges && rm -rf dist && tsc",
10
- "make-badges": "istanbul-badges-readme"
15
+ "test:package": "npm run build && node scripts/check-package.mjs",
16
+ "test:api": "npm run build && node scripts/check-api.mjs",
17
+ "test:compat": "npm run build && node compat/run.mjs",
18
+ "test:downstream": "npm run build && node compat/downstream.mjs",
19
+ "bench": "npm run build && node bench/bench.mjs",
20
+ "check": "npm run typecheck && npm test && npm run test:package && node scripts/check-api.mjs",
21
+ "make-badges": "istanbul-badges-readme",
22
+ "prepublishOnly": "npm run check && npm run make-badges"
11
23
  },
12
24
  "author": "furkantoprak",
13
25
  "keywords": [
@@ -15,20 +27,28 @@
15
27
  "bm25",
16
28
  "ranking",
17
29
  "relevance",
18
- "information retrieval"
30
+ "information retrieval",
31
+ "search",
32
+ "typescript"
19
33
  ],
20
34
  "repository": {
21
35
  "type": "git",
22
36
  "url": "https://github.com/FurkanToprak/OkapiBM25.git"
23
37
  },
38
+ "bugs": {
39
+ "url": "https://github.com/FurkanToprak/OkapiBM25/issues"
40
+ },
41
+ "homepage": "https://github.com/FurkanToprak/OkapiBM25#readme",
24
42
  "license": "MIT",
25
43
  "devDependencies": {
26
- "@babel/preset-env": "^7.25.4",
27
- "@babel/preset-typescript": "^7.14.5",
28
- "@types/jest": "^26.0.24",
29
- "istanbul-badges-readme": "^1.4.0",
30
- "jest": "^27.0.6",
31
- "ts-node": "^10.1.0",
32
- "typescript": "^4.2.2"
44
+ "@babel/core": "^8.1.3",
45
+ "@babel/preset-env": "^8.0.7",
46
+ "@babel/preset-typescript": "^8.0.7",
47
+ "@types/jest": "^30.0.0",
48
+ "@types/node": "^26.6.6",
49
+ "fast-check": "^4.11.0",
50
+ "istanbul-badges-readme": "^1.9.0",
51
+ "jest": "^30.5.2",
52
+ "typescript": "^7.0.2"
33
53
  }
34
54
  }
package/BM25.test.ts DELETED
@@ -1,109 +0,0 @@
1
- import BM25, { BMDocument, getTermFrequency, getWordCount } from "./BM25";
2
-
3
- describe("Bare bones functionality", () => {
4
- test("Irrelevant queries should return 0.", () => {
5
- const documents = ["fee", "fi", "fum"];
6
- const query = ["qwerty"];
7
- const results = BM25(documents, query, { k1: 1.3, b: 0.9 }) as number[];
8
- results.forEach((result: number) => {
9
- expect(result).toBe(0);
10
- });
11
- });
12
-
13
- test("Relevant queries should be greater than 0.", () => {
14
- const documents = ["fee", "feel", "I'm feeling lucky."];
15
- const query = ["fee"];
16
- const results = BM25(documents, query) as number[];
17
- results.forEach((result: number) => {
18
- expect(result).toBeGreaterThan(0);
19
- });
20
- });
21
-
22
- test("Make sure word count is detected correctly", () => {
23
- const expectResults = [
24
- {
25
- corpus: "Pass the potatoes.",
26
- expect: 3,
27
- },
28
- { corpus: "pass.the.potatoes", expect: 3 },
29
- { corpus: "pass\nthe\npotatoes.", expect: 3 },
30
- ];
31
- expectResults.forEach((expectResult) => {
32
- const wordCount = getWordCount(expectResult.corpus);
33
- expect(wordCount).toBe(expectResult.expect);
34
- });
35
- const emptyWordCount = getWordCount(null);
36
- expect(emptyWordCount).toBe(0);
37
- });
38
-
39
- test("Expect word frequency to be detected correctly", () => {
40
- // @ts-ignore
41
- const emptyWordFrequency = getTermFrequency("anything", null);
42
- expect(emptyWordFrequency).toBe(0);
43
- const expectResults = [
44
- {
45
- corpus: "Pass the pass.",
46
- term: "pass",
47
- expect: 1,
48
- },
49
- {
50
- corpus: "Pass the pass.",
51
- term: "Pass",
52
- expect: 1,
53
- },
54
- {
55
- corpus: "Pass.pass.pass.",
56
- term: "pass",
57
- expect: 2,
58
- },
59
- ];
60
- expectResults.forEach((expectResult) => {
61
- const result = getTermFrequency(expectResult.term, expectResult.corpus);
62
- expect(result).toBe(expectResult.expect);
63
- });
64
- });
65
- });
66
-
67
- describe("Testing fancy sorting mechanism.", () => {
68
- test("Should sort in ascending order", () => {
69
- const expectResults = new Map<number, string>();
70
- expectResults.set(0, "The least relevant");
71
- expectResults.set(1, "Medium relevant relevant");
72
- expectResults.set(2, "The most relevant relevant relevant relevant");
73
-
74
- const corpuses = Array.from(expectResults.values());
75
- const results = BM25(
76
- corpuses,
77
- ["relevant"],
78
- undefined,
79
- (firstEl, secondEl) => {
80
- return firstEl.score - secondEl.score;
81
- }
82
- ) as BMDocument[];
83
- results.forEach((result, index) => {
84
- const expectedDocument = expectResults.get(index);
85
- expect(expectedDocument).toEqual(result.document);
86
- });
87
- });
88
-
89
- test("Should sort in descending order", () => {
90
- const expectResults = new Map<number, string>();
91
- expectResults.set(2, "The least relevant");
92
- expectResults.set(1, "Medium relevant relevant");
93
- expectResults.set(0, "The most relevant relevant relevant relevant");
94
-
95
- const corpuses = Array.from(expectResults.values());
96
- const results = BM25(
97
- corpuses,
98
- ["relevant"],
99
- undefined,
100
- (firstEl, secondEl) => {
101
- return secondEl.score - firstEl.score;
102
- }
103
- ) as BMDocument[];
104
- results.forEach((result, index) => {
105
- const expectedDocument = expectResults.get(index);
106
- expect(expectedDocument).toEqual(result.document);
107
- });
108
- });
109
- });