1 // rmfinalepsilon.h 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // 16 // \file 17 // Function to remove of final states that have epsilon only input arcs. 18 19 #ifndef FST_LIB_RMFINALEPSILON_H__ 20 #define FST_LIB_RMFINALEPSILON_H__ 21 22 #include <unordered_set> 23 24 #include "fst/lib/connect.h" 25 #include "fst/lib/mutable-fst.h" 26 27 namespace fst { 28 29 template<class A> 30 void RmFinalEpsilon(MutableFst<A>* fst) { 31 typedef typename A::StateId StateId; 32 typedef typename A::Weight Weight; 33 34 // Determine the coaccesibility of states. 35 vector<bool> access; 36 vector<bool> coaccess; 37 uint64 props = 0; 38 SccVisitor<A> scc_visitor(0, &access, &coaccess, &props); 39 DfsVisit(*fst, &scc_visitor); 40 41 // Find potential list of removable final states. These are final states 42 // that have no outgoing transitions or final states that have a 43 // non-coaccessible future. Complexity O(S) 44 std::unordered_set<StateId> finals; 45 for (StateIterator<Fst<A> > siter(*fst); !siter.Done(); siter.Next()) { 46 StateId s = siter.Value(); 47 if (fst->Final(s) != Weight::Zero()) { 48 bool future_coaccess = false; 49 for (ArcIterator<Fst<A> > aiter(*fst, s); !aiter.Done(); aiter.Next()) { 50 const A& arc = aiter.Value(); 51 if (coaccess[arc.nextstate]) { 52 future_coaccess = true; 53 break; 54 } 55 } 56 if (!future_coaccess) { 57 finals.insert(s); 58 } 59 } 60 } 61 62 // Move the final weight. Complexity O(E) 63 vector<A> arcs; 64 for (StateIterator<Fst<A> > siter(*fst); !siter.Done(); siter.Next()) { 65 StateId s = siter.Value(); 66 Weight w(fst->Final(s)); 67 68 arcs.clear(); 69 for (ArcIterator<Fst<A> > aiter(*fst, s); !aiter.Done(); aiter.Next()) { 70 const A& arc = aiter.Value(); 71 // is next state in the list of finals 72 if (finals.find(arc.nextstate) != finals.end()) { 73 // sum up all epsilon arcs 74 if (arc.ilabel == 0 && arc.olabel == 0) { 75 w = Plus(Times(fst->Final(arc.nextstate), arc.weight), w); 76 } else { 77 arcs.push_back(arc); 78 } 79 } else { 80 arcs.push_back(arc); 81 } 82 } 83 84 // If some arcs (epsilon arcs) were deleted, delete all 85 // arcs and add back only the non epsilon arcs 86 if (arcs.size() < fst->NumArcs(s)) { 87 fst->DeleteArcs(s); 88 fst->SetFinal(s, w); 89 for (size_t i = 0; i < arcs.size(); ++i) { 90 fst->AddArc(s, arcs[i]); 91 } 92 } 93 } 94 95 Connect(fst); 96 } 97 98 } 99 100 #endif // FST_LIB_RMFINALEPSILON_H__ 101