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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! State sorting for FST normalization and optimization
//!
//! Renumbers states according to specified traversal order while preserving
//! FST structure, labels, and weights.
//!
//! ## Overview
//!
//! State sorting creates a new FST with states renumbered according to a traversal
//! order (breadth-first, depth-first, or topological) while preserving all structural
//! properties. This improves cache locality during traversal and enables certain
//! optimizations.
//!
//! ## Algorithm
//!
//! 1. Traverse FST using specified order (BFS/DFS/topological)
//! 2. Build state renumbering map: old_id → new_id
//! 3. Create new FST with renumbered states
//! 4. Copy arcs with updated state IDs
//!
//! ## Complexity
//!
//! - **Time:** O(|V| + |E|) - single traversal plus copying
//! - **Space:** O(|V|) - state mapping and queue/stack
//!
//! ## Use Cases
//!
//! - **Cache Optimization:** Improve memory access patterns during FST traversal
//! - **Canonical Ordering:** Standardize state ordering for FST comparison
//! - **Algorithm Preprocessing:** Optimize state order for specific algorithms
//! - **Debugging:** Simplify FST visualization with logical state ordering
//!
//! ## Examples
//!
//! ### Breadth-First Ordering
//!
//! ```
//! use arcweight::prelude::*;
//!
//! let mut fst = VectorFst::<TropicalWeight>::new();
//! let s0 = fst.add_state();
//! let s1 = fst.add_state();
//! let s2 = fst.add_state();
//! fst.set_start(s0);
//! fst.set_final(s2, TropicalWeight::one());
//! fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
//! fst.add_arc(s0, Arc::new(2, 2, TropicalWeight::new(0.3), s2));
//! fst.add_arc(s1, Arc::new(3, 3, TropicalWeight::new(0.2), s2));
//!
//! let sorted = state_sort(&fst, StateSortType::BreadthFirst)?;
//!
//! // Start state is now 0, BFS order for rest
//! assert_eq!(sorted.start(), Some(0));
//! assert_eq!(sorted.num_states(), fst.num_states());
//! # Ok::<(), arcweight::Error>(())
//! ```
//!
//! ### Topological Ordering (Acyclic FST)
//!
//! ```
//! use arcweight::prelude::*;
//!
//! let mut fst = VectorFst::<TropicalWeight>::new();
//! let s0 = fst.add_state();
//! let s1 = fst.add_state();
//! let s2 = fst.add_state();
//! fst.set_start(s0);
//! fst.set_final(s2, TropicalWeight::one());
//! fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
//! fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(0.3), s2));
//!
//! let sorted = state_sort(&fst, StateSortType::Topological)?;
//!
//! // States ordered topologically
//! assert_eq!(sorted.start(), Some(0));
//! # Ok::<(), arcweight::Error>(())
//! ```
//!
//! ## References
//!
//! - Moore, E. F. (1959). The shortest path through a maze. In *Proceedings of
//!   the International Symposium on the Theory of Switching* (pp. 285-292).
//!   Harvard University Press.
//! - Kahn, A. B. (1962). Topological sorting of large networks. *Communications
//!   of the ACM*, 5(11), 558-562. <https://doi.org/10.1145/368996.369025>
//! - Tarjan, R. E. (1972). Depth-first search and linear graph algorithms.
//!   *SIAM Journal on Computing*, 1(2), 146-160. <https://doi.org/10.1137/0201010>

use crate::arc::Arc;
use crate::fst::{Fst, MutableFst, StateId, VectorFst};
use crate::semiring::Semiring;
use crate::{Error, Result};
use std::collections::{HashMap, HashSet, VecDeque};

/// State sorting strategies
///
/// Specifies how states should be renumbered in the output FST.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateSortType {
    /// Breadth-first order from start state
    ///
    /// States are visited in BFS order, ensuring parent states have
    /// lower IDs than their children. Useful for cache locality.
    ///
    /// # Example
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let mut fst = VectorFst::<TropicalWeight>::new();
    /// let s0 = fst.add_state();
    /// let s1 = fst.add_state();
    /// let s2 = fst.add_state();
    /// fst.set_start(s0);
    /// fst.set_final(s2, TropicalWeight::one());
    /// fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
    /// fst.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s2));
    ///
    /// let sorted = state_sort(&fst, StateSortType::BreadthFirst)?;
    /// assert_eq!(sorted.start(), Some(0));
    /// # Ok::<(), arcweight::Error>(())
    /// ```
    BreadthFirst,

    /// Depth-first order from start state
    ///
    /// States are visited in DFS order. Useful for certain graph algorithms
    /// and can improve cache performance for linear paths.
    ///
    /// # Example
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let mut fst = VectorFst::<TropicalWeight>::new();
    /// let s0 = fst.add_state();
    /// let s1 = fst.add_state();
    /// let s2 = fst.add_state();
    /// fst.set_start(s0);
    /// fst.set_final(s2, TropicalWeight::one());
    /// fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
    /// fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));
    ///
    /// let sorted = state_sort(&fst, StateSortType::DepthFirst)?;
    /// assert_eq!(sorted.start(), Some(0));
    /// # Ok::<(), arcweight::Error>(())
    /// ```
    DepthFirst,

    /// Topological order (requires acyclic FST)
    ///
    /// States are ordered such that for every arc (s, a, w, t), state s
    /// comes before state t. Only valid for acyclic FSTs.
    ///
    /// # Example
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let mut fst = VectorFst::<TropicalWeight>::new();
    /// let s0 = fst.add_state();
    /// let s1 = fst.add_state();
    /// let s2 = fst.add_state();
    /// fst.set_start(s0);
    /// fst.set_final(s2, TropicalWeight::one());
    /// fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
    /// fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));
    ///
    /// let sorted = state_sort(&fst, StateSortType::Topological)?;
    /// assert_eq!(sorted.start(), Some(0));
    /// # Ok::<(), arcweight::Error>(())
    /// ```
    Topological,
}

/// Sorts FST states by renumbering them according to specified order.
///
/// Creates a new FST with states renumbered to follow the traversal order
/// while preserving all arcs, labels, weights, and finality. The start state
/// always becomes state 0.
///
/// # Complexity
///
/// - **Time:** O(|V| + |E|) where V = states, E = arcs
///   - Traversal (BFS/DFS/Topological): O(|V| + |E|)
///   - State renumbering and copying: O(|V| + |E|)
/// - **Space:** O(|V|) for state mapping and traversal queue/stack
///
/// # Algorithm
///
/// Generic state renumbering with traversal strategies:
/// 1. **Breadth-First:** Use queue for level-order traversal from start state
/// 2. **Depth-First:** Use recursive DFS to visit states depth-first
/// 3. **Topological:** Use DFS with cycle detection for DAG ordering
/// 4. Build renumbering map: old_id → new_id based on visit order
/// 5. Create output FST with states and arcs in new order
///
/// Based on Moore (1959) "The shortest path through a maze" for BFS,
/// Tarjan (1972) "Depth-first search and linear graph algorithms" for DFS,
/// and Kahn (1962) "Topological sorting of large networks" for topological ordering.
///
/// # Performance Notes
///
/// - **BFS:** Best for cache locality; parent states precede children
/// - **DFS:** Efficient for deep paths; good for linear chains
/// - **Topological:** Enables forward-arc-only algorithms on DAGs
/// - **Memory:** BFS uses queue (O(width)), DFS uses stack (O(depth))
/// - **Preprocessing:** Consider [`connect`] first to remove unreachable states
///
/// [`connect`]: crate::algorithms::connect::connect
///
/// # Errors
///
/// Returns error if:
/// - FST has no start state
/// - Topological sort requested on cyclic FST
///
/// # Examples
///
/// ## Breadth-First Ordering
///
/// ```
/// use arcweight::prelude::*;
///
/// let mut fst = VectorFst::<TropicalWeight>::new();
/// let s0 = fst.add_state();
/// let s1 = fst.add_state();
/// let s2 = fst.add_state();
/// fst.set_start(s0);
/// fst.set_final(s2, TropicalWeight::one());
/// fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
/// fst.add_arc(s0, Arc::new(2, 2, TropicalWeight::new(0.3), s2));
/// fst.add_arc(s1, Arc::new(3, 3, TropicalWeight::new(0.2), s2));
///
/// let sorted = state_sort(&fst, StateSortType::BreadthFirst)?;
///
/// // Start state is now 0, BFS order for rest
/// assert_eq!(sorted.start(), Some(0));
/// assert_eq!(sorted.num_states(), fst.num_states());
/// # Ok::<(), arcweight::Error>(())
/// ```
///
/// ## Topological Ordering (Acyclic FST)
///
/// ```
/// use arcweight::prelude::*;
///
/// let mut fst = VectorFst::<TropicalWeight>::new();
/// let s0 = fst.add_state();
/// let s1 = fst.add_state();
/// let s2 = fst.add_state();
/// fst.set_start(s0);
/// fst.set_final(s2, TropicalWeight::one());
/// fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
/// fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(0.3), s2));
///
/// let sorted = state_sort(&fst, StateSortType::Topological)?;
///
/// // States ordered topologically
/// assert_eq!(sorted.start(), Some(0));
/// # Ok::<(), arcweight::Error>(())
/// ```
///
/// # See Also
///
/// - [`connect`] - Removes unreachable states before sorting
/// - [`StateSortType`] - Enumeration of available sorting strategies
///
/// [`connect`]: crate::algorithms::connect::connect
pub fn state_sort<W, F>(fst: &F, sort_type: StateSortType) -> Result<VectorFst<W>>
where
    W: Semiring + Clone,
    F: Fst<W>,
{
    // Empty FST case
    if fst.num_states() == 0 {
        return Ok(VectorFst::new());
    }

    // Compute state ordering based on sort type
    let order = match sort_type {
        StateSortType::BreadthFirst => compute_bfs_order(fst)?,
        StateSortType::DepthFirst => compute_dfs_order(fst)?,
        StateSortType::Topological => compute_topological_order(fst)?,
    };

    // Build state renumbering map
    let mut state_map = HashMap::new();
    for (new_id, &old_id) in order.iter().enumerate() {
        state_map.insert(old_id, new_id as StateId);
    }

    // Create result FST with renumbered states
    let mut result = VectorFst::new();

    // Add all states in new order
    for _ in &order {
        result.add_state();
    }

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

    // Copy states with renumbered IDs
    for &old_state in &order {
        if let Some(&new_state) = state_map.get(&old_state) {
            // Copy final weight
            if let Some(weight) = fst.final_weight(old_state) {
                result.set_final(new_state, weight.clone());
            }

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

    Ok(result)
}

/// Compute breadth-first ordering of states
fn compute_bfs_order<W: Semiring, F: Fst<W>>(fst: &F) -> Result<Vec<StateId>> {
    let start = fst
        .start()
        .ok_or_else(|| Error::Algorithm("FST has no start state".into()))?;

    let mut order = Vec::new();
    let mut visited = HashSet::new();
    let mut queue = VecDeque::new();

    queue.push_back(start);
    visited.insert(start);

    while let Some(state) = queue.pop_front() {
        order.push(state);

        for arc in fst.arcs(state) {
            if !visited.contains(&arc.nextstate) {
                visited.insert(arc.nextstate);
                queue.push_back(arc.nextstate);
            }
        }
    }

    // Add any unreachable states at the end
    for state in fst.states() {
        if !visited.contains(&state) {
            order.push(state);
        }
    }

    Ok(order)
}

/// Compute depth-first ordering of states
fn compute_dfs_order<W: Semiring, F: Fst<W>>(fst: &F) -> Result<Vec<StateId>> {
    let start = fst
        .start()
        .ok_or_else(|| Error::Algorithm("FST has no start state".into()))?;

    let mut order = Vec::new();
    let mut visited = HashSet::new();

    fn dfs<W: Semiring, F: Fst<W>>(
        fst: &F,
        state: StateId,
        visited: &mut HashSet<StateId>,
        order: &mut Vec<StateId>,
    ) {
        visited.insert(state);
        order.push(state);

        for arc in fst.arcs(state) {
            if !visited.contains(&arc.nextstate) {
                dfs(fst, arc.nextstate, visited, order);
            }
        }
    }

    dfs(fst, start, &mut visited, &mut order);

    // Add any unreachable states at the end
    for state in fst.states() {
        if !visited.contains(&state) {
            dfs(fst, state, &mut visited, &mut order);
        }
    }

    Ok(order)
}

/// Compute topological ordering of states (for acyclic FSTs)
fn compute_topological_order<W: Semiring, F: Fst<W>>(fst: &F) -> Result<Vec<StateId>> {
    let mut visited = HashSet::new();
    let mut finished = HashSet::new();
    let mut order = Vec::new();

    fn dfs<W: Semiring, F: Fst<W>>(
        fst: &F,
        state: StateId,
        visited: &mut HashSet<StateId>,
        finished: &mut HashSet<StateId>,
        order: &mut Vec<StateId>,
    ) -> Result<()> {
        visited.insert(state);

        for arc in fst.arcs(state) {
            if !visited.contains(&arc.nextstate) {
                dfs(fst, arc.nextstate, visited, finished, order)?;
            } else if !finished.contains(&arc.nextstate) {
                return Err(Error::Algorithm(
                    "FST has cycles, cannot perform topological sort".into(),
                ));
            }
        }

        finished.insert(state);
        order.push(state);
        Ok(())
    }

    // Start DFS from start state if it exists
    if let Some(start) = fst.start() {
        if !visited.contains(&start) {
            dfs(fst, start, &mut visited, &mut finished, &mut order)?;
        }
    }

    // Visit any remaining unvisited states
    for state in fst.states() {
        if !visited.contains(&state) {
            dfs(fst, state, &mut visited, &mut finished, &mut order)?;
        }
    }

    order.reverse();
    Ok(order)
}

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

    #[test]
    fn test_state_sort_breadth_first_simple() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::one());

        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
        fst.add_arc(s0, Arc::new(2, 2, TropicalWeight::new(0.3), s2));
        fst.add_arc(s1, Arc::new(3, 3, TropicalWeight::new(0.2), s2));

        let sorted = state_sort(&fst, StateSortType::BreadthFirst).unwrap();

        assert_eq!(sorted.start(), Some(0));
        assert_eq!(sorted.num_states(), fst.num_states());

        // Check that at least one state is final
        let has_final = sorted.states().any(|s| sorted.is_final(s));
        assert!(has_final);
    }

    #[test]
    fn test_state_sort_depth_first_simple() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::one());

        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(0.3), s2));

        let sorted = state_sort(&fst, StateSortType::DepthFirst).unwrap();

        assert_eq!(sorted.start(), Some(0));
        assert_eq!(sorted.num_states(), fst.num_states());
    }

    #[test]
    fn test_state_sort_topological_simple() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::one());

        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(0.5), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(0.3), s2));

        let sorted = state_sort(&fst, StateSortType::Topological).unwrap();

        assert_eq!(sorted.start(), Some(0));
        assert_eq!(sorted.num_states(), fst.num_states());

        // Verify topological order: all arcs go forward
        for state in sorted.states() {
            for arc in sorted.arcs(state) {
                assert!(
                    state < arc.nextstate,
                    "Arc from {} to {} violates topological order",
                    state,
                    arc.nextstate
                );
            }
        }
    }

    #[test]
    fn test_state_sort_preserves_structure() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::new(2.5));

        fst.add_arc(s0, Arc::new(1, 10, TropicalWeight::new(0.5), s1));
        fst.add_arc(s1, Arc::new(2, 20, TropicalWeight::new(0.3), s2));

        let sorted = state_sort(&fst, StateSortType::BreadthFirst).unwrap();

        // Check structure is preserved
        assert_eq!(sorted.num_states(), fst.num_states());

        let orig_arc_count: usize = fst.states().map(|s| fst.num_arcs(s)).sum();
        let sorted_arc_count: usize = sorted.states().map(|s| sorted.num_arcs(s)).sum();
        assert_eq!(orig_arc_count, sorted_arc_count);
    }

    #[test]
    fn test_state_sort_breadth_first_complex() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let states: Vec<_> = (0..6).map(|_| fst.add_state()).collect();

        fst.set_start(states[0]);
        fst.set_final(states[5], TropicalWeight::one());

        // Create complex structure
        fst.add_arc(states[0], Arc::new(1, 1, TropicalWeight::one(), states[1]));
        fst.add_arc(states[0], Arc::new(2, 2, TropicalWeight::one(), states[2]));
        fst.add_arc(states[1], Arc::new(3, 3, TropicalWeight::one(), states[3]));
        fst.add_arc(states[2], Arc::new(4, 4, TropicalWeight::one(), states[4]));
        fst.add_arc(states[3], Arc::new(5, 5, TropicalWeight::one(), states[5]));
        fst.add_arc(states[4], Arc::new(6, 6, TropicalWeight::one(), states[5]));

        let sorted = state_sort(&fst, StateSortType::BreadthFirst).unwrap();

        assert_eq!(sorted.start(), Some(0));
        assert_eq!(sorted.num_states(), 6);
    }

    #[test]
    fn test_state_sort_depth_first_complex() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let states: Vec<_> = (0..5).map(|_| fst.add_state()).collect();

        fst.set_start(states[0]);
        fst.set_final(states[4], TropicalWeight::one());

        // Create branching structure
        fst.add_arc(states[0], Arc::new(1, 1, TropicalWeight::one(), states[1]));
        fst.add_arc(states[1], Arc::new(2, 2, TropicalWeight::one(), states[2]));
        fst.add_arc(states[2], Arc::new(3, 3, TropicalWeight::one(), states[3]));
        fst.add_arc(states[3], Arc::new(4, 4, TropicalWeight::one(), states[4]));
        fst.add_arc(states[0], Arc::new(5, 5, TropicalWeight::one(), states[4]));

        let sorted = state_sort(&fst, StateSortType::DepthFirst).unwrap();

        assert_eq!(sorted.start(), Some(0));
        assert_eq!(sorted.num_states(), 5);
    }

    #[test]
    fn test_state_sort_single_state() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s0, TropicalWeight::new(1.5));

        for sort_type in [
            StateSortType::BreadthFirst,
            StateSortType::DepthFirst,
            StateSortType::Topological,
        ] {
            let sorted = state_sort(&fst, sort_type).unwrap();

            assert_eq!(sorted.num_states(), 1);
            assert_eq!(sorted.start(), Some(0));
            assert!(sorted.is_final(0));
            assert_eq!(sorted.final_weight(0), Some(&TropicalWeight::new(1.5)));
        }
    }

    #[test]
    fn test_state_sort_linear_chain() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let states: Vec<_> = (0..5).map(|_| fst.add_state()).collect();

        fst.set_start(states[0]);
        fst.set_final(states[4], TropicalWeight::one());

        for i in 0..4 {
            fst.add_arc(
                states[i],
                Arc::new(
                    (i + 1) as u32,
                    (i + 1) as u32,
                    TropicalWeight::one(),
                    states[i + 1],
                ),
            );
        }

        for sort_type in [
            StateSortType::BreadthFirst,
            StateSortType::DepthFirst,
            StateSortType::Topological,
        ] {
            let sorted = state_sort(&fst, sort_type).unwrap();

            assert_eq!(sorted.num_states(), 5);
            assert_eq!(sorted.start(), Some(0));

            // For topological sort, verify ordering
            if sort_type == StateSortType::Topological {
                for state in sorted.states() {
                    for arc in sorted.arcs(state) {
                        assert!(state < arc.nextstate);
                    }
                }
            }
        }
    }

    #[test]
    fn test_state_sort_branching_fst() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();
        let s3 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s3, TropicalWeight::one());

        // Diamond pattern
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s2));
        fst.add_arc(s1, Arc::new(3, 3, TropicalWeight::one(), s3));
        fst.add_arc(s2, Arc::new(4, 4, TropicalWeight::one(), s3));

        for sort_type in [
            StateSortType::BreadthFirst,
            StateSortType::DepthFirst,
            StateSortType::Topological,
        ] {
            let sorted = state_sort(&fst, sort_type).unwrap();

            assert_eq!(sorted.num_states(), 4);
            assert_eq!(sorted.start(), Some(0));
        }
    }

    #[test]
    fn test_state_sort_with_cycles_bfs() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::one());

        // Create cycle
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));
        fst.add_arc(s2, Arc::new(3, 3, TropicalWeight::one(), s0));

        let sorted = state_sort(&fst, StateSortType::BreadthFirst).unwrap();

        assert_eq!(sorted.num_states(), 3);
        assert_eq!(sorted.start(), Some(0));
    }

    #[test]
    fn test_state_sort_with_cycles_dfs() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::one());

        // Create cycle
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));
        fst.add_arc(s2, Arc::new(3, 3, TropicalWeight::one(), s1));

        let sorted = state_sort(&fst, StateSortType::DepthFirst).unwrap();

        assert_eq!(sorted.num_states(), 3);
        assert_eq!(sorted.start(), Some(0));
    }

    #[test]
    fn test_state_sort_topological_acyclic_only() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::one());

        // Acyclic: 0 -> 1 -> 2, 0 -> 2
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));
        fst.add_arc(s0, Arc::new(3, 3, TropicalWeight::one(), s2));

        let sorted = state_sort(&fst, StateSortType::Topological).unwrap();

        // Verify topological property
        for state in sorted.states() {
            for arc in sorted.arcs(state) {
                assert!(state < arc.nextstate);
            }
        }
    }

    #[test]
    fn test_state_sort_topological_rejects_cycles() {
        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());

        // Create cycle
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s0));

        let result = state_sort(&fst, StateSortType::Topological);
        assert!(result.is_err());
    }

    #[test]
    fn test_state_sort_different_semirings() {
        // Test with LogWeight
        let mut fst = VectorFst::<LogWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s1, LogWeight::one());
        fst.add_arc(s0, Arc::new(1, 1, LogWeight::new(0.5), s1));

        let sorted = state_sort(&fst, StateSortType::BreadthFirst).unwrap();
        assert_eq!(sorted.num_states(), 2);

        // Test with IntegerWeight
        let mut fst2 = VectorFst::<IntegerWeight>::new();
        let s0 = fst2.add_state();
        let s1 = fst2.add_state();

        fst2.set_start(s0);
        fst2.set_final(s1, IntegerWeight::one());
        fst2.add_arc(s0, Arc::new(1, 1, IntegerWeight::new(42), s1));

        let sorted2 = state_sort(&fst2, StateSortType::DepthFirst).unwrap();
        assert_eq!(sorted2.num_states(), 2);
    }

    #[test]
    fn test_state_sort_preserves_weights() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::new(3.5));

        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(1.2), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(2.3), s2));

        let sorted = state_sort(&fst, StateSortType::BreadthFirst).unwrap();

        // Verify weights are preserved
        let orig_weights: f32 = fst
            .states()
            .flat_map(|s| fst.arcs(s))
            .map(|arc| *arc.weight.value())
            .sum();
        let sorted_weights: f32 = sorted
            .states()
            .flat_map(|s| sorted.arcs(s))
            .map(|arc| *arc.weight.value())
            .sum();

        assert!((orig_weights - sorted_weights).abs() < 1e-6);
    }

    #[test]
    fn test_state_sort_error_no_start_state() {
        let fst = VectorFst::<TropicalWeight>::new();

        let result = state_sort(&fst, StateSortType::BreadthFirst);
        assert!(result.is_ok()); // Empty FST is OK

        let mut fst2 = VectorFst::<TropicalWeight>::new();
        fst2.add_state();
        // No start state set

        let result2 = state_sort(&fst2, StateSortType::BreadthFirst);
        assert!(result2.is_err());
    }

    #[test]
    fn test_state_sort_with_epsilon_arcs() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s2, TropicalWeight::one());

        // Add epsilon arc (label 0)
        fst.add_arc(s0, Arc::new(0, 0, TropicalWeight::one(), s1));
        fst.add_arc(s1, Arc::new(1, 1, TropicalWeight::one(), s2));

        for sort_type in [
            StateSortType::BreadthFirst,
            StateSortType::DepthFirst,
            StateSortType::Topological,
        ] {
            let sorted = state_sort(&fst, sort_type).unwrap();

            assert_eq!(sorted.num_states(), 3);
            assert_eq!(sorted.start(), Some(0));

            // Verify epsilon arc is preserved
            let has_epsilon = sorted
                .states()
                .any(|s| sorted.arcs(s).any(|arc| arc.ilabel == 0 && arc.olabel == 0));
            assert!(has_epsilon);
        }
    }

    #[test]
    fn test_state_sort_diamond_structure() {
        let mut fst = VectorFst::<TropicalWeight>::new();
        let s0 = fst.add_state();
        let s1 = fst.add_state();
        let s2 = fst.add_state();
        let s3 = fst.add_state();

        fst.set_start(s0);
        fst.set_final(s3, TropicalWeight::one());

        // Diamond: 0 -> {1, 2} -> 3
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst.add_arc(s0, Arc::new(2, 2, TropicalWeight::one(), s2));
        fst.add_arc(s1, Arc::new(3, 3, TropicalWeight::one(), s3));
        fst.add_arc(s2, Arc::new(4, 4, TropicalWeight::one(), s3));

        let bfs = state_sort(&fst, StateSortType::BreadthFirst).unwrap();
        let dfs = state_sort(&fst, StateSortType::DepthFirst).unwrap();
        let topo = state_sort(&fst, StateSortType::Topological).unwrap();

        // All should have same structure
        assert_eq!(bfs.num_states(), 4);
        assert_eq!(dfs.num_states(), 4);
        assert_eq!(topo.num_states(), 4);

        // Topological should maintain forward arcs
        for state in topo.states() {
            for arc in topo.arcs(state) {
                assert!(state < arc.nextstate);
            }
        }
    }

    #[test]
    fn test_state_sort_empty_fst() {
        let fst = VectorFst::<TropicalWeight>::new();

        for sort_type in [
            StateSortType::BreadthFirst,
            StateSortType::DepthFirst,
            StateSortType::Topological,
        ] {
            let sorted = state_sort(&fst, sort_type).unwrap();
            assert_eq!(sorted.num_states(), 0);
            assert!(sorted.is_empty());
        }
    }
}