BaumWelch  baumwelch-0.3.8
OpenGrm-BaumWelch library
log-adder.h
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 //
13 // Copyright 2017 and onwards Google, Inc.
14 
15 #ifndef NLP_GRM2_BAUMWELCH_LOG_ADDER_H_
16 #define NLP_GRM2_BAUMWELCH_LOG_ADDER_H_
17 
18 #include <type_traits>
19 
20 #include <fst/float-weight.h>
21 #include <fst/weight.h>
22 
23 namespace fst {
24 
25 // This wraps the Adder class, using LogWeight(Tpl) of the appropriate size
26 // internally and hiding conversion. It assumes the existence of a valid weight
27 // converters between the template weight type and the said LogWeight.
28 template <class Weight>
29 class LogAdder {
30  public:
31  // HelperWeight is Weight for non-idempotent weights, as is the converter;
32  // it is a LogWeightTpl of appropriate precision otherwise.
33  using HelperWeight =
34  typename std::conditional_t<IsIdempotent<Weight>::value,
35  LogWeightTpl<typename Weight::ValueType>,
36  Weight>;
37 
38  explicit LogAdder(Weight weight = Weight::Zero())
39  : sum_(LogAdder<Weight>::To(weight)) {}
40 
41  // Adds a weight to the sum.
42  void Add(const Weight &weight) { sum_.Add(LogAdder<Weight>::To(weight)); }
43 
44  // Gets the sum in the template-argument weight type.
45  Weight Sum() const { return LogAdder<Weight>::From(sum_.Sum()); }
46 
47  private:
48  static HelperWeight To(const Weight &weight) {
49  static const WeightConvert<Weight, HelperWeight> to;
50  return to(weight);
51  }
52 
53  static Weight From(const HelperWeight &weight) {
54  static const WeightConvert<HelperWeight, Weight> from;
55  return from(weight);
56  }
57 
58  Adder<HelperWeight> sum_;
59 };
60 
61 } // namespace fst
62 
63 #endif // NLP_GRM2_BAUMWELCH_LOG_ADDER_H_
64 
void Add(const Weight &weight)
Definition: log-adder.h:42
LogAdder(Weight weight=Weight::Zero())
Definition: log-adder.h:38
Definition: a-star.h:30
typename std::conditional_t< IsIdempotent< Weight >::value, LogWeightTpl< typename Weight::ValueType >, Weight > HelperWeight
Definition: log-adder.h:36
Weight Sum() const
Definition: log-adder.h:45