You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

798 lines
32 KiB

  1. // fstext/pre-determinize-inl.h
  2. // Copyright 2009-2011 Microsoft Corporation
  3. // See ../../COPYING for clarification regarding multiple authors
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  12. // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  13. // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  14. // MERCHANTABLITY OR NON-INFRINGEMENT.
  15. // See the Apache 2 License for the specific language governing permissions and
  16. // limitations under the License.
  17. #ifndef KALDI_FSTEXT_PRE_DETERMINIZE_INL_H_
  18. #define KALDI_FSTEXT_PRE_DETERMINIZE_INL_H_
  19. #include <algorithm>
  20. #include <map>
  21. #include <set>
  22. #include <string>
  23. #include <utility>
  24. #include <vector>
  25. /* Do not include this file directly. It is an implementation file included by
  26. * PreDeterminize.h */
  27. /*
  28. Predeterminization
  29. This is a function that makes an FST compactly determinizable by inserting
  30. symbols on the input side as necessary for disambiguation. Note that we do
  31. not treat epsilon as a real symbol when measuring determinizability in this
  32. sense. The extra symbols are added to the vocabulary, on the input side;
  33. these are of the form (prefix)1, (prefix)2, and so on without limit, where
  34. (prefix) is some prefix the user provides, e.g. '#' (the function checks that
  35. this will not lead to conflicts with symbols already in the FST). The
  36. function tells us how many such symbols it created.
  37. Note that there is a paper "Generalized optimization algorithm for speech
  38. recognition transducers" by Allauzen and Mohri, that deals with a similar
  39. issue, but this is a very different algorithm that only aims to ensure
  40. determinizability, but not *compact* determinizability.
  41. Our algorithm is slightly heuristic, and probably not optimal, but does
  42. ensure that the output is compactly determinizable, possibly at the expense of
  43. inserting unnecessary symbols. We considered more sophisticated algorithms,
  44. but these were extremely complicated and would give the same output for the
  45. kinds of inputs that we envisage.
  46. Suppose the input FST is T. We want to ensure that in det(T), if we consider
  47. the states of det(T) as weighted subsets of states of T, each state of T only
  48. appears once in any given subset. This ensures that det(T) is no larger than
  49. T in an appropriate sense. The way we do this is as follows. We identify all
  50. states in T that have multiple input transitions (counting "being an initial
  51. state" as an input transition). Let's call these "problematic" states. For a
  52. problematic state p we stipulate that it can never appear in any state of
  53. det(T) unless that state equals (p, \bar{1}) [i.e. p, unweighted]. In order
  54. to ensure this, we insert input symbols on the transitions to these
  55. problematic states (this may necessitate adding extra states).
  56. We also stipulate that the path through det(T) should always be sufficient
  57. to tell us the path through T (and we insert extra symbols sufficient to make
  58. this so). This is to simplify the algorithm, so that we don't have to
  59. consider the output symbols or weights when predeterminizing.
  60. The algorithm is as follows.
  61. (A) Definitions
  62. (i) Define a *problematic state* as a state that either has multiple
  63. input transitions, or is an initial state and has at least one input
  64. transition.
  65. (ii) For an arc a, define:
  66. i[a] = input symbol on a
  67. o[a] = output symbol on a
  68. n[a] = dest-state of a
  69. p[a] = origin-state of a
  70. For a state q, define
  71. E[q] = set of transitions leaving q.
  72. For a set of states Q, define
  73. E[Q] = set of transitions leaving some q in Q
  74. (iii) For a state s, define Closure(s) as the union of state s, and all
  75. states t that are reachable via sequences of arcs a such that i[a]=epsilon and
  76. n[a] is not problematic.
  77. For a set of states S, define Closure(S) as the union of the closures
  78. of states s in S.
  79. (B) Inputs and outputs.
  80. (i) Inputs and preconditions. Input is an FST, which should have a symbol
  81. table compiled into it, and a prefix (e.g. #) for symbols to be added. We
  82. check that the input FST is trim, and that it does not have any symbols that
  83. appear on its arcs, that are equal to the prefix followed by digits.
  84. (ii) Outputs: The algorithm modifies the FST that is given to it, and
  85. returns the number of the highest numbered "extra symbol" inserted. The extra
  86. symbols are numbered #1, #2 and so on without limit (as integers). They are
  87. inserted into the symbol table in a sequential way by calling AvailableKey()
  88. for each in turn (this is stipulated in case we need to keep other
  89. symbol tables in sync).
  90. (C) Sub-algorithm: Closure(S). This requires the array p(s), defined
  91. below, which is true if s is problematic. This also requires, for efficiency,
  92. that the arcs be sorted on input label. Input: a set of states S. [plus, the
  93. fst and the array p]. Output: a set of states T. Algorithm: set T <-- S, Q <--
  94. S. while Q is nonempty: pop a state s from Q. for each transition a from state
  95. s with epsilon on the input label [we can find these efficiently using the
  96. sorting on arcs]: If p(n[a]) is false and n[a] is not in T: Insert n[a] into
  97. T. Add n[a] to Q. return T.
  98. (D) Main algorithm.
  99. (i) (a) Check preconditions (FST is trim)
  100. (b) Make sure there is just one final state (insert epsilon
  101. transitions as necessary). (c) Sort arcs on input label (so epsilon arcs are
  102. at the start of arc lists).
  103. (ii) Work out the set of problematic states by constructing a boolean
  104. array indexed by states, i.e. p(s) which is true if the state is problematic.
  105. We can do this by constructing an array t(s) to store the number of
  106. transitions into each state [adding one for the initial state], and then
  107. setting p(s) = true if t(s) > 1.
  108. Also create a boolean array d(s), defined for states, and set d(s) =
  109. false. This array is purely for sanity-checking that we are processing each
  110. state exactly once.
  111. (iii) Set up an array of integers m(a), indexed by arcs (how exactly we
  112. store these is implementation-dependent, but this will probably be a hash from
  113. (state, arc-index) to integers. m(a) will store the extra symbol, if any, to
  114. be added to that arc (or -1 if no such symbol; we can also simply have the arc
  115. not present in the hash). The initial value of m(a) is -1 (if array), or
  116. undefined (if hash).
  117. (iv) Initialize a set of sets-of-states S, and a queue of pairs Q, as
  118. follows. The pairs in Q are a pair of (set-of-states, integer), where the
  119. integer is the number of "special symbols" already used up for that state.
  120. Note that we use a special indexing for the sets in both S and Q,
  121. rather than using std::set. We use a sorted vector of StateId's. And in S,
  122. we index them by the lowest-numbered state-id. Because each state is supposed
  123. to only ever be a member of one set, if there is an attempt to add another,
  124. different set with the same lowest-numbered state-id, we detect an error.
  125. Let I be the single initial state (OpenFST only supports one).
  126. We set:
  127. S = { Closure(I) }
  128. Push (Closure(I), 0) onto Q.
  129. Then for each state s such that p(s) = true, and s is not an initial
  130. state: S <-- S u { Closure(s) } Push (Closure(s), 0) onto Q.
  131. (v) While Q is nonempty:
  132. (a) Pop pair (A, n) from Q (queue discipline is arbitrary).
  133. (b) For each state s in A, check that d(s) is false, and set d(s) to
  134. true. This is for sanity checking only.
  135. (c)
  136. Let S_\eps be the set of epsilon-transitions from members of A to
  137. problematic states (i.e. S_\eps = \{ a \in E[A]: i[a]=\epsilon, p(n[a]) = true
  138. \}).
  139. Next, we will define, for each t \neq \epsilon, S_t as the set of
  140. transitions from some state s in S with t as the input label,
  141. i.e.: S_t = \{ a \in E[A]: i[a] = t \} We further define T_t and U_t as the
  142. subsets of S where the destination state is problematic and non-problematic
  143. respectively, i.e: T_t = \{ a \in E[A]: i[a] = t, p(n[a]) = true \} U_t = \{ a
  144. \in E[A]: i[a] = t, p(n[a]) = false \}
  145. The easiest way to obtain these sets is probably to have a hash
  146. indexed by t that maps to a list of pairs (state, arc-offset) that stores S_t.
  147. From this we can work out the sizes of T_t and U_t on the fly.
  148. (d)
  149. for each transition a in S_\eps:
  150. m(a) <-- n # Will put symbol n on this transition.
  151. n <-- n+1 # Note, same n as in pair (A, n)
  152. (e)
  153. next,
  154. for each t\neq epsilon s.t. S_t is nonempty,
  155. if |S_t| > 1 #if-statement is because if |S_t|=|T_t|=1, no need
  156. for prefix. k = 0 for each transition a in T_t: set m(a) to k. set k = k+1
  157. if |U_t| > 0
  158. Let V_t be the set of destination-states of arcs in U_t.
  159. if Closure(V_t) is not in S:
  160. insert Closure(V_t) into S, and add the pair (Closure(V_t),
  161. k) to Q.
  162. (vi) Check that for each state in the FST, d(s) = true.
  163. (vii) Let n = max_a m(a). This is the highest-numbered extra symbol
  164. (extra symbols start from zero, in this numbering which doesn't correspond to
  165. the symbol-table numbering). Here we add n+1 extra symbols to the symbol
  166. table and store the mappings from 0, 1, ... n to the symbol-id.
  167. (viii) Set up a hash h from (state, int) to (state-id) such that
  168. t = h(s, k)
  169. will be the state-id of a newly-created state that has a transition
  170. to state s with input-label #k.
  171. (ix) For each arc a such that m(a) != 0:
  172. If i[a] = epsilon (the input label is epsilon):
  173. Change i[a] to #m(a). [i.e. prefix then digit m(a)]
  174. Otherwise:
  175. If t = h(n[a], m(a)) is not defined [where n[a] is the
  176. dest-state]: create a new state t with a transition to n[a], with input-label
  177. #m(a) and no output-label or weight. Set h(n[a], m(a)) = t. Change n[a] to
  178. h(n[a], m(a)).
  179. */
  180. namespace fst {
  181. namespace pre_determinize_helpers {
  182. // make it inline to avoid having to put it in a .cc file which most functions
  183. // here could not go in.
  184. inline bool HasBannedPrefixPlusDigits(SymbolTable* symTable, std::string prefix,
  185. std::string* bad_sym) {
  186. // returns true if the symbol table contains any string consisting of this
  187. // (possibly empty) prefix followed by a nonempty sequence of digits (0 to 9).
  188. // requires symTable to be non-NULL.
  189. // if bad_sym != NULL, puts the first bad symbol it finds in *bad_sym.
  190. assert(symTable != NULL);
  191. const char* prefix_ptr = prefix.c_str();
  192. size_t prefix_len =
  193. strlen(prefix_ptr); // allowed to be zero but not encouraged.
  194. for (SymbolTableIterator siter(*symTable); !siter.Done(); siter.Next()) {
  195. const std::string& sym = siter.Symbol();
  196. if (!strncmp(prefix_ptr, sym.c_str(), prefix_len)) { // has prefix.
  197. if (isdigit(sym[prefix_len])) { // we don't allow prefix followed by a
  198. // digit, as a symbol.
  199. // Has at least one digit.
  200. size_t pos;
  201. for (pos = prefix_len; sym[pos] != '\0'; pos++)
  202. if (!isdigit(sym[pos])) break;
  203. if (sym[pos] == '\0') { // All remaining characters were digits.
  204. if (bad_sym != NULL) *bad_sym = sym;
  205. return true;
  206. }
  207. } // else OK because prefix was followed by '\0' or a non-digit.
  208. }
  209. }
  210. return false; // doesn't have banned symbol.
  211. }
  212. template <class T>
  213. void CopySetToVector(const std::set<T> s, std::vector<T>* v) {
  214. // adds members of s to v, in sorted order from lowest to highest
  215. // (because the set was in sorted order).
  216. assert(v != NULL);
  217. v->resize(s.size());
  218. typename std::set<T>::const_iterator siter = s.begin();
  219. typename std::vector<T>::iterator viter = v->begin();
  220. for (; siter != s.end(); ++siter, ++viter) {
  221. assert(viter != v->end());
  222. *viter = *siter;
  223. }
  224. }
  225. // Warning. This function calls 'new'.
  226. template <class T>
  227. std::vector<T>* InsertMember(const std::vector<T> m,
  228. std::vector<std::vector<T>*>* S) {
  229. assert(m.size() > 0);
  230. T idx = m[0];
  231. assert(idx >= (T)0 && idx < (T)S->size());
  232. if ((*S)[idx] != NULL) {
  233. assert(*((*S)[idx]) == m);
  234. // The vectors should be the same. Otherwise this is a bug in the
  235. // algorithm. It could either be a programming error or a deeper conceptual
  236. // bug.
  237. return NULL; // nothing was inserted.
  238. } else {
  239. std::vector<T>* ret = (*S)[idx] = new std::vector<T>(m); // New copy of m.
  240. return ret; // was inserted.
  241. }
  242. }
  243. // See definition of Closure(S) in item A(iii) in the comment above. it's the
  244. // set of states that are reachable from S via sequences of arcs a such that
  245. // i[a]=epsilon and n[a] is not problematic. We assume that the fst is sorted
  246. // on input label (so epsilon arcs first) The algorithm is described in section
  247. // (C) above. We use the same variable for S and T.
  248. template <class Arc>
  249. void Closure(MutableFst<Arc>* fst, std::set<typename Arc::StateId>* S,
  250. const std::vector<bool>& pVec) {
  251. typedef typename Arc::StateId StateId;
  252. std::vector<StateId> Q;
  253. CopySetToVector(*S, &Q);
  254. while (Q.size() != 0) {
  255. StateId s = Q.back();
  256. Q.pop_back();
  257. for (ArcIterator<MutableFst<Arc> > aiter(*fst, s); !aiter.Done();
  258. aiter.Next()) {
  259. const Arc& arc = aiter.Value();
  260. if (arc.ilabel != 0)
  261. break; // Break from the loop: due to sorting there will be no
  262. // more transitions with epsilons as input labels.
  263. if (!pVec[arc.nextstate]) { // Next state is not problematic -> we can
  264. // use this transition.
  265. std::pair<typename std::set<StateId>::iterator, bool> p =
  266. S->insert(arc.nextstate);
  267. if (p.second) { // True means: was inserted into S (wasn't already
  268. // there).
  269. Q.push_back(arc.nextstate);
  270. }
  271. }
  272. }
  273. }
  274. } // end function Closure.
  275. } // end namespace pre_determinize_helpers.
  276. template <class Arc, class Int>
  277. void PreDeterminize(MutableFst<Arc>* fst, typename Arc::Label first_new_sym,
  278. std::vector<Int>* symsOut) {
  279. typedef typename Arc::Label Label;
  280. typedef typename Arc::StateId StateId;
  281. typedef size_t ArcId; // Our own typedef, not standard OpenFst. Use size_t
  282. // for compatibility with argument of ArcIterator::Seek().
  283. typedef typename Arc::Weight Weight;
  284. assert(first_new_sym > 0);
  285. assert(fst != NULL);
  286. if (fst->Start() == kNoStateId) return; // for empty FST, nothing to do.
  287. assert(symsOut != NULL &&
  288. symsOut->size() == 0); // we will output the symbols we add into this.
  289. { // (D)(i)(a): check is trim (i.e. connected, in OpenFST parlance).
  290. KALDI_VLOG(2) << "PreDeterminize: Checking FST properties";
  291. uint64 props = fst->Properties(
  292. kAccessible | kCoAccessible,
  293. true); // true-> computes properties if unknown at time when called.
  294. if (props !=
  295. (kAccessible | kCoAccessible)) { // All states are not both accessible
  296. // and co-accessible...
  297. KALDI_ERR << "PreDeterminize: FST is not trim";
  298. }
  299. }
  300. { // (D)(i)(b): make single final state.
  301. KALDI_VLOG(2) << "PreDeterminize: creating single final state";
  302. CreateSuperFinal(fst);
  303. }
  304. { // (D)(i)(c): sort arcs on input.
  305. KALDI_VLOG(2) << "PreDeterminize: sorting arcs on input";
  306. ILabelCompare<Arc> icomp;
  307. ArcSort(fst, icomp);
  308. }
  309. StateId n_states = 0,
  310. max_state =
  311. 0; // Compute n_states, max_state = highest-numbered state.
  312. { // compute nStates, maxStates.
  313. for (StateIterator<MutableFst<Arc> > iter(*fst); !iter.Done();
  314. iter.Next()) {
  315. StateId state = iter.Value();
  316. assert(state >= 0);
  317. n_states++;
  318. if (state > max_state) max_state = state;
  319. }
  320. KALDI_VLOG(2) << "PreDeterminize: n_states = " << (n_states)
  321. << ", max_state =" << (max_state);
  322. }
  323. std::vector<bool> p_vec(max_state + 1, false); // compute this next.
  324. { // D(ii): computing the array p. ["problematic states, i.e. states with >1
  325. // input transition,
  326. // counting being the initial state as an input transition"].
  327. std::vector<bool> seen_vec(
  328. max_state + 1,
  329. false); // rather than counting incoming transitions we just have a
  330. // bool that says we saw at least one.
  331. seen_vec[fst->Start()] = true;
  332. for (StateIterator<MutableFst<Arc> > siter(*fst); !siter.Done();
  333. siter.Next()) {
  334. for (ArcIterator<MutableFst<Arc> > aiter(*fst, siter.Value());
  335. !aiter.Done(); aiter.Next()) {
  336. const Arc& arc = aiter.Value();
  337. assert(arc.nextstate >= 0 && arc.nextstate < max_state + 1);
  338. if (seen_vec[arc.nextstate])
  339. p_vec[arc.nextstate] =
  340. true; // now have >1 transition in, so problematic.
  341. else
  342. seen_vec[arc.nextstate] = true;
  343. }
  344. }
  345. }
  346. // D(iii): set up m(a)
  347. std::map<std::pair<StateId, ArcId>, size_t> m_map;
  348. // This is the array m, indexed by arcs. It maps to the index of the symbol
  349. // we add.
  350. // WARNING: we should be sure to clean up this memory before exiting. Do not
  351. // return or throw an exception from this function, later than this point,
  352. // without cleaning up! Note that the vectors are shared between Q and S (they
  353. // "belong to" S.
  354. std::vector<std::vector<StateId>*> S(max_state + 1,
  355. (std::vector<StateId>*)(void*)0);
  356. std::vector<std::pair<std::vector<StateId>*, size_t> > Q;
  357. // D(iv): initialize S and Q.
  358. {
  359. std::vector<StateId>
  360. all_seed_states; // all "problematic" states, plus initial state (if
  361. // not problematic).
  362. if (!p_vec[fst->Start()]) all_seed_states.push_back(fst->Start());
  363. for (StateId s = 0; s <= max_state; s++)
  364. if (p_vec[s]) all_seed_states.push_back(s);
  365. for (size_t idx = 0; idx < all_seed_states.size(); idx++) {
  366. StateId s = all_seed_states[idx];
  367. std::set<StateId> closure_s;
  368. closure_s.insert(s); // insert "seed" state.
  369. pre_determinize_helpers::Closure(
  370. fst, &closure_s,
  371. p_vec); // follow epsilons to non-problematic states.
  372. // Closure in this case whis will usually not add anything, for typical
  373. // topologies in speech
  374. std::vector<StateId> closure_s_vec;
  375. pre_determinize_helpers::CopySetToVector(closure_s, &closure_s_vec);
  376. KALDI_ASSERT(closure_s_vec.size() != 0);
  377. std::vector<StateId>* ptr =
  378. pre_determinize_helpers::InsertMember(closure_s_vec, &S);
  379. KALDI_ASSERT(ptr != NULL); // Or conceptual bug or programming error.
  380. Q.push_back(std::pair<std::vector<StateId>*, size_t>(ptr, 0));
  381. }
  382. }
  383. std::vector<bool> d_vec(max_state + 1,
  384. false); // "done vector". Purely for debugging.
  385. size_t num_extra_det_states = 0;
  386. // (D)(v)
  387. while (Q.size() != 0) {
  388. // (D)(v)(a)
  389. std::pair<std::vector<StateId>*, size_t> cur_pair(Q.back());
  390. Q.pop_back();
  391. const std::vector<StateId>& A(*cur_pair.first);
  392. size_t n = cur_pair.second; // next special symbol to add.
  393. // (D)(v)(b)
  394. for (size_t idx = 0; idx < A.size(); idx++) {
  395. assert(d_vec[A[idx]] == false &&
  396. "This state has been seen before. Algorithm error.");
  397. d_vec[A[idx]] = true;
  398. }
  399. // From here is (D)(v)(c). We work out S_\eps and S_t (for t\neq eps)
  400. // simultaneously at first.
  401. std::map<Label, std::set<std::pair<std::pair<StateId, ArcId>, StateId> > >
  402. arc_hash;
  403. // arc_hash is a hash with info of all arcs from states in the set A to
  404. // non-problematic states.
  405. // It is a map from ilabel to pair(pair(start-state, arc-offset),
  406. // end-state). Here, arc-offset reflects the order in which we accessed the
  407. // arc using the ArcIterator (zero for the first arc).
  408. { // This block sets up arc_hash
  409. for (size_t idx = 0; idx < A.size(); idx++) {
  410. StateId s = A[idx];
  411. assert(s >= 0 && s <= max_state);
  412. ArcId arc_id = 0;
  413. for (ArcIterator<MutableFst<Arc> > aiter(*fst, s); !aiter.Done();
  414. aiter.Next(), ++arc_id) {
  415. const Arc& arc = aiter.Value();
  416. std::pair<std::pair<StateId, ArcId>, StateId> this_pair(
  417. std::pair<StateId, ArcId>(s, arc_id), arc.nextstate);
  418. bool inserted = (arc_hash[arc.ilabel].insert(this_pair)).second;
  419. assert(inserted); // Otherwise we had a duplicate.
  420. }
  421. }
  422. }
  423. // (D)(v)(d)
  424. if (arc_hash.count(0) == 1) { // We have epsilon transitions out.
  425. std::set<std::pair<std::pair<StateId, ArcId>, StateId> >& eps_set =
  426. arc_hash[0];
  427. typedef typename std::set<
  428. std::pair<std::pair<StateId, ArcId>, StateId> >::iterator set_iter_t;
  429. for (set_iter_t siter = eps_set.begin(); siter != eps_set.end();
  430. ++siter) {
  431. const std::pair<std::pair<StateId, ArcId>, StateId>& this_pr = *siter;
  432. if (p_vec[this_pr.second]) { // Eps-transition to problematic state.
  433. assert(m_map.count(this_pr.first) == 0);
  434. m_map[this_pr.first] = n;
  435. n++;
  436. }
  437. }
  438. }
  439. // (D)(v)(e)
  440. {
  441. typedef typename std::map<
  442. Label,
  443. std::set<std::pair<std::pair<StateId, ArcId>, StateId> > >::iterator
  444. map_iter_t;
  445. typedef typename std::set<
  446. std::pair<std::pair<StateId, ArcId>, StateId> >::iterator set_iter_t2;
  447. for (map_iter_t miter = arc_hash.begin(); miter != arc_hash.end();
  448. ++miter) {
  449. Label t = miter->first;
  450. std::set<std::pair<std::pair<StateId, ArcId>, StateId> >& S_t =
  451. miter->second;
  452. if (t != 0) { // For t != epsilon,
  453. std::set<StateId> V_t; // set of destination non-problem states. Will
  454. // create this set now.
  455. // exists_noproblem is true iff |U_t| > 0.
  456. size_t k = 0;
  457. // First loop "for each transition a in T_t" (i.e. transitions to
  458. // problematic states) The if-statement if (|S_t|>1) is pushed inside
  459. // the loop, as the loop also computes the set V_t.
  460. for (set_iter_t2 siter = S_t.begin(); siter != S_t.end(); ++siter) {
  461. const std::pair<std::pair<StateId, ArcId>, StateId>& this_pr =
  462. *siter;
  463. if (p_vec[this_pr.second]) { // only consider problematic states
  464. // (just set T_t)
  465. if (S_t.size() >
  466. 1) { // This is where we pushed the if-statement in.
  467. assert(m_map.count(this_pr.first) == 0);
  468. m_map[this_pr.first] = k;
  469. k++;
  470. num_extra_det_states++;
  471. }
  472. } else { // Create the set V_t.
  473. V_t.insert(this_pr.second);
  474. }
  475. }
  476. if (V_t.size() != 0) {
  477. pre_determinize_helpers::Closure(
  478. fst, &V_t,
  479. p_vec); // follow epsilons to non-problematic states.
  480. std::vector<StateId> closure_V_t_vec;
  481. pre_determinize_helpers::CopySetToVector(V_t, &closure_V_t_vec);
  482. std::vector<StateId>* ptr =
  483. pre_determinize_helpers::InsertMember(closure_V_t_vec, &S);
  484. if (ptr != NULL) { // was inserted.
  485. Q.push_back(std::pair<std::vector<StateId>*, size_t>(ptr, k));
  486. }
  487. }
  488. }
  489. }
  490. }
  491. } // end while (Q.size() != 0)
  492. { // (D)(vi): Check that for each state in the FST, d(s) = true.
  493. for (StateIterator<MutableFst<Arc> > siter(*fst); !siter.Done();
  494. siter.Next()) {
  495. StateId val = siter.Value();
  496. assert(d_vec[val] == true);
  497. }
  498. }
  499. { // (D)(vii): compute symbol-table ID's.
  500. // sets up symsOut array.
  501. int64 n = -1;
  502. for (typename std::map<std::pair<StateId, ArcId>, size_t>::iterator m_iter =
  503. m_map.begin();
  504. m_iter != m_map.end(); ++m_iter) {
  505. n = std::max(n,
  506. static_cast<int64>(
  507. m_iter->second)); // m_iter->second is of type size_t.
  508. }
  509. // At this point n is the highest symbol-id (type size_t) of symbols we must
  510. // add.
  511. n++; // This is now the number of symbols we must add.
  512. for (size_t i = 0; static_cast<int64>(i) < n; i++)
  513. symsOut->push_back(first_new_sym + i);
  514. }
  515. // (D)(viii): set up hash.
  516. std::map<std::pair<StateId, size_t>, StateId> h_map;
  517. { // D(ix): add extra symbols! This is where the work gets done.
  518. // Core part of this is below, search for (*)
  519. size_t n_states_added = 0;
  520. for (typename std::map<std::pair<StateId, ArcId>, size_t>::iterator m_iter =
  521. m_map.begin();
  522. m_iter != m_map.end(); ++m_iter) {
  523. StateId state = m_iter->first.first;
  524. ArcId arcpos = m_iter->first.second;
  525. size_t m_a = m_iter->second;
  526. MutableArcIterator<MutableFst<Arc> > aiter(fst, state);
  527. aiter.Seek(arcpos);
  528. Arc arc = aiter.Value();
  529. // (*) core part here.
  530. if (arc.ilabel == 0) {
  531. arc.ilabel = (*symsOut)[m_a];
  532. } else {
  533. std::pair<StateId, size_t> pr(arc.nextstate, m_a);
  534. if (!h_map.count(pr)) {
  535. n_states_added++;
  536. StateId newstate = fst->AddState();
  537. assert(newstate >= 0);
  538. Arc new_arc((*symsOut)[m_a], (Label)0, Weight::One(), arc.nextstate);
  539. fst->AddArc(newstate, new_arc);
  540. h_map[pr] = newstate;
  541. }
  542. arc.nextstate = h_map[pr];
  543. }
  544. aiter.SetValue(arc);
  545. }
  546. KALDI_VLOG(2) << "Added " << (n_states_added)
  547. << " new states and added/changed " << (m_map.size())
  548. << " arcs";
  549. }
  550. // Now free up memory.
  551. for (size_t i = 0; i < S.size(); i++) delete S[i];
  552. } // end function PreDeterminize
  553. template <class Label>
  554. void CreateNewSymbols(SymbolTable* input_sym_table, int nSym,
  555. std::string prefix, std::vector<Label>* symsOut) {
  556. // Creates nSym new symbols named (prefix)0, (prefix)1 and so on.
  557. // Crashes if it cannot create them because one or more of them were in the
  558. // symbol table already.
  559. assert(symsOut && symsOut->size() == 0);
  560. for (int i = 0; i < nSym; i++) {
  561. std::stringstream ss;
  562. ss << prefix << i;
  563. std::string str = ss.str();
  564. if (input_sym_table->Find(str) != -1) { // should not be present.
  565. }
  566. assert(symsOut);
  567. symsOut->push_back((Label)input_sym_table->AddSymbol(str));
  568. }
  569. }
  570. // see pre-determinize.h for documentation.
  571. template <class Arc>
  572. void AddSelfLoops(MutableFst<Arc>* fst,
  573. const std::vector<typename Arc::Label>& isyms,
  574. const std::vector<typename Arc::Label>& osyms) {
  575. assert(fst != NULL);
  576. assert(isyms.size() == osyms.size());
  577. typedef typename Arc::Label Label;
  578. typedef typename Arc::StateId StateId;
  579. typedef typename Arc::Weight Weight;
  580. size_t n = isyms.size();
  581. if (n == 0) return; // Nothing to do.
  582. // {
  583. // the following declarations and statements are for quick detection of these
  584. // symbols, which is purely for debugging/checking purposes.
  585. Label isyms_min = *std::min_element(isyms.begin(), isyms.end()),
  586. isyms_max = *std::max_element(isyms.begin(), isyms.end()),
  587. osyms_min = *std::min_element(osyms.begin(), osyms.end()),
  588. osyms_max = *std::max_element(osyms.begin(), osyms.end());
  589. std::set<Label> isyms_set, osyms_set;
  590. for (size_t i = 0; i < isyms.size(); i++) {
  591. assert(isyms[i] > 0 &&
  592. osyms[i] > 0); // should not have epsilon or invalid symbols.
  593. isyms_set.insert(isyms[i]);
  594. osyms_set.insert(osyms[i]);
  595. }
  596. assert(isyms_set.size() == n && osyms_set.size() == n);
  597. // } end block.
  598. for (StateIterator<MutableFst<Arc> > siter(*fst); !siter.Done();
  599. siter.Next()) {
  600. StateId state = siter.Value();
  601. bool this_state_needs_self_loops = (fst->Final(state) != Weight::Zero());
  602. for (ArcIterator<MutableFst<Arc> > aiter(*fst, state); !aiter.Done();
  603. aiter.Next()) {
  604. const Arc& arc = aiter.Value();
  605. // If one of the following asserts fails, it means that the input FST
  606. // already had the symbols we are inserting. This is contrary to the
  607. // preconditions of this algorithm.
  608. assert(!(arc.ilabel >= isyms_min && arc.ilabel <= isyms_max &&
  609. isyms_set.count(arc.ilabel) != 0));
  610. assert(!(arc.olabel >= osyms_min && arc.olabel <= osyms_max &&
  611. osyms_set.count(arc.olabel) != 0));
  612. if (arc.olabel != 0) // Has non-epsilon output label -> need self loops.
  613. this_state_needs_self_loops = true;
  614. }
  615. if (this_state_needs_self_loops) {
  616. for (size_t i = 0; i < n; i++) {
  617. Arc arc;
  618. arc.ilabel = isyms[i];
  619. arc.olabel = osyms[i];
  620. arc.weight = Weight::One();
  621. arc.nextstate = state;
  622. fst->AddArc(state, arc);
  623. }
  624. }
  625. }
  626. }
  627. template <class Arc>
  628. int64 DeleteISymbols(MutableFst<Arc>* fst,
  629. std::vector<typename Arc::Label> isyms) {
  630. // We could do this using the Mapper concept, but this is much easier to
  631. // understand.
  632. typedef typename Arc::Label Label;
  633. typedef typename Arc::StateId StateId;
  634. int64 num_deleted = 0;
  635. if (isyms.size() == 0) return 0;
  636. Label isyms_min = *std::min_element(isyms.begin(), isyms.end()),
  637. isyms_max = *std::max_element(isyms.begin(), isyms.end());
  638. bool isyms_consecutive =
  639. (isyms_max + 1 - isyms_min == static_cast<Label>(isyms.size()));
  640. std::set<Label> isyms_set;
  641. if (!isyms_consecutive) {
  642. for (size_t i = 0; i < isyms.size(); i++) isyms_set.insert(isyms[i]);
  643. }
  644. for (StateIterator<MutableFst<Arc> > siter(*fst); !siter.Done();
  645. siter.Next()) {
  646. StateId state = siter.Value();
  647. for (MutableArcIterator<MutableFst<Arc> > aiter(fst, state); !aiter.Done();
  648. aiter.Next()) {
  649. const Arc& arc = aiter.Value();
  650. if (arc.ilabel >= isyms_min && arc.ilabel <= isyms_max) {
  651. if (isyms_consecutive || isyms_set.count(arc.ilabel) != 0) {
  652. num_deleted++;
  653. Arc mod_arc(arc);
  654. mod_arc.ilabel = 0; // change label to epsilon.
  655. aiter.SetValue(mod_arc);
  656. }
  657. }
  658. }
  659. }
  660. return num_deleted;
  661. }
  662. template <class Arc>
  663. typename Arc::StateId CreateSuperFinal(MutableFst<Arc>* fst) {
  664. typedef typename Arc::StateId StateId;
  665. typedef typename Arc::Weight Weight;
  666. assert(fst != NULL);
  667. StateId num_states = fst->NumStates();
  668. StateId num_final = 0;
  669. std::vector<StateId> final_states;
  670. for (StateId s = 0; s < num_states; s++) {
  671. if (fst->Final(s) != Weight::Zero()) {
  672. num_final++;
  673. final_states.push_back(s);
  674. }
  675. }
  676. if (final_states.size() == 1) {
  677. if (fst->Final(final_states[0]) == Weight::One()) {
  678. ArcIterator<MutableFst<Arc> > iter(*fst, final_states[0]);
  679. if (iter.Done()) {
  680. // We already have a final state w/ no transitions out and unit weight.
  681. // So we're done.
  682. return final_states[0];
  683. }
  684. }
  685. }
  686. StateId final_state = fst->AddState();
  687. fst->SetFinal(final_state, Weight::One());
  688. for (size_t idx = 0; idx < final_states.size(); idx++) {
  689. StateId s = final_states[idx];
  690. Weight weight = fst->Final(s);
  691. fst->SetFinal(s, Weight::Zero());
  692. Arc arc;
  693. arc.ilabel = 0;
  694. arc.olabel = 0;
  695. arc.nextstate = final_state;
  696. arc.weight = weight;
  697. fst->AddArc(s, arc);
  698. }
  699. return final_state;
  700. }
  701. } // namespace fst
  702. #endif // KALDI_FSTEXT_PRE_DETERMINIZE_INL_H_