arcweight 0.3.0

A high-performance, modular library for weighted finite state transducers with comprehensive examples and benchmarks
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//! FST difference algorithm.
//!
//! Computes the language difference between two weighted finite-state acceptors,
//! creating an acceptor that recognizes strings accepted by the first but not the second.
//!
//! For acceptors $`A_1`$ and $`A_2`$:
//! $`L(A_1 - A_2) = L(A_1) \cap \overline{L(A_2)} = \{w : w \in L(A_1) \text{ and } w \notin L(A_2)\}`$
//!
//! # Implementation
//!
//! The algorithm constructs the complement of $`A_2`$ by:
//! 1. Determinizing $`A_2`$ to ensure one transition per symbol per state
//! 2. Making the FST complete by adding a sink state for missing transitions
//! 3. Flipping final states (final becomes non-final, non-final becomes final)
//!
//! The result is then computed as $`A_1 \cap \overline{A_2}`$ via intersection.
//!
//! # Complexity
//!
//! - **Time:** $`O(2^{|V_2|})`$ worst case for determinization, then $`O(|V_1| \times |V_2'|)`$ for intersection
//! - **Space:** $`O(|V_1| \times |V_2'|)`$ for state cross product after determinization
//!
//! where $`V_2'`$ is the determinized complement size.
//!
//! # References
//!
//! - John E. Hopcroft and Jeffrey D. Ullman. 1979. *Introduction to Automata Theory,
//!   Languages, and Computation*. Addison-Wesley, Reading, MA.
//! - Mehryar Mohri. 2009. Weighted automata algorithms. In *Handbook of Weighted
//!   Automata*, Manfred Droste, Werner Kuich, and Heiko Vogler (Eds.). Springer,
//!   Berlin, Heidelberg, 213-254.

use crate::algorithms::{determinize, intersect};
use crate::arc::Arc;
use crate::fst::{Fst, Label, MutableFst};
use crate::semiring::{DivisibleSemiring, Semiring};
use crate::{Error, Result};
use core::hash::Hash;
use std::collections::{HashMap, HashSet};

/// Computes the language difference between two finite-state acceptors.
///
/// Creates an acceptor recognizing strings accepted by the first but not the second:
/// $`L(A_1 - A_2) = \{w : w \in L(A_1) \text{ and } w \notin L(A_2)\}`$
///
/// # Arguments
///
/// * `fst1` - The first acceptor (minuend)
/// * `fst2` - The second acceptor (subtrahend)
///
/// # Type Parameters
///
/// * `W` - Weight type implementing [`DivisibleSemiring`] + [`Ord`] + [`Hash`]
/// * `F1` - First FST type implementing [`Fst<W>`]
/// * `F2` - Second FST type implementing [`Fst<W>`]
/// * `M` - Output FST type implementing [`MutableFst<W>`] and [`Default`]
///
/// # Returns
///
/// A new acceptor recognizing the language difference.
///
/// # Errors
///
/// Returns [`Error::Algorithm`] if:
/// - Either input FST is not an acceptor (input labels must equal output labels)
/// - The combined alphabet is empty (no non-epsilon labels)
/// - Determinization or intersection fails
///
/// # Examples
///
/// ```rust
/// use arcweight::prelude::*;
/// use arcweight::algorithms::difference;
///
/// // Acceptor 1: accepts "a" and "ab"
/// let mut acc1 = VectorFst::<TropicalWeight>::new();
/// let s0 = acc1.add_state();
/// let s1 = acc1.add_state();
/// let s2 = acc1.add_state();
/// acc1.set_start(s0);
/// acc1.set_final(s1, TropicalWeight::one()); // accepts "a"
/// acc1.set_final(s2, TropicalWeight::one()); // accepts "ab"
/// acc1.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
/// acc1.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));
///
/// // Acceptor 2: accepts "ab"
/// let mut acc2 = VectorFst::<TropicalWeight>::new();
/// let s0 = acc2.add_state();
/// let s1 = acc2.add_state();
/// let s2 = acc2.add_state();
/// acc2.set_start(s0);
/// acc2.set_final(s2, TropicalWeight::one());
/// acc2.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
/// acc2.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));
///
/// // Difference accepts "a" but not "ab"
/// let diff: VectorFst<TropicalWeight> = difference(&acc1, &acc2)?;
/// assert!(diff.start().is_some());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # References
///
/// - John E. Hopcroft and Jeffrey D. Ullman. 1979. *Introduction to Automata Theory,
///   Languages, and Computation*. Addison-Wesley, Reading, MA.
///
/// [`DivisibleSemiring`]: crate::semiring::DivisibleSemiring
pub fn difference<W, F1, F2, M>(fst1: &F1, fst2: &F2) -> Result<M>
where
    W: DivisibleSemiring + Hash + Clone + Ord + Eq,
    F1: Fst<W>,
    F2: Fst<W>,
    M: MutableFst<W> + Default,
{
    // Step 1: Validate inputs are acceptors
    validate_acceptor(fst1)?;
    validate_acceptor(fst2)?;

    // Step 2: Collect alphabet from both FSTs
    let alphabet = collect_alphabet(fst1, fst2)?;

    // Step 3: Build complement of fst2
    let complement_fst2: M = build_complement(fst2, &alphabet)?;

    // Step 4: Compute intersection of fst1 with complement(fst2)
    intersect(fst1, &complement_fst2)
}

/// Validate that an FST is an acceptor (input labels = output labels)
fn validate_acceptor<W: Semiring, F: Fst<W>>(fst: &F) -> Result<()> {
    for state in fst.states() {
        for arc in fst.arcs(state) {
            if arc.ilabel != arc.olabel {
                return Err(Error::Algorithm(
                    "FST must be an acceptor (input = output labels)".into(),
                ));
            }
        }
    }
    Ok(())
}

/// Collect the alphabet (all non-epsilon labels) used in both FSTs
fn collect_alphabet<W: Semiring, F1: Fst<W>, F2: Fst<W>>(
    fst1: &F1,
    fst2: &F2,
) -> Result<HashSet<Label>> {
    let mut alphabet = HashSet::new();

    // Collect labels from fst1
    for state in fst1.states() {
        for arc in fst1.arcs(state) {
            if arc.ilabel != 0 {
                // Skip epsilon
                alphabet.insert(arc.ilabel);
            }
        }
    }

    // Collect labels from fst2
    for state in fst2.states() {
        for arc in fst2.arcs(state) {
            if arc.ilabel != 0 {
                // Skip epsilon
                alphabet.insert(arc.ilabel);
            }
        }
    }

    if alphabet.is_empty() {
        return Err(Error::Algorithm(
            "Empty alphabet in difference operation".into(),
        ));
    }

    Ok(alphabet)
}

/// Build the complement acceptor for the given FST over the specified alphabet
fn build_complement<
    W: DivisibleSemiring + Clone + Ord + Hash + Eq,
    F: Fst<W>,
    M: MutableFst<W> + Default,
>(
    fst: &F,
    alphabet: &HashSet<Label>,
) -> Result<M> {
    // First, ensure the FST is deterministic and complete
    let det_fst: M = determinize(fst)?;
    let complete_fst: M = make_complete(&det_fst, alphabet)?;

    // Now build the complement by flipping final states
    let mut complement = M::default();

    // Copy all states
    let mut state_map = HashMap::new();
    for state in complete_fst.states() {
        let new_state = complement.add_state();
        state_map.insert(state, new_state);
    }

    // Set start state
    if let Some(start) = complete_fst.start() {
        if let Some(&new_start) = state_map.get(&start) {
            complement.set_start(new_start);
        }
    }

    // Copy all arcs
    for state in complete_fst.states() {
        if let Some(&new_state) = state_map.get(&state) {
            for arc in complete_fst.arcs(state) {
                if let Some(&new_nextstate) = state_map.get(&arc.nextstate) {
                    complement.add_arc(
                        new_state,
                        Arc::new(arc.ilabel, arc.olabel, arc.weight.clone(), new_nextstate),
                    );
                }
            }
        }
    }

    // Flip final states: non-final becomes final, final becomes non-final
    for state in complete_fst.states() {
        if let Some(&new_state) = state_map.get(&state) {
            if complete_fst.final_weight(state).is_none() {
                // Was non-final, make it final in complement
                complement.set_final(new_state, W::one());
            }
            // Was final, leave it non-final in complement (don't set final weight)
        }
    }

    Ok(complement)
}

/// Make an FST complete by adding transitions to a sink state for missing alphabet symbols
fn make_complete<
    W: DivisibleSemiring + Clone + Ord + Hash + Eq,
    F: Fst<W>,
    M: MutableFst<W> + Default,
>(
    fst: &F,
    alphabet: &HashSet<Label>,
) -> Result<M> {
    let mut complete = M::default();

    // Copy all original states
    let mut state_map = HashMap::new();
    for state in fst.states() {
        let new_state = complete.add_state();
        state_map.insert(state, new_state);
    }

    // Add sink state (non-final state that accepts everything)
    let sink_state = complete.add_state();

    // Set start state
    if let Some(start) = fst.start() {
        if let Some(&new_start) = state_map.get(&start) {
            complete.set_start(new_start);
        }
    }

    // Copy original arcs and final weights
    for state in fst.states() {
        if let Some(&new_state) = state_map.get(&state) {
            // Copy final weight
            if let Some(weight) = fst.final_weight(state) {
                complete.set_final(new_state, weight.clone());
            }

            // Copy arcs
            for arc in fst.arcs(state) {
                if let Some(&new_nextstate) = state_map.get(&arc.nextstate) {
                    complete.add_arc(
                        new_state,
                        Arc::new(arc.ilabel, arc.olabel, arc.weight.clone(), new_nextstate),
                    );
                }
            }
        }
    }

    // Add missing transitions to sink state
    for state in fst.states() {
        if let Some(&new_state) = state_map.get(&state) {
            // Collect existing outgoing labels for this state
            let mut existing_labels = HashSet::new();
            for arc in fst.arcs(state) {
                if arc.ilabel != 0 {
                    existing_labels.insert(arc.ilabel);
                }
            }

            // Add transitions to sink for missing labels
            for &label in alphabet {
                if !existing_labels.contains(&label) {
                    complete.add_arc(new_state, Arc::new(label, label, W::one(), sink_state));
                }
            }
        }
    }

    // Add self-loops on sink state for all alphabet symbols
    for &label in alphabet {
        complete.add_arc(sink_state, Arc::new(label, label, W::one(), sink_state));
    }

    Ok(complete)
}

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

    #[test]
    fn test_validate_acceptor_valid() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        fst.set_start(s0);
        fst.set_final(s1, TropicalWeight::one());

        // Valid acceptor: input = output labels
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));

        assert!(validate_acceptor(&fst).is_ok());
    }

    #[test]
    fn test_validate_acceptor_invalid() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        fst.set_start(s0);
        fst.set_final(s1, TropicalWeight::one());

        // Invalid: different input/output labels (transducer)
        fst.add_arc(s0, Arc::new(1, 2, TropicalWeight::one(), s1));

        assert!(validate_acceptor(&fst).is_err());
    }

    #[test]
    fn test_collect_alphabet_basic() {
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let mut fst2 = VectorFst::<TropicalWeight>::new();

        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst1.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s0));

        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        fst2.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s1));
        fst2.add_arc(s1, Arc::new(3, 3, TropicalWeight::one(), s0));

        let alphabet = collect_alphabet(&fst1, &fst2).unwrap();
        assert_eq!(alphabet.len(), 3);
        assert!(alphabet.contains(&1));
        assert!(alphabet.contains(&2));
        assert!(alphabet.contains(&3));
    }

    #[test]
    fn test_collect_alphabet_with_epsilon() {
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let mut fst2 = VectorFst::<TropicalWeight>::new();

        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.add_arc(s0, Arc::new(0, 0, TropicalWeight::one(), s1)); // Epsilon
        fst1.add_arc(s1, Arc::new(1, 1, TropicalWeight::one(), s0));

        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        fst2.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s1));

        let alphabet = collect_alphabet(&fst1, &fst2).unwrap();
        assert_eq!(alphabet.len(), 2);
        assert!(alphabet.contains(&1));
        assert!(alphabet.contains(&2));
        assert!(!alphabet.contains(&0)); // Epsilon should be excluded
    }

    #[test]
    fn test_collect_alphabet_empty() {
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let mut fst2 = VectorFst::<TropicalWeight>::new();

        // Only epsilon arcs
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.add_arc(s0, Arc::new(0, 0, TropicalWeight::one(), s1));

        let _s0 = fst2.add_state();
        // No arcs in fst2

        let result = collect_alphabet(&fst1, &fst2);
        assert!(result.is_err()); // Should fail with empty alphabet
    }

    #[test]
    fn test_make_complete_basic() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        fst.set_start(s0);
        fst.set_final(s1, TropicalWeight::one());
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));

        let mut alphabet = HashSet::new();
        alphabet.insert(1);
        alphabet.insert(2);

        let complete: VectorFst<TropicalWeight> = make_complete(&fst, &alphabet).unwrap();

        // Should have original states plus sink state
        assert_eq!(complete.num_states(), 3);
        assert!(complete.start().is_some());

        // Should have transitions for all alphabet symbols from all states
        assert!(complete.num_arcs_total() > fst.num_arcs_total());
    }

    #[test]
    fn test_build_complement_simple() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        fst.set_start(s0);
        fst.set_final(s1, TropicalWeight::one());
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));

        let mut alphabet = HashSet::new();
        alphabet.insert(1);

        let complement: VectorFst<TropicalWeight> = build_complement(&fst, &alphabet).unwrap();

        // Complement should have more states (original + sink)
        assert!(complement.num_states() >= fst.num_states());
        assert!(complement.start().is_some());
    }

    #[test]
    fn test_difference_basic() {
        // FST1 accepts "a"
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s1, TropicalWeight::one());
        fst1.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));

        // FST2 accepts "b"
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s1, TropicalWeight::one());
        fst2.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s1));

        // Difference should accept "a" (fst1 - fst2)
        let diff: VectorFst<TropicalWeight> = difference(&fst1, &fst2).unwrap();
        assert!(diff.start().is_some());
        assert!(diff.num_states() > 0);
    }

    #[test]
    fn test_difference_self() {
        // FST accepts "a"
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        fst.set_start(s0);
        fst.set_final(s1, TropicalWeight::one());
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));

        // Difference with itself should be empty
        let diff: VectorFst<TropicalWeight> = difference(&fst, &fst).unwrap();

        // Result should have no final states or should be empty
        let final_count = diff.states().filter(|&s| diff.is_final(s)).count();
        assert_eq!(final_count, 0);
    }

    #[test]
    fn test_difference_empty_fst() {
        let fst1 = VectorFst::<TropicalWeight>::new();
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s0, TropicalWeight::one());

        // Difference with empty FST should fail (empty alphabet)
        let result = difference::<TropicalWeight, _, _, VectorFst<TropicalWeight>>(&fst1, &fst2);
        assert!(result.is_err());
    }

    #[test]
    fn test_difference_non_acceptor() {
        // Create transducer (not acceptor)
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s1, TropicalWeight::one());
        fst1.add_arc(s0, Arc::new(1, 2, TropicalWeight::one(), s1)); // Different input/output

        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s1, TropicalWeight::one());
        fst2.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));

        // Should fail because fst1 is not an acceptor
        let result = difference::<TropicalWeight, _, _, VectorFst<TropicalWeight>>(&fst1, &fst2);
        assert!(result.is_err());
    }

    #[test]
    fn test_difference_overlapping_languages() {
        // FST1 accepts "a" and "ab"
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        let s2 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s1, TropicalWeight::one()); // accepts "a"
        fst1.set_final(s2, TropicalWeight::one()); // accepts "ab"
        fst1.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1)); // a
        fst1.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2)); // b

        // FST2 accepts "ab"
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        let s2 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s2, TropicalWeight::one());
        fst2.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1)); // a
        fst2.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2)); // b

        // Difference should accept "a" but not "ab"
        let diff: VectorFst<TropicalWeight> = difference(&fst1, &fst2).unwrap();
        assert!(diff.start().is_some());
        assert!(diff.num_states() > 0);
    }

    #[test]
    fn test_difference_disjoint_languages() {
        // FST1 accepts "a"
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s1, TropicalWeight::one());
        fst1.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));

        // FST2 accepts "b"
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s1, TropicalWeight::one());
        fst2.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s1));

        // Since languages are disjoint, difference should equal fst1
        let diff: VectorFst<TropicalWeight> = difference(&fst1, &fst2).unwrap();
        assert!(diff.start().is_some());
        assert!(diff.num_states() > 0);

        // Should have at least one final state
        let final_count = diff.states().filter(|&s| diff.is_final(s)).count();
        assert!(final_count > 0);
    }

    #[test]
    fn test_difference_complex_automata() {
        // FST1: accepts strings ending with "a"
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s1, TropicalWeight::one());
        fst1.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1)); // a (final)
        fst1.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s0)); // b (stay)
        fst1.add_arc(s1, Arc::new(1, 1, TropicalWeight::one(), s1)); // a (final)
        fst1.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s0)); // b (back to start)

        // FST2: accepts single "a"
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s1, TropicalWeight::one());
        fst2.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1)); // a

        // Difference should accept strings ending with "a" except single "a"
        let diff: VectorFst<TropicalWeight> = difference(&fst1, &fst2).unwrap();
        assert!(diff.start().is_some());
        assert!(diff.num_states() > 0);
    }

    #[test]
    fn test_difference_preserves_weights() {
        // FST1 with weighted arcs
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s1, TropicalWeight::new(2.0));
        fst1.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(1.5), s1));

        // FST2: empty language (no final states)
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        fst2.set_start(s0);
        fst2.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s0));
        // No final states - accepts nothing

        // Difference should preserve fst1 exactly
        let diff: VectorFst<TropicalWeight> = difference(&fst1, &fst2).unwrap();
        assert!(diff.start().is_some());

        // Check that some weights are preserved (structure may differ)
        let has_final = diff.states().any(|s| diff.is_final(s));
        assert!(has_final);
    }

    #[test]
    fn test_difference_single_state_acceptors() {
        // FST1: single state accepting empty string
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s0, TropicalWeight::one());
        fst1.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s0)); // Self-loop on "a"

        // FST2: different single state
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s0, TropicalWeight::one());
        fst2.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s0)); // Self-loop on "b"

        let diff: VectorFst<TropicalWeight> = difference(&fst1, &fst2).unwrap();
        assert!(diff.start().is_some());
    }

    #[test]
    fn test_difference_epsilon_handling() {
        // FST1 with epsilon transitions
        let mut fst1 = VectorFst::<TropicalWeight>::new();
        let s0 = fst1.add_state();
        let s1 = fst1.add_state();
        let s2 = fst1.add_state();
        fst1.set_start(s0);
        fst1.set_final(s2, TropicalWeight::one());
        fst1.add_arc(s0, Arc::new(0, 0, TropicalWeight::one(), s1)); // epsilon
        fst1.add_arc(s1, Arc::new(1, 1, TropicalWeight::one(), s2)); // a

        // FST2: simple acceptor
        let mut fst2 = VectorFst::<TropicalWeight>::new();
        let s0 = fst2.add_state();
        let s1 = fst2.add_state();
        fst2.set_start(s0);
        fst2.set_final(s1, TropicalWeight::one());
        fst2.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s1)); // b

        // Should handle epsilon transitions properly
        let diff: VectorFst<TropicalWeight> = difference(&fst1, &fst2).unwrap();
        assert!(diff.start().is_some());
    }
}