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
//! Core semiring trait definitions.
//!
//! Semirings provide the algebraic structure for weighted automata operations.
//! The traits here form a hierarchy:
//!
//! - [`Semiring`]: Basic semiring operations (⊕, ⊗, 0̄, 1̄)
//! - [`DivisibleSemiring`]: Semirings with division (for weight pushing)
//! - [`StarSemiring`]: Semirings with Kleene closure (for epsilon removal)
//!
//! # Algebraic Property Markers
//!
//! Additional marker traits encode algebraic properties that enable compile-time
//! verification of algorithm requirements:
//!
//! - [`IdempotentSemiring`]: ⊕ is idempotent (`a ⊕ a = a`)
//! - [`KClosedSemiring`]: Star operation converges in bounded iterations
//! - [`ZeroSumFreeSemiring`]: `a ⊕ b = 0̄` implies `a = b = 0̄`
//! - [`WeaklyLeftDivisibleSemiring`]: Left quotient exists for sums
//! - [`CommutativeTimesSemiring`]: ⊗ is commutative (`a ⊗ b = b ⊗ a`)
use Debug;
use Hash;
/// Algebraic semiring for WFST weight operations.
///
/// A semiring (K, ⊕, ⊗, 0̄, 1̄) satisfies the following axioms:
///
/// 1. (K, ⊕, 0̄) is a commutative monoid:
/// - Associativity: (a ⊕ b) ⊕ c = a ⊕ (b ⊕ c)
/// - Commutativity: a ⊕ b = b ⊕ a
/// - Identity: a ⊕ 0̄ = a
///
/// 2. (K, ⊗, 1̄) is a monoid:
/// - Associativity: (a ⊗ b) ⊗ c = a ⊗ (b ⊗ c)
/// - Identity: a ⊗ 1̄ = 1̄ ⊗ a = a
///
/// 3. ⊗ distributes over ⊕:
/// - Left: a ⊗ (b ⊕ c) = (a ⊗ b) ⊕ (a ⊗ c)
/// - Right: (a ⊕ b) ⊗ c = (a ⊗ c) ⊕ (b ⊗ c)
///
/// 4. 0̄ is an annihilator for ⊗:
/// - 0̄ ⊗ a = a ⊗ 0̄ = 0̄
///
/// # Semantic Interpretation
///
/// - **⊕ (plus)**: Combines weights of parallel paths (e.g., min for shortest path)
/// - **⊗ (times)**: Combines weights of sequential transitions (e.g., + for costs)
/// - **0̄ (zero)**: Identity for ⊕, annihilator for ⊗ (e.g., ∞ for tropical)
/// - **1̄ (one)**: Identity for ⊗ (e.g., 0 for tropical costs)
/// Semiring with division operation.
///
/// Division is required for weight pushing algorithms that redistribute
/// weights along paths. Not all semirings support division (e.g., boolean).
///
/// # Requirements
///
/// For a ∈ K and b ∈ K where b ≠ 0̄:
/// - `(a.times(&b)).divide(&b) == Some(a)`
/// Semiring with Kleene closure (star) operation.
///
/// The star operation computes the infinite sum:
/// `a* = 1̄ ⊕ a ⊕ (a ⊗ a) ⊕ (a ⊗ a ⊗ a) ⊕ ...`
///
/// This is required for epsilon removal and other WFST algorithms that
/// need to handle cycles.
///
/// # Convergence
///
/// The star operation may not converge for all weights. Implementations
/// should return `None` when the series does not converge.
/// Marker trait for semirings that can be used as HashMap keys.
///
/// This requires the semiring to implement `Eq` and `Hash`, which means
/// it must have exact equality semantics. Floating-point semirings typically
/// cannot implement this trait directly.
/// Trait for semirings that have an underlying numerical value.
///
/// This is used for algorithms that need to extract the raw numerical
/// value from a weight, such as quantization for approximate comparison.
///
/// Implemented for numerical semirings like Tropical, Log, and Probability.
/// Not applicable to non-numerical semirings like Boolean or String.
// ============================================================================
// Algebraic Property Marker Traits
// ============================================================================
/// Marker trait for semirings where ⊕ is idempotent.
///
/// # Property
///
/// For all `a ∈ K`: `a ⊕ a = a`
///
/// # Implications
///
/// - The semiring forms a join-semilattice under ⊕
/// - Shortest-path algorithms (e.g., Dijkstra) work correctly
/// - Epsilon removal can safely revisit states
///
/// # Implementations
///
/// - [`TropicalWeight`]: `min(a, a) = a`
/// - [`BoolWeight`]: `a ∨ a = a`
/// Trait for k-closed semirings where the star operation converges in bounded iterations.
///
/// # Property
///
/// For all `a ∈ K`, there exists `k ≥ 0` such that:
/// ```text
/// ⊕_{n=0}^{k+1} aⁿ = ⊕_{n=0}^{k} aⁿ
/// ```
///
/// That is, the infinite sum `a* = 1̄ ⊕ a ⊕ a² ⊕ ...` stabilizes after k iterations.
///
/// # Implications
///
/// - FIFO queue shortest-distance algorithms terminate
/// - Epsilon removal on cyclic graphs converges
/// - The closure bound can be used to optimize star computation
///
/// # Implementations
///
/// - [`TropicalWeight`]: k=0 for non-negative weights (min stabilizes immediately)
/// - [`LogWeight`]: k=0 for weights ≥ 1 (log-sum-exp stabilizes)
/// - `BoolWeight`: k=0 (`true* = true`, `false* = true`)
/// Marker trait for zero-sum-free semirings.
///
/// # Property
///
/// For all `a, b ∈ K`: `a ⊕ b = 0̄` implies `a = 0̄` and `b = 0̄`
///
/// # Implications
///
/// - Weighted determinization is well-defined (subset weights are non-zero)
/// - Stochastic sampling is possible (weights sum to non-zero)
/// - The sum operation never "cancels out" to zero
///
/// # Implementations
///
/// All numerical semirings with non-negative weights:
/// - [`TropicalWeight`]: `min(a, b) = ∞` only if both are `∞`
/// - [`LogWeight`]: `log-add(a, b) = ∞` only if both are `∞`
/// - [`ProbabilityWeight`]: `a + b = 0` only if both are `0`
/// - [`ExpectationWeight`]: Component-wise zero-sum-free
/// - [`PowerWeight`]: `(a^{1/η} + b^{1/η})^η = 0` only if both are `0`
/// Trait for weakly left-divisible semirings.
///
/// # Property
///
/// For all `a, b ∈ K` where `a ⊕ b ≠ 0̄`, there exists `c ∈ K` such that:
/// ```text
/// c ⊗ (a ⊕ b) = a
/// ```
///
/// This is weaker than full divisibility because it only requires left quotients
/// to exist for sums, not for arbitrary products.
///
/// # Implications
///
/// - Weight normalization in determinization is possible
/// - Weights can be "factored out" during powerset construction
/// - Enables canonical subset representation
///
/// # Difference from [`DivisibleSemiring`]
///
/// - `DivisibleSemiring`: `(a ⊗ b) / b = a` (product inverse)
/// - `WeaklyLeftDivisibleSemiring`: `c ⊗ (a ⊕ b) = a` (left quotient for sums)
///
/// All divisible semirings are weakly left divisible, but not vice versa.
///
/// # Implementations
///
/// - [`TropicalWeight`]: `left_divide(a, min(a,b)) = 0` or `a - min(a,b)`
/// - [`LogWeight`]: `left_divide(a, log-add(a,b)) = a - log-add(a,b)`
/// - [`ProbabilityWeight`]: `left_divide(a, a+b) = a / (a+b)`
/// - [`ExpectationWeight`]: Component-wise left division
/// Marker trait for semirings where ⊗ is commutative.
///
/// # Property
///
/// For all `a, b ∈ K`: `a ⊗ b = b ⊗ a`
///
/// Note: The base [`Semiring`] trait already requires ⊕ to be commutative.
/// This trait additionally requires ⊗ to be commutative.
///
/// # Implications
///
/// - Order of sequential transitions doesn't affect the weight
/// - Some determinization variants can be optimized
/// - Enables symmetric algorithm formulations
///
/// # Implementations
///
/// Most numerical semirings:
/// - [`TropicalWeight`]: `a + b = b + a`
/// - [`LogWeight`]: `a + b = b + a`
/// - [`ProbabilityWeight`]: `a × b = b × a`
/// - [`BoolWeight`]: `a ∧ b = b ∧ a`
/// - [`ExpectationWeight`]: Component-wise commutative
/// - [`PowerWeight`]: `a × b = b × a`
///
/// Not implemented for string semirings (concatenation is not commutative).
// ============================================================================
// Algorithm Requirement Traits
// ============================================================================
/// Marker trait for semirings with a total order on weights.
///
/// # Property
///
/// For all `a, b ∈ K`, exactly one of these holds:
/// - `a < b`
/// - `a = b`
/// - `a > b`
///
/// This is stronger than `PartialOrd`, which allows incomparable elements.
///
/// # Implications
///
/// - Determinization can safely compute minimum weights without fallback
/// - Sorting operations are well-defined
/// - Priority queue comparisons are always valid
///
/// # Algorithm Requirements
///
/// Required by:
/// - `determinize`: For computing minimum weights in weighted subsets
///
/// # Implementations
///
/// All numerical semirings with `OrderedFloat`:
/// - [`TropicalWeight`]: Real numbers with infinity have total order
/// - [`LogWeight`]: Negative log probabilities have total order
/// - [`ProbabilityWeight`]: Non-negative reals have total order
/// - [`PowerWeight`]: Non-negative reals with eta have total order
/// - [`ExpectationWeight`]: Lexicographic order on (value, expectation)
/// Marker trait for semirings where all weights are non-negative.
///
/// # Property
///
/// For all `a ∈ K`, the weight represents a non-negative quantity in its
/// natural interpretation (costs, probabilities, distances).
///
/// # Implications
///
/// - Dijkstra's algorithm produces correct results
/// - ShortestFirstQueue can safely use a min-heap
/// - No negative cycles exist that could cause infinite loops
///
/// # Algorithm Requirements
///
/// Required by:
/// - `ShortestFirstQueue`: Dijkstra-style priority queue
///
/// # Note on Interpretation
///
/// This trait asserts that the semiring is *used* in a context where weights
/// are non-negative. The tropical semiring can represent negative costs, but
/// when used for shortest-path problems with non-negative edge weights, it
/// satisfies this property.
///
/// # Implementations
///
/// - [`TropicalWeight`]: When used with non-negative costs
/// - [`LogWeight`]: Negative log probabilities are always non-negative
/// - [`ProbabilityWeight`]: Probabilities are in [0, 1]
/// - [`PowerWeight`]: Values are clamped to non-negative
/// Trait for semirings whose weights can be quantized for approximate comparison.
///
/// # Property
///
/// Weights can be mapped to integers such that "close" weights map to the
/// same integer, enabling HashMap-based equivalence testing.
///
/// # Implications
///
/// - Minimization can use HashMap for partition refinement
/// - Approximate equality testing is efficient
/// - Floating-point artifacts from weight pushing are handled gracefully
///
/// # Algorithm Requirements
///
/// Required by:
/// - `minimize`: For HashMap-based partition refinement
///
/// # Implementations
///
/// All [`NumericalWeight`] types that represent floating-point values.
/// Trait for semirings whose weights can be interpreted as probabilities for sampling.
///
/// # Property
///
/// Weights can be converted to non-negative real numbers suitable for
/// probability-proportional sampling. The returned value represents an
/// unnormalized probability (higher = more likely to be sampled).
///
/// # Implications
///
/// - Proportional path sampling is well-defined
/// - Monte Carlo estimation over paths is possible
/// - RRWM and similar algorithms can sample paths
///
/// # Algorithm Requirements
///
/// Required by:
/// - `sample_path`: For proportional sampling strategy
///
/// # Implementations
///
/// - [`TropicalWeight`]: `exp(-x)` converts cost to probability-like value
/// - [`LogWeight`]: `exp(-x)` recovers probability from negative log space
/// - [`ProbabilityWeight`]: Direct probability value
/// - [`PowerWeight`]: Via power-to-probability isomorphism
/// Test utilities for verifying semiring axioms.