1 // See www.openfst.org for extensive documentation on this weighted
2 // finite-state transducer library.
4 // Functions and classes to invert an FST.
9 #include <fst/arc-map.h>
10 #include <fst/mutable-fst.h>
15 // Mapper to implement inversion of an arc.
23 ToArc operator()(const FromArc &arc) {
24 return ToArc(arc.olabel, arc.ilabel, arc.weight, arc.nextstate);
27 MapFinalAction FinalAction() const { return MAP_NO_SUPERFINAL; }
29 MapSymbolsAction InputSymbolsAction() const { return MAP_CLEAR_SYMBOLS; }
31 MapSymbolsAction OutputSymbolsAction() const { return MAP_CLEAR_SYMBOLS; }
33 uint64 Properties(uint64 props) { return InvertProperties(props); }
36 // Inverts the transduction corresponding to an FST by exchanging the
37 // FST's input and output labels. This version modifies its input.
44 // where V is the number of states and E is the number of arcs.
46 inline void Invert(MutableFst<Arc> *fst) {
47 std::unique_ptr<SymbolTable> input(
48 fst->InputSymbols() ? fst->InputSymbols()->Copy() : nullptr);
49 std::unique_ptr<SymbolTable> output(
50 fst->OutputSymbols() ? fst->OutputSymbols()->Copy() : nullptr);
51 ArcMap(fst, InvertMapper<Arc>());
52 fst->SetInputSymbols(output.get());
53 fst->SetOutputSymbols(input.get());
56 // Inverts the transduction corresponding to an FST by exchanging the
57 // FST's input and output labels. This version is a delayed FST.
64 // where v is the number of states visited and e is the number of arcs visited.
65 // Constant time and to visit an input state or arc is assumed and exclusive of
68 class InvertFst : public ArcMapFst<A, A, InvertMapper<A>> {
72 using Mapper = InvertMapper<Arc>;
73 using Impl = internal::ArcMapFstImpl<A, A, InvertMapper<A>>;
75 explicit InvertFst(const Fst<Arc> &fst)
76 : ArcMapFst<Arc, Arc, Mapper>(fst, Mapper()) {
77 GetMutableImpl()->SetOutputSymbols(fst.InputSymbols());
78 GetMutableImpl()->SetInputSymbols(fst.OutputSymbols());
81 // See Fst<>::Copy() for doc.
82 InvertFst(const InvertFst<Arc> &fst, bool safe = false)
83 : ArcMapFst<Arc, Arc, Mapper>(fst, safe) {}
85 // Get a copy of this InvertFst. See Fst<>::Copy() for further doc.
86 InvertFst<Arc> *Copy(bool safe = false) const override {
87 return new InvertFst(*this, safe);
91 using ImplToFst<Impl>::GetMutableImpl;
94 // Specialization for InvertFst.
96 class StateIterator<InvertFst<Arc>>
97 : public StateIterator<ArcMapFst<Arc, Arc, InvertMapper<Arc>>> {
99 explicit StateIterator(const InvertFst<Arc> &fst)
100 : StateIterator<ArcMapFst<Arc, Arc, InvertMapper<Arc>>>(fst) {}
103 // Specialization for InvertFst.
105 class ArcIterator<InvertFst<Arc>>
106 : public ArcIterator<ArcMapFst<Arc, Arc, InvertMapper<Arc>>> {
108 using StateId = typename Arc::StateId;
110 ArcIterator(const InvertFst<Arc> &fst, StateId s)
111 : ArcIterator<ArcMapFst<Arc, Arc, InvertMapper<Arc>>>(fst, s) {}
114 // Useful alias when using StdArc.
115 using StdInvertFst = InvertFst<StdArc>;
119 #endif // FST_INVERT_H_