Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Tests/PredictionCoreTests/LexiconTests.swift10// Description : Lexicon parsing and index, folding, bigram table, edit11// distance.12// Module : PredictionCoreTests13// Repository : https://git.spboucher.ai/sp-keyboard14// Created : 2026-12-0115// Last Modified : 2026-12-0116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import XCTest90@testable import PredictionCore9192final class LexiconTests: XCTestCase {93 private func lexicon(_ text: String) throws -> Lexicon {94 try Lexicon(data: Data(text.utf8), language: .french)95 }9697 func testFoldingMatchesTheBuildScript() {98 XCTAssertEqual(TextFolding.fold("École"), "ecole")99 XCTAssertEqual(TextFolding.fold("niño"), "nino")100 XCTAssertEqual(TextFolding.fold("ÇA"), "ca")101 XCTAssertEqual(TextFolding.fold("cœur"), "coeur")102 XCTAssertEqual(TextFolding.fold("aujourd’hui"), "aujourd'hui")103 XCTAssertEqual(TextFolding.fold("déjà-vu"), "deja-vu")104 XCTAssertEqual(TextFolding.fold("plain"), "plain")105 XCTAssertEqual(TextFolding.fold(""), "")106 XCTAssertEqual(TextFolding.fold("e\u{0301}cole"), "ecole", "decomposed input folds like precomposed input")107 }108109 func testParsesSortedFile() throws {110 let lex = try lexicon("a\t10\nà\t20\nbon\t5\nbonjour\t50\n")111 XCTAssertEqual(lex.words, ["a", "à", "bon", "bonjour"])112 XCTAssertEqual(lex.exactRange(Array("a".utf8)).count, 2)113 XCTAssertEqual(lex.prefixRange(Array("bon".utf8)).map { lex.words[$0] }, ["bon", "bonjour"])114 XCTAssertEqual(lex.exactRange(Array("bon".utf8)).map { lex.words[$0] }, ["bon"])115 XCTAssertTrue(lex.prefixRange(Array("z".utf8)).isEmpty)116 XCTAssertTrue(lex.prefixRange([]).isEmpty)117 XCTAssertEqual(lex.logFrequency.max(), 0)118 XCTAssertEqual(lex.byLength[3].count, 1)119 }120121 func testSortsAnUnsortedFileAndToleratesNoise() throws {122 let lex = try lexicon("zèbre\t3\r\n\nno-tab-here\nbad\tcount\n\t7\nword with space\t4\nabc\t9\n" + String(repeating: "x", count: 60) + "\t2\nmot\t99999999999999999999\n")123 XCTAssertEqual(lex.words, ["abc", "zèbre"], "only well-formed lines survive, in folded order")124 }125126 func testMalformedDataThrows() {127 XCTAssertThrowsError(try lexicon("")) { XCTAssertEqual($0 as? LexiconError, .malformed(.french)) }128 XCTAssertThrowsError(try lexicon("just some prose without any tab\n"))129 XCTAssertThrowsError(try Lexicon(data: Data([0xFF, 0xFE, 0x00, 0x09, 0x31, 0x0A, 0xC3, 0x28, 0x09, 0x31]), language: .english))130 XCTAssertThrowsError(try Lexicon(data: Data((0..<4096).map { UInt8(truncatingIfNeeded: $0 &* 31) }), language: .spanish))131 }132133 func testShippedLexiconsAreSaneAndSorted() throws {134 let provider = DirectoryLexiconProvider(directory: repositoryLexicons)135 let expectations: [(LexiconLanguage, [String])] = [136 (.french, ["bonjour", "école", "courriel", "dépanneur", "magasiner", "tuque", "poutine", "cégep", "pourriel", "aujourd'hui", "Québec", "Montréal"]),137 (.english, ["hello", "I", "I'm", "don't", "tomorrow", "London", "weekend"]),138 (.spanish, ["hola", "gracias", "niño", "mañana", "también", "Madrid"]),139 ]140 for (language, mustContain) in expectations {141 let data = try provider.data(for: language, resource: .words)142 XCTAssertLessThan(data.count, 500_000, "\(language) lexicon stays under 500 KB")143 let lex = try Lexicon(data: data, language: language)144 XCTAssertGreaterThan(lex.count, 29_000)145 XCTAssertLessThan(lex.count, 31_000)146 XCTAssertLessThan(lex.estimatedBytes, 2_000_000)147 for word in mustContain {148 let range = lex.exactRange(Array(TextFolding.fold(word).utf8))149 XCTAssertTrue(range.contains { lex.words[$0] == word }, "\(language): \(word)")150 }151 for index in 1..<lex.count {152 let a = Array(lex.keyBytes[lex.keyRange(index - 1)]), b = Array(lex.keyBytes[lex.keyRange(index)])153 XCTAssertFalse(b.lexicographicallyPrecedes(a), "\(language) not sorted at \(index)")154 }155 let bigrams = BigramTable(data: try provider.data(for: language, resource: .bigrams))156 XCTAssertGreaterThan(bigrams.pairCount, 250)157 XCTAssertFalse(bigrams.continuations(after: BigramTable.sentenceStart).isEmpty)158 XCTAssertFalse(bigrams.continuations(after: BigramTable.fallback).isEmpty)159 }160 // English noise is filtered out of the French and Spanish lists, and elision stubs are not words.161 let french = try Lexicon(data: provider.data(for: .french, resource: .words), language: .french)162 for junk in ["the", "you", "street", "j'", "qu'", "ecole"] {163 XCTAssertFalse(french.exactRange(Array(junk.utf8)).contains { french.words[$0] == junk }, junk)164 }165 }166167 func testBigramTableParsing() {168 let table = BigramTable(data: Data("je\tsuis\t9\nje\tvais\t8\n<s>\tBonjour\t9\nbroken line\nje\tx\tNaN?\n\tempty\t3\n".utf8))169 XCTAssertEqual(table.continuations(after: "je").map(\.word), ["suis", "vais"])170 XCTAssertEqual(table.weight(after: "je", of: "vais"), 8)171 XCTAssertEqual(table.weight(after: "je", of: "rien"), 0)172 XCTAssertEqual(table.weight(after: "tu", of: "es"), 0)173 XCTAssertEqual(table.pairCount, 3)174 XCTAssertEqual(BigramTable(data: Data([0xFF, 0x00, 0xFE])).pairCount, 0)175 }176177 // MARK: Edit distance178179 private func cost(_ typed: String, _ candidate: String, geometry: KeyGeometry = .qwerty, limit: Float = 2) -> Float? {180 var scratch = EditDistanceScratch()181 let blob = Array(candidate.utf8)182 return EditDistance.cost(typed: Array(typed.utf8), candidate: blob, range: 0..<blob.count,183 proximity: .table(for: geometry), limit: limit, scratch: &scratch)184 }185186 func testEditCosts() throws {187 XCTAssertEqual(cost("bonjour", "bonjour"), 0)188 XCTAssertEqual(try XCTUnwrap(cost("bonjuor", "bonjour")), EditDistance.transposition, accuracy: 0.001)189 XCTAssertEqual(try XCTUnwrap(cost("teh", "the", limit: 0.75)), EditDistance.transposition, accuracy: 0.001, "final transposition under a tight limit")190 XCTAssertEqual(try XCTUnwrap(cost("merxi", "merci")), EditDistance.neighbourSubstitution, accuracy: 0.001)191 XCTAssertEqual(try XCTUnwrap(cost("merpi", "merci")), EditDistance.substitution, accuracy: 0.001)192 XCTAssertEqual(try XCTUnwrap(cost("bonjur", "bonjour")), EditDistance.missingLetter, accuracy: 0.001)193 XCTAssertEqual(try XCTUnwrap(cost("adrese", "adresse")), EditDistance.missingDoubledLetter, accuracy: 0.001)194 XCTAssertEqual(try XCTUnwrap(cost("mercii", "merci")), EditDistance.extraDoubledLetter, accuracy: 0.001)195 XCTAssertEqual(try XCTUnwrap(cost("dont", "don't")), EditDistance.missingPunctuation, accuracy: 0.001)196 XCTAssertEqual(try XCTUnwrap(cost("xerci", "merci")), EditDistance.substitution + EditDistance.firstLetterPenalty, accuracy: 0.001)197 XCTAssertNil(cost("bonjour", "maison"))198 XCTAssertNil(cost("abc", "xyz", limit: 1))199 XCTAssertNil(cost("", "abc"))200 XCTAssertNil(cost(String(repeating: "a", count: 80), "abc"))201 }202203 func testKeyProximityDependsOnGeometry() {204 let q = KeyProximity.qwerty, a = KeyProximity.azerty205 XCTAssertTrue(q.areNeighbours(UInt8(ascii: "q"), UInt8(ascii: "w")))206 XCTAssertTrue(q.areNeighbours(UInt8(ascii: "g"), UInt8(ascii: "t")))207 XCTAssertFalse(q.areNeighbours(UInt8(ascii: "q"), UInt8(ascii: "p")))208 XCTAssertTrue(a.areNeighbours(UInt8(ascii: "a"), UInt8(ascii: "z")))209 XCTAssertFalse(q.areNeighbours(UInt8(ascii: "a"), UInt8(ascii: "z")) && !q.areNeighbours(UInt8(ascii: "a"), UInt8(ascii: "s")))210 XCTAssertFalse(a.areNeighbours(UInt8(ascii: "q"), UInt8(ascii: "w")) && a.areNeighbours(UInt8(ascii: "a"), UInt8(ascii: "p")))211 XCTAssertFalse(q.areNeighbours(UInt8(ascii: "'"), UInt8(ascii: "a")))212 // Symmetric213 for x in UInt8(ascii: "a")...UInt8(ascii: "z") {214 for y in UInt8(ascii: "a")...UInt8(ascii: "z") {215 XCTAssertEqual(q.areNeighbours(x, y), q.areNeighbours(y, x))216 XCTAssertEqual(a.areNeighbours(x, y), a.areNeighbours(y, x))217 }218 }219 XCTAssertLessThan(try XCTUnwrap(cost("mazson", "maison", geometry: .azerty)), 1.0 + 0.001)220 }221}222