liblevenshtein 0.9.1

Levenshtein/Universal Automata for approximate string matching using various dictionary backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Articulatory-aware operation costs for Levenshtein automata.
//!
//! This module provides `ArticulatoryCosts`, a configuration structure for
//! assigning phonetically-informed substitution costs based on articulatory
//! feature distances between characters.
//!
//! # Overview
//!
//! Unlike standard Levenshtein distance where all substitutions cost 1.0,
//! articulatory costs reflect phonetic similarity:
//!
//! - **Similar sounds**: /p/ → /b/ (voicing only) costs less than /p/ → /h/
//! - **Vowel gradation**: /i/ → /e/ (height difference) costs less than /i/ → /o/
//! - **Place of articulation**: Adjacent places (bilabial ↔ labiodental) cost less
//!
//! # Example
//!
//! ```rust,ignore
//! use liblevenshtein::transducer::ArticulatoryCosts;
//!
//! let costs = ArticulatoryCosts::default();
//!
//! // Similar sounds have low substitution cost
//! let pb_cost = costs.substitution_cost('p', 'b');
//! assert!(pb_cost < 0.5); // Only voicing differs
//!
//! // Distant sounds have high substitution cost
//! let ph_cost = costs.substitution_cost('p', 'h');
//! assert!(ph_cost > 0.7); // Place + manner differ significantly
//! ```
//!
//! # Integration with Automata
//!
//! These costs integrate with the float-weighted Levenshtein automata
//! (`IntersectionF64`, `QueryIteratorF64`) for phonetically-aware fuzzy matching.
//!
//! # Theoretical Basis
//!
//! The articulatory distance model is based on IPA phonetic features:
//! - **Place of articulation**: bilabial → glottal (9 positions)
//! - **Manner of articulation**: stop, fricative, nasal, approximant, etc.
//! - **Voicing**: voiced vs voiceless
//! - **Vowel features**: height, backness, rounding
//!
//! See `src/phonetic/feature_distance.rs` for the underlying distance computation.

use std::fmt;

use super::costs_f64::OperationCostsF64;
// `crate::phonetic` (hence `FeatureDistanceWeights`) is gated behind
// `phonetic-rules`; this module is always compiled, so the per-feature weight
// support is itself gated behind the same feature.
#[cfg(feature = "phonetic-rules")]
use crate::phonetic::feature_distance::FeatureDistanceWeights;

/// Weight for articulatory distance in substitution cost blending.
/// 0.0 = use base cost only, 1.0 = use articulatory distance only.
const DEFAULT_ARTICULATION_WEIGHT: f64 = 0.6;

/// Threshold below which substitution is considered "free" (near-identical sounds).
const FREE_SUBSTITUTION_THRESHOLD: f64 = 0.15;

/// Operation costs with articulatory feature awareness.
///
/// Extends `OperationCostsF64` by providing character-specific substitution
/// costs based on phonetic similarity.
///
/// # Fields
///
/// | Field | Description |
/// |-------|-------------|
/// | `base` | Base operation costs (insertion, deletion, transposition, etc.) |
/// | `articulation_weight` | Weight for articulatory distance in substitution (0.0-1.0) |
/// | `free_substitution_threshold` | Distance below which sounds are "free" to substitute |
///
/// # Cost Blending
///
/// The substitution cost is computed as:
///
/// ```text
/// cost = base.substitution * (1 - weight) + art_distance * weight
/// ```
///
/// Where `art_distance` is the articulatory distance from `feature_distance.rs`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ArticulatoryCosts {
    /// Base operation costs for non-substitution operations.
    pub base: OperationCostsF64,

    /// Weight for articulatory distance in substitution cost (0.0-1.0).
    ///
    /// - 0.0: Use base substitution cost only (ignores phonetics)
    /// - 0.5: Equal blend of base cost and articulatory distance
    /// - 1.0: Use articulatory distance only
    pub articulation_weight: f64,

    /// Distance threshold for "free" substitutions.
    ///
    /// If articulatory distance is below this threshold, the sounds are
    /// considered nearly identical and substitution cost is reduced to near-zero.
    pub free_substitution_threshold: f64,

    /// Per-dimension articulatory feature weights used when computing the
    /// articulatory distance for substitution costs. `Default`/`standard`
    /// reproduces liblevenshtein's built-in IPA constants.
    #[cfg(feature = "phonetic-rules")]
    pub feature_weights: FeatureDistanceWeights,
}

impl ArticulatoryCosts {
    /// Create articulatory costs with default settings.
    ///
    /// Uses standard base costs, 0.6 articulation weight, and 0.15 free threshold.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use liblevenshtein::transducer::ArticulatoryCosts;
    ///
    /// let costs = ArticulatoryCosts::new();
    /// assert_eq!(costs.articulation_weight, 0.6);
    /// ```
    #[inline]
    pub const fn new() -> Self {
        Self {
            base: OperationCostsF64::standard(),
            articulation_weight: DEFAULT_ARTICULATION_WEIGHT,
            free_substitution_threshold: FREE_SUBSTITUTION_THRESHOLD,
            #[cfg(feature = "phonetic-rules")]
            feature_weights: FeatureDistanceWeights::standard(),
        }
    }

    /// Create articulatory costs with custom articulation weight.
    ///
    /// # Arguments
    ///
    /// * `weight` - Articulation weight (0.0-1.0)
    ///
    /// # Panics
    ///
    /// Panics if weight is not in [0.0, 1.0].
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use liblevenshtein::transducer::ArticulatoryCosts;
    ///
    /// // Heavily weight articulatory features
    /// let costs = ArticulatoryCosts::with_weight(0.8);
    /// ```
    pub fn with_weight(weight: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&weight),
            "Articulation weight must be in [0.0, 1.0], got {}",
            weight
        );
        Self {
            base: OperationCostsF64::standard(),
            articulation_weight: weight,
            free_substitution_threshold: FREE_SUBSTITUTION_THRESHOLD,
            #[cfg(feature = "phonetic-rules")]
            feature_weights: FeatureDistanceWeights::standard(),
        }
    }

    /// Create articulatory costs with custom base costs.
    ///
    /// # Arguments
    ///
    /// * `base` - Base operation costs
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use liblevenshtein::transducer::{ArticulatoryCosts, OperationCostsF64};
    ///
    /// let base = OperationCostsF64::typo_friendly();
    /// let costs = ArticulatoryCosts::with_base(base);
    /// ```
    pub fn with_base(base: OperationCostsF64) -> Self {
        Self {
            base,
            articulation_weight: DEFAULT_ARTICULATION_WEIGHT,
            free_substitution_threshold: FREE_SUBSTITUTION_THRESHOLD,
            #[cfg(feature = "phonetic-rules")]
            feature_weights: FeatureDistanceWeights::standard(),
        }
    }

    /// Create fully customized articulatory costs.
    ///
    /// # Arguments
    ///
    /// * `base` - Base operation costs
    /// * `articulation_weight` - Weight for articulatory distance (0.0-1.0)
    /// * `free_threshold` - Threshold for free substitutions
    ///
    /// # Panics
    ///
    /// Panics if articulation_weight is not in [0.0, 1.0] or free_threshold is negative.
    pub fn custom(base: OperationCostsF64, articulation_weight: f64, free_threshold: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&articulation_weight),
            "Articulation weight must be in [0.0, 1.0], got {}",
            articulation_weight
        );
        assert!(
            free_threshold >= 0.0,
            "Free substitution threshold must be non-negative, got {}",
            free_threshold
        );
        Self {
            base,
            articulation_weight,
            free_substitution_threshold: free_threshold,
            #[cfg(feature = "phonetic-rules")]
            feature_weights: FeatureDistanceWeights::standard(),
        }
    }

    /// Create articulatory costs with custom per-dimension feature weights
    /// (otherwise default base costs / articulation weight / free threshold).
    #[cfg(feature = "phonetic-rules")]
    pub fn with_feature_weights(feature_weights: FeatureDistanceWeights) -> Self {
        Self {
            base: OperationCostsF64::standard(),
            articulation_weight: DEFAULT_ARTICULATION_WEIGHT,
            free_substitution_threshold: FREE_SUBSTITUTION_THRESHOLD,
            feature_weights,
        }
    }

    /// Compute substitution cost between two characters.
    ///
    /// Blends the base substitution cost with the articulatory distance
    /// according to the articulation weight.
    ///
    /// # Arguments
    ///
    /// * `from` - Source character
    /// * `to` - Target character
    ///
    /// # Returns
    ///
    /// Substitution cost in [0.0, base.substitution]
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use liblevenshtein::transducer::ArticulatoryCosts;
    ///
    /// let costs = ArticulatoryCosts::default();
    ///
    /// // Same character = free
    /// assert_eq!(costs.substitution_cost('a', 'a'), 0.0);
    ///
    /// // Similar sounds = cheap
    /// let pb = costs.substitution_cost('p', 'b');
    /// let pk = costs.substitution_cost('p', 'k');
    /// assert!(pb < pk); // p→b cheaper than p→k
    /// ```
    #[cfg(feature = "phonetic-rules")]
    pub fn substitution_cost(&self, from: char, to: char) -> f64 {
        if from == to {
            return 0.0;
        }

        let art_dist = crate::phonetic::feature_distance::articulatory_distance_weighted(
            from,
            to,
            &self.feature_weights,
        );

        // Check for free substitution (very similar sounds)
        if art_dist < self.free_substitution_threshold {
            return art_dist * 0.1; // Near-zero but not exactly zero
        }

        // Blend base cost with articulatory distance
        self.base.substitution * (1.0 - self.articulation_weight)
            + art_dist * self.articulation_weight
    }

    /// Compute substitution cost between two characters (fallback without phonetic-rules).
    #[cfg(not(feature = "phonetic-rules"))]
    pub fn substitution_cost(&self, from: char, to: char) -> f64 {
        if from == to {
            0.0
        } else {
            self.base.substitution
        }
    }

    /// Check if substitution between two characters is "free" (near-identical sounds).
    ///
    /// Returns `true` if the articulatory distance is below the free threshold.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use liblevenshtein::transducer::ArticulatoryCosts;
    ///
    /// let costs = ArticulatoryCosts::default();
    ///
    /// // Voicing pairs are often free
    /// assert!(costs.is_free_substitution('p', 'b'));
    /// assert!(costs.is_free_substitution('t', 'd'));
    ///
    /// // Distant sounds are not free
    /// assert!(!costs.is_free_substitution('p', 'h'));
    /// ```
    #[cfg(feature = "phonetic-rules")]
    pub fn is_free_substitution(&self, from: char, to: char) -> bool {
        if from == to {
            return true;
        }
        crate::phonetic::feature_distance::articulatory_distance_weighted(
            from,
            to,
            &self.feature_weights,
        ) < self.free_substitution_threshold
    }

    /// Check if substitution is free (fallback without phonetic-rules).
    #[cfg(not(feature = "phonetic-rules"))]
    pub fn is_free_substitution(&self, from: char, to: char) -> bool {
        from == to
    }

    /// Get the insertion cost.
    #[inline]
    pub fn insertion_cost(&self) -> f64 {
        self.base.insertion
    }

    /// Get the deletion cost.
    #[inline]
    pub fn deletion_cost(&self) -> f64 {
        self.base.deletion
    }

    /// Get the transposition cost.
    #[inline]
    pub fn transposition_cost(&self) -> f64 {
        self.base.transposition
    }

    /// Get the split cost.
    #[inline]
    pub fn split_cost(&self) -> f64 {
        self.base.split
    }

    /// Get the merge cost.
    #[inline]
    pub fn merge_cost(&self) -> f64 {
        self.base.merge
    }

    /// Validate that all costs are properly configured.
    ///
    /// Returns `true` if:
    /// - Base costs are valid
    /// - Articulation weight is in [0.0, 1.0]
    /// - Free threshold is non-negative
    pub fn is_valid(&self) -> bool {
        self.base.is_valid()
            && (0.0..=1.0).contains(&self.articulation_weight)
            && self.free_substitution_threshold >= 0.0
    }

    /// Get the minimum non-zero cost among all operations.
    ///
    /// This is useful for computing lower bounds in pruning strategies.
    /// Note: Substitution minimum depends on character pairs, so this
    /// uses the theoretical minimum (near-zero for free substitutions).
    pub fn min_nonzero_cost(&self) -> f64 {
        // Minimum substitution cost is near-zero for free substitutions
        let min_sub = self.free_substitution_threshold * 0.1;

        let costs = [
            min_sub,
            self.base.insertion,
            self.base.deletion,
            self.base.transposition,
            self.base.split,
            self.base.merge,
        ];

        costs
            .iter()
            .copied()
            .filter(|&c| c > 0.0)
            .min_by(|a, b| a.partial_cmp(b).expect("valid f64"))
            .unwrap_or(0.01) // Fallback for edge cases
    }
}

impl Default for ArticulatoryCosts {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for ArticulatoryCosts {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ArticulatoryCosts(weight={:.2}, threshold={:.2}, base={})",
            self.articulation_weight, self.free_substitution_threshold, self.base
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const EPSILON: f64 = 1e-10;

    #[test]
    fn test_default_costs() {
        let costs = ArticulatoryCosts::default();
        assert!((costs.articulation_weight - 0.6).abs() < EPSILON);
        assert!((costs.free_substitution_threshold - 0.15).abs() < EPSILON);
        assert!(costs.is_valid());
    }

    #[test]
    fn test_with_weight() {
        let costs = ArticulatoryCosts::with_weight(0.8);
        assert!((costs.articulation_weight - 0.8).abs() < EPSILON);
        assert!(costs.is_valid());
    }

    #[test]
    fn test_with_base() {
        let base = OperationCostsF64::typo_friendly();
        let costs = ArticulatoryCosts::with_base(base);
        assert!((costs.base.transposition - 0.5).abs() < EPSILON);
        assert!(costs.is_valid());
    }

    #[test]
    fn test_custom() {
        let base = OperationCostsF64::standard();
        let costs = ArticulatoryCosts::custom(base, 0.9, 0.2);
        assert!((costs.articulation_weight - 0.9).abs() < EPSILON);
        assert!((costs.free_substitution_threshold - 0.2).abs() < EPSILON);
        assert!(costs.is_valid());
    }

    #[test]
    #[should_panic(expected = "Articulation weight must be in [0.0, 1.0]")]
    fn test_invalid_weight_panics() {
        ArticulatoryCosts::with_weight(1.5);
    }

    #[test]
    #[should_panic(expected = "Free substitution threshold must be non-negative")]
    fn test_negative_threshold_panics() {
        let base = OperationCostsF64::standard();
        ArticulatoryCosts::custom(base, 0.5, -0.1);
    }

    #[test]
    fn test_same_character_free() {
        let costs = ArticulatoryCosts::default();
        assert!((costs.substitution_cost('a', 'a') - 0.0).abs() < EPSILON);
        assert!((costs.substitution_cost('z', 'z') - 0.0).abs() < EPSILON);
    }

    #[cfg(feature = "phonetic-rules")]
    #[test]
    fn test_voicing_pairs_cheap() {
        let costs = ArticulatoryCosts::default();

        // Voicing pairs should be cheaper than unrelated sounds
        let pb = costs.substitution_cost('p', 'b');
        let ph = costs.substitution_cost('p', 'h');
        assert!(pb < ph, "p→b ({}) should be cheaper than p→h ({})", pb, ph);

        let td = costs.substitution_cost('t', 'd');
        let th = costs.substitution_cost('t', 'h');
        assert!(td < th, "t→d ({}) should be cheaper than t→h ({})", td, th);
    }

    #[cfg(feature = "phonetic-rules")]
    #[test]
    fn test_free_substitution() {
        let costs = ArticulatoryCosts::default();

        // Same character is always free
        assert!(costs.is_free_substitution('a', 'a'));
        assert!(costs.is_free_substitution('p', 'p'));

        // Distant sounds are not free
        assert!(!costs.is_free_substitution('a', 'z'));
        assert!(!costs.is_free_substitution('p', 'h'));
    }

    #[test]
    fn test_other_costs() {
        let costs = ArticulatoryCosts::default();
        assert!((costs.insertion_cost() - 1.0).abs() < EPSILON);
        assert!((costs.deletion_cost() - 1.0).abs() < EPSILON);
        assert!((costs.transposition_cost() - 1.0).abs() < EPSILON);
        assert!((costs.split_cost() - 1.0).abs() < EPSILON);
        assert!((costs.merge_cost() - 1.0).abs() < EPSILON);
    }

    #[test]
    fn test_min_nonzero_cost() {
        let costs = ArticulatoryCosts::default();
        let min = costs.min_nonzero_cost();
        assert!(min > 0.0);
        assert!(min < 1.0); // Should be the near-zero free substitution minimum
    }

    #[test]
    fn test_display() {
        let costs = ArticulatoryCosts::default();
        let s = format!("{}", costs);
        assert!(s.contains("weight=0.60"));
        assert!(s.contains("threshold=0.15"));
    }

    #[cfg(feature = "phonetic-rules")]
    #[test]
    fn articulatory_costs_responds_to_feature_weights() {
        // p/t (voiceless stops, place diff 3) has default articulatory distance
        // 3*0.15 = 0.45 (above the 0.15 free threshold, so it takes the blend
        // branch). Raising `place_step` to 0.4 pushes that distance to the 1.0 cap,
        // which must raise the blended substitution cost.
        let default_costs = ArticulatoryCosts::default();
        let heavy_place = ArticulatoryCosts::with_feature_weights(FeatureDistanceWeights {
            place_step: 0.4,
            ..Default::default()
        });

        let base_cost = default_costs.substitution_cost('p', 't');
        let heavy_cost = heavy_place.substitution_cost('p', 't');
        assert!(
            heavy_cost > base_cost,
            "heavier place_step must raise p/t substitution cost: {base_cost} vs {heavy_cost}"
        );

        // The builder leaves the other configuration knobs at their defaults.
        assert!((heavy_place.articulation_weight - 0.6).abs() < EPSILON);
        assert!((heavy_place.free_substitution_threshold - 0.15).abs() < EPSILON);
        assert!(heavy_place.is_valid());
    }
}