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
//! # Arc
//!
//! Arc types and traits for weighted finite-state transducers.
//!
//! ## Overview
//!
//! This module provides the fundamental arc representation used throughout
//! the library. Arcs represent weighted transitions between states in a
//! finite-state transducer (FST), forming the edges of the underlying graph.
//!
//! An [`Arc`] consists of four components:
//!
//! | Component | Field | Description |
//! |-----------|-------|-------------|
//! | Input label | `ilabel` | Symbol consumed from input tape |
//! | Output label | `olabel` | Symbol produced on output tape |
//! | Weight | `weight` | Cost or probability of the transition |
//! | Next state | `nextstate` | Target state ID |
//!
//! ## Arc Variants
//!
//! ### Regular Arcs
//!
//! Standard transitions with explicit input/output labels:
//!
//! ```
//! use arcweight::prelude::*;
//!
//! // Transducer arc: transforms input 1 to output 2
//! let arc = Arc::new(1, 2, TropicalWeight::new(0.5), 3);
//! assert_eq!(arc.ilabel, 1);
//! assert_eq!(arc.olabel, 2);
//! ```
//!
//! ### Acceptor Arcs
//!
//! When input and output labels match (common in acceptors):
//!
//! ```
//! use arcweight::prelude::*;
//!
//! // Acceptor arc: consumes and produces symbol 1
//! let arc = Arc::new(1, 1, TropicalWeight::one(), 2);
//! assert_eq!(arc.ilabel, arc.olabel);
//! ```
//!
//! ### Epsilon Arcs
//!
//! Transitions that consume or produce no symbols (label = 0):
//!
//! ```
//! use arcweight::prelude::*;
//!
//! // Full epsilon arc: no input or output symbols
//! let eps = Arc::epsilon(TropicalWeight::new(0.1), 1);
//! assert!(eps.is_epsilon());
//!
//! // Input epsilon: produces output without consuming input
//! let in_eps = Arc::new(0, 5, TropicalWeight::one(), 2);
//! assert!(in_eps.is_epsilon_input());
//! assert!(!in_eps.is_epsilon_output());
//! ```
//!
//! ## Memory Layout
//!
//! Arcs are stored inline with their weight type, making them cache-efficient
//! for common weight types like [`TropicalWeight`] (8 bytes for the weight,
//! 16 bytes total for labels and next state).
//!
//! ## Arc Iterators
//!
//! The [`ArcIterator`] trait provides a common interface for iterating
//! over arcs leaving a state. Different FST implementations provide
//! optimized iterators.
//!
//! ```
//! use arcweight::prelude::*;
//!
//! let mut fst = VectorFst::<TropicalWeight>::new();
//! let s0 = fst.add_state();
//! fst.add_arc(s0, Arc::new(1, 2, TropicalWeight::one(), s0));
//!
//! // Iterate over arcs from state s0
//! for arc in fst.arcs(s0) {
//!     println!("Arc: {} -> {}", arc.ilabel, arc.olabel);
//! }
//! ```
//!
//! ## Examples
//!
//! ### Building an FST with Arcs
//!
//! ```
//! 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());
//!
//! // Chain of arcs forming a path
//! 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));
//! ```
//!
//! ### Arc Comparison and Hashing
//!
//! Arcs implement [`Eq`] and [`Hash`], enabling use in collections:
//!
//! ```
//! use arcweight::prelude::*;
//! use std::collections::HashSet;
//!
//! let mut seen = HashSet::new();
//! let arc = Arc::new(1, 2, TropicalWeight::new(0.5), 3);
//! seen.insert(arc.clone());
//!
//! assert!(seen.contains(&arc));
//! ```
//!
//! [`TropicalWeight`]: crate::semiring::TropicalWeight

use crate::fst::{Label, StateId};
use crate::semiring::Semiring;
use core::fmt;

/// A weighted arc (transition) in a finite-state transducer.
///
/// Arcs are the fundamental building blocks of FSTs, representing labeled,
/// weighted transitions between states. Each arc specifies:
///
/// - An input symbol to consume (or epsilon if `ilabel == 0`)
/// - An output symbol to produce (or epsilon if `olabel == 0`)
/// - A weight from the semiring `W`
/// - The destination state
///
/// # Type Parameters
///
/// * `W` - The semiring type for arc weights (e.g., [`TropicalWeight`], [`LogWeight`])
///
/// # Fields
///
/// | Field | Type | Description |
/// |-------|------|-------------|
/// | `ilabel` | [`Label`] | Input symbol (0 = epsilon) |
/// | `olabel` | [`Label`] | Output symbol (0 = epsilon) |
/// | `weight` | `W` | Transition weight |
/// | `nextstate` | [`StateId`] | Destination state ID |
///
/// # Examples
///
/// Creating different types of arcs:
///
/// ```
/// use arcweight::prelude::*;
///
/// // Regular arc with different input/output labels
/// let arc1 = Arc::new(1, 2, TropicalWeight::new(0.5), 3);
///
/// // Acceptor arc (same input/output)
/// let arc2 = Arc::new(1, 1, TropicalWeight::one(), 2);
///
/// // Epsilon arc (input=0, output=0)
/// let epsilon = Arc::epsilon(TropicalWeight::new(0.1), 1);
///
/// assert_eq!(arc1.ilabel, 1);
/// assert_eq!(arc1.olabel, 2);
/// assert!(epsilon.is_epsilon());
/// ```
///
/// Using arcs in FST construction:
///
/// ```
/// use arcweight::prelude::*;
///
/// let mut fst = VectorFst::<TropicalWeight>::new();
/// let s0 = fst.add_state();
/// let s1 = fst.add_state();
///
/// // Add a transducer arc
/// fst.add_arc(s0, Arc::new(1, 2, TropicalWeight::new(0.5), s1));
/// ```
///
/// [`TropicalWeight`]: crate::semiring::TropicalWeight
/// [`LogWeight`]: crate::semiring::LogWeight
/// [`Label`]: crate::fst::Label
/// [`StateId`]: crate::fst::StateId
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Arc<W: Semiring> {
    /// Input label consumed by this transition.
    ///
    /// A value of 0 indicates an epsilon transition on the input tape,
    /// meaning no symbol is consumed.
    pub ilabel: Label,

    /// Output label produced by this transition.
    ///
    /// A value of 0 indicates an epsilon transition on the output tape,
    /// meaning no symbol is produced.
    pub olabel: Label,

    /// Weight of this transition in the semiring `W`.
    ///
    /// The weight represents the cost, probability, or other measure
    /// associated with taking this transition, as defined by the semiring.
    pub weight: W,

    /// Destination state ID.
    ///
    /// The state that becomes current after taking this transition.
    pub nextstate: StateId,
}

impl<W: Semiring> Arc<W> {
    /// Creates a new arc with the specified labels, weight, and destination.
    ///
    /// This is the primary constructor for arcs in FST construction.
    ///
    /// # Arguments
    ///
    /// * `ilabel` - Input label (0 for epsilon)
    /// * `olabel` - Output label (0 for epsilon)
    /// * `weight` - Arc weight in the semiring
    /// * `nextstate` - Destination state ID
    ///
    /// # Returns
    ///
    /// A new `Arc` with the specified components.
    ///
    /// # Examples
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let arc = Arc::new(1, 2, TropicalWeight::new(0.5), 3);
    ///
    /// assert_eq!(arc.ilabel, 1);
    /// assert_eq!(arc.olabel, 2);
    /// assert_eq!(arc.weight, TropicalWeight::new(0.5));
    /// assert_eq!(arc.nextstate, 3);
    /// ```
    #[inline]
    pub fn new(ilabel: Label, olabel: Label, weight: W, nextstate: StateId) -> Self {
        Self {
            ilabel,
            olabel,
            weight,
            nextstate,
        }
    }

    /// Creates an epsilon arc (no input or output symbol).
    ///
    /// Epsilon arcs have input and output labels of 0, representing
    /// transitions that neither consume nor produce symbols. These are
    /// commonly used in NFA-to-DFA conversions and composition algorithms.
    ///
    /// # Arguments
    ///
    /// * `weight` - Arc weight in the semiring
    /// * `nextstate` - Destination state ID
    ///
    /// # Returns
    ///
    /// A new `Arc` with `ilabel = 0` and `olabel = 0`.
    ///
    /// # Examples
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let epsilon = Arc::epsilon(TropicalWeight::one(), 2);
    ///
    /// assert_eq!(epsilon.ilabel, 0);
    /// assert_eq!(epsilon.olabel, 0);
    /// assert!(epsilon.is_epsilon());
    /// assert!(epsilon.is_epsilon_input());
    /// assert!(epsilon.is_epsilon_output());
    /// ```
    #[inline]
    pub fn epsilon(weight: W, nextstate: StateId) -> Self {
        Self::new(0, 0, weight, nextstate)
    }

    /// Returns `true` if the input label is epsilon (0).
    ///
    /// An epsilon input means this transition does not consume
    /// any symbol from the input tape.
    ///
    /// # Returns
    ///
    /// `true` if `ilabel == 0`, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let eps = Arc::new(0, 5, TropicalWeight::one(), 1);
    /// let regular = Arc::new(1, 5, TropicalWeight::one(), 1);
    ///
    /// assert!(eps.is_epsilon_input());
    /// assert!(!regular.is_epsilon_input());
    /// ```
    #[inline]
    pub fn is_epsilon_input(&self) -> bool {
        self.ilabel == 0
    }

    /// Returns `true` if the output label is epsilon (0).
    ///
    /// An epsilon output means this transition does not produce
    /// any symbol on the output tape.
    ///
    /// # Returns
    ///
    /// `true` if `olabel == 0`, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let eps = Arc::new(5, 0, TropicalWeight::one(), 1);
    /// let regular = Arc::new(5, 1, TropicalWeight::one(), 1);
    ///
    /// assert!(eps.is_epsilon_output());
    /// assert!(!regular.is_epsilon_output());
    /// ```
    #[inline]
    pub fn is_epsilon_output(&self) -> bool {
        self.olabel == 0
    }

    /// Returns `true` if both input and output labels are epsilon.
    ///
    /// A fully epsilon arc neither consumes input nor produces output,
    /// representing a "free" transition between states. Such arcs are
    /// commonly removed during epsilon removal optimization.
    ///
    /// # Returns
    ///
    /// `true` if both `ilabel == 0` and `olabel == 0`, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let full_eps = Arc::epsilon(TropicalWeight::one(), 1);
    /// let input_eps = Arc::new(0, 5, TropicalWeight::one(), 1);
    /// let regular = Arc::new(1, 2, TropicalWeight::one(), 1);
    ///
    /// assert!(full_eps.is_epsilon());
    /// assert!(!input_eps.is_epsilon());  // Only input is epsilon
    /// assert!(!regular.is_epsilon());
    /// ```
    #[inline]
    pub fn is_epsilon(&self) -> bool {
        self.is_epsilon_input() && self.is_epsilon_output()
    }
}

impl<W: Semiring> fmt::Display for Arc<W> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}:{}:{} -> {}",
            self.ilabel, self.olabel, self.weight, self.nextstate
        )
    }
}

/// Iterator over arcs leaving a state in an FST.
///
/// This trait extends [`Iterator`] to provide a uniform interface for
/// iterating over arcs from a particular state. Different FST implementations
/// provide optimized concrete iterator types implementing this trait.
///
/// # Type Parameters
///
/// * `W` - The semiring type for arc weights
///
/// # Provided Methods
///
/// * [`reset()`](ArcIterator::reset) - Resets the iterator to the beginning
///
/// # Usage
///
/// Arc iterators are typically obtained from FST types via the `arcs()` method:
///
/// ```
/// use arcweight::prelude::*;
///
/// let mut fst = VectorFst::<TropicalWeight>::new();
/// let state = fst.add_state();
/// fst.add_arc(state, Arc::new(1, 2, TropicalWeight::new(0.5), state));
/// fst.add_arc(state, Arc::new(3, 4, TropicalWeight::new(0.3), state));
///
/// // Iterate over all arcs from state
/// for arc in fst.arcs(state) {
///     println!("Arc: {} -> {} (weight: {})", arc.ilabel, arc.olabel, arc.weight);
/// }
/// ```
///
/// # Implementation Notes
///
/// - Iterators may cache arcs internally for efficiency
/// - The [`reset()`](ArcIterator::reset) method enables iterator reuse without reallocation
/// - Some implementations lazily compute arcs during iteration
/// - Iteration order depends on the FST implementation (typically insertion order)
///
/// # Implementors
///
/// This trait is implemented by iterator types from:
///
/// - [`VectorFst`](crate::fst::VectorFst) - Direct slice iteration
/// - [`ConstFst`](crate::fst::ConstFst) - Index-based iteration
/// - Lazy FST types - On-demand arc generation
pub trait ArcIterator<W: Semiring>: Iterator<Item = Arc<W>> {
    /// Resets the iterator to the beginning of the arc sequence.
    ///
    /// This method allows reusing an iterator without creating a new one,
    /// which can be more efficient for algorithms that need to iterate
    /// over the same arcs multiple times.
    ///
    /// # Default Implementation
    ///
    /// The default implementation is a no-op, suitable for iterators
    /// that don't maintain resettable state. Implementations that support
    /// true reset should override this method.
    ///
    /// # Examples
    ///
    /// ```
    /// use arcweight::prelude::*;
    ///
    /// let mut fst = VectorFst::<TropicalWeight>::new();
    /// let s0 = fst.add_state();
    /// fst.add_arc(s0, Arc::new(1, 1, TropicalWeight::one(), s0));
    ///
    /// // Note: VectorFst returns a fresh iterator each call,
    /// // so reset() is not typically needed in practice
    /// let count1: usize = fst.arcs(s0).count();
    /// let count2: usize = fst.arcs(s0).count();
    /// assert_eq!(count1, count2);
    /// ```
    fn reset(&mut self) {
        // Default implementation does nothing
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fst::{NO_LABEL, NO_STATE_ID};
    use crate::semiring::TropicalWeight;

    #[test]
    fn test_arc_creation() {
        let arc = Arc::new(1, 2, TropicalWeight::new(3.0), 4);

        assert_eq!(arc.ilabel, 1);
        assert_eq!(arc.olabel, 2);
        assert_eq!(*arc.weight.value(), 3.0);
        assert_eq!(arc.nextstate, 4);
    }

    #[test]
    fn test_epsilon_arc() {
        let arc = Arc::epsilon(TropicalWeight::new(1.5), 5);

        assert_eq!(arc.ilabel, NO_LABEL);
        assert_eq!(arc.olabel, NO_LABEL);
        assert_eq!(*arc.weight.value(), 1.5);
        assert_eq!(arc.nextstate, 5);
        assert!(arc.is_epsilon());
    }

    #[test]
    fn test_epsilon_checks() {
        let epsilon_arc = Arc::epsilon(TropicalWeight::new(1.0), 1);
        let regular_arc = Arc::new(1, 2, TropicalWeight::new(1.0), 1);
        let epsilon_input = Arc::new(0, 2, TropicalWeight::new(1.0), 1);
        let epsilon_output = Arc::new(1, 0, TropicalWeight::new(1.0), 1);

        // Full epsilon
        assert!(epsilon_arc.is_epsilon());
        assert!(epsilon_arc.is_epsilon_input());
        assert!(epsilon_arc.is_epsilon_output());

        // Regular arc
        assert!(!regular_arc.is_epsilon());
        assert!(!regular_arc.is_epsilon_input());
        assert!(!regular_arc.is_epsilon_output());

        // Epsilon input only
        assert!(!epsilon_input.is_epsilon());
        assert!(epsilon_input.is_epsilon_input());
        assert!(!epsilon_input.is_epsilon_output());

        // Epsilon output only
        assert!(!epsilon_output.is_epsilon());
        assert!(!epsilon_output.is_epsilon_input());
        assert!(epsilon_output.is_epsilon_output());
    }

    #[test]
    fn test_arc_display() {
        let arc = Arc::new(1, 2, TropicalWeight::new(3.0), 4);
        let display_str = format!("{arc}");

        assert!(display_str.contains("1"));
        assert!(display_str.contains("2"));
        assert!(display_str.contains("3"));
        assert!(display_str.contains("4"));
    }

    #[test]
    fn test_arc_equality() {
        let arc1 = Arc::new(1, 2, TropicalWeight::new(3.0), 4);
        let arc2 = Arc::new(1, 2, TropicalWeight::new(3.0), 4);
        let arc3 = Arc::new(1, 2, TropicalWeight::new(3.1), 4);
        let arc4 = Arc::new(1, 3, TropicalWeight::new(3.0), 4);

        assert_eq!(arc1, arc2);
        assert_ne!(arc1, arc3);
        assert_ne!(arc1, arc4);
    }

    #[test]
    fn test_arc_clone() {
        let arc = Arc::new(1, 2, TropicalWeight::new(3.0), 4);
        let arc_clone = arc.clone();

        assert_eq!(arc, arc_clone);
        assert_eq!(arc.ilabel, arc_clone.ilabel);
        assert_eq!(arc.olabel, arc_clone.olabel);
        assert_eq!(arc.weight, arc_clone.weight);
        assert_eq!(arc.nextstate, arc_clone.nextstate);
    }

    #[test]
    fn test_arc_debug() {
        let arc = Arc::new(1, 2, TropicalWeight::new(3.0), 4);
        let debug_str = format!("{arc:?}");

        assert!(debug_str.contains("Arc"));
        assert!(debug_str.contains("ilabel"));
        assert!(debug_str.contains("olabel"));
        assert!(debug_str.contains("weight"));
        assert!(debug_str.contains("nextstate"));
    }

    #[test]
    fn test_arc_special_labels() {
        let arc = Arc::new(NO_LABEL, NO_LABEL, TropicalWeight::new(1.0), 0);
        assert!(arc.is_epsilon());

        let arc = Arc::new(NO_STATE_ID, NO_LABEL, TropicalWeight::new(1.0), 0);
        assert_eq!(arc.ilabel, NO_STATE_ID);
    }

    #[test]
    fn test_arc_display_format() {
        let arc = Arc::new(10, 20, TropicalWeight::new(0.5), 30);
        let display = format!("{arc}");
        assert_eq!(display, "10:20:0.5 -> 30");
    }

    #[test]
    fn test_arc_hash() {
        use std::collections::HashSet;

        let mut set = HashSet::new();
        let arc1 = Arc::new(1, 2, TropicalWeight::new(3.0), 4);
        let arc2 = Arc::new(1, 2, TropicalWeight::new(3.0), 4);
        let arc3 = Arc::new(1, 2, TropicalWeight::new(3.1), 4);

        set.insert(arc1);
        assert!(set.contains(&arc2)); // Same arc
        assert!(!set.contains(&arc3)); // Different weight
    }

    // Property-based tests
    mod proptests {
        use super::*;
        use proptest::prelude::*;

        proptest! {
            #[test]
            fn test_arc_consistency_property(
                ilabel: u32,
                olabel: u32,
                weight: f32,
                nextstate in 0..100u32,
            ) {
                let arc = Arc::new(
                    ilabel,
                    olabel,
                    TropicalWeight::new(weight),
                    nextstate,
                );

                assert_eq!(arc.ilabel, ilabel);
                assert_eq!(arc.olabel, olabel);
                assert_eq!(*arc.weight.value(), weight);
                assert_eq!(arc.nextstate, nextstate);

                // Epsilon check consistency
                let is_epsilon = ilabel == NO_LABEL && olabel == NO_LABEL;
                assert_eq!(arc.is_epsilon(), is_epsilon);
            }
        }
    }
}