FST  openfst-1.8.2
OpenFst Library
equivalent.h
Go to the documentation of this file.
1 // Copyright 2005-2020 Google LLC
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 // See www.openfst.org for extensive documentation on this weighted
16 // finite-state transducer library.
17 //
18 // Functions and classes to determine the equivalence of two FSTs.
19 
20 #ifndef FST_EQUIVALENT_H_
21 #define FST_EQUIVALENT_H_
22 
23 #include <algorithm>
24 #include <cstdint>
25 #include <queue>
26 #include <vector>
27 
28 #include <fst/log.h>
29 
30 #include <fst/encode.h>
31 #include <fst/push.h>
32 #include <fst/union-find.h>
33 #include <fst/vector-fst.h>
34 #include <unordered_map>
35 
36 
37 namespace fst {
38 namespace internal {
39 
40 // Traits-like struct holding utility functions/typedefs/constants for
41 // the equivalence algorithm.
42 //
43 // Encoding device: in order to make the statesets of the two acceptors
44 // disjoint, we map Arc::StateId on the type MappedId. The states of
45 // the first acceptor are mapped on odd numbers (s -> 2s + 1), and
46 // those of the second one on even numbers (s -> 2s + 2). The number 0
47 // is reserved for an implicit (non-final) dead state (required for
48 // the correct treatment of non-coaccessible states; kNoStateId is mapped to
49 // kDeadState for both acceptors). The union-find algorithm operates on the
50 // mapped IDs.
51 template <class Arc>
53  using StateId = typename Arc::StateId;
54  using Weight = typename Arc::Weight;
55 
56  using MappedId = StateId; // ID for an equivalence class.
57 
58  // MappedId for an implicit dead state.
59  static constexpr MappedId kDeadState = 0;
60 
61  // MappedId for lookup failure.
62  static constexpr MappedId kInvalidId = -1;
63 
64  // Maps state ID to the representative of the corresponding
65  // equivalence class. The parameter 'which_fst' takes the values 1
66  // and 2, identifying the input FST.
67  static MappedId MapState(StateId s, int32_t which_fst) {
68  return (kNoStateId == s) ? kDeadState
69  : (static_cast<MappedId>(s) << 1) + which_fst;
70  }
71 
72  // Maps set ID to State ID.
74  return static_cast<StateId>((--id) >> 1);
75  }
76 
77  // Convenience function: checks if state with MappedId s is final in
78  // acceptor fa.
79  static bool IsFinal(const Fst<Arc> &fa, MappedId s) {
80  return (kDeadState == s) ? false
81  : (fa.Final(UnMapState(s)) != Weight::Zero());
82  }
83  // Convenience function: returns the representative of ID in sets,
84  // creating a new set if needed.
86  const auto repr = sets->FindSet(id);
87  if (repr != kInvalidId) {
88  return repr;
89  } else {
90  sets->MakeSet(id);
91  return id;
92  }
93  }
94 };
95 
96 } // namespace internal
97 
98 // Equivalence checking algorithm: determines if the two FSTs fst1 and fst2
99 // are equivalent. The input FSTs must be deterministic input-side epsilon-free
100 // acceptors, unweighted or with weights over a left semiring. Two acceptors are
101 // considered equivalent if they accept exactly the same set of strings (with
102 // the same weights).
103 //
104 // The algorithm (cf. Aho, Hopcroft and Ullman, "The Design and Analysis of
105 // Computer Programs") successively constructs sets of states that can be
106 // reached by the same prefixes, starting with a set containing the start states
107 // of both acceptors. A disjoint tree forest (the union-find algorithm) is used
108 // to represent the sets of states. The algorithm returns false if one of the
109 // constructed sets contains both final and non-final states. Returns an
110 // optional error value (useful when FST_FLAGS_error_fatal = false).
111 //
112 // Complexity:
113 //
114 // Quasi-linear, i.e., O(n G(n)), where
115 //
116 // n = |S1| + |S2| is the number of states in both acceptors
117 //
118 // G(n) is a very slowly growing function that can be approximated
119 // by 4 by all practical purposes.
120 template <class Arc>
121 bool Equivalent(const Fst<Arc> &fst1, const Fst<Arc> &fst2,
122  float delta = kDelta, bool *error = nullptr) {
123  using Weight = typename Arc::Weight;
124  if (error) *error = false;
125  // Check that the symbol table are compatible.
126  if (!CompatSymbols(fst1.InputSymbols(), fst2.InputSymbols()) ||
127  !CompatSymbols(fst1.OutputSymbols(), fst2.OutputSymbols())) {
128  FSTERROR() << "Equivalent: Input/output symbol tables of 1st argument "
129  << "do not match input/output symbol tables of 2nd argument";
130  if (error) *error = true;
131  return false;
132  }
133  // Check properties first.
134  static constexpr auto props = kNoEpsilons | kIDeterministic | kAcceptor;
135  if (fst1.Properties(props, true) != props) {
136  FSTERROR() << "Equivalent: 1st argument not an"
137  << " epsilon-free deterministic acceptor";
138  if (error) *error = true;
139  return false;
140  }
141  if (fst2.Properties(props, true) != props) {
142  FSTERROR() << "Equivalent: 2nd argument not an"
143  << " epsilon-free deterministic acceptor";
144  if (error) *error = true;
145  return false;
146  }
147  if ((fst1.Properties(kUnweighted, true) != kUnweighted) ||
148  (fst2.Properties(kUnweighted, true) != kUnweighted)) {
149  VectorFst<Arc> efst1(fst1);
150  VectorFst<Arc> efst2(fst2);
151  Push(&efst1, REWEIGHT_TO_INITIAL, delta);
152  Push(&efst2, REWEIGHT_TO_INITIAL, delta);
153  ArcMap(&efst1, QuantizeMapper<Arc>(delta));
154  ArcMap(&efst2, QuantizeMapper<Arc>(delta));
156  ArcMap(&efst1, &mapper);
157  ArcMap(&efst2, &mapper);
158  return Equivalent(efst1, efst2);
159  }
160  using Util = internal::EquivalenceUtil<Arc>;
161  using MappedId = typename Util::MappedId;
162  enum { FST1 = 1, FST2 = 2 }; // Required by Util::MapState(...)
163  auto s1 = Util::MapState(fst1.Start(), FST1);
164  auto s2 = Util::MapState(fst2.Start(), FST2);
165  // The union-find structure.
166  UnionFind<MappedId> eq_classes(1000, Util::kInvalidId);
167  // Initializes the union-find structure.
168  eq_classes.MakeSet(s1);
169  eq_classes.MakeSet(s2);
170  // Data structure for the (partial) acceptor transition function of fst1 and
171  // fst2: input labels mapped to pairs of MappedIds representing destination
172  // states of the corresponding arcs in fst1 and fst2, respectively.
173  using Label2StatePairMap =
174  std::unordered_map<typename Arc::Label, std::pair<MappedId, MappedId>>;
175  Label2StatePairMap arc_pairs;
176  // Pairs of MappedId's to be processed, organized in a queue.
177  std::queue<std::pair<MappedId, MappedId>> q;
178  bool ret = true;
179  // Returns early if the start states differ w.r.t. finality.
180  if (Util::IsFinal(fst1, s1) != Util::IsFinal(fst2, s2)) ret = false;
181  // Main loop: explores the two acceptors in a breadth-first manner, updating
182  // the equivalence relation on the statesets. Loop invariant: each block of
183  // the states contains either final states only or non-final states only.
184  for (q.emplace(s1, s2); ret && !q.empty(); q.pop()) {
185  s1 = q.front().first;
186  s2 = q.front().second;
187  // Representatives of the equivalence classes of s1/s2.
188  const auto rep1 = Util::FindSet(&eq_classes, s1);
189  const auto rep2 = Util::FindSet(&eq_classes, s2);
190  if (rep1 != rep2) {
191  eq_classes.Union(rep1, rep2);
192  arc_pairs.clear();
193  // Copies outgoing arcs starting at s1 into the hash-table.
194  if (Util::kDeadState != s1) {
195  ArcIterator<Fst<Arc>> arc_iter(fst1, Util::UnMapState(s1));
196  for (; !arc_iter.Done(); arc_iter.Next()) {
197  const auto &arc = arc_iter.Value();
198  // Zero-weight arcs are treated as if they did not exist.
199  if (arc.weight != Weight::Zero()) {
200  arc_pairs[arc.ilabel].first = Util::MapState(arc.nextstate, FST1);
201  }
202  }
203  }
204  // Copies outgoing arcs starting at s2 into the hashtable.
205  if (Util::kDeadState != s2) {
206  ArcIterator<Fst<Arc>> arc_iter(fst2, Util::UnMapState(s2));
207  for (; !arc_iter.Done(); arc_iter.Next()) {
208  const auto &arc = arc_iter.Value();
209  // Zero-weight arcs are treated as if they did not exist.
210  if (arc.weight != Weight::Zero()) {
211  arc_pairs[arc.ilabel].second = Util::MapState(arc.nextstate, FST2);
212  }
213  }
214  }
215  // Iterates through the hashtable and process pairs of target states.
216  for (const auto &arc_iter : arc_pairs) {
217  const auto &pair = arc_iter.second;
218  if (Util::IsFinal(fst1, pair.first) !=
219  Util::IsFinal(fst2, pair.second)) {
220  // Detected inconsistency: return false.
221  ret = false;
222  break;
223  }
224  q.push(pair);
225  }
226  }
227  }
228  if (fst1.Properties(kError, false) || fst2.Properties(kError, false)) {
229  if (error) *error = true;
230  return false;
231  }
232  return ret;
233 }
234 
235 } // namespace fst
236 
237 #endif // FST_EQUIVALENT_H_
void ArcMap(MutableFst< A > *fst, C *mapper)
Definition: arc-map.h:110
static constexpr MappedId kDeadState
Definition: equivalent.h:59
virtual uint64_t Properties(uint64_t mask, bool test) const =0
static MappedId MapState(StateId s, int32_t which_fst)
Definition: equivalent.h:67
constexpr uint64_t kError
Definition: properties.h:51
virtual Weight Final(StateId) const =0
constexpr int kNoStateId
Definition: fst.h:202
const Arc & Value() const
Definition: fst.h:537
#define FSTERROR()
Definition: util.h:53
constexpr uint8_t kEncodeLabels
Definition: encode.h:43
constexpr uint64_t kNoEpsilons
Definition: properties.h:80
static MappedId FindSet(UnionFind< MappedId > *sets, MappedId id)
Definition: equivalent.h:85
static StateId UnMapState(MappedId id)
Definition: equivalent.h:73
virtual StateId Start() const =0
bool Done() const
Definition: fst.h:533
typename Arc::Weight Weight
Definition: equivalent.h:54
constexpr uint64_t kIDeterministic
Definition: properties.h:68
void Push(MutableFst< Arc > *fst, ReweightType type=REWEIGHT_TO_INITIAL, float delta=kShortestDelta, bool remove_total_weight=false)
Definition: push.h:91
constexpr uint8_t kEncodeWeights
Definition: encode.h:44
constexpr uint64_t kUnweighted
Definition: properties.h:105
virtual const SymbolTable * InputSymbols() const =0
T MakeSet(T item)
Definition: union-find.h:60
bool Equivalent(const Fst< Arc > &fst1, const Fst< Arc > &fst2, float delta=kDelta, bool *error=nullptr)
Definition: equivalent.h:121
typename Arc::StateId StateId
Definition: equivalent.h:53
bool CompatSymbols(const SymbolTable *syms1, const SymbolTable *syms2, bool warning=true)
T FindSet(T item)
Definition: union-find.h:39
static bool IsFinal(const Fst< Arc > &fa, MappedId s)
Definition: equivalent.h:79
constexpr float kDelta
Definition: weight.h:130
constexpr uint64_t kAcceptor
Definition: properties.h:63
virtual const SymbolTable * OutputSymbols() const =0
void Next()
Definition: fst.h:541
static constexpr MappedId kInvalidId
Definition: equivalent.h:62