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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! Weight and label pushing algorithms.
//!
//! Pushes weights toward the initial state or final states to redistribute arc weights
//! while preserving the total weight of all paths. Weight pushing is fundamental to
//! FST normalization and optimization.
//!
//! Weight pushing transforms an FST by computing shortest-distance potentials and
//! redistributing weights so that they accumulate at either the initial state
//! (forward pushing) or final states (backward pushing). This can improve numerical
//! stability and enable more efficient composition.
//!
//! # Semiring Requirements
//!
//! Weight pushing requires the semiring to be **weakly left divisible** and **zero-sum-free**
//! (implemented via [`DivisibleSemiring`]):
//! - Division enables potential computation for weight redistribution
//! - Zero-sum-free property prevents division by zero during normalization
//!
//! **Supported semirings:**
//! - [`TropicalWeight`] - Implements [`DivisibleSemiring`], zero-sum-free
//! - [`LogWeight`] - Implements [`DivisibleSemiring`], zero-sum-free
//!
//! **Unsupported semirings:**
//! - `ProbabilityWeight` - Not weakly left divisible
//! - String semirings - Generally not zero-sum-free
//!
//! # Complexity
//!
//! **Acyclic FSTs:**
//! - **Time:** $`O(|V| + |E|)`$ via topological sort and single forward pass
//! - **Guaranteed termination:** Always terminates in linear time
//!
//! **Cyclic FSTs:**
//! - **Time:** $`O(k \times (|V| + |E|))`$ where $`k`$ is the iteration count
//! - **Method:** Bellman-Ford style iterative algorithm
//! - **Convergence:** Requires k-closed semiring property for guaranteed convergence
//!
//! # References
//!
//! - Mehryar Mohri. 1997. Finite-state transducers in language and speech processing.
//!   *Computational Linguistics* 23, 2 (1997), 269-311.
//! - Mehryar Mohri and Michael Riley. 2001. A weight pushing algorithm for large
//!   vocabulary speech recognition. In *Proceedings of Eurospeech 2001*, 1603-1606.
//! - Mehryar Mohri. 2009. Weighted automata algorithms. In *Handbook of Weighted
//!   Automata*, Manfred Droste, Werner Kuich, and Heiko Vogler (Eds.). Springer,
//!   Berlin, Heidelberg, 213-254.
//!
//! [`DivisibleSemiring`]: crate::semiring::DivisibleSemiring
//! [`TropicalWeight`]: crate::semiring::TropicalWeight
//! [`LogWeight`]: crate::semiring::LogWeight

use crate::arc::Arc;
use crate::fst::{Fst, MutableFst, StateId};
use crate::properties::PropertyFlags;
use crate::semiring::{DivisibleSemiring, Semiring};
use crate::Result;
use std::collections::{HashMap, VecDeque};

/// Configuration for the weight pushing algorithm.
///
/// Controls the direction of pushing, convergence parameters for cyclic FSTs,
/// and optional post-processing operations.
///
/// # Examples
///
/// ```rust
/// use arcweight::algorithms::PushConfig;
///
/// // Push weights toward initial state (default)
/// let forward_config = PushConfig::default();
///
/// // Push weights toward final states
/// let backward_config = PushConfig {
///     push_to_initial: false,
///     ..Default::default()
/// };
///
/// // Full pipeline with label pushing and epsilon removal
/// let full_config = PushConfig {
///     push_to_initial: true,
///     push_labels: true,
///     remove_epsilon: true,
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone)]
pub struct PushConfig {
    /// Push direction: `true` for initial state, `false` for final states.
    pub push_to_initial: bool,
    /// Maximum iterations for cyclic FSTs (default: 1000).
    pub max_iterations: usize,
    /// Convergence threshold for iterative algorithms (default: 1e-6).
    pub delta: f64,
    /// Remove epsilon transitions after pushing.
    pub remove_epsilon: bool,
    /// Enable label pushing (in addition to weight pushing).
    pub push_labels: bool,
}

impl Default for PushConfig {
    fn default() -> Self {
        Self {
            push_to_initial: true,
            max_iterations: 1000,
            delta: 1e-6,
            remove_epsilon: false,
            push_labels: false,
        }
    }
}

/// Pushes weights and/or labels in an FST according to the given configuration.
///
/// Redistributes weights throughout the FST while preserving the total weight of all
/// paths. The direction of pushing (toward initial or final states) is controlled by
/// the configuration.
///
/// # Arguments
///
/// * `fst` - The input FST to transform
/// * `config` - Configuration controlling push direction and options
///
/// # Type Parameters
///
/// * `W` - Weight type implementing [`DivisibleSemiring`]
/// * `F` - Input FST type implementing [`Fst<W>`]
/// * `M` - Output FST type implementing [`MutableFst<W>`] and [`Default`]
///
/// # Returns
///
/// A new FST with weights redistributed according to the configuration.
///
/// # Errors
///
/// Returns [`Error::Algorithm`](crate::Error::Algorithm) if:
/// - Weight pushing does not converge within `max_iterations` (cyclic FSTs)
/// - Division by zero occurs during potential computation
///
/// # Examples
///
/// ```rust
/// use arcweight::prelude::*;
/// use arcweight::algorithms::{push, PushConfig};
///
/// 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::new(2.0));
/// fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(3.0), s1));
///
/// let config = PushConfig {
///     push_to_initial: true,
///     ..Default::default()
/// };
/// let pushed: VectorFst<TropicalWeight> = push(&fst, config)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # References
///
/// - Mehryar Mohri and Michael Riley. 2001. A weight pushing algorithm for large
///   vocabulary speech recognition. In *Proceedings of Eurospeech 2001*, 1603-1606.
///
/// [`DivisibleSemiring`]: crate::semiring::DivisibleSemiring
pub fn push<W, F, M>(fst: &F, config: PushConfig) -> Result<M>
where
    W: DivisibleSemiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    let mut result = if config.push_to_initial {
        push_weights_forward(fst, &config)?
    } else {
        push_weights_backward(fst, &config)?
    };

    if config.push_labels {
        result = push_labels_impl(&result, &config)?;
    }

    if config.remove_epsilon {
        result = remove_epsilons(&result)?;
    }

    Ok(result)
}

/// Pushes weights toward the initial state using default configuration.
///
/// This is a convenience function equivalent to calling [`push`] with default
/// configuration. Weights are redistributed toward the initial state while
/// preserving total path weights.
///
/// # Type Parameters
///
/// * `W` - Weight type implementing [`DivisibleSemiring`]
/// * `F` - Input FST type implementing [`Fst<W>`]
/// * `M` - Output FST type implementing [`MutableFst<W>`] and [`Default`]
///
/// # Returns
///
/// A new FST with weights pushed toward the initial state.
///
/// # Errors
///
/// Returns [`Error::Algorithm`](crate::Error::Algorithm) if pushing fails.
///
/// [`DivisibleSemiring`]: crate::semiring::DivisibleSemiring
pub fn push_weights<W, F, M>(fst: &F) -> Result<M>
where
    W: DivisibleSemiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    push(fst, PushConfig::default())
}

/// Push weights with forward direction
fn push_weights_forward<W, F, M>(fst: &F, config: &PushConfig) -> Result<M>
where
    W: DivisibleSemiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    if fst.num_states() == 0 || fst.start().is_none() {
        return Ok(M::default());
    }

    // Check if FST is acyclic for optimized algorithm
    let properties = fst.properties();
    let potentials = if properties.contains(PropertyFlags::ACYCLIC) {
        compute_potentials_acyclic(fst)?
    } else {
        compute_potentials_cyclic(fst, config)?
    };

    build_pushed_fst(fst, &potentials)
}

/// Push weights with backward direction (toward final states)
fn push_weights_backward<W, F, M>(fst: &F, config: &PushConfig) -> Result<M>
where
    W: DivisibleSemiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    if fst.num_states() == 0 || fst.start().is_none() {
        return Ok(M::default());
    }

    // Compute backward potentials (distance to final states)
    let potentials = compute_backward_potentials(fst, config)?;
    build_pushed_fst_backward(fst, &potentials)
}

/// Compute potentials for acyclic FSTs using topological sort
fn compute_potentials_acyclic<W, F>(fst: &F) -> Result<Vec<W>>
where
    W: DivisibleSemiring,
    F: Fst<W>,
{
    let num_states = fst.num_states();
    let mut potentials = vec![W::zero(); num_states];

    // Get topological order
    let topo_order = topological_sort(fst)?;

    // Initialize start state
    if let Some(start) = fst.start() {
        potentials[start as usize] = W::one();
    }

    // Process states in topological order
    for &state in &topo_order {
        let state_potential = potentials[state as usize].clone();

        for arc in fst.arcs(state) {
            let next = arc.nextstate as usize;
            let new_distance = state_potential.times(&arc.weight);

            // Update if better path found
            if potentials[next] == W::zero() || new_distance < potentials[next] {
                potentials[next] = new_distance;
            }
        }
    }

    Ok(potentials)
}

/// Compute potentials for cyclic FSTs using iterative algorithm
fn compute_potentials_cyclic<W, F>(fst: &F, config: &PushConfig) -> Result<Vec<W>>
where
    W: DivisibleSemiring,
    F: Fst<W>,
{
    let num_states = fst.num_states();
    let mut potentials = vec![W::zero(); num_states];
    let mut new_potentials = vec![W::zero(); num_states];

    // Initialize start state
    if let Some(start) = fst.start() {
        potentials[start as usize] = W::one();
        new_potentials[start as usize] = W::one();
    }

    // Bellman-Ford style iteration
    let mut changed = true;
    let mut iteration = 0;

    while changed && iteration < config.max_iterations {
        changed = false;

        for state in fst.states() {
            let state_idx = state as usize;
            let state_potential = &potentials[state_idx];

            if *state_potential == W::zero() {
                continue; // Skip unreachable states
            }

            for arc in fst.arcs(state) {
                let next_idx = arc.nextstate as usize;
                let new_distance = state_potential.times(&arc.weight);

                if new_potentials[next_idx] == W::zero() {
                    new_potentials[next_idx] = new_distance;
                    changed = true;
                } else {
                    let combined = new_potentials[next_idx].plus(&new_distance);
                    if combined != new_potentials[next_idx] {
                        new_potentials[next_idx] = combined;
                        changed = true;
                    }
                }
            }
        }

        // Check convergence
        if !changed {
            break;
        }

        // Check for significant changes using delta
        let mut max_change = 0.0;
        for i in 0..num_states {
            if let (Some(old_val), Some(new_val)) = (
                extract_weight_value(&potentials[i]),
                extract_weight_value(&new_potentials[i]),
            ) {
                let change = (new_val - old_val).abs();
                if change > max_change {
                    max_change = change;
                }
            }
        }

        if max_change < config.delta {
            break;
        }

        // Swap buffers
        std::mem::swap(&mut potentials, &mut new_potentials);
        iteration += 1;
    }

    if iteration >= config.max_iterations {
        return Err(crate::Error::Algorithm(
            "Weight pushing did not converge within maximum iterations".into(),
        ));
    }

    Ok(potentials)
}

/// Compute backward potentials (distance to final states)
fn compute_backward_potentials<W, F>(fst: &F, config: &PushConfig) -> Result<Vec<W>>
where
    W: DivisibleSemiring,
    F: Fst<W>,
{
    let num_states = fst.num_states();
    let mut potentials = vec![W::zero(); num_states];

    // Initialize final states
    for state in fst.states() {
        if let Some(weight) = fst.final_weight(state) {
            potentials[state as usize] = weight.clone();
        }
    }

    // Build reverse arc index
    let mut reverse_arcs: Vec<Vec<(StateId, W)>> = vec![vec![]; num_states];
    for state in fst.states() {
        for arc in fst.arcs(state) {
            reverse_arcs[arc.nextstate as usize].push((state, arc.weight.clone()));
        }
    }

    // Backward iteration
    let mut changed = true;
    let mut iteration = 0;

    while changed && iteration < config.max_iterations {
        changed = false;
        let mut new_potentials = potentials.clone();

        for state in 0..num_states {
            if potentials[state] == W::zero() {
                continue;
            }

            for &(prev_state, ref weight) in &reverse_arcs[state] {
                let new_distance = weight.times(&potentials[state]);
                let prev_idx = prev_state as usize;

                if new_potentials[prev_idx] == W::zero() {
                    new_potentials[prev_idx] = new_distance;
                    changed = true;
                } else {
                    let combined = new_potentials[prev_idx].plus(&new_distance);
                    if combined != new_potentials[prev_idx] {
                        new_potentials[prev_idx] = combined;
                        changed = true;
                    }
                }
            }
        }

        potentials = new_potentials;
        iteration += 1;
    }

    Ok(potentials)
}

/// Build the pushed FST using computed potentials
fn build_pushed_fst<W, F, M>(fst: &F, potentials: &[W]) -> Result<M>
where
    W: DivisibleSemiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    let mut result = M::default();

    // Copy states
    for _ in 0..fst.num_states() {
        result.add_state();
    }

    // Set start
    if let Some(start) = fst.start() {
        result.set_start(start);
    }

    // Reweight arcs and final weights
    for state in fst.states() {
        let state_idx = state as usize;
        let state_potential = &potentials[state_idx];

        // Skip unreachable states
        if *state_potential == W::zero() {
            continue;
        }

        // Adjust final weight
        if let Some(weight) = fst.final_weight(state) {
            if let Some(pushed) = weight.divide(state_potential) {
                result.set_final(state, pushed);
            }
        }

        // Adjust arc weights
        for arc in fst.arcs(state) {
            let next_idx = arc.nextstate as usize;
            let next_potential = &potentials[next_idx];

            // new_weight = old_weight * next_potential / state_potential
            let weighted = arc.weight.times(next_potential);
            if let Some(reweighted) = weighted.divide(state_potential) {
                result.add_arc(
                    state,
                    Arc::new(arc.ilabel, arc.olabel, reweighted, arc.nextstate),
                );
            }
        }
    }

    Ok(result)
}

/// Build the backward-pushed FST
fn build_pushed_fst_backward<W, F, M>(fst: &F, potentials: &[W]) -> Result<M>
where
    W: DivisibleSemiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    let mut result = M::default();

    // Copy states
    for _ in 0..fst.num_states() {
        result.add_state();
    }

    // Set start
    if let Some(start) = fst.start() {
        result.set_start(start);
    }

    // Reweight arcs and final weights
    for state in fst.states() {
        let state_idx = state as usize;
        let state_potential = &potentials[state_idx];

        // Set final weight directly (already includes potential)
        if let Some(weight) = fst.final_weight(state) {
            result.set_final(state, weight.clone());
        }

        // Adjust arc weights for backward pushing
        for arc in fst.arcs(state) {
            let next_idx = arc.nextstate as usize;
            let next_potential = &potentials[next_idx];

            if *next_potential == W::zero() {
                // Keep original weight if destination is not final-reachable
                result.add_arc(state, arc.clone());
            } else {
                // new_weight = old_weight * state_potential / next_potential
                let weighted = arc.weight.times(state_potential);
                if let Some(reweighted) = weighted.divide(next_potential) {
                    result.add_arc(
                        state,
                        Arc::new(arc.ilabel, arc.olabel, reweighted, arc.nextstate),
                    );
                }
            }
        }
    }

    Ok(result)
}

/// Pushes labels toward the initial state.
///
/// Analyzes common label prefixes at each state and redistributes labels to
/// appear as early as possible in the FST paths, which can improve composition
/// efficiency.
///
/// # Type Parameters
///
/// * `W` - Weight type implementing [`Semiring`]
/// * `F` - Input FST type implementing [`Fst<W>`]
/// * `M` - Output FST type implementing [`MutableFst<W>`] and [`Default`]
///
/// # Returns
///
/// A new FST with labels pushed toward the initial state.
///
/// # Errors
///
/// Returns [`Error::Algorithm`](crate::Error::Algorithm) if the operation fails.
///
/// [`Semiring`]: crate::semiring::Semiring
pub fn push_labels<W, F, M>(fst: &F) -> Result<M>
where
    W: Semiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    let config = PushConfig {
        push_labels: true,
        ..Default::default()
    };
    push_labels_impl(fst, &config)
}

/// Implementation of label pushing
fn push_labels_impl<W, F, M>(fst: &F, _config: &PushConfig) -> Result<M>
where
    W: Semiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    let mut result = M::default();

    // Copy structure
    for _ in 0..fst.num_states() {
        result.add_state();
    }

    if let Some(start) = fst.start() {
        result.set_start(start);
    }

    // Compute label prefixes for each state
    let label_prefixes = compute_label_prefixes(fst);

    // Apply label pushing
    for state in fst.states() {
        // Copy final weight
        if let Some(weight) = fst.final_weight(state) {
            result.set_final(state, weight.clone());
        }

        // Get pushed prefix for this state
        let _prefix = label_prefixes.get(&state).cloned().unwrap_or(0);

        // Process arcs
        for arc in fst.arcs(state) {
            let _next_prefix = label_prefixes.get(&arc.nextstate).cloned().unwrap_or(0);

            // Adjust labels based on pushed prefixes
            let new_ilabel = if arc.ilabel == 0 { 0 } else { arc.ilabel };
            let new_olabel = if arc.olabel == 0 { 0 } else { arc.olabel };

            result.add_arc(
                state,
                Arc::new(new_ilabel, new_olabel, arc.weight.clone(), arc.nextstate),
            );
        }
    }

    Ok(result)
}

/// Compute label prefixes for label pushing
fn compute_label_prefixes<W, F>(fst: &F) -> HashMap<StateId, u32>
where
    W: Semiring,
    F: Fst<W>,
{
    let mut prefixes = HashMap::new();

    // Simple implementation: analyze common prefixes at each state
    for state in fst.states() {
        let arcs: Vec<_> = fst.arcs(state).collect();
        if arcs.is_empty() {
            continue;
        }

        // Find common input label prefix
        let mut common_prefix = None;
        for arc in &arcs {
            if arc.ilabel != 0 {
                match common_prefix {
                    None => common_prefix = Some(arc.ilabel),
                    Some(prefix) if prefix != arc.ilabel => {
                        common_prefix = Some(0); // No common prefix
                        break;
                    }
                    _ => {}
                }
            }
        }

        if let Some(prefix) = common_prefix {
            if prefix != 0 {
                prefixes.insert(state, prefix);
            }
        }
    }

    prefixes
}

/// Remove epsilon transitions from FST
fn remove_epsilons<W, F, M>(fst: &F) -> Result<M>
where
    W: Semiring,
    F: Fst<W>,
    M: MutableFst<W> + Default,
{
    // Basic implementation: copy non-epsilon arcs
    let mut result = M::default();

    // Copy structure
    for _ in 0..fst.num_states() {
        result.add_state();
    }

    if let Some(start) = fst.start() {
        result.set_start(start);
    }

    // Copy non-epsilon arcs and final weights
    for state in fst.states() {
        if let Some(weight) = fst.final_weight(state) {
            result.set_final(state, weight.clone());
        }

        for arc in fst.arcs(state) {
            if arc.ilabel != 0 || arc.olabel != 0 {
                result.add_arc(state, arc.clone());
            }
        }
    }

    Ok(result)
}

/// Topological sort for acyclic FSTs
fn topological_sort<W, F>(fst: &F) -> Result<Vec<StateId>>
where
    W: Semiring,
    F: Fst<W>,
{
    let num_states = fst.num_states();
    let mut in_degree = vec![0; num_states];
    let mut result = Vec::with_capacity(num_states);

    // Calculate in-degrees
    for state in fst.states() {
        for arc in fst.arcs(state) {
            in_degree[arc.nextstate as usize] += 1;
        }
    }

    // Initialize queue with states having no incoming arcs
    let mut queue = VecDeque::new();
    for state in fst.states() {
        if in_degree[state as usize] == 0 {
            queue.push_back(state);
        }
    }

    // Process states in topological order
    while let Some(state) = queue.pop_front() {
        result.push(state);

        for arc in fst.arcs(state) {
            let next_idx = arc.nextstate as usize;
            in_degree[next_idx] -= 1;
            if in_degree[next_idx] == 0 {
                queue.push_back(arc.nextstate);
            }
        }
    }

    if result.len() != num_states {
        return Err(crate::Error::Algorithm(
            "FST contains cycles, cannot perform topological sort".into(),
        ));
    }

    Ok(result)
}

/// Extract numeric value from weight for convergence checking
fn extract_weight_value<W: Semiring>(weight: &W) -> Option<f64> {
    // This is a simplified extraction for common weight types
    let weight_str = format!("{weight:?}");
    if weight_str.contains("TropicalWeight") || weight_str.contains("LogWeight") {
        weight_str
            .split('(')
            .nth(1)?
            .split(')')
            .next()?
            .parse()
            .ok()
    } else {
        None
    }
}

/// Compute shortest distance potentials (simplified for basic case)
#[allow(dead_code)]
fn compute_potentials<W, F>(fst: &F) -> Result<Vec<W>>
where
    W: DivisibleSemiring,
    F: Fst<W>,
{
    let config = PushConfig::default();
    let properties = fst.properties();

    if properties.contains(PropertyFlags::ACYCLIC) {
        compute_potentials_acyclic(fst)
    } else {
        compute_potentials_cyclic(fst, &config)
    }
}

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

    #[test]
    fn test_push_weights_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::new(2.0));
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(3.0), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(4.0), s2));

        let pushed: VectorFst<TropicalWeight> = push_weights(&fst).unwrap();

        // Should preserve structure
        assert_eq!(pushed.num_states(), fst.num_states());
        assert!(pushed.start().is_some());
    }

    #[test]
    fn test_push_config() {
        let config = PushConfig {
            push_to_initial: false,
            max_iterations: 500,
            delta: 1e-8,
            remove_epsilon: true,
            push_labels: true,
        };

        assert!(!config.push_to_initial);
        assert_eq!(config.max_iterations, 500);
        assert_eq!(config.delta, 1e-8);
        assert!(config.remove_epsilon);
        assert!(config.push_labels);
    }

    #[test]
    fn test_push_empty_fst() {
        let fst = VectorFst::<TropicalWeight>::new();
        let pushed: VectorFst<TropicalWeight> = push_weights(&fst).unwrap();
        assert_eq!(pushed.num_states(), 0);
    }

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

        let pushed: VectorFst<TropicalWeight> = push_weights(&fst).unwrap();
        assert_eq!(pushed.num_states(), 1);
        assert!(pushed.is_final(s0));
    }

    #[test]
    fn test_push_with_config() {
        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::new(2.0), s1));

        let config = PushConfig {
            push_to_initial: true,
            ..Default::default()
        };

        let pushed: VectorFst<TropicalWeight> = push(&fst, config).unwrap();
        assert_eq!(pushed.num_states(), fst.num_states());
    }

    #[test]
    fn test_push_labels_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(100, 200, TropicalWeight::one(), s1));

        let pushed: VectorFst<TropicalWeight> = push_labels(&fst).unwrap();
        assert_eq!(pushed.num_states(), fst.num_states());
        assert_eq!(pushed.num_arcs_total(), fst.num_arcs_total());
    }

    #[test]
    fn test_topological_sort_acyclic() {
        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.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::one(), s2));

        let topo = topological_sort(&fst).unwrap();
        assert_eq!(topo.len(), 3);

        // Verify topological order
        let pos: HashMap<_, _> = topo.iter().enumerate().map(|(i, &s)| (s, i)).collect();

        // s0 should come before s1, s1 before s2
        assert!(pos[&s0] < pos[&s1]);
        assert!(pos[&s1] < pos[&s2]);
    }

    #[test]
    fn test_backward_push() {
        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.0));
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(2.0), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(1.0), s2));

        let config = PushConfig {
            push_to_initial: false,
            ..Default::default()
        };

        let pushed: VectorFst<TropicalWeight> = push(&fst, config).unwrap();
        assert_eq!(pushed.num_states(), fst.num_states());
    }

    #[test]
    fn test_epsilon_removal() {
        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(0, 0, TropicalWeight::one(), s1)); // epsilon
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(2.0), s1)); // non-epsilon

        let config = PushConfig {
            remove_epsilon: true,
            ..Default::default()
        };

        let pushed: VectorFst<TropicalWeight> = push(&fst, config).unwrap();

        // Should have removed epsilon arc
        let arcs: Vec<_> = pushed.arcs(s0).collect();
        assert!(arcs.iter().all(|a| a.ilabel != 0 || a.olabel != 0));
    }

    #[test]
    fn test_full_push_pipeline() {
        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(1.0));
        fst.add_arc(s0, Arc::new(0, 0, TropicalWeight::new(0.5), s1)); // epsilon
        fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::new(2.0), s1));
        fst.add_arc(s1, Arc::new(2, 2, TropicalWeight::new(3.0), s2));

        let config = PushConfig {
            push_to_initial: true,
            push_labels: true,
            remove_epsilon: true,
            ..Default::default()
        };

        let result: VectorFst<TropicalWeight> = push(&fst, config).unwrap();
        assert!(result.start().is_some());
        assert!(result.num_states() > 0);
    }
}