FST  openfst-1.8.3
OpenFst Library
reverse.h
Go to the documentation of this file.
1 // Copyright 2005-2024 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 // Reverses an MPDT.
19 
20 #ifndef FST_EXTENSIONS_MPDT_REVERSE_H_
21 #define FST_EXTENSIONS_MPDT_REVERSE_H_
22 
23 #include <limits>
24 #include <utility>
25 #include <vector>
26 
27 #include <fst/fst.h>
28 #include <fst/mutable-fst.h>
29 #include <fst/relabel.h>
30 #include <fst/reverse.h>
31 
32 namespace fst {
33 
34 // Reverses a multi-stack pushdown transducer (MPDT) encoded as an FST.
35 template <class Arc, class RevArc>
36 void Reverse(
37  const Fst<Arc> &ifst,
38  const std::vector<std::pair<typename Arc::Label, typename Arc::Label>>
39  &parens,
40  std::vector<typename Arc::Label> *assignments, MutableFst<RevArc> *ofst) {
41  using Label = typename Arc::Label;
42  // Reverses FST component.
43  Reverse(ifst, ofst);
44  // Exchanges open and close parenthesis pairs.
45  std::vector<std::pair<Label, Label>> relabel_pairs;
46  relabel_pairs.reserve(2 * parens.size());
47  for (const auto &pair : parens) {
48  relabel_pairs.emplace_back(pair.first, pair.second);
49  relabel_pairs.emplace_back(pair.second, pair.first);
50  }
51  Relabel(ofst, relabel_pairs, relabel_pairs);
52  // Computes new bounds for the stack assignments.
53  Label max_level = -1;
54  Label min_level = std::numeric_limits<Label>::max();
55  for (const auto assignment : *assignments) {
56  if (assignment < min_level) {
57  min_level = assignment;
58  } else if (assignment > max_level) {
59  max_level = assignment;
60  }
61  }
62  // Actually reverses stack assignments.
63  for (auto &assignment : *assignments) {
64  assignment = (max_level - assignment) + min_level;
65  }
66 }
67 
68 } // namespace fst
69 
70 #endif // FST_EXTENSIONS_MPDT_REVERSE_H_
void Relabel(MutableFst< Arc > *fst, const std::vector< std::pair< typename Arc::Label, typename Arc::Label >> &ipairs, const std::vector< std::pair< typename Arc::Label, typename Arc::Label >> &opairs)
Definition: relabel.h:49
void Reverse(const Fst< Arc > &ifst, const std::vector< std::pair< typename Arc::Label, typename Arc::Label >> &parens, std::vector< typename Arc::Label > *assignments, MutableFst< RevArc > *ofst)
Definition: reverse.h:36