SPB Git

Repository Public

EditDistance.swift 10.9 KB 242 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : Shared/Sources/PredictionCore/EditDistance.swift10// Description      : Bounded, weighted Damerau-Levenshtein (optimal string11//                    alignment) with key-proximity costs.12// Module           : PredictionCore13// 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 Foundation9091/// Which keys touch which, for a physical layout. Bit n of `neighbours[m]` = letter n is adjacent to letter m.92struct KeyProximity: Sendable {93    let neighbours: [UInt32]9495    static let qwerty = KeyProximity(rows: [("qwertyuiop", 0), ("asdfghjkl", 0.5), ("zxcvbnm", 1.5)])96    static let azerty = KeyProximity(rows: [("azertyuiop", 0), ("qsdfghjklm", 0), ("wxcvbn", 2)])9798    static func table(for geometry: KeyGeometry) -> KeyProximity {99        switch geometry {100        case .qwerty: qwerty101        case .azerty: azerty102        }103    }104105    private init(rows: [(String, Double)]) {106        var positions: [(letter: Int, row: Int, x: Double)] = []107        for (rowIndex, row) in rows.enumerated() {108            for (column, scalar) in row.0.unicodeScalars.enumerated() {109                positions.append((Int(scalar.value) - 0x61, rowIndex, Double(column) + row.1))110            }111        }112        var neighbours = [UInt32](repeating: 0, count: 26)113        for a in positions {114            for b in positions where a.letter != b.letter {115                let rowGap = abs(a.row - b.row)116                let reach = rowGap == 0 ? 1.0 : 0.75117                if rowGap <= 1, abs(a.x - b.x) <= reach {118                    neighbours[a.letter] |= 1 << UInt32(b.letter)119                }120            }121        }122        self.neighbours = neighbours123    }124125    @inline(__always)126    func areNeighbours(_ a: UInt8, _ b: UInt8) -> Bool {127        guard a >= 0x61, a <= 0x7A, b >= 0x61, b <= 0x7A else { return false }128        return neighbours[Int(a - 0x61)] & (1 << UInt32(b - 0x61)) != 0129    }130}131132/// Reusable scratch rows so that scanning thousands of candidates allocates nothing.133struct EditDistanceScratch {134    var previous2 = [Float](repeating: 0, count: Lexicon.maxKeyLength + 2)135    var previous = [Float](repeating: 0, count: Lexicon.maxKeyLength + 2)136    var current = [Float](repeating: 0, count: Lexicon.maxKeyLength + 2)137}138139enum EditDistance {140    static let neighbourSubstitution: Float = 0.55141    static let substitution: Float = 1.0142    static let missingLetter: Float = 0.9143    static let missingDoubledLetter: Float = 0.6144    static let missingPunctuation: Float = 0.25145    static let extraLetter: Float = 0.9146    static let extraDoubledLetter: Float = 0.5147    static let extraNeighbourLetter: Float = 0.7148    static let transposition: Float = 0.7149    static let firstLetterPenalty: Float = 0.45150151    /// Cost of turning what was typed into `candidate`, or nil when it exceeds `limit`.152    /// Both are folded UTF-8 keys; `candidate` is addressed inside a shared blob to avoid copies.153    static func cost(154        typed: [UInt8],155        candidate blob: [UInt8],156        range: Range<Int>,157        proximity: KeyProximity,158        limit: Float,159        scratch: inout EditDistanceScratch160    ) -> Float? {161        let n = typed.count, m = range.count162        guard n <= Lexicon.maxKeyLength, m <= Lexicon.maxKeyLength, n > 0, m > 0 else { return nil }163        let base = range.lowerBound164        return typed.withUnsafeBufferPointer { t -> Float? in165            blob.withUnsafeBufferPointer { c -> Float? in166                scratch.previous2.withUnsafeMutableBufferPointer { p2 -> Float? in167                    scratch.previous.withUnsafeMutableBufferPointer { p1 -> Float? in168                        scratch.current.withUnsafeMutableBufferPointer { cur -> Float? in169                            var rowPrev2 = p2, rowPrev = p1, rowCur = cur170                            // Row 0: the candidate's first j letters are all missing from what was typed.171                            rowPrev[0] = 0172                            var j = 1173                            while j <= m {174                                rowPrev[j] = rowPrev[j - 1] + insertCost(c, base, j - 1, m)175                                j += 1176                            }177                            var previousRowMin: Float = 0178                            var i = 1179                            while i <= n {180                                let ti = t[i - 1]181                                rowCur[0] = rowPrev[0] + deleteCost(t, i - 1, n, proximity)182                                var rowMin = rowCur[0]183                                j = 1184                                while j <= m {185                                    let cj = c[base + j - 1]186                                    var sub: Float = 0187                                    if ti != cj {188                                        sub = proximity.areNeighbours(ti, cj) ? neighbourSubstitution : substitution189                                        if i == 1, j == 1 { sub += firstLetterPenalty }190                                    }191                                    var best = rowPrev[j - 1] + sub192                                    let del = rowPrev[j] + deleteCost(t, i - 1, n, proximity)193                                    if del < best { best = del }194                                    let ins = rowCur[j - 1] + insertCost(c, base, j - 1, m)195                                    if ins < best { best = ins }196                                    if i > 1, j > 1, ti == c[base + j - 2], t[i - 2] == cj, ti != cj {197                                        let swap = rowPrev2[j - 2] + transposition198                                        if swap < best { best = swap }199                                    }200                                    rowCur[j] = best201                                    if best < rowMin { rowMin = best }202                                    j += 1203                                }204                                // A transposition reaches back two rows, so both must be over the limit to give up.205                                if rowMin > limit, previousRowMin > limit { return nil }206                                previousRowMin = rowMin207                                let recycled = rowPrev2208                                rowPrev2 = rowPrev209                                rowPrev = rowCur210                                rowCur = recycled211                                i += 1212                            }213                            let total = rowPrev[m]214                            return total <= limit ? total : nil215                        }216                    }217                }218            }219        }220    }221222    /// A letter of the candidate that was not typed.223    @inline(__always)224    private static func insertCost(_ c: UnsafeBufferPointer<UInt8>, _ base: Int, _ j: Int, _ m: Int) -> Float {225        let letter = c[base + j]226        if letter == 0x27 || letter == 0x2D { return missingPunctuation }227        if (j > 0 && c[base + j - 1] == letter) || (j + 1 < m && c[base + j + 1] == letter) { return missingDoubledLetter }228        return j == 0 ? missingLetter + firstLetterPenalty : missingLetter229    }230231    /// A typed letter that is not in the candidate.232    @inline(__always)233    private static func deleteCost(_ t: UnsafeBufferPointer<UInt8>, _ i: Int, _ n: Int, _ proximity: KeyProximity) -> Float {234        let letter = t[i]235        if (i > 0 && t[i - 1] == letter) || (i + 1 < n && t[i + 1] == letter) { return extraDoubledLetter }236        if (i > 0 && proximity.areNeighbours(t[i - 1], letter)) || (i + 1 < n && proximity.areNeighbours(t[i + 1], letter)) {237            return i == 0 ? extraNeighbourLetter + firstLetterPenalty : extraNeighbourLetter238        }239        return i == 0 ? extraLetter + firstLetterPenalty : extraLetter240    }241}242
Files main
Menu

Theme