summaryrefslogtreecommitdiff
path: root/tools/thirdparty/OpenFst/fst/lib/prune.h
blob: 42c340eafb6dac5c7648387580ef28027d68a1d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// prune.h
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: allauzen@cs.nyu.edu (Cyril Allauzen)
//
// \file
// Functions implementing pruning.

#ifndef FST_LIB_PRUNE_H__
#define FST_LIB_PRUNE_H__

#include "fst/lib/arcfilter.h"
#include "fst/lib/shortest-distance.h"

namespace fst {

template <class A, class ArcFilter>
class PruneOptions {
 public:
  typedef typename A::Weight Weight;

  // Pruning threshold.
  Weight threshold;
  // Arc filter.
  ArcFilter filter;
  // If non-zero, passes in pre-computed shortest distance from initial state
  // (possibly resized).
  vector<Weight> *idistance;
  // If non-zero, passes in pre-computed shortest distance to final states
  // (possibly resized).
  vector<Weight> *fdistance;

  PruneOptions(const Weight& t, ArcFilter f, vector<Weight> *id = 0,
               vector<Weight> *fd = 0)
      : threshold(t), filter(f), idistance(id), fdistance(fd) {}
};


// Pruning algorithm: this version modifies its input and it takes an
// options class as an argment. Delete states and arcs in 'fst' that
// do not belong to a successful path whose weight is no more than
// 'opts.threshold' Times() the weight of the shortest path. Weights
// need to be commutative and have the path property.
template <class Arc, class ArcFilter>
void Prune(MutableFst<Arc> *fst,
           const PruneOptions<Arc, ArcFilter> &opts) {
  typedef typename Arc::Weight Weight;
  typedef typename Arc::StateId StateId;

  if ((Weight::Properties() & (kPath | kCommutative))
      != (kPath | kCommutative))
    LOG(FATAL) << "Prune: Weight needs to have the path property and"
               << " be commutative: "
               << Weight::Type();

  StateId ns = fst->NumStates();
  if (ns == 0) return;

  vector<Weight> *idistance = opts.idistance;
  vector<Weight> *fdistance = opts.fdistance;

  if (!idistance) {
    idistance = new vector<Weight>(ns, Weight::Zero());
    ShortestDistance(*fst, idistance, false);
  } else {
    idistance->resize(ns, Weight::Zero());
  }

  if (!fdistance) {
    fdistance = new vector<Weight>(ns, Weight::Zero());
    ShortestDistance(*fst, fdistance, true);
  } else {
    fdistance->resize(ns, Weight::Zero());
  }

  vector<StateId> dead;
  dead.push_back(fst->AddState());
  NaturalLess<Weight> less;
  Weight ceiling = Times((*fdistance)[fst->Start()], opts.threshold);

  for (StateId state = 0; state < ns; ++state) {
    if (less(ceiling, Times((*idistance)[state], (*fdistance)[state]))) {
      dead.push_back(state);
      continue;
    }
    for (MutableArcIterator< MutableFst<Arc> > it(fst, state);
         !it.Done();
         it.Next()) {
      Arc arc = it.Value();
      if (!opts.filter(arc)) continue;
      Weight weight = Times(Times((*idistance)[state], arc.weight),
                           (*fdistance)[arc.nextstate]);
      if(less(ceiling, weight)) {
        arc.nextstate = dead[0];
        it.SetValue(arc);
      }
    }
    if (less(ceiling, Times((*idistance)[state], fst->Final(state))))
      fst->SetFinal(state, Weight::Zero());
  }

  fst->DeleteStates(dead);

  if (!opts.idistance)
    delete idistance;
  if (!opts.fdistance)
    delete fdistance;
}


// Pruning algorithm: this version modifies its input and simply takes
// the pruning threshold as an argument. Delete states and arcs in
// 'fst' that do not belong to a successful path whose weight is no
// more than 'opts.threshold' Times() the weight of the shortest
// path. Weights need to be commutative and have the path property.
template <class Arc>
void Prune(MutableFst<Arc> *fst, typename Arc::Weight threshold) {
  PruneOptions<Arc, AnyArcFilter<Arc> > opts(threshold, AnyArcFilter<Arc>());
  Prune(fst, opts);
}


// Pruning algorithm: this version writes the pruned input Fst to an
// output MutableFst and it takes an options class as an argument.
// 'ofst' contains states and arcs that belong to a successful path in
// 'ifst' whose weight is no more than 'opts.threshold' Times() the
// weight of the shortest path. Weights need to be commutative and
// have the path property.
template <class Arc, class ArcFilter>
void Prune(const Fst<Arc> &ifst,
           MutableFst<Arc> *ofst,
           const PruneOptions<Arc, ArcFilter> &opts) {
  typedef typename Arc::Weight Weight;
  typedef typename Arc::StateId StateId;

  if ((Weight::Properties() & (kPath | kCommutative))
      != (kPath | kCommutative))
    LOG(FATAL) << "Prune: Weight needs to have the path property and"
               << " be commutative: "
               << Weight::Type();

  ofst->DeleteStates();

  if (ifst.Start() == kNoStateId)
    return;

  vector<Weight> *idistance = opts.idistance;
  vector<Weight> *fdistance = opts.fdistance;

  if (!idistance) {
    idistance = new vector<Weight>;
    ShortestDistance(ifst, idistance, false);
  }

  if (!fdistance) {
    fdistance = new vector<Weight>;
    ShortestDistance(ifst, fdistance, true);
  }

  vector<StateId> copy;
  NaturalLess<Weight> less;
  while (fdistance->size() <= ifst.Start())
    fdistance->push_back(Weight::Zero());
  Weight ceiling = Times((*fdistance)[ifst.Start()], opts.threshold);

  for (StateIterator< Fst<Arc> > sit(ifst);
       !sit.Done();
       sit.Next()) {
    StateId state = sit.Value();
    while (idistance->size() <= state)
      idistance->push_back(Weight::Zero());
    while (fdistance->size() <= state)
      fdistance->push_back(Weight::Zero());
    while (copy.size() <= state)
      copy.push_back(kNoStateId);

    if (less(ceiling, Times((*idistance)[state], (*fdistance)[state])))
      continue;

    if (copy[state] == kNoStateId)
      copy[state] = ofst->AddState();
    if (!less(ceiling, Times((*idistance)[state], ifst.Final(state))))
      ofst->SetFinal(copy[state], ifst.Final(state));

    for (ArcIterator< Fst<Arc> > ait(ifst, state);
         !ait.Done();
         ait.Next()) {
      Arc arc = ait.Value();

      if (!opts.filter(arc)) continue;

      while (idistance->size() <= arc.nextstate)
        idistance->push_back(Weight::Zero());
      while (fdistance->size() <= arc.nextstate)
        fdistance->push_back(Weight::Zero());
      while (copy.size() <= arc.nextstate)
        copy.push_back(kNoStateId);

      Weight weight = Times(Times((*idistance)[state], arc.weight),
                           (*fdistance)[arc.nextstate]);

      if (!less(ceiling, weight)) {
        if (copy[arc.nextstate] == kNoStateId)
          copy[arc.nextstate] = ofst->AddState();
        arc.nextstate = copy[arc.nextstate];
        ofst->AddArc(copy[state], arc);
      }
    }
  }

  ofst->SetStart(copy[ifst.Start()]);

  if (!opts.idistance)
    delete idistance;
  if (!opts.fdistance)
    delete fdistance;
}


// Pruning algorithm: this version writes the pruned input Fst to an
// output MutableFst and simply takes the pruning threshold as an
// argument.  'ofst' contains states and arcs that belong to a
// successful path in 'ifst' whose weight is no more than
// 'opts.threshold' Times() the weight of the shortest path. Weights
// need to be commutative and have the path property.
template <class Arc>
void Prune(const Fst<Arc> &ifst,
           MutableFst<Arc> *ofst,
           typename Arc::Weight threshold) {
  PruneOptions<Arc, AnyArcFilter<Arc> > opts(threshold, AnyArcFilter<Arc>());
  Prune(ifst, ofst, opts);
}

} // namespace fst

#endif // FST_LIB_PRUNE_H_