Blame view

tools/openfst-1.6.7/src/include/fst/state-map.h 17.9 KB
8dcb6dfcb   Yannick Estève   first commit
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
  // See www.openfst.org for extensive documentation on this weighted
  // finite-state transducer library.
  //
  // Class to map over/transform states e.g., sort transitions.
  //
  // Consider using when operation does not change the number of states.
  
  #ifndef FST_STATE_MAP_H_
  #define FST_STATE_MAP_H_
  
  #include <algorithm>
  #include <string>
  #include <utility>
  
  #include <fst/log.h>
  
  #include <fst/arc-map.h>
  #include <fst/cache.h>
  #include <fst/mutable-fst.h>
  
  
  namespace fst {
  
  // StateMapper Interface. The class determines how states are mapped; useful for
  // implementing operations that do not change the number of states.
  //
  // class StateMapper {
  //  public:
  //   using FromArc = A;
  //   using ToArc = B;
  //
  //   // Typical constructor.
  //   StateMapper(const Fst<A> &fst);
  //
  //   // Required copy constructor that allows updating FST argument;
  //   // pass only if relevant and changed.
  //   StateMapper(const StateMapper &mapper, const Fst<A> *fst = 0);
  //
  //   // Specifies initial state of result.
  //   B::StateId Start() const;
  //   // Specifies state's final weight in result.
  //   B::Weight Final(B::StateId state) const;
  //
  //   // These methods iterate through a state's arcs in result.
  //
  //   // Specifies state to iterate over.
  //   void SetState(B::StateId state);
  //
  //   // End of arcs?
  //   bool Done() const;
  //
  //   // Current arc.
  //   const B &Value() const;
  //
  //   // Advances to next arc (when !Done)
  //   void Next();
  //
  //   // Specifies input symbol table action the mapper requires (see above).
  //   MapSymbolsAction InputSymbolsAction() const;
  //
  //   // Specifies output symbol table action the mapper requires (see above).
  //   MapSymbolsAction OutputSymbolsAction() const;
  //
  //   // This specifies the known properties of an FST mapped by this
  //   // mapper. It takes as argument the input FST's known properties.
  //   uint64 Properties(uint64 props) const;
  // };
  //
  // We include a various state map versions below. One dimension of variation is
  // whether the mapping mutates its input, writes to a new result FST, or is an
  // on-the-fly Fst. Another dimension is how we pass the mapper. We allow passing
  // the mapper by pointer for cases that we need to change the state of the
  // user's mapper. We also include map versions that pass the mapper by value or
  // const reference when this suffices.
  
  // Maps an arc type A using a mapper function object C, passed by pointer. This
  // version modifies the input FST.
  template <class A, class C>
  void StateMap(MutableFst<A> *fst, C *mapper) {
    if (mapper->InputSymbolsAction() == MAP_CLEAR_SYMBOLS) {
      fst->SetInputSymbols(nullptr);
    }
    if (mapper->OutputSymbolsAction() == MAP_CLEAR_SYMBOLS) {
      fst->SetOutputSymbols(nullptr);
    }
    if (fst->Start() == kNoStateId) return;
    const auto props = fst->Properties(kFstProperties, false);
    fst->SetStart(mapper->Start());
    for (StateIterator<Fst<A>> siter(*fst); !siter.Done(); siter.Next()) {
      const auto state = siter.Value();
      mapper->SetState(state);
      fst->DeleteArcs(state);
      for (; !mapper->Done(); mapper->Next()) {
        fst->AddArc(state, mapper->Value());
      }
      fst->SetFinal(state, mapper->Final(state));
    }
    fst->SetProperties(mapper->Properties(props), kFstProperties);
  }
  
  // Maps an arc type A using a mapper function object C, passed by value.
  // This version modifies the input FST.
  template <class A, class C>
  void StateMap(MutableFst<A> *fst, C mapper) {
    StateMap(fst, &mapper);
  }
  
  // Maps an arc type A to an arc type B using mapper functor C, passed by
  // pointer. This version writes to an output FST.
  template <class A, class B, class C>
  void StateMap(const Fst<A> &ifst, MutableFst<B> *ofst, C *mapper) {
    ofst->DeleteStates();
    if (mapper->InputSymbolsAction() == MAP_COPY_SYMBOLS) {
      ofst->SetInputSymbols(ifst.InputSymbols());
    } else if (mapper->InputSymbolsAction() == MAP_CLEAR_SYMBOLS) {
      ofst->SetInputSymbols(nullptr);
    }
    if (mapper->OutputSymbolsAction() == MAP_COPY_SYMBOLS) {
      ofst->SetOutputSymbols(ifst.OutputSymbols());
    } else if (mapper->OutputSymbolsAction() == MAP_CLEAR_SYMBOLS) {
      ofst->SetOutputSymbols(nullptr);
    }
    const auto iprops = ifst.Properties(kCopyProperties, false);
    if (ifst.Start() == kNoStateId) {
      if (iprops & kError) ofst->SetProperties(kError, kError);
      return;
    }
    // Adds all states.
    if (ifst.Properties(kExpanded, false)) ofst->ReserveStates(CountStates(ifst));
    for (StateIterator<Fst<A>> siter(ifst); !siter.Done(); siter.Next()) {
      ofst->AddState();
    }
    ofst->SetStart(mapper->Start());
    for (StateIterator<Fst<A>> siter(ifst); !siter.Done(); siter.Next()) {
      const auto state = siter.Value();
      mapper->SetState(state);
      for (; !mapper->Done(); mapper->Next()) {
        ofst->AddArc(state, mapper->Value());
      }
      ofst->SetFinal(state, mapper->Final(state));
    }
    const auto oprops = ofst->Properties(kFstProperties, false);
    ofst->SetProperties(mapper->Properties(iprops) | oprops, kFstProperties);
  }
  
  // Maps an arc type A to an arc type B using mapper functor object C, passed by
  // value. This version writes to an output FST.
  template <class A, class B, class C>
  void StateMap(const Fst<A> &ifst, MutableFst<B> *ofst, C mapper) {
    StateMap(ifst, ofst, &mapper);
  }
  
  using StateMapFstOptions = CacheOptions;
  
  template <class A, class B, class C>
  class StateMapFst;
  
  // Facade around StateIteratorBase<A> inheriting from StateIteratorBase<B>.
  template <class A, class B>
  class StateMapStateIteratorBase : public StateIteratorBase<B> {
   public:
    using Arc = B;
    using StateId = typename Arc::StateId;
  
    explicit StateMapStateIteratorBase(StateIteratorBase<A> *base)
        : base_(base) {}
  
    bool Done() const final { return base_->Done(); }
  
    StateId Value() const final { return base_->Value(); }
  
    void Next() final { base_->Next(); }
  
    void Reset() final { base_->Reset(); }
  
   private:
    std::unique_ptr<StateIteratorBase<A>> base_;
  
    StateMapStateIteratorBase() = delete;
  };
  
  namespace internal {
  
  // Implementation of delayed StateMapFst.
  template <class A, class B, class C>
  class StateMapFstImpl : public CacheImpl<B> {
   public:
    using Arc = B;
    using StateId = typename Arc::StateId;
    using Weight = typename Arc::Weight;
  
    using FstImpl<B>::SetType;
    using FstImpl<B>::SetProperties;
    using FstImpl<B>::SetInputSymbols;
    using FstImpl<B>::SetOutputSymbols;
  
    using CacheImpl<B>::PushArc;
    using CacheImpl<B>::HasArcs;
    using CacheImpl<B>::HasFinal;
    using CacheImpl<B>::HasStart;
    using CacheImpl<B>::SetArcs;
    using CacheImpl<B>::SetFinal;
    using CacheImpl<B>::SetStart;
  
    friend class StateIterator<StateMapFst<A, B, C>>;
  
    StateMapFstImpl(const Fst<A> &fst, const C &mapper,
                    const StateMapFstOptions &opts)
        : CacheImpl<B>(opts),
          fst_(fst.Copy()),
          mapper_(new C(mapper, fst_.get())),
          own_mapper_(true) {
      Init();
    }
  
    StateMapFstImpl(const Fst<A> &fst, C *mapper, const StateMapFstOptions &opts)
        : CacheImpl<B>(opts),
          fst_(fst.Copy()),
          mapper_(mapper),
          own_mapper_(false) {
      Init();
    }
  
    StateMapFstImpl(const StateMapFstImpl<A, B, C> &impl)
        : CacheImpl<B>(impl),
          fst_(impl.fst_->Copy(true)),
          mapper_(new C(*impl.mapper_, fst_.get())),
          own_mapper_(true) {
      Init();
    }
  
    ~StateMapFstImpl() override {
      if (own_mapper_) delete mapper_;
    }
  
    StateId Start() {
      if (!HasStart()) SetStart(mapper_->Start());
      return CacheImpl<B>::Start();
    }
  
    Weight Final(StateId state) {
      if (!HasFinal(state)) SetFinal(state, mapper_->Final(state));
      return CacheImpl<B>::Final(state);
    }
  
    size_t NumArcs(StateId state) {
      if (!HasArcs(state)) Expand(state);
      return CacheImpl<B>::NumArcs(state);
    }
  
    size_t NumInputEpsilons(StateId state) {
      if (!HasArcs(state)) Expand(state);
      return CacheImpl<B>::NumInputEpsilons(state);
    }
  
    size_t NumOutputEpsilons(StateId state) {
      if (!HasArcs(state)) Expand(state);
      return CacheImpl<B>::NumOutputEpsilons(state);
    }
  
    void InitStateIterator(StateIteratorData<B> *datb) const {
      StateIteratorData<A> data;
      fst_->InitStateIterator(&data);
      datb->base = data.base ? new StateMapStateIteratorBase<A, B>(data.base)
          : nullptr;
      datb->nstates = data.nstates;
    }
  
    void InitArcIterator(StateId state, ArcIteratorData<B> *data) {
      if (!HasArcs(state)) Expand(state);
      CacheImpl<B>::InitArcIterator(state, data);
    }
  
    uint64 Properties() const override { return Properties(kFstProperties); }
  
    uint64 Properties(uint64 mask) const override {
      if ((mask & kError) && (fst_->Properties(kError, false) ||
                              (mapper_->Properties(0) & kError))) {
        SetProperties(kError, kError);
      }
      return FstImpl<Arc>::Properties(mask);
    }
  
    void Expand(StateId state) {
      // Adds exiting arcs.
      for (mapper_->SetState(state); !mapper_->Done(); mapper_->Next()) {
        PushArc(state, mapper_->Value());
      }
      SetArcs(state);
    }
  
    const Fst<A> *GetFst() const { return fst_.get(); }
  
   private:
    void Init() {
      SetType("statemap");
      if (mapper_->InputSymbolsAction() == MAP_COPY_SYMBOLS) {
        SetInputSymbols(fst_->InputSymbols());
      } else if (mapper_->InputSymbolsAction() == MAP_CLEAR_SYMBOLS) {
        SetInputSymbols(nullptr);
      }
      if (mapper_->OutputSymbolsAction() == MAP_COPY_SYMBOLS) {
        SetOutputSymbols(fst_->OutputSymbols());
      } else if (mapper_->OutputSymbolsAction() == MAP_CLEAR_SYMBOLS) {
        SetOutputSymbols(nullptr);
      }
      const auto props = fst_->Properties(kCopyProperties, false);
      SetProperties(mapper_->Properties(props));
    }
  
    std::unique_ptr<const Fst<A>> fst_;
    C *mapper_;
    bool own_mapper_;
  };
  
  }  // namespace internal
  
  // Maps an arc type A to an arc type B using Mapper function object
  // C. This version is a delayed FST.
  template <class A, class B, class C>
  class StateMapFst : public ImplToFst<internal::StateMapFstImpl<A, B, C>> {
   public:
    friend class ArcIterator<StateMapFst<A, B, C>>;
  
    using Arc = B;
    using StateId = typename Arc::StateId;
    using Weight = typename Arc::Weight;
    using Store = DefaultCacheStore<Arc>;
    using State = typename Store::State;
    using Impl = internal::StateMapFstImpl<A, B, C>;
  
    StateMapFst(const Fst<A> &fst, const C &mapper,
                const StateMapFstOptions &opts)
        : ImplToFst<Impl>(std::make_shared<Impl>(fst, mapper, opts)) {}
  
    StateMapFst(const Fst<A> &fst, C *mapper, const StateMapFstOptions &opts)
        : ImplToFst<Impl>(std::make_shared<Impl>(fst, mapper, opts)) {}
  
    StateMapFst(const Fst<A> &fst, const C &mapper)
        : ImplToFst<Impl>(
              std::make_shared<Impl>(fst, mapper, StateMapFstOptions())) {}
  
    StateMapFst(const Fst<A> &fst, C *mapper)
        : ImplToFst<Impl>(
              std::make_shared<Impl>(fst, mapper, StateMapFstOptions())) {}
  
    // See Fst<>::Copy() for doc.
    StateMapFst(const StateMapFst<A, B, C> &fst, bool safe = false)
        : ImplToFst<Impl>(fst, safe) {}
  
    // Get a copy of this StateMapFst. See Fst<>::Copy() for further doc.
    StateMapFst<A, B, C> *Copy(bool safe = false) const override {
      return new StateMapFst<A, B, C>(*this, safe);
    }
  
    void InitStateIterator(StateIteratorData<B> *data) const override {
      GetImpl()->InitStateIterator(data);
    }
  
    void InitArcIterator(StateId state, ArcIteratorData<B> *data) const override {
      GetMutableImpl()->InitArcIterator(state, data);
    }
  
   protected:
    using ImplToFst<Impl>::GetImpl;
    using ImplToFst<Impl>::GetMutableImpl;
  
   private:
    StateMapFst &operator=(const StateMapFst &) = delete;
  };
  
  // Specialization for StateMapFst.
  template <class A, class B, class C>
  class ArcIterator<StateMapFst<A, B, C>>
      : public CacheArcIterator<StateMapFst<A, B, C>> {
   public:
    using StateId = typename A::StateId;
  
    ArcIterator(const StateMapFst<A, B, C> &fst, StateId state)
        : CacheArcIterator<StateMapFst<A, B, C>>(fst.GetMutableImpl(), state) {
      if (!fst.GetImpl()->HasArcs(state)) fst.GetMutableImpl()->Expand(state);
    }
  };
  
  // Utility mappers.
  
  // Mapper that returns its input.
  template <class Arc>
  class IdentityStateMapper {
   public:
    using FromArc = Arc;
    using ToArc = Arc;
  
    using StateId = typename Arc::StateId;
    using Weight = typename Arc::Weight;
  
    explicit IdentityStateMapper(const Fst<Arc> &fst) : fst_(fst) {}
  
    // Allows updating FST argument; pass only if changed.
    IdentityStateMapper(const IdentityStateMapper<Arc> &mapper,
                        const Fst<Arc> *fst = nullptr)
        : fst_(fst ? *fst : mapper.fst_) {}
  
    StateId Start() const { return fst_.Start(); }
  
    Weight Final(StateId state) const { return fst_.Final(state); }
  
    void SetState(StateId state) {
      aiter_.reset(new ArcIterator<Fst<Arc>>(fst_, state));
    }
  
    bool Done() const { return aiter_->Done(); }
  
    const Arc &Value() const { return aiter_->Value(); }
  
    void Next() { aiter_->Next(); }
  
    constexpr MapSymbolsAction InputSymbolsAction() const {
      return MAP_COPY_SYMBOLS;
    }
  
    constexpr MapSymbolsAction OutputSymbolsAction() const {
      return MAP_COPY_SYMBOLS;
    }
  
    uint64 Properties(uint64 props) const { return props; }
  
   private:
    const Fst<Arc> &fst_;
    std::unique_ptr<ArcIterator<Fst<Arc>>> aiter_;
  };
  
  template <class Arc>
  class ArcSumMapper {
   public:
    using FromArc = Arc;
    using ToArc = Arc;
  
    using StateId = typename Arc::StateId;
    using Weight = typename Arc::Weight;
  
    explicit ArcSumMapper(const Fst<Arc> &fst) : fst_(fst), i_(0) {}
  
    // Allows updating FST argument; pass only if changed.
    ArcSumMapper(const ArcSumMapper<Arc> &mapper, const Fst<Arc> *fst = nullptr)
        : fst_(fst ? *fst : mapper.fst_), i_(0) {}
  
    StateId Start() const { return fst_.Start(); }
  
    Weight Final(StateId state) const { return fst_.Final(state); }
  
    void SetState(StateId state) {
      i_ = 0;
      arcs_.clear();
      arcs_.reserve(fst_.NumArcs(state));
      for (ArcIterator<Fst<Arc>> aiter(fst_, state); !aiter.Done();
           aiter.Next()) {
        arcs_.push_back(aiter.Value());
      }
      // First sorts the exiting arcs by input label, output label and destination
      // state and then sums weights of arcs with the same input label, output
      // label, and destination state.
      std::sort(arcs_.begin(), arcs_.end(), comp_);
      size_t narcs = 0;
      for (const auto &arc : arcs_) {
        if (narcs > 0 && equal_(arc, arcs_[narcs - 1])) {
          arcs_[narcs - 1].weight = Plus(arcs_[narcs - 1].weight, arc.weight);
        } else {
          arcs_[narcs] = arc;
          ++narcs;
        }
      }
      arcs_.resize(narcs);
    }
  
    bool Done() const { return i_ >= arcs_.size(); }
  
    const Arc &Value() const { return arcs_[i_]; }
  
    void Next() { ++i_; }
  
    constexpr MapSymbolsAction InputSymbolsAction() const {
      return MAP_COPY_SYMBOLS;
    }
  
    constexpr MapSymbolsAction OutputSymbolsAction() const {
      return MAP_COPY_SYMBOLS;
    }
  
    uint64 Properties(uint64 props) const {
      return props & kArcSortProperties & kDeleteArcsProperties &
             kWeightInvariantProperties;
    }
  
   private:
    struct Compare {
      bool operator()(const Arc &x, const Arc &y) const {
        if (x.ilabel < y.ilabel) return true;
        if (x.ilabel > y.ilabel) return false;
        if (x.olabel < y.olabel) return true;
        if (x.olabel > y.olabel) return false;
        if (x.nextstate < y.nextstate) return true;
        if (x.nextstate > y.nextstate) return false;
        return false;
      }
    };
  
    struct Equal {
      bool operator()(const Arc &x, const Arc &y) const {
        return (x.ilabel == y.ilabel && x.olabel == y.olabel &&
                x.nextstate == y.nextstate);
      }
    };
  
    const Fst<Arc> &fst_;
    Compare comp_;
    Equal equal_;
    std::vector<Arc> arcs_;
    ssize_t i_;  // Current arc position.
  
    ArcSumMapper &operator=(const ArcSumMapper &) = delete;
  };
  
  template <class Arc>
  class ArcUniqueMapper {
   public:
    using FromArc = Arc;
    using ToArc = Arc;
  
    using StateId = typename Arc::StateId;
    using Weight = typename Arc::Weight;
  
    explicit ArcUniqueMapper(const Fst<Arc> &fst) : fst_(fst), i_(0) {}
  
    // Allows updating FST argument; pass only if changed.
    ArcUniqueMapper(const ArcUniqueMapper<Arc> &mapper,
                    const Fst<Arc> *fst = nullptr)
        : fst_(fst ? *fst : mapper.fst_), i_(0) {}
  
    StateId Start() const { return fst_.Start(); }
  
    Weight Final(StateId state) const { return fst_.Final(state); }
  
    void SetState(StateId state) {
      i_ = 0;
      arcs_.clear();
      arcs_.reserve(fst_.NumArcs(state));
      for (ArcIterator<Fst<Arc>> aiter(fst_, state); !aiter.Done();
           aiter.Next()) {
        arcs_.push_back(aiter.Value());
      }
      // First sorts the exiting arcs by input label, output label and destination
      // state and then uniques identical arcs.
      std::sort(arcs_.begin(), arcs_.end(), comp_);
      arcs_.erase(std::unique(arcs_.begin(), arcs_.end(), equal_), arcs_.end());
    }
  
    bool Done() const { return i_ >= arcs_.size(); }
  
    const Arc &Value() const { return arcs_[i_]; }
  
    void Next() { ++i_; }
  
    constexpr MapSymbolsAction InputSymbolsAction() const {
      return MAP_COPY_SYMBOLS;
    }
  
    constexpr MapSymbolsAction OutputSymbolsAction() const {
      return MAP_COPY_SYMBOLS;
    }
  
    uint64 Properties(uint64 props) const {
      return props & kArcSortProperties & kDeleteArcsProperties;
    }
  
   private:
    struct Compare {
      bool operator()(const Arc &x, const Arc &y) const {
        if (x.ilabel < y.ilabel) return true;
        if (x.ilabel > y.ilabel) return false;
        if (x.olabel < y.olabel) return true;
        if (x.olabel > y.olabel) return false;
        if (x.nextstate < y.nextstate) return true;
        if (x.nextstate > y.nextstate) return false;
        return false;
      }
    };
  
    struct Equal {
      bool operator()(const Arc &x, const Arc &y) const {
        return (x.ilabel == y.ilabel && x.olabel == y.olabel &&
                x.nextstate == y.nextstate && x.weight == y.weight);
      }
    };
  
    const Fst<Arc> &fst_;
    Compare comp_;
    Equal equal_;
    std::vector<Arc> arcs_;
    size_t i_;  // Current arc position.
  
    ArcUniqueMapper &operator=(const ArcUniqueMapper &) = delete;
  };
  
  // Useful aliases when using StdArc.
  
  using StdArcSumMapper = ArcSumMapper<StdArc>;
  
  using StdArcUniqueMapper = ArcUniqueMapper<StdArc>;
  
  }  // namespace fst
  
  #endif  // FST_STATE_MAP_H_