packages
The Louise packages, each released on its own
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#35 · main · 4 min 07 s
0Étoiles
0Forks
3Issues
| 1 | /// An FM-index over a text (Ferragina & Manzini, 2000): a full-text |
| 2 | /// substring index that answers [`count`] and [`locate`] in time |
| 3 | /// proportional to the pattern, not the text, and [`extract`]s any slice of |
| 4 | /// the text. [`build_corpus`] indexes a list of documents as one text and |
| 5 | /// maps occurrences back to `(document, offset)`. |
| 6 | /// |
| 7 | /// import search/fm |
| 8 | /// |
| 9 | /// let idx = fm.build "banana" |
| 10 | /// fm.count idx "ana" // 2 |
| 11 | /// fm.locate idx "ana" // [1, 3] |
| 12 | /// fm.extract idx 1 3 // "ana" |
| 13 | /// |
| 14 | /// The pieces: a suffix array of the text plus a sentinel (built by prefix |
| 15 | /// doubling, O(n log² n)), its Burrows–Wheeler transform, a table of the |
| 16 | /// characters smaller than each, and occurrence checkpoints every 64 rows |
| 17 | /// of the transform, which backward search walks. Characters are mapped to |
| 18 | /// small integer codes first, so rows compare as `Int`s. |
| 19 | /// |
| 20 | /// An empty pattern has no matches (`count` is 0, `locate` is `[]`). |
| 21 | /// |
| 22 | /// Building is O(n log² n) time and O(n) space: right for a per-user corpus |
| 23 | /// (notes, messages), not for a document store. In the interpreter keep the |
| 24 | /// text small; native builds are the fast ones. |
| 25 | |
| 26 | import std/array.{type Array} |
| 27 | import std/dict.{type Dict} |
| 28 | import std/list |
| 29 | import std/string |
| 30 | |
| 31 | /// An FM-index over one text. |
| 32 | pub opaque type Index |
| 33 | { Index( |
| 34 | text: String // The suffix array of `text` with a sentinel appended (code 0, smaller |
| 35 | // than every character's code): the `n + 1` suffix start positions, |
| 36 | // sorted by the suffix. |
| 37 | , sa: Array< |
| 38 | Int |
| 39 | > // `bwt[i]` is the code of the character before `sa[i]`, cyclically. |
| 40 | , bwt: Array< |
| 41 | Int |
| 42 | > // `c_table[c]`: the rows before code `c` — the count of characters |
| 43 | // smaller than it. |
| 44 | , c_table: Array< |
| 45 | Int |
| 46 | > // `occ[c][j]`: the count of code `c` in the first `j * checkpoint()` |
| 47 | // rows of `bwt`. |
| 48 | , occ: Array< |
| 49 | Array<Int> |
| 50 | > // Each character of the text and its code (1 and up; 0 is the |
| 51 | // sentinel). |
| 52 | , alphabet: Dict<String, Int> |
| 53 | ) |
| 54 | } |
| 55 | |
| 56 | /// An FM-index over a list of documents: their texts joined with the |
| 57 | /// U+0000 separator, and each document's start, so [`corpus_locate`] can |
| 58 | /// answer `(document, offset)` pairs. Documents and patterns may not |
| 59 | /// contain U+0000. |
| 60 | pub opaque type Corpus { Corpus(index: Index, offsets: Array<Int>) } |
| 61 | |
| 62 | /// The occurrence checkpoint period, in `bwt` rows. |
| 63 | fn checkpoint :: -> Int |
| 64 | { |
| 65 | 64 |
| 66 | } |
| 67 | |
| 68 | /// The document separator of a `Corpus`; never in a document or a pattern. |
| 69 | fn separator :: -> String |
| 70 | { |
| 71 | "\u{0}" |
| 72 | } |
| 73 | |
| 74 | /// The element at `i` of `a`, which the caller keeps in range. |
| 75 | fn at :: a: Array<a> i: Int -> a |
| 76 | { |
| 77 | match array.get a i |
| 78 | { Some(x) -> x, None -> panic "search/fm: index {i} out of range" } |
| 79 | } |
| 80 | |
| 81 | /// `n` zeros. |
| 82 | fn zeros :: n: Int -> Array<Int> |
| 83 | { |
| 84 | array.from_list (list.map (list.range 1 n) fn _ { 0 }) |
| 85 | } |
| 86 | |
| 87 | // ---- building ------------------------------------------------------------- |
| 88 | |
| 89 | /// The index of `text`. |
| 90 | pub fn build :: text: String -> Index |
| 91 | { |
| 92 | let chars = string.chars text |
| 93 | let alphabet = make_alphabet chars |
| 94 | let k = dict.size alphabet |
| 95 | let codes = list.map chars fn c { code_of alphabet c } |
| 96 | let ext = array.from_list (list.append codes [0]) |
| 97 | let m = string.length text + 1 |
| 98 | let sa = suffix_array ext |
| 99 | let bwt = array.map sa fn s { at ext ((s + m - 1) % m) } |
| 100 | Index( text: text |
| 101 | , sa: sa |
| 102 | , bwt: bwt |
| 103 | , c_table: c_table_of ext k |
| 104 | , occ: occ_of bwt k |
| 105 | , alphabet: alphabet |
| 106 | ) |
| 107 | } |
| 108 | |
| 109 | /// The distinct characters of `chars`, in order, with codes from 1. |
| 110 | fn make_alphabet :: chars: List<String> -> Dict<String, Int> |
| 111 | { |
| 112 | let (_, d) = |
| 113 | list.fold |
| 114 | (dedupe (list.sort chars)) |
| 115 | (1, dict.empty ()) |
| 116 | fn acc c |
| 117 | { |
| 118 | let (next, d) = acc |
| 119 | (next + 1, dict.insert d c next) |
| 120 | } |
| 121 | d |
| 122 | } |
| 123 | |
| 124 | /// `xs` without duplicates (`xs` is sorted). |
| 125 | fn dedupe :: xs: List<String> -> List<String> |
| 126 | { |
| 127 | match xs |
| 128 | { [x, y, ..rest] -> if x == y |
| 129 | { |
| 130 | dedupe [y, ..rest] |
| 131 | } |
| 132 | else |
| 133 | { |
| 134 | [x, ..dedupe [y, ..rest]] |
| 135 | } |
| 136 | , _ -> xs |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | /// The code of character `c`, which is in the alphabet. |
| 141 | fn code_of :: alphabet: Dict<String, Int> c: String -> Int |
| 142 | { |
| 143 | match dict.get alphabet c |
| 144 | { Some(code) -> code |
| 145 | , None -> panic "search/fm: character not in the alphabet" |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// The suffix array of `codes` by prefix doubling: sort by the first |
| 150 | /// character, then repeatedly by twice as many characters (the rank of the |
| 151 | /// first half and of the second), until every suffix has its own rank. |
| 152 | fn suffix_array :: codes: Array<Int> -> Array<Int> |
| 153 | { |
| 154 | let m = array.length codes |
| 155 | let sa = |
| 156 | list.map |
| 157 | (list.sort (list.map (list.range 0 (m - 1)) fn i { (at codes i, i) })) |
| 158 | fn p { p.1 } |
| 159 | // The codes themselves are the first ranks, in the right order. |
| 160 | double codes sa codes 1 (max_rank codes 0) |
| 161 | } |
| 162 | |
| 163 | fn max_rank :: codes: Array<Int> acc: Int -> Int |
| 164 | { |
| 165 | array.fold |
| 166 | codes |
| 167 | acc |
| 168 | fn hi c |
| 169 | { |
| 170 | if c > hi |
| 171 | { |
| 172 | c |
| 173 | } |
| 174 | else |
| 175 | { |
| 176 | hi |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | fn double :: |
| 182 | codes: Array<Int> |
| 183 | sa: List<Int> |
| 184 | ranks: Array<Int> |
| 185 | k: Int |
| 186 | max_rank: Int |
| 187 | -> Array<Int> |
| 188 | { |
| 189 | let m = array.length codes |
| 190 | if max_rank == m - 1 |
| 191 | { |
| 192 | array.from_list sa |
| 193 | } |
| 194 | else |
| 195 | { |
| 196 | let keyed = list.map sa fn i { (at ranks i, rank_at ranks (i + k), i) } |
| 197 | let sorted = list.sort keyed |
| 198 | let (ranks2, max2) = rerank sorted (zeros m) (-1) (-1, -1) |
| 199 | double codes (list.map sorted fn t { t.2 }) ranks2 (k * 2) max2 |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | /// The rank of the suffix at `i`; `-1` past the end (it sorts first). |
| 204 | fn rank_at :: ranks: Array<Int> i: Int -> Int |
| 205 | { |
| 206 | match array.get ranks i { Some(r) -> r, None -> -1 } |
| 207 | } |
| 208 | |
| 209 | /// Fresh ranks for the sorted `(first, second, index)` triples: equal keys |
| 210 | /// share a rank. Answers the ranks and the highest one. |
| 211 | fn rerank :: |
| 212 | sorted: List<(Int, Int, Int)> |
| 213 | ranks: Array<Int> |
| 214 | r: Int |
| 215 | prev: (Int, Int) |
| 216 | -> (Array<Int>, Int) |
| 217 | { |
| 218 | match sorted |
| 219 | { [] -> (ranks, r) |
| 220 | , [(a, b, i), ..rest] -> |
| 221 | { |
| 222 | let r2 = if (a, b) == prev { r } else { r + 1 } |
| 223 | rerank rest (array.set ranks i r2) r2 (a, b) |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | /// `c_table[c]`: the count of codes smaller than `c` in `codes`. |
| 229 | fn c_table_of :: codes: Array<Int> k: Int -> Array<Int> |
| 230 | { |
| 231 | let counts = |
| 232 | array.fold codes (zeros (k + 1)) fn acc c { array.set acc c (at acc c + 1) } |
| 233 | prefix counts 0 (array.with_capacity (k + 1)) 0 |
| 234 | } |
| 235 | |
| 236 | /// `acc` with the running sum of `counts` from `i` on, as prefix sums. |
| 237 | fn prefix :: counts: Array<Int> i: Int acc: Array<Int> sum: Int -> Array<Int> |
| 238 | { |
| 239 | if i >= array.length counts |
| 240 | { |
| 241 | acc |
| 242 | } |
| 243 | else |
| 244 | { |
| 245 | prefix counts (i + 1) (array.push acc sum) (sum + at counts i) |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | /// The occurrence checkpoints of `bwt`: `occ[c][j]` counts code `c` in the |
| 250 | /// first `j * checkpoint()` rows. |
| 251 | fn occ_of :: bwt: Array<Int> k: Int -> Array<Array<Int>> |
| 252 | { |
| 253 | walk bwt 0 (zeros (k + 1)) (empty_rows (k + 1)) |
| 254 | } |
| 255 | |
| 256 | fn empty_rows :: n: Int -> Array<Array<Int>> |
| 257 | { |
| 258 | array.from_list (list.map (list.range 1 n) fn _ { array.empty () }) |
| 259 | } |
| 260 | |
| 261 | fn walk :: |
| 262 | bwt: Array<Int> |
| 263 | i: Int |
| 264 | counts: Array<Int> |
| 265 | occ: Array<Array<Int>> |
| 266 | -> Array<Array<Int>> |
| 267 | { |
| 268 | let m = array.length bwt |
| 269 | if i > m |
| 270 | { |
| 271 | occ |
| 272 | } |
| 273 | else |
| 274 | { |
| 275 | let occ = if i % checkpoint () == 0 { snapshot occ counts 0 } else { occ } |
| 276 | if i == m |
| 277 | { |
| 278 | occ |
| 279 | } |
| 280 | else |
| 281 | { |
| 282 | let c = at bwt i |
| 283 | walk bwt (i + 1) (array.set counts c (at counts c + 1)) occ |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | /// `occ` with the running `counts` appended to every code's checkpoints. |
| 289 | fn snapshot :: |
| 290 | occ: Array<Array<Int>> |
| 291 | counts: Array<Int> |
| 292 | c: Int |
| 293 | -> Array<Array<Int>> |
| 294 | { |
| 295 | if c >= array.length occ |
| 296 | { |
| 297 | occ |
| 298 | } |
| 299 | else |
| 300 | { |
| 301 | snapshot |
| 302 | (array.set occ c (array.push (at occ c) (at counts c))) |
| 303 | counts |
| 304 | (c + 1) |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | // ---- querying --------------------------------------------------------------- |
| 309 | |
| 310 | /// The occurrences of `pattern`'s characters as codes, or `None` when one |
| 311 | /// is not in the text at all. |
| 312 | fn codes_of :: idx: Index pattern: String -> Option<List<Int>> |
| 313 | { |
| 314 | codes_acc idx.alphabet (string.chars pattern) [] |
| 315 | } |
| 316 | |
| 317 | fn codes_acc :: |
| 318 | alphabet: Dict<String, Int> |
| 319 | chars: List<String> |
| 320 | acc: List<Int> |
| 321 | -> Option<List<Int>> |
| 322 | { |
| 323 | match chars |
| 324 | { [] -> Some(list.reverse acc) |
| 325 | , [c, ..rest] -> match dict.get alphabet c |
| 326 | { Some(code) -> codes_acc alphabet rest [code, ..acc], None -> None } |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | /// The count of code `c` in the first `i` rows of `bwt`. |
| 331 | fn occ_at :: idx: Index c: Int i: Int -> Int |
| 332 | { |
| 333 | let base = at (at idx.occ c) (i / checkpoint ()) |
| 334 | scan idx.bwt c ((i / checkpoint ()) * checkpoint ()) i base |
| 335 | } |
| 336 | |
| 337 | fn scan :: bwt: Array<Int> c: Int j: Int i: Int acc: Int -> Int |
| 338 | { |
| 339 | if j >= i |
| 340 | { |
| 341 | acc |
| 342 | } |
| 343 | else |
| 344 | { |
| 345 | scan bwt c (j + 1) i (if at bwt j == c { acc + 1 } else { acc }) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | /// The suffix-array rows `[sp, ep)` whose suffix starts with `codes` |
| 350 | /// (matched from the last back), or `(0, 0)` for none. |
| 351 | fn row_range :: idx: Index codes: List<Int> sp: Int ep: Int -> (Int, Int) |
| 352 | { |
| 353 | match codes |
| 354 | { [] -> (sp, ep) |
| 355 | , [c, ..rest] -> |
| 356 | { |
| 357 | let first_row = at idx.c_table c |
| 358 | let sp = first_row + occ_at idx c sp |
| 359 | let ep = first_row + occ_at idx c ep |
| 360 | if sp >= ep |
| 361 | { |
| 362 | (0, 0) |
| 363 | } |
| 364 | else |
| 365 | { |
| 366 | row_range idx rest sp ep |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | /// The rows of `pattern` in `idx`: `(0, 0)` for none. An empty pattern |
| 373 | /// has none. |
| 374 | fn rows_of :: idx: Index pattern: String -> (Int, Int) |
| 375 | { |
| 376 | if pattern == "" |
| 377 | { |
| 378 | (0, 0) |
| 379 | } |
| 380 | else |
| 381 | { |
| 382 | match codes_of idx pattern |
| 383 | { None -> (0, 0) |
| 384 | , Some(codes) -> row_range idx (list.reverse codes) 0 (array.length idx.bwt) |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | /// The number of occurrences of `pattern` in the text, overlapping ones |
| 390 | /// included: `count (build "banana") "ana"` is 2. |
| 391 | pub fn count :: idx: Index pattern: String -> Int |
| 392 | { |
| 393 | let (sp, ep) = rows_of idx pattern |
| 394 | ep - sp |
| 395 | } |
| 396 | |
| 397 | /// Whether `pattern` occurs in the text. |
| 398 | pub fn contains :: idx: Index pattern: String -> Bool |
| 399 | { |
| 400 | count idx pattern > 0 |
| 401 | } |
| 402 | |
| 403 | /// The positions where `pattern` occurs in the text, ascending. |
| 404 | pub fn locate :: idx: Index pattern: String -> List<Int> |
| 405 | { |
| 406 | let (sp, ep) = rows_of idx pattern |
| 407 | list.sort (list.map (list.range sp (ep - 1)) fn i { at idx.sa i }) |
| 408 | } |
| 409 | |
| 410 | /// The characters of the text from `at` up to `at + length`. |
| 411 | pub fn extract :: idx: Index at: Int length: Int -> String |
| 412 | { |
| 413 | string.slice idx.text at (at + length) |
| 414 | } |
| 415 | |
| 416 | /// The number of characters of the indexed text. |
| 417 | pub fn length :: idx: Index -> Int |
| 418 | { |
| 419 | string.length idx.text |
| 420 | } |
| 421 | |
| 422 | // ---- corpora ----------------------------------------------------------------- |
| 423 | |
| 424 | /// The index of `docs` as one corpus. Panics when a document contains the |
| 425 | /// U+0000 separator. |
| 426 | pub fn build_corpus :: docs: List<String> -> Corpus |
| 427 | { |
| 428 | check_docs docs |
| 429 | Corpus( index: build (string.join docs (separator ())) |
| 430 | , offsets: offsets_of docs |
| 431 | ) |
| 432 | } |
| 433 | |
| 434 | fn check_docs :: docs: List<String> -> () |
| 435 | { |
| 436 | match docs |
| 437 | { [] -> () |
| 438 | , [doc, ..rest] -> if string.contains doc (separator ()) |
| 439 | { |
| 440 | panic |
| 441 | "search/fm.build_corpus: a document contains U+0000, the document separator" |
| 442 | } |
| 443 | else |
| 444 | { |
| 445 | check_docs rest |
| 446 | } |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | /// Each document's start in the joined text. |
| 451 | fn offsets_of :: docs: List<String> -> Array<Int> |
| 452 | { |
| 453 | let (_, offsets) = |
| 454 | list.fold |
| 455 | docs |
| 456 | (0, []) |
| 457 | fn acc doc |
| 458 | { |
| 459 | let (pos, offsets) = acc |
| 460 | (pos + string.length doc + 1, [pos, ..offsets]) |
| 461 | } |
| 462 | array.from_list (list.reverse offsets) |
| 463 | } |
| 464 | |
| 465 | /// The number of occurrences of `pattern` over the whole corpus. A pattern |
| 466 | /// containing U+0000 has none. |
| 467 | pub fn corpus_count :: c: Corpus pattern: String -> Int |
| 468 | { |
| 469 | if string.contains pattern (separator ()) |
| 470 | { |
| 471 | 0 |
| 472 | } |
| 473 | else |
| 474 | { |
| 475 | count c.index pattern |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | /// The `(document, offset)` pairs where `pattern` occurs, ascending by |
| 480 | /// document, then offset. A pattern containing U+0000 has none. |
| 481 | pub fn corpus_locate :: c: Corpus pattern: String -> List<(Int, Int)> |
| 482 | { |
| 483 | if string.contains pattern (separator ()) |
| 484 | { |
| 485 | [] |
| 486 | } |
| 487 | else |
| 488 | { |
| 489 | use pos <- list.map (locate c.index pattern) |
| 490 | let doc = doc_of c.offsets pos |
| 491 | (doc, pos - at c.offsets doc) |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | /// The document containing position `pos`: the last offset not past it |
| 496 | /// (`offsets[0]` is 0, so a real occurrence always has one). |
| 497 | fn doc_of :: offsets: Array<Int> pos: Int -> Int |
| 498 | { |
| 499 | bisect offsets 0 (array.length offsets) pos |
| 500 | } |
| 501 | |
| 502 | /// The last index in `[lo, hi)` whose offset is at most `pos`; `lo - 1` |
| 503 | /// when there is none. |
| 504 | fn bisect :: offsets: Array<Int> lo: Int hi: Int pos: Int -> Int |
| 505 | { |
| 506 | if lo >= hi |
| 507 | { |
| 508 | lo - 1 |
| 509 | } |
| 510 | else |
| 511 | { |
| 512 | let mid = (lo + hi) / 2 |
| 513 | if at offsets mid <= pos |
| 514 | { |
| 515 | bisect offsets (mid + 1) hi pos |
| 516 | } |
| 517 | else |
| 518 | { |
| 519 | bisect offsets lo mid pos |
| 520 | } |
| 521 | } |
| 522 | } |