ErrorModel

Struct ErrorModel 

Source
pub struct ErrorModel {
    pub p_deletion: f64,
    pub p_insertion: f64,
    pub p_substitution: f64,
    pub p_transposition: f64,
    /* private fields */
}
Expand description

Error model for the noisy channel model

Fields§

§p_deletion: f64

Probability of deletion errors

§p_insertion: f64

Probability of insertion errors

§p_substitution: f64

Probability of substitution errors

§p_transposition: f64

Probability of transposition errors

Implementations§

Source§

impl ErrorModel

Source

pub fn new( p_deletion: f64, p_insertion: f64, p_substitution: f64, p_transposition: f64, ) -> Self

Create a new error model with custom error probabilities

Examples found in repository?
examples/statistical_spelling_demo.rs (line 393)
387fn noise_model_demo() -> Result<(), Box<dyn std::error::Error>> {
388    println!("\n=== Error Model Demo ===\n");
389
390    // Create different error models with varying error type probabilities
391    let models = [
392        ("Default", ErrorModel::default()),
393        ("Deletion-heavy", ErrorModel::new(0.7, 0.1, 0.1, 0.1)),
394        ("Insertion-heavy", ErrorModel::new(0.1, 0.7, 0.1, 0.1)),
395        ("Substitution-heavy", ErrorModel::new(0.1, 0.1, 0.7, 0.1)),
396        ("Transposition-heavy", ErrorModel::new(0.1, 0.1, 0.1, 0.7)),
397    ];
398
399    // Test cases for different error types
400    let test_pairs = [
401        ("recieve", "receive"),        // Transposition (i and e)
402        ("acheive", "achieve"),        // Transposition (i and e)
403        ("languge", "language"),       // Deletion (missing 'a')
404        ("programing", "programming"), // Deletion (missing 'm')
405        ("probblem", "problem"),       // Insertion (extra 'b')
406        ("committe", "committee"),     // Insertion (missing 'e')
407        ("definately", "definitely"),  // Substitution ('a' instead of 'i')
408        ("seperate", "separate"),      // Substitution ('e' instead of 'a')
409    ];
410
411    // Test each error model
412    println!(
413        "{:<20} {:<12} {:<12} {:<12} {:<12} {:<12}",
414        "Model", "Delete Prob", "Insert Prob", "Subst Prob", "Transp Prob", "Example"
415    );
416    println!("{:-<80}", "");
417
418    for (name, model) in &models {
419        // Pick one example to show
420        let (typo, correct) = test_pairs[0];
421        let probability = model.error_probability(typo, correct);
422
423        println!(
424            "{:<20} {:<12.2} {:<12.2} {:<12.2} {:<12.2} {:<12.4}",
425            name,
426            model.p_deletion,
427            model.p_insertion,
428            model.p_substitution,
429            model.p_transposition,
430            probability
431        );
432    }
433
434    println!("\nError probabilities for different error types (using default model):");
435
436    let default_model = ErrorModel::default();
437
438    for (typo, correct) in &test_pairs {
439        let prob = default_model.error_probability(typo, correct);
440        println!("{typo:<12} -> {correct:<12}: {prob:.6}");
441    }
442
443    println!("\nImpact on correction with custom error model:");
444
445    // Create a statistical corrector with a custom error model
446    let custom_config = StatisticalCorrectorConfig {
447        language_model_weight: 0.3,
448        edit_distance_weight: 0.7,
449        ..Default::default()
450    };
451
452    let mut custom_corrector = StatisticalCorrector::new(custom_config);
453    train_language_model(&mut custom_corrector);
454    add_example_words(&mut custom_corrector);
455
456    // Create a transposition-heavy error model (good for common spelling errors)
457    let transposition_model = ErrorModel::new(0.1, 0.1, 0.1, 0.7);
458    custom_corrector.set_error_model(transposition_model);
459
460    // Test some examples
461    println!("\nCorrecting text with transposition-heavy error model:");
462    let testtext = "I recieved a mesage about thier acheivements.";
463    let corrected = custom_corrector.correcttext(testtext)?;
464
465    println!("Before: {testtext}");
466    println!("After:  {corrected}");
467
468    Ok(())
469}
Source

pub fn with_max_distance(self, maxdistance: usize) -> Self

Set the maximum edit distance to consider

Source

pub fn error_probability(&self, typo: &str, correct: &str) -> f64

Calculate the error probability P(typo | correct)

Examples found in repository?
examples/statistical_spelling_demo.rs (line 421)
387fn noise_model_demo() -> Result<(), Box<dyn std::error::Error>> {
388    println!("\n=== Error Model Demo ===\n");
389
390    // Create different error models with varying error type probabilities
391    let models = [
392        ("Default", ErrorModel::default()),
393        ("Deletion-heavy", ErrorModel::new(0.7, 0.1, 0.1, 0.1)),
394        ("Insertion-heavy", ErrorModel::new(0.1, 0.7, 0.1, 0.1)),
395        ("Substitution-heavy", ErrorModel::new(0.1, 0.1, 0.7, 0.1)),
396        ("Transposition-heavy", ErrorModel::new(0.1, 0.1, 0.1, 0.7)),
397    ];
398
399    // Test cases for different error types
400    let test_pairs = [
401        ("recieve", "receive"),        // Transposition (i and e)
402        ("acheive", "achieve"),        // Transposition (i and e)
403        ("languge", "language"),       // Deletion (missing 'a')
404        ("programing", "programming"), // Deletion (missing 'm')
405        ("probblem", "problem"),       // Insertion (extra 'b')
406        ("committe", "committee"),     // Insertion (missing 'e')
407        ("definately", "definitely"),  // Substitution ('a' instead of 'i')
408        ("seperate", "separate"),      // Substitution ('e' instead of 'a')
409    ];
410
411    // Test each error model
412    println!(
413        "{:<20} {:<12} {:<12} {:<12} {:<12} {:<12}",
414        "Model", "Delete Prob", "Insert Prob", "Subst Prob", "Transp Prob", "Example"
415    );
416    println!("{:-<80}", "");
417
418    for (name, model) in &models {
419        // Pick one example to show
420        let (typo, correct) = test_pairs[0];
421        let probability = model.error_probability(typo, correct);
422
423        println!(
424            "{:<20} {:<12.2} {:<12.2} {:<12.2} {:<12.2} {:<12.4}",
425            name,
426            model.p_deletion,
427            model.p_insertion,
428            model.p_substitution,
429            model.p_transposition,
430            probability
431        );
432    }
433
434    println!("\nError probabilities for different error types (using default model):");
435
436    let default_model = ErrorModel::default();
437
438    for (typo, correct) in &test_pairs {
439        let prob = default_model.error_probability(typo, correct);
440        println!("{typo:<12} -> {correct:<12}: {prob:.6}");
441    }
442
443    println!("\nImpact on correction with custom error model:");
444
445    // Create a statistical corrector with a custom error model
446    let custom_config = StatisticalCorrectorConfig {
447        language_model_weight: 0.3,
448        edit_distance_weight: 0.7,
449        ..Default::default()
450    };
451
452    let mut custom_corrector = StatisticalCorrector::new(custom_config);
453    train_language_model(&mut custom_corrector);
454    add_example_words(&mut custom_corrector);
455
456    // Create a transposition-heavy error model (good for common spelling errors)
457    let transposition_model = ErrorModel::new(0.1, 0.1, 0.1, 0.7);
458    custom_corrector.set_error_model(transposition_model);
459
460    // Test some examples
461    println!("\nCorrecting text with transposition-heavy error model:");
462    let testtext = "I recieved a mesage about thier acheivements.";
463    let corrected = custom_corrector.correcttext(testtext)?;
464
465    println!("Before: {testtext}");
466    println!("After:  {corrected}");
467
468    Ok(())
469}
Source

pub fn min_edit_operations(&self, typo: &str, correct: &str) -> Vec<EditOp>

Find the minimum edit operations to transform correct into typo

Source

pub fn levenshtein_with_ops( &self, s1: &str, s2: &str, operations: &mut Vec<EditOp>, ) -> usize

Legacy implementation of Levenshtein distance with operations tracking

Trait Implementations§

Source§

impl Clone for ErrorModel

Source§

fn clone(&self) -> ErrorModel

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ErrorModel

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ErrorModel

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V