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
//! OpenFST binary format compatibility layer.
//!
//! This module provides read/write support for the OpenFST binary format,
//! enabling interoperability with the widely-used OpenFST C++ library and
//! its extensive ecosystem of tools.
//!
//! # Overview
//!
//! OpenFST is the de facto standard library for weighted finite-state transducer
//! manipulation, used extensively in:
//!
//! - **Speech recognition:** Kaldi, ESPnet, wav2vec2, Whisper pipelines
//! - **Natural language processing:** Pronunciation lexicons, G2P models
//! - **Machine translation:** Phrase-based and neural hybrid systems
//! - **Text processing:** Tokenization, normalization, transliteration
//!
//! This module ensures seamless integration between ArcWeight and existing
//! OpenFST-based pipelines.
//!
//! # Format Specification
//!
//! The OpenFST binary format uses little-endian byte ordering:
//!
//! ```text
//! +------------------+------------------+
//! | Magic (4B) | FST Type (8B) | Header
//! +------------------+------------------+
//! | Arc Type (16B) | Version (4B) |
//! +------------------+------------------+
//! | Flags (4B) | Properties (8B) |
//! +------------------+------------------+
//! | Start State (8B) | Num States (8B) |
//! +------------------+------------------+
//! | Num Arcs (8B) | |
//! +------------------+------------------+
//! | State 0: final_weight (4B) | States
//! | num_arcs (8B) |
//! | arc_0 ... arc_n |
//! +------------------------------------+
//! | State 1: ... |
//! +------------------------------------+
//! ```
//!
//! Each arc contains:
//! - Input label (4 bytes, i32)
//! - Output label (4 bytes, i32)
//! - Weight (4 bytes, f32 for tropical)
//! - Next state (4 bytes, i32)
//!
//! ## Header Constants
//!
//! - **Magic number:** 2125659606
//! - **FST type:** "vector" (null-padded to 8 bytes)
//! - **Arc type:** "tropical" (null-padded to 16 bytes)
//! - **Version:** 1
//!
//! # Current Limitations
//!
//! | Feature | Status |
//! |---------|--------|
//! | Vector FSTs | Supported |
//! | Const FSTs | Not supported |
//! | Tropical semiring | Supported |
//! | Log semiring | Not supported |
//! | Symbol tables | Not supported |
//! | Property flags | Written as 0 |
//!
//! # Examples
//!
//! ## Reading OpenFST Files
//!
//! ```no_run
//! use arcweight::prelude::*;
//! use arcweight::io::read_openfst;
//! use std::fs::File;
//!
//! // Read FST created by OpenFST tools (fstcompile, fstdeterminize, etc.)
//! let mut file = File::open("model.fst")?;
//! let fst: VectorFst<TropicalWeight> = read_openfst(&mut file)?;
//!
//! println!("Loaded FST with {} states", fst.num_states());
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Writing OpenFST Files
//!
//! ```no_run
//! use arcweight::prelude::*;
//! use arcweight::io::write_openfst;
//! use std::fs::File;
//!
//! 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(0.5), s1));
//!
//! // Write in OpenFST format
//! let mut file = File::create("output.fst")?;
//! write_openfst(&fst, &mut file)?;
//!
//! // Now usable with OpenFST command-line tools:
//! // $ fstinfo output.fst
//! // $ fstdraw output.fst | dot -Tpng > fst.png
//! // $ fstprint output.fst
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Pipeline Integration with Kaldi
//!
//! ```no_run
//! use arcweight::prelude::*;
//! use arcweight::io::{read_openfst, write_openfst};
//! use std::fs::File;
//!
//! // Read lexicon FST from Kaldi
//! let mut file = File::open("L.fst")?;
//! let lexicon: VectorFst<TropicalWeight> = read_openfst(&mut file)?;
//!
//! // Optimize with ArcWeight
//! let optimized: VectorFst<TropicalWeight> = minimize(&lexicon)?;
//!
//! // Write back for use in Kaldi
//! let mut out = File::create("L_opt.fst")?;
//! write_openfst(&optimized, &mut out)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! # Weight Representation
//!
//! The tropical semiring in OpenFST uses IEEE 754 single-precision floats:
//!
//! | Semiring Element | OpenFST Representation |
//! |------------------|------------------------|
//! | Zero (annihilator) | `+inf` (positive infinity) |
//! | One (identity) | `0.0` |
//! | General weight | float value (lower = better) |
//!
//! # State Numbering
//!
//! - States are numbered consecutively from 0
//! - State IDs are preserved exactly during read/write
//! - The special value -1 indicates "no start state"
//!
//! # References
//!
//! - Allauzen, C., Riley, M., Schalkwyk, J., Skut, W., & Mohri, M. (2007).
//! OpenFst: A general and efficient weighted finite-state transducer library.
//! In *Implementation and Application of Automata* (CIAA 2007), pp. 11-23.
//! Springer. <https://doi.org/10.1007/978-3-540-76336-9_3>
//!
//! - OpenFST Library. <https://www.openfst.org/>
//!
//! - Povey, D., et al. (2011). The Kaldi speech recognition toolkit.
//! In *IEEE Workshop on Automatic Speech Recognition and Understanding*.
use crateArc;
use crate;
use crate;
use crate::;
use ;
use ;
const OPENFST_MAGIC: i32 = 2_125_659_606;
/// FST type in OpenFST format
/// Writes an FST in OpenFST binary format.
///
/// Serializes the FST to the standard OpenFST binary format, making it compatible
/// with OpenFST command-line tools (`fstinfo`, `fstdraw`, `fstprint`, etc.) and
/// other libraries that read OpenFST files (Kaldi, ESPnet, etc.).
///
/// # Type Parameters
///
/// * `F` - The FST type, must implement `Fst<TropicalWeight>`
/// * `Writer` - The output writer type, must implement `Write + Seek`
///
/// # Arguments
///
/// * `fst` - Reference to the FST to serialize
/// * `writer` - Mutable reference to the output writer (must support seeking)
///
/// # Returns
///
/// Returns `Ok(())` on successful serialization.
///
/// # Errors
///
/// Returns [`Error::Io`] if the writer encounters an I/O error
/// during writing or seeking.
///
/// # Complexity
///
/// - **Time:** O(|V| + |E|) where |V| is the number of states and |E| is
/// the number of arcs
/// - **Space:** O(1) additional space (streaming write)
///
/// # Format Details
///
/// The output file uses:
/// - Magic number: 2125659606
/// - FST type: "vector"
/// - Arc type: "tropical"
/// - Little-endian byte order
/// - IEEE 754 f32 for weights (+inf = zero element)
///
/// # Examples
///
/// ```no_run
/// use arcweight::prelude::*;
/// use arcweight::io::write_openfst;
/// use std::fs::File;
///
/// 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, 2, TropicalWeight::new(0.5), s1));
///
/// let mut file = File::create("output.fst")?;
/// write_openfst(&fst, &mut file)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # See Also
///
/// - [`read_openfst`] - Read FSTs in OpenFST format
/// - [`write_binary`](super::write_binary) - Native binary format (Rust-only)
/// Reads an FST from OpenFST binary format.
///
/// Parses the standard OpenFST binary format, enabling loading of FSTs created
/// by OpenFST command-line tools (`fstcompile`, `fstdeterminize`, etc.) or other
/// compatible libraries.
///
/// # Type Parameters
///
/// * `M` - The mutable FST type to construct, must implement
/// `MutableFst<TropicalWeight> + Default`
/// * `Reader` - The input reader type, must implement `Read`
///
/// # Arguments
///
/// * `reader` - Mutable reference to the input reader
///
/// # Returns
///
/// Returns the parsed FST on success.
///
/// # Errors
///
/// Returns [`Error::Serialization`] if the magic
/// number is invalid (file is not in OpenFST format).
///
/// Returns [`Error::Io`] if the reader encounters an I/O error.
///
/// # Complexity
///
/// - **Time:** O(|V| + |E|) where |V| is the number of states and |E| is
/// the number of arcs
/// - **Space:** O(|V| + |E|) for the output FST
///
/// # Correctness
///
/// This function guarantees compatibility with OpenFST:
/// - Reads files written by OpenFST tools
/// - Produces FSTs that can be written back in OpenFST format
/// - Language is preserved: L(read(write(T))) = L(T)
/// - State IDs are preserved exactly
///
/// # Limitations
///
/// - Only supports vector FSTs (not const FSTs)
/// - Only supports tropical semiring weights
/// - Does not read symbol tables (use separate `.syms` files)
/// - Does not preserve property flags
///
/// # Examples
///
/// ```no_run
/// use arcweight::prelude::*;
/// use arcweight::io::read_openfst;
/// use std::fs::File;
///
/// let mut file = File::open("model.fst")?;
/// let fst: VectorFst<TropicalWeight> = read_openfst(&mut file)?;
///
/// println!("States: {}", fst.num_states());
/// println!("Start: {:?}", fst.start());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// # See Also
///
/// - [`write_openfst`] - Write FSTs in OpenFST format
/// - [`read_binary`](super::read_binary) - Native binary format (faster, Rust-only)