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
//! FST projection algorithms.
//!
//! Extracts input or output labels from weighted finite-state transducers,
//! converting transducers into acceptors that recognize single label sequences.
//!
//! # Overview
//!
//! Projection is a fundamental operation that converts a transducer (FST) into
//! an acceptor (FSA) by selecting either the input or output labels. The
//! resulting acceptor recognizes the domain (input projection) or range
//! (output projection) of the original transducer.
//!
//! # Algorithm
//!
//! For each arc in the FST:
//! - **Input projection:** Set both labels to the original input label
//! - **Output projection:** Set both labels to the original output label
//!
//! All weights and structural properties are preserved.
//!
//! # Complexity
//!
//! - **Time:** $`O(|V| + |E|)`$ for linear state and arc processing
//! - **Space:** $`O(|V| + |E|)`$ for the result FST
//!
//! # Mathematical Foundation
//!
//! For a transducer $`T`$ mapping strings $`x`$ to $`y`$ with weight $`w`$:
//! - **Input projection:** $`\text{Domain}(T) = \{x : \exists y, w \text{ such that } T(x,y) = w\}`$
//! - **Output projection:** $`\text{Range}(T) = \{y : \exists x, w \text{ such that } T(x,y) = w\}`$
//!
//! # Use Cases
//!
//! - **Language Extraction:** Extract source or target language from translation models
//! - **Vocabulary Analysis:** Determine input/output vocabulary coverage
//! - **Cascade Preparation:** Create acceptors for composition pipelines
//! - **Validation:** Build input validators from transducer specifications
//!
//! # Examples
//!
//! ```rust
//! use arcweight::prelude::*;
//!
//! // Create a simple transducer: 'a' -> 'x', 'b' -> 'y'
//! 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('a' as u32, 'x' as u32, TropicalWeight::one(), s1));
//! fst.add_arc(s1, Arc::new('b' as u32, 'y' as u32, TropicalWeight::one(), s2));
//!
//! // Project to input labels: acceptor for "ab"
//! let input_fsa: VectorFst<TropicalWeight> = arcweight::algorithms::project_input(&fst)?;
//! assert_eq!(input_fsa.num_states(), 3);
//!
//! // Project to output labels: acceptor for "xy"
//! let output_fsa: VectorFst<TropicalWeight> = arcweight::algorithms::project_output(&fst)?;
//! assert_eq!(output_fsa.num_states(), 3);
//! # Ok::<(), arcweight::Error>(())
//! ```
//!
//! # References
//!
//! - Mohri, M., Pereira, F., and Riley, M. (2008). Speech recognition with weighted
//! finite-state transducers. In *Springer Handbook of Speech Processing*
//! (pp. 559-584). Springer. <https://doi.org/10.1007/978-3-540-49127-9_28>
//! - Mohri, M. (2009). Weighted automata algorithms. In *Handbook of Weighted
//! Automata* (pp. 213-254). Springer. <https://doi.org/10.1007/978-3-642-01492-5_6>
use crateArc;
use crate;
use crateSemiring;
use crateResult;
/// Project FST onto its input labels, creating an acceptor that recognizes input sequences
///
/// Converts a finite-state transducer (FST) into a finite-state acceptor (FSA)
/// by extracting the input labels and setting both input and output labels to
/// the same values. The result accepts exactly the input language of the original FST.
///
/// # Algorithm Details
///
/// - **Label Extraction:** Extract input labels from all arcs
/// - **Label Duplication:** Set both input and output labels to the same value
/// - **Time Complexity:** O(|V| + |E|) for linear traversal and copying
/// - **Space Complexity:** O(|V| + |E|) for the result FST
/// - **Language Relationship:** L(project_input(T)) = Domain(T)
///
/// # Mathematical Foundation
///
/// For an FST T that maps strings x to strings y with weights w,
/// the input projection extracts the domain:
/// - **Domain Extraction:** Domain(T) = {x : ∃y,w such that T(x,y) = w}
/// - **Acceptor Creation:** Result recognizes input strings regardless of output
/// - **Weight Preservation:** All path weights maintained exactly
///
/// # Algorithm Steps
///
/// 1. **Structure Copy:** Copy all states and state connectivity from original FST
/// 2. **Start/Final Copy:** Preserve start state and all final weights
/// 3. **Arc Projection:** For each arc (s, i:o/w, t), create arc (s, i:i/w, t)
/// 4. **Label Unification:** Both input and output labels become the same
/// 5. **Weight Preservation:** All arc and final weights remain unchanged
///
/// # Examples
///
/// ## Basic Input Projection
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // FST that maps "hello" -> "hi" and "world" -> "earth"
/// 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());
///
/// // "hello" -> "hi"
/// fst.add_arc(s0, Arc::new('h' as u32, 'h' as u32, TropicalWeight::one(), s1));
/// fst.add_arc(s1, Arc::new('i' as u32, 'e' as u32, TropicalWeight::one(), s2));
///
/// // Project to input: result accepts "hi" (input sequence)
/// let input_acceptor: VectorFst<TropicalWeight> = project_input(&fst)?;
///
/// // Result is an acceptor for the input language
/// assert_eq!(input_acceptor.num_states(), fst.num_states());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Translation System Projection
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Translation FST: English -> French
/// let mut translator = VectorFst::<TropicalWeight>::new();
/// let s0 = translator.add_state();
/// let s1 = translator.add_state();
/// let s2 = translator.add_state();
///
/// translator.set_start(s0);
/// translator.set_final(s2, TropicalWeight::one());
///
/// // "cat" -> "chat" (1:3, 2:4 represent word IDs)
/// translator.add_arc(s0, Arc::new(1, 3, TropicalWeight::new(0.8), s1));
/// translator.add_arc(s1, Arc::new(2, 4, TropicalWeight::new(0.9), s2));
///
/// // Extract English vocabulary (input projection)
/// let english_vocab: VectorFst<TropicalWeight> = project_input(&translator)?;
///
/// // Result accepts English word sequences regardless of translation
/// println!("English vocabulary extractor created");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Morphological Analysis Projection
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Morphological analyzer: surface -> analysis
/// let mut morph = VectorFst::<TropicalWeight>::new();
/// let s0 = morph.add_state();
/// let s1 = morph.add_state();
/// let s2 = morph.add_state();
///
/// morph.set_start(s0);
/// morph.set_final(s2, TropicalWeight::one());
///
/// // "running" -> "run+VERB+PRESENT"
/// morph.add_arc(s0, Arc::new('r' as u32, 'r' as u32, TropicalWeight::one(), s1));
/// morph.add_arc(s1, Arc::new('u' as u32, '+' as u32, TropicalWeight::one(), s2));
///
/// // Extract surface forms (input projection)
/// let surface_forms: VectorFst<TropicalWeight> = project_input(&morph)?;
///
/// // Result recognizes surface word forms only
/// assert!(surface_forms.start().is_some());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Multi-Level Processing
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Speech recognition: phoneme -> word
/// let mut speech = VectorFst::<TropicalWeight>::new();
/// let s0 = speech.add_state();
/// let s1 = speech.add_state();
///
/// speech.set_start(s0);
/// speech.set_final(s1, TropicalWeight::one());
///
/// // Phoneme sequence -> word
/// speech.add_arc(s0, Arc::new(1, 100, TropicalWeight::new(0.7), s1)); // /k/ -> "cat"
///
/// // Extract phoneme acceptor (input projection)
/// let phoneme_acceptor: VectorFst<TropicalWeight> = project_input(&speech)?;
///
/// // Result accepts phoneme sequences independent of word recognition
/// println!("Phoneme acceptor extracted");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Weighted Path Extraction
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Weighted transducer with costs
/// let mut weighted_fst = VectorFst::<TropicalWeight>::new();
/// let s0 = weighted_fst.add_state();
/// let s1 = weighted_fst.add_state();
///
/// weighted_fst.set_start(s0);
/// weighted_fst.set_final(s1, TropicalWeight::new(0.5));
///
/// weighted_fst.add_arc(s0, Arc::new('a' as u32, 'x' as u32, TropicalWeight::new(1.2), s1));
///
/// // Project with weight preservation
/// let weighted_acceptor: VectorFst<TropicalWeight> = project_input(&weighted_fst)?;
///
/// // Input acceptor maintains all path costs
/// assert_eq!(weighted_acceptor.num_states(), weighted_fst.num_states());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Use Cases
///
/// ## Language Analysis
/// - **Source Language Extraction:** Extract source vocabulary from translation models
/// - **Input Validation:** Create acceptors to validate system inputs
/// - **Morphological Analysis:** Extract surface forms from analysis transducers
/// - **Speech Recognition:** Extract phoneme sequences from recognition models
///
/// ## System Design
/// - **Input Space Analysis:** Understand what inputs a system can handle
/// - **Vocabulary Coverage:** Determine input vocabulary requirements
/// - **Interface Design:** Design input interfaces based on system capabilities
/// - **Constraint Definition:** Define input constraints from system models
///
/// ## Preprocessing
/// - **Filter Creation:** Create input filters for preprocessing pipelines
/// - **Validation Sets:** Build input validation from known good inputs
/// - **Test Generation:** Generate test inputs from system specifications
/// - **Data Preparation:** Prepare input data for further processing
///
/// # Performance Characteristics
///
/// - **Time Complexity:** O(|V| + |E|) for linear state and arc processing
/// - **Space Complexity:** O(|V| + |E|) matching the original FST size
/// - **Memory Efficiency:** Simple copying with minimal overhead
/// - **Cache Friendly:** Sequential access pattern improves performance
/// - **Parallelizable:** State processing can be parallelized easily
///
/// # Mathematical Properties
///
/// Input projection preserves essential FST properties:
/// - **Language Preservation:** Domain exactly preserved in acceptor form
/// - **Weight Preservation:** All path weights maintained identically
/// - **Structural Properties:** State connectivity and reachability preserved
/// - **Determinism:** Deterministic FSTs produce deterministic acceptors
/// - **Compositionality:** project_input(T₁ ∘ T₂) relates to domain analysis
///
/// # Implementation Details
///
/// The algorithm performs a simple structural copy with label transformation.
/// For each arc (s, i:o/w, t) in the original FST, it creates (s, i:i/w, t)
/// in the result. This preserves all structural and weight information while
/// creating an acceptor that recognizes the input language.
///
/// # Optimization Opportunities
///
/// After input projection, consider these optimizations:
/// - **Determinization:** Convert to deterministic acceptor if needed
/// - **Minimization:** Reduce state count through equivalence merging
/// - **Connection:** Remove unreachable states from the result
/// - **Epsilon Removal:** Eliminate epsilon transitions for efficiency
///
/// # Errors
///
/// Returns [`Error::Algorithm`](crate::Error::Algorithm) if:
/// - The input FST is invalid, corrupted, or malformed
/// - Memory allocation fails during computation or result construction
/// - The projection operation encounters invalid state or arc data
/// - State or arc enumeration fails due to data corruption
/// - Weight operations fail during arc creation
///
/// # See Also
///
/// - [`project_output`] for extracting output language from FSTs
/// - [`compose()`](crate::algorithms::compose()) for combining projections with other FSTs
/// - [`union()`](crate::algorithms::union()) for combining multiple projections
/// - [Working with FSTs - Projection](../../docs/working-with-fsts/structural-operations.md#projection) for usage patterns
/// - [Core Concepts](../../docs/core-concepts/algorithms.md#projection) for mathematical theory
/// Project FST onto its output labels, creating an acceptor that recognizes output sequences
///
/// Converts a finite-state transducer (FST) into a finite-state acceptor (FSA)
/// by extracting the output labels and setting both input and output labels to
/// the same values. The result accepts exactly the output language of the original FST.
///
/// # Algorithm Details
///
/// - **Label Extraction:** Extract output labels from all arcs
/// - **Label Duplication:** Set both input and output labels to the same value
/// - **Time Complexity:** O(|V| + |E|) for linear traversal and copying
/// - **Space Complexity:** O(|V| + |E|) for the result FST
/// - **Language Relationship:** L(project_output(T)) = Range(T)
///
/// # Mathematical Foundation
///
/// For an FST T that maps strings x to strings y with weights w,
/// the output projection extracts the range:
/// - **Range Extraction:** Range(T) = {y : ∃x,w such that T(x,y) = w}
/// - **Acceptor Creation:** Result recognizes output strings regardless of input
/// - **Weight Preservation:** All path weights maintained exactly
///
/// # Examples
///
/// ## Basic Output Projection
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // FST that maps "hello" -> "hi" and "world" -> "earth"
/// 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());
///
/// // "hello" -> "hi": input 'h' -> output 'h', input 'i' -> output 'e'
/// fst.add_arc(s0, Arc::new('h' as u32, 'h' as u32, TropicalWeight::one(), s1));
/// fst.add_arc(s1, Arc::new('i' as u32, 'e' as u32, TropicalWeight::one(), s2));
///
/// // Project to output: result accepts "he" (output sequence)
/// let output_acceptor: VectorFst<TropicalWeight> = project_output(&fst)?;
///
/// // Result is an acceptor for the output language
/// assert_eq!(output_acceptor.num_states(), fst.num_states());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Translation Target Extraction
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Translation FST: English -> French
/// let mut translator = VectorFst::<TropicalWeight>::new();
/// let s0 = translator.add_state();
/// let s1 = translator.add_state();
/// let s2 = translator.add_state();
///
/// translator.set_start(s0);
/// translator.set_final(s2, TropicalWeight::one());
///
/// // "cat" -> "chat" (1:3, 2:4 represent word IDs)
/// translator.add_arc(s0, Arc::new(1, 3, TropicalWeight::new(0.8), s1));
/// translator.add_arc(s1, Arc::new(2, 4, TropicalWeight::new(0.9), s2));
///
/// // Extract French vocabulary (output projection)
/// let french_vocab: VectorFst<TropicalWeight> = project_output(&translator)?;
///
/// // Result accepts French word sequences regardless of English input
/// println!("French vocabulary extractor created");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Generated Text Recognition
///
/// ```rust
/// use arcweight::prelude::*;
///
/// // Text generation FST: concept -> surface text
/// let mut generator = VectorFst::<TropicalWeight>::new();
/// let s0 = generator.add_state();
/// let s1 = generator.add_state();
///
/// generator.set_start(s0);
/// generator.set_final(s1, TropicalWeight::one());
///
/// // Concept -> Text: "GREETING" -> "hello"
/// generator.add_arc(s0, Arc::new(1, 'h' as u32, TropicalWeight::one(), s1));
///
/// // Extract generated text acceptor (output projection)
/// let text_acceptor: VectorFst<TropicalWeight> = project_output(&generator)?;
///
/// // Result recognizes generated text sequences
/// assert!(text_acceptor.start().is_some());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # Use Cases
///
/// ## Language Analysis
/// - **Target Language Extraction:** Extract target vocabulary from translation models
/// - **Generated Text Analysis:** Analyze possible outputs from generation systems
/// - **Morphological Generation:** Extract generated surface forms
/// - **Speech Synthesis:** Extract possible acoustic outputs
///
/// ## System Validation
/// - **Output Space Analysis:** Understand what outputs a system can produce
/// - **Vocabulary Coverage:** Determine output vocabulary coverage
/// - **Quality Assessment:** Analyze generated content possibilities
/// - **Constraint Verification:** Ensure outputs meet requirements
///
/// ## Preprocessing
/// - **Cascade Preparation:** Prepare acceptors for further composition
/// - **Filter Creation:** Create filters based on desired outputs
/// - **Validation Sets:** Build validation acceptors from known good outputs
/// - **Testing Infrastructure:** Create test cases from system capabilities
///
/// # Errors
///
/// Returns [`Error::Algorithm`](crate::Error::Algorithm) if:
/// - The input FST is invalid, corrupted, or malformed
/// - Memory allocation fails during computation or result construction
/// - The projection operation encounters invalid state or arc data
/// - State or arc enumeration fails due to data corruption
/// - Weight operations fail during arc creation
///
/// # See Also
///
/// - [`project_input`] for extracting input language from FSTs
/// - [`compose()`](crate::algorithms::compose()) for combining projections with other FSTs
/// - [`union()`](crate::algorithms::union()) for combining multiple projections
/// - [Working with FSTs - Projection](../../docs/working-with-fsts/structural-operations.md#projection) for usage patterns
/// - [Core Concepts](../../docs/core-concepts/algorithms.md#projection) for mathematical theory